xref: /sqlite-3.40.0/src/insert.c (revision abb6fcab)
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*abb6fcabSdrh ** $Id: insert.c,v 1.190 2007/08/16 12:24:02 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;
44*abb6fcabSdrh     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 
55956bc92cSdrh   sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
56a37cdde0Sdanielk1977 }
57a37cdde0Sdanielk1977 
58a37cdde0Sdanielk1977 /*
59a37cdde0Sdanielk1977 ** Set P3 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;
83*abb6fcabSdrh     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 
98956bc92cSdrh   sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
993d1bfeaaSdanielk1977 }
1003d1bfeaaSdanielk1977 
1014d88778bSdanielk1977 /*
1024d88778bSdanielk1977 ** Return non-zero if SELECT statement p opens the table with rootpage
1034d88778bSdanielk1977 ** iTab in database iDb.  This is used to see if a statement of the form
1044d88778bSdanielk1977 ** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
1054d88778bSdanielk1977 ** table for the results of the SELECT.
1064d88778bSdanielk1977 **
1074d88778bSdanielk1977 ** No checking is done for sub-selects that are part of expressions.
1084d88778bSdanielk1977 */
109e501b89aSdanielk1977 static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
1104d88778bSdanielk1977   int i;
1114d88778bSdanielk1977   struct SrcList_item *pItem;
1124d88778bSdanielk1977   if( p->pSrc==0 ) return 0;
1134d88778bSdanielk1977   for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
1144d88778bSdanielk1977     if( pItem->pSelect ){
115da184236Sdanielk1977       if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
1164d88778bSdanielk1977     }else{
117da184236Sdanielk1977       if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
1184d88778bSdanielk1977     }
1194d88778bSdanielk1977   }
1204d88778bSdanielk1977   return 0;
1214d88778bSdanielk1977 }
1223d1bfeaaSdanielk1977 
1239d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1249d9cf229Sdrh /*
1259d9cf229Sdrh ** Write out code to initialize the autoincrement logic.  This code
1269d9cf229Sdrh ** looks up the current autoincrement value in the sqlite_sequence
1279d9cf229Sdrh ** table and stores that value in a memory cell.  Code generated by
1289d9cf229Sdrh ** autoIncStep() will keep that memory cell holding the largest
1299d9cf229Sdrh ** rowid value.  Code generated by autoIncEnd() will write the new
1309d9cf229Sdrh ** largest value of the counter back into the sqlite_sequence table.
1319d9cf229Sdrh **
1329d9cf229Sdrh ** This routine returns the index of the mem[] cell that contains
1339d9cf229Sdrh ** the maximum rowid counter.
1349d9cf229Sdrh **
1359d9cf229Sdrh ** Two memory cells are allocated.  The next memory cell after the
1369d9cf229Sdrh ** one returned holds the rowid in sqlite_sequence where we will
1379d9cf229Sdrh ** write back the revised maximum rowid.
1389d9cf229Sdrh */
1399d9cf229Sdrh static int autoIncBegin(
1409d9cf229Sdrh   Parse *pParse,      /* Parsing context */
1419d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
1429d9cf229Sdrh   Table *pTab         /* The table we are writing to */
1439d9cf229Sdrh ){
1449d9cf229Sdrh   int memId = 0;
1459d9cf229Sdrh   if( pTab->autoInc ){
1469d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
1479d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
1489d9cf229Sdrh     int iCur = pParse->nTab;
1499d9cf229Sdrh     int addr;
1509d9cf229Sdrh     assert( v );
1519d9cf229Sdrh     addr = sqlite3VdbeCurrentAddr(v);
1529d9cf229Sdrh     memId = pParse->nMem+1;
1539d9cf229Sdrh     pParse->nMem += 2;
1549d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
1559d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
1569d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
1579d9cf229Sdrh     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
1589d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
1599d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
1609d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
1619d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
1629d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
1639d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
1649d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
1659d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
1669d9cf229Sdrh   }
1679d9cf229Sdrh   return memId;
1689d9cf229Sdrh }
1699d9cf229Sdrh 
1709d9cf229Sdrh /*
1719d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
1729d9cf229Sdrh **
1739d9cf229Sdrh ** This routine should be called when the top of the stack holds a
1749d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
1759d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
1769d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
1779d9cf229Sdrh */
1789d9cf229Sdrh static void autoIncStep(Parse *pParse, int memId){
1799d9cf229Sdrh   if( memId>0 ){
1809d9cf229Sdrh     sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
1819d9cf229Sdrh   }
1829d9cf229Sdrh }
1839d9cf229Sdrh 
1849d9cf229Sdrh /*
1859d9cf229Sdrh ** After doing one or more inserts, the maximum rowid is stored
1869d9cf229Sdrh ** in mem[memId].  Generate code to write this value back into the
1879d9cf229Sdrh ** the sqlite_sequence table.
1889d9cf229Sdrh */
1899d9cf229Sdrh static void autoIncEnd(
1909d9cf229Sdrh   Parse *pParse,     /* The parsing context */
1919d9cf229Sdrh   int iDb,           /* Index of the database holding pTab */
1929d9cf229Sdrh   Table *pTab,       /* Table we are inserting into */
1939d9cf229Sdrh   int memId          /* Memory cell holding the maximum rowid */
1949d9cf229Sdrh ){
1959d9cf229Sdrh   if( pTab->autoInc ){
1969d9cf229Sdrh     int iCur = pParse->nTab;
1979d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
1989d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
1999d9cf229Sdrh     int addr;
2009d9cf229Sdrh     assert( v );
2019d9cf229Sdrh     addr = sqlite3VdbeCurrentAddr(v);
2029d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
2039d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
2049d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
2059d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2069d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
2079d9cf229Sdrh     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
2089d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
2099d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
210e4d90813Sdrh     sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
2119d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
2129d9cf229Sdrh   }
2139d9cf229Sdrh }
2149d9cf229Sdrh #else
2159d9cf229Sdrh /*
2169d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
2179d9cf229Sdrh ** above are all no-ops
2189d9cf229Sdrh */
2199d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
2209d9cf229Sdrh # define autoIncStep(A,B)
2219d9cf229Sdrh # define autoIncEnd(A,B,C,D)
2229d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
2239d9cf229Sdrh 
2249d9cf229Sdrh 
2259d9cf229Sdrh /* Forward declaration */
2269d9cf229Sdrh static int xferOptimization(
2279d9cf229Sdrh   Parse *pParse,        /* Parser context */
2289d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
2299d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
2309d9cf229Sdrh   int onError,          /* How to handle constraint errors */
2319d9cf229Sdrh   int iDbDest           /* The database of pDest */
2329d9cf229Sdrh );
2339d9cf229Sdrh 
2343d1bfeaaSdanielk1977 /*
2351ccde15dSdrh ** This routine is call to handle SQL of the following forms:
236cce7d176Sdrh **
237cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
2381ccde15dSdrh **    insert into TABLE (IDLIST) select
239cce7d176Sdrh **
2401ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
2411ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
242967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
2431ccde15dSdrh **
2441ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
2451ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
2461ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
2471ccde15dSdrh ** data for the insert.
248142e30dfSdrh **
2499d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
250142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
251142e30dfSdrh ** once straight down through.  The template looks like this:
252142e30dfSdrh **
253142e30dfSdrh **         open write cursor to <table> and its indices
254142e30dfSdrh **         puts VALUES clause expressions onto the stack
255142e30dfSdrh **         write the resulting record into <table>
256142e30dfSdrh **         cleanup
257142e30dfSdrh **
2589d9cf229Sdrh ** The three remaining templates assume the statement is of the form
259142e30dfSdrh **
260142e30dfSdrh **   INSERT INTO <table> SELECT ...
261142e30dfSdrh **
2629d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
2639d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
2649d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
2659d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
2669d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
2679d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
2689d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
2699d9cf229Sdrh ** template.  This is the second template.
2709d9cf229Sdrh **
2719d9cf229Sdrh **         open a write cursor to <table>
2729d9cf229Sdrh **         open read cursor on <table2>
2739d9cf229Sdrh **         transfer all records in <table2> over to <table>
2749d9cf229Sdrh **         close cursors
2759d9cf229Sdrh **         foreach index on <table>
2769d9cf229Sdrh **           open a write cursor on the <table> index
2779d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
2789d9cf229Sdrh **           transfer all records from the read to the write cursors
2799d9cf229Sdrh **           close cursors
2809d9cf229Sdrh **         end foreach
2819d9cf229Sdrh **
2829d9cf229Sdrh ** The third template is for when the second template does not apply
2839d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
2849d9cf229Sdrh ** The generated code follows this template:
285142e30dfSdrh **
286142e30dfSdrh **         goto B
287142e30dfSdrh **      A: setup for the SELECT
2889d9cf229Sdrh **         loop over the rows in the SELECT
289142e30dfSdrh **           gosub C
290142e30dfSdrh **         end loop
291142e30dfSdrh **         cleanup after the SELECT
292142e30dfSdrh **         goto D
293142e30dfSdrh **      B: open write cursor to <table> and its indices
294142e30dfSdrh **         goto A
295142e30dfSdrh **      C: insert the select result into <table>
296142e30dfSdrh **         return
297142e30dfSdrh **      D: cleanup
298142e30dfSdrh **
2999d9cf229Sdrh ** The fourth template is used if the insert statement takes its
300142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
301142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
302142e30dfSdrh ** we have to use a intermediate table to store the results of
303142e30dfSdrh ** the select.  The template is like this:
304142e30dfSdrh **
305142e30dfSdrh **         goto B
306142e30dfSdrh **      A: setup for the SELECT
307142e30dfSdrh **         loop over the tables in the SELECT
308142e30dfSdrh **           gosub C
309142e30dfSdrh **         end loop
310142e30dfSdrh **         cleanup after the SELECT
311142e30dfSdrh **         goto D
312142e30dfSdrh **      C: insert the select result into the intermediate table
313142e30dfSdrh **         return
314142e30dfSdrh **      B: open a cursor to an intermediate table
315142e30dfSdrh **         goto A
316142e30dfSdrh **      D: open write cursor to <table> and its indices
317142e30dfSdrh **         loop over the intermediate table
318142e30dfSdrh **           transfer values form intermediate table into <table>
319142e30dfSdrh **         end the loop
320142e30dfSdrh **         cleanup
321cce7d176Sdrh */
3224adee20fSdanielk1977 void sqlite3Insert(
323cce7d176Sdrh   Parse *pParse,        /* Parser context */
324113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
325cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
3265974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
3279cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
3289cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
329cce7d176Sdrh ){
3305974a30fSdrh   Table *pTab;          /* The table to insert into */
331113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
332e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
3335974a30fSdrh   int i, j, idx;        /* Loop counters */
3345974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
3355974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
336967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
337cfe9a69fSdanielk1977   int base = 0;         /* VDBE Cursor number for pTab */
338cfe9a69fSdanielk1977   int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
3399bb575fdSdrh   sqlite3 *db;          /* The main database structure */
3404a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
3410ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
3424d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
343cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
344cfe9a69fSdanielk1977   int iSelectLoop = 0;  /* Address of code that implements the SELECT */
345cfe9a69fSdanielk1977   int iCleanup = 0;     /* Address of the cleanup code */
346cfe9a69fSdanielk1977   int iInsertBlock = 0; /* Address of the subroutine used to insert data */
347cfe9a69fSdanielk1977   int iCntMem = 0;      /* Memory cell used for the row counter */
348798da52cSdrh   int newIdx = -1;      /* Cursor for the NEW table */
3492958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
3502958a4e6Sdrh   int counterMem = 0;   /* Memory cell holding AUTOINCREMENT counter */
351e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
352da184236Sdanielk1977   int iDb;
353cce7d176Sdrh 
354034ca14fSdanielk1977   int nHidden = 0;
355034ca14fSdanielk1977 
356798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
357798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
358dca76841Sdrh   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
359798da52cSdrh #endif
360c3f9bad2Sdanielk1977 
36117435752Sdrh   db = pParse->db;
36217435752Sdrh   if( pParse->nErr || db->mallocFailed ){
3636f7adc8aSdrh     goto insert_cleanup;
3646f7adc8aSdrh   }
365daffd0e5Sdrh 
3661ccde15dSdrh   /* Locate the table into which we will be inserting new information.
3671ccde15dSdrh   */
368113088ecSdrh   assert( pTabList->nSrc==1 );
369113088ecSdrh   zTab = pTabList->a[0].zName;
370daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
3714adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
372c3f9bad2Sdanielk1977   if( pTab==0 ){
373c3f9bad2Sdanielk1977     goto insert_cleanup;
374c3f9bad2Sdanielk1977   }
375da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
376da184236Sdanielk1977   assert( iDb<db->nDb );
377da184236Sdanielk1977   pDb = &db->aDb[iDb];
3782958a4e6Sdrh   zDb = pDb->zName;
3794adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
3801962bda7Sdrh     goto insert_cleanup;
3811962bda7Sdrh   }
382c3f9bad2Sdanielk1977 
383b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
384b7f9164eSdrh   ** inserted into is a view
385b7f9164eSdrh   */
386b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
387dca76841Sdrh   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
388b7f9164eSdrh   isView = pTab->pSelect!=0;
389b7f9164eSdrh #else
390dca76841Sdrh # define triggers_exist 0
391b7f9164eSdrh # define isView 0
392b7f9164eSdrh #endif
393b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
394b7f9164eSdrh # undef isView
395b7f9164eSdrh # define isView 0
396b7f9164eSdrh #endif
397b7f9164eSdrh 
398c3f9bad2Sdanielk1977   /* Ensure that:
399c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
400c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
401c3f9bad2Sdanielk1977   */
402dca76841Sdrh   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
403c3f9bad2Sdanielk1977     goto insert_cleanup;
404c3f9bad2Sdanielk1977   }
40543617e9aSdrh   assert( pTab!=0 );
4061ccde15dSdrh 
407f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
408b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
409b3d24bf8Sdanielk1977   ** module table).
410f573c99bSdrh   */
411b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
412f573c99bSdrh     goto insert_cleanup;
413f573c99bSdrh   }
414f573c99bSdrh 
4151ccde15dSdrh   /* Allocate a VDBE
4161ccde15dSdrh   */
4174adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
4185974a30fSdrh   if( v==0 ) goto insert_cleanup;
4194794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
420da184236Sdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
4211ccde15dSdrh 
422c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
423dca76841Sdrh   if( triggers_exist ){
424c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
425f29ce559Sdanielk1977   }
426c3f9bad2Sdanielk1977 
4279d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
4289d9cf229Sdrh   /* If the statement is of the form
4299d9cf229Sdrh   **
4309d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
4319d9cf229Sdrh   **
4329d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
4339d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
4349d9cf229Sdrh   */
4359d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
4369d9cf229Sdrh     assert( !triggers_exist );
4379d9cf229Sdrh     assert( pList==0 );
4389d9cf229Sdrh     goto insert_cleanup;
4399d9cf229Sdrh   }
4409d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
4419d9cf229Sdrh 
4422958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
443f3388144Sdrh   ** sqlite_sequence table and store it in memory cell counterMem.  Also
444f3388144Sdrh   ** remember the rowid of the sqlite_sequence table entry in memory cell
445f3388144Sdrh   ** counterRowid.
4462958a4e6Sdrh   */
4479d9cf229Sdrh   counterMem = autoIncBegin(pParse, iDb, pTab);
4482958a4e6Sdrh 
4491ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
450142e30dfSdrh   ** is coming from a SELECT statement, then this step also generates
451142e30dfSdrh   ** all the code to implement the SELECT statement and invoke a subroutine
452142e30dfSdrh   ** to process each row of the result. (Template 2.) If the SELECT
453142e30dfSdrh   ** statement uses the the table that is being inserted into, then the
454142e30dfSdrh   ** subroutine is also coded here.  That subroutine stores the SELECT
455142e30dfSdrh   ** results in a temporary table. (Template 3.)
4561ccde15dSdrh   */
4575974a30fSdrh   if( pSelect ){
458142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
459142e30dfSdrh     */
460142e30dfSdrh     int rc, iInitCode;
4614adee20fSdanielk1977     iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
4624adee20fSdanielk1977     iSelectLoop = sqlite3VdbeCurrentAddr(v);
4634adee20fSdanielk1977     iInsertBlock = sqlite3VdbeMakeLabel(v);
464b3bce662Sdanielk1977 
465b3bce662Sdanielk1977     /* Resolve the expressions in the SELECT statement and execute it. */
466b3bce662Sdanielk1977     rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
46717435752Sdrh     if( rc || pParse->nErr || db->mallocFailed ){
4686f7adc8aSdrh       goto insert_cleanup;
4696f7adc8aSdrh     }
470b3bce662Sdanielk1977 
4714adee20fSdanielk1977     iCleanup = sqlite3VdbeMakeLabel(v);
4724adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
4735974a30fSdrh     assert( pSelect->pEList );
474967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
475142e30dfSdrh 
476142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
477142e30dfSdrh     ** should be written into a temporary table.  Set to FALSE if each
478142e30dfSdrh     ** row of the SELECT can be written directly into the result table.
479048c530cSdrh     **
480048c530cSdrh     ** A temp table must be used if the table being updated is also one
481048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
482048c530cSdrh     ** temp table in the case of row triggers.
483142e30dfSdrh     */
484da184236Sdanielk1977     if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
485048c530cSdrh       useTempTable = 1;
486048c530cSdrh     }
487142e30dfSdrh 
488142e30dfSdrh     if( useTempTable ){
489142e30dfSdrh       /* Generate the subroutine that SELECT calls to process each row of
490142e30dfSdrh       ** the result.  Store the result in a temporary table
491142e30dfSdrh       */
492142e30dfSdrh       srcTab = pParse->nTab++;
4934adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iInsertBlock);
4944adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
495f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
4964adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
497e4d90813Sdrh       sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
4984adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
499142e30dfSdrh 
500142e30dfSdrh       /* The following code runs first because the GOTO at the very top
501142e30dfSdrh       ** of the program jumps to it.  Create the temporary table, then jump
502142e30dfSdrh       ** back up and execute the SELECT code above.
503142e30dfSdrh       */
504d654be80Sdrh       sqlite3VdbeJumpHere(v, iInitCode);
505b9bb7c18Sdrh       sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
506b6f5452fSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
5074adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
5084adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCleanup);
5095974a30fSdrh     }else{
510d654be80Sdrh       sqlite3VdbeJumpHere(v, iInitCode);
511142e30dfSdrh     }
512142e30dfSdrh   }else{
513142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
514142e30dfSdrh     ** clause
515142e30dfSdrh     */
516b3bce662Sdanielk1977     NameContext sNC;
517b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
518b3bce662Sdanielk1977     sNC.pParse = pParse;
5195974a30fSdrh     srcTab = -1;
520142e30dfSdrh     useTempTable = 0;
521147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
522e64e7b20Sdrh     for(i=0; i<nColumn; i++){
523b3bce662Sdanielk1977       if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
524b04a5d87Sdrh         goto insert_cleanup;
525b04a5d87Sdrh       }
526e64e7b20Sdrh     }
5275974a30fSdrh   }
5281ccde15dSdrh 
5291ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
5301ccde15dSdrh   ** of columns to be inserted into the table.
5311ccde15dSdrh   */
532034ca14fSdanielk1977   if( IsVirtual(pTab) ){
533034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
534034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
535034ca14fSdanielk1977     }
536034ca14fSdanielk1977   }
537034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
5384adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
539da93d238Sdrh        "table %S has %d columns but %d values were supplied",
540da93d238Sdrh        pTabList, 0, pTab->nCol, nColumn);
541cce7d176Sdrh     goto insert_cleanup;
542cce7d176Sdrh   }
543967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
5444adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
545cce7d176Sdrh     goto insert_cleanup;
546cce7d176Sdrh   }
5471ccde15dSdrh 
5481ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
5491ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
5501ccde15dSdrh   ** remember the column indices.
551c8392586Sdrh   **
552c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
553c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
554c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
555c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
556c8392586Sdrh   ** is appears in the original table.  (The index of the primary
557c8392586Sdrh   ** key in the original table is pTab->iPKey.)
5581ccde15dSdrh   */
559967e8b73Sdrh   if( pColumn ){
560967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
561967e8b73Sdrh       pColumn->a[i].idx = -1;
562cce7d176Sdrh     }
563967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
564cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
5654adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
566967e8b73Sdrh           pColumn->a[i].idx = j;
5674a32431cSdrh           if( j==pTab->iPKey ){
5689aa028daSdrh             keyColumn = i;
5694a32431cSdrh           }
570cce7d176Sdrh           break;
571cce7d176Sdrh         }
572cce7d176Sdrh       }
573cce7d176Sdrh       if( j>=pTab->nCol ){
5744adee20fSdanielk1977         if( sqlite3IsRowid(pColumn->a[i].zName) ){
575a0217ba7Sdrh           keyColumn = i;
576a0217ba7Sdrh         }else{
5774adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
578da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
579cce7d176Sdrh           pParse->nErr++;
580cce7d176Sdrh           goto insert_cleanup;
581cce7d176Sdrh         }
582cce7d176Sdrh       }
583cce7d176Sdrh     }
584a0217ba7Sdrh   }
5851ccde15dSdrh 
586aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
587c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
588c8392586Sdrh   ** in the original table definition.
5894a32431cSdrh   */
590147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
5914a32431cSdrh     keyColumn = pTab->iPKey;
5924a32431cSdrh   }
5934a32431cSdrh 
594142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
595142e30dfSdrh   */
596dca76841Sdrh   if( triggers_exist ){
5974adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
59884ac9d02Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
599f29ce559Sdanielk1977   }
600c3f9bad2Sdanielk1977 
601c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
6021ccde15dSdrh   */
603142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
604142e30dfSdrh     iCntMem = pParse->nMem++;
605d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
606c3f9bad2Sdanielk1977   }
607c3f9bad2Sdanielk1977 
608c3f9bad2Sdanielk1977   /* Open tables and indices if there are no row triggers */
609dca76841Sdrh   if( !triggers_exist ){
6105974a30fSdrh     base = pParse->nTab;
611290c1948Sdrh     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
612feeb1394Sdrh   }
613feeb1394Sdrh 
614142e30dfSdrh   /* If the data source is a temporary table, then we have to create
6151ccde15dSdrh   ** a loop because there might be multiple rows of data.  If the data
616142e30dfSdrh   ** source is a subroutine call from the SELECT statement, then we need
617142e30dfSdrh   ** to launch the SELECT statement processing.
6181ccde15dSdrh   */
619142e30dfSdrh   if( useTempTable ){
6204adee20fSdanielk1977     iBreak = sqlite3VdbeMakeLabel(v);
6214adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
6224adee20fSdanielk1977     iCont = sqlite3VdbeCurrentAddr(v);
623142e30dfSdrh   }else if( pSelect ){
6244adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
6254adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iInsertBlock);
626bed8690fSdrh   }
6271ccde15dSdrh 
6285cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
62970ce3f0cSdrh   */
6304adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
631dca76841Sdrh   if( triggers_exist & TRIGGER_BEFORE ){
632c3f9bad2Sdanielk1977 
63370ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
63470ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
63570ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
63670ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
63770ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
63870ce3f0cSdrh     */
63970ce3f0cSdrh     if( keyColumn<0 ){
6404adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
64170ce3f0cSdrh     }else if( useTempTable ){
6424adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
64370ce3f0cSdrh     }else{
644d6fe961eSdrh       assert( pSelect==0 );  /* Otherwise useTempTable is true */
6454adee20fSdanielk1977       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
6464adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
6474adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
6484adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
6494adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
65070ce3f0cSdrh     }
65170ce3f0cSdrh 
652034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
653034ca14fSdanielk1977     ** this block would have to account for hidden column.
654034ca14fSdanielk1977     */
655034ca14fSdanielk1977     assert(!IsVirtual(pTab));
656034ca14fSdanielk1977 
65770ce3f0cSdrh     /* Create the new column data
65870ce3f0cSdrh     */
659c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
660c3f9bad2Sdanielk1977       if( pColumn==0 ){
661c3f9bad2Sdanielk1977         j = i;
662c3f9bad2Sdanielk1977       }else{
663c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
664c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
665c3f9bad2Sdanielk1977         }
666c3f9bad2Sdanielk1977       }
667c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
6687977a17fSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
669142e30dfSdrh       }else if( useTempTable ){
6704adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
671c3f9bad2Sdanielk1977       }else{
672d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
67325303780Sdrh         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
674c3f9bad2Sdanielk1977       }
675c3f9bad2Sdanielk1977     }
6764adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
677a37cdde0Sdanielk1977 
678a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
679a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
680a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
681a37cdde0Sdanielk1977     ** table column affinities.
682a37cdde0Sdanielk1977     */
683a37cdde0Sdanielk1977     if( !isView ){
684a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
685a37cdde0Sdanielk1977     }
686f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
687c3f9bad2Sdanielk1977 
6885cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
689dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
690b2fe7d8cSdrh         newIdx, -1, onError, endOfLoop) ){
691f29ce559Sdanielk1977       goto insert_cleanup;
692f29ce559Sdanielk1977     }
69370ce3f0cSdrh   }
694c3f9bad2Sdanielk1977 
69570ce3f0cSdrh   /* If any triggers exists, the opening of tables and indices is deferred
69670ce3f0cSdrh   ** until now.
69770ce3f0cSdrh   */
698dca76841Sdrh   if( triggers_exist && !isView ){
699c3f9bad2Sdanielk1977     base = pParse->nTab;
700290c1948Sdrh     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
701c3f9bad2Sdanielk1977   }
702c3f9bad2Sdanielk1977 
7034a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
704f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
7054a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
706b419a926Sdrh   ** case the record number is the same as that column.
7071ccde15dSdrh   */
7085cf590c1Sdrh   if( !isView ){
7094cbdda9eSdrh     if( IsVirtual(pTab) ){
7104cbdda9eSdrh       /* The row that the VUpdate opcode will delete:  none */
7114cbdda9eSdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
7124cbdda9eSdrh     }
7134a32431cSdrh     if( keyColumn>=0 ){
714142e30dfSdrh       if( useTempTable ){
7154adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
716142e30dfSdrh       }else if( pSelect ){
7174adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
7184a32431cSdrh       }else{
719e4d90813Sdrh         VdbeOp *pOp;
7204adee20fSdanielk1977         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
721e4d90813Sdrh         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
72201256832Sdanielk1977         if( pOp && pOp->opcode==OP_Null ){
723e4d90813Sdrh           appendFlag = 1;
724e4d90813Sdrh           pOp->opcode = OP_NewRowid;
725e4d90813Sdrh           pOp->p1 = base;
726e4d90813Sdrh           pOp->p2 = counterMem;
727e4d90813Sdrh         }
72827a32783Sdrh       }
729f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
730e1e68f49Sdrh       ** to generate a unique primary key value.
731e1e68f49Sdrh       */
732e4d90813Sdrh       if( !appendFlag ){
7334adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
7344adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
735f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
7364adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
737e4d90813Sdrh       }
7384cbdda9eSdrh     }else if( IsVirtual(pTab) ){
7394cbdda9eSdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
7404a32431cSdrh     }else{
741f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
742e4d90813Sdrh       appendFlag = 1;
7434a32431cSdrh     }
7449d9cf229Sdrh     autoIncStep(pParse, counterMem);
7454a32431cSdrh 
746aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
7474a32431cSdrh     ** with the first column.
7484a32431cSdrh     */
749034ca14fSdanielk1977     nHidden = 0;
750cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
7514a32431cSdrh       if( i==pTab->iPKey ){
7524a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
753aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
754aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
755aacc543eSdrh         ** taking up data space with information that will never be used. */
756f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
7574a32431cSdrh         continue;
7584a32431cSdrh       }
759967e8b73Sdrh       if( pColumn==0 ){
760034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
761034ca14fSdanielk1977           assert( IsVirtual(pTab) );
762034ca14fSdanielk1977           j = -1;
763034ca14fSdanielk1977           nHidden++;
764034ca14fSdanielk1977         }else{
765034ca14fSdanielk1977           j = i - nHidden;
766034ca14fSdanielk1977         }
767cce7d176Sdrh       }else{
768967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
769967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
770cce7d176Sdrh         }
771cce7d176Sdrh       }
772034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
7737977a17fSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
774142e30dfSdrh       }else if( useTempTable ){
7754adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
776142e30dfSdrh       }else if( pSelect ){
77716ed8a64Sdrh         sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
778cce7d176Sdrh       }else{
7794adee20fSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr);
780cce7d176Sdrh       }
781cce7d176Sdrh     }
7821ccde15dSdrh 
7830ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
7840ca3e24bSdrh     ** do the insertion.
7854a32431cSdrh     */
7864cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
7874cbdda9eSdrh     if( IsVirtual(pTab) ){
788f9e7dda7Sdanielk1977       pParse->pVirtualLock = pTab;
7891f6eec54Sdanielk1977       sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
7904cbdda9eSdrh                      (const char*)pTab->pVtab, P3_VTAB);
7914cbdda9eSdrh     }else
7924cbdda9eSdrh #endif
7934cbdda9eSdrh     {
7944adee20fSdanielk1977       sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
795a0217ba7Sdrh                                      0, onError, endOfLoop);
7964adee20fSdanielk1977       sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
797e4d90813Sdrh                             (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
798e4d90813Sdrh                             appendFlag);
7995cf590c1Sdrh     }
8004cbdda9eSdrh   }
8011bee3d7bSdrh 
802feeb1394Sdrh   /* Update the count of rows that are inserted
8031bee3d7bSdrh   */
804142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
80515007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
8061bee3d7bSdrh   }
807c3f9bad2Sdanielk1977 
808dca76841Sdrh   if( triggers_exist ){
809c3f9bad2Sdanielk1977     /* Close all tables opened */
8105cf590c1Sdrh     if( !isView ){
8114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, base, 0);
812c3f9bad2Sdanielk1977       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
8134adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
814c3f9bad2Sdanielk1977       }
815c3f9bad2Sdanielk1977     }
816c3f9bad2Sdanielk1977 
817c3f9bad2Sdanielk1977     /* Code AFTER triggers */
818dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
819dca76841Sdrh           newIdx, -1, onError, endOfLoop) ){
820f29ce559Sdanielk1977       goto insert_cleanup;
821f29ce559Sdanielk1977     }
822c3f9bad2Sdanielk1977   }
8231bee3d7bSdrh 
8241ccde15dSdrh   /* The bottom of the loop, if the data source is a SELECT statement
8251ccde15dSdrh   */
8264adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
827142e30dfSdrh   if( useTempTable ){
8284adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
8294adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iBreak);
8304adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
831142e30dfSdrh   }else if( pSelect ){
8324adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
8334adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Return, 0, 0);
8344adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iCleanup);
8356b56344dSdrh   }
836c3f9bad2Sdanielk1977 
8374cbdda9eSdrh   if( !triggers_exist && !IsVirtual(pTab) ){
838c3f9bad2Sdanielk1977     /* Close all tables opened */
8394adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Close, base, 0);
8406b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
8414adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
842cce7d176Sdrh     }
843c3f9bad2Sdanielk1977   }
844c3f9bad2Sdanielk1977 
845f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
846f3388144Sdrh   ** counter value in memory counterMem back into the sqlite_sequence
847f3388144Sdrh   ** table.
8482958a4e6Sdrh   */
8499d9cf229Sdrh   autoIncEnd(pParse, iDb, pTab, counterMem);
8502958a4e6Sdrh 
8511bee3d7bSdrh   /*
852e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
853e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
854e7de6f25Sdanielk1977   ** invoke the callback function.
8551bee3d7bSdrh   */
856cc6bd383Sdanielk1977   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
8574adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
8584adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
85922322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
860955de52cSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
8611bee3d7bSdrh   }
862cce7d176Sdrh 
863cce7d176Sdrh insert_cleanup:
8644adee20fSdanielk1977   sqlite3SrcListDelete(pTabList);
865d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
866d5d56523Sdanielk1977   sqlite3SelectDelete(pSelect);
8674adee20fSdanielk1977   sqlite3IdListDelete(pColumn);
868cce7d176Sdrh }
8699cfcf5d4Sdrh 
8709cfcf5d4Sdrh /*
8719cfcf5d4Sdrh ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
8729cfcf5d4Sdrh **
8739cfcf5d4Sdrh ** When this routine is called, the stack contains (from bottom to top)
8740ca3e24bSdrh ** the following values:
8750ca3e24bSdrh **
876f0863fe5Sdrh **    1.  The rowid of the row to be updated before the update.  This
877b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
878b419a926Sdrh **        change to the record number.
8790ca3e24bSdrh **
880f0863fe5Sdrh **    2.  The rowid of the row after the update.
8810ca3e24bSdrh **
8820ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
8830ca3e24bSdrh **
8840ca3e24bSdrh **    i.  Data from middle columns...
8850ca3e24bSdrh **
8860ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
8870ca3e24bSdrh **
888f0863fe5Sdrh ** The old rowid shown as entry (1) above is omitted unless both isUpdate
889f0863fe5Sdrh ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
890f0863fe5Sdrh ** INSERTs and rowidChng is true if the record number is being changed.
8910ca3e24bSdrh **
8920ca3e24bSdrh ** The code generated by this routine pushes additional entries onto
8930ca3e24bSdrh ** the stack which are the keys for new index entries for the new record.
8940ca3e24bSdrh ** The order of index keys is the same as the order of the indices on
8950ca3e24bSdrh ** the pTable->pIndex list.  A key is only created for index i if
8960ca3e24bSdrh ** aIdxUsed!=0 and aIdxUsed[i]!=0.
8979cfcf5d4Sdrh **
8989cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
8999cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
9001c92853dSdrh ** then the appropriate action is performed.  There are five possible
9011c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
9029cfcf5d4Sdrh **
9039cfcf5d4Sdrh **  Constraint type  Action       What Happens
9049cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
9051c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
90624b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
9079cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
9089cfcf5d4Sdrh **
9091c92853dSdrh **  any              ABORT        Back out changes from the current command
9101c92853dSdrh **                                only (do not do a complete rollback) then
91124b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
9121c92853dSdrh **                                with SQLITE_CONSTRAINT.
9131c92853dSdrh **
9141c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
9151c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
9161c92853dSdrh **                                transaction is not rolled back and any
9171c92853dSdrh **                                prior changes are retained.
9181c92853dSdrh **
9199cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
9209cfcf5d4Sdrh **                                the stack and there is an immediate jump
9219cfcf5d4Sdrh **                                to label ignoreDest.
9229cfcf5d4Sdrh **
9239cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
9249cfcf5d4Sdrh **                                value for that column.  If the default value
9259cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
9269cfcf5d4Sdrh **
9279cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
9289cfcf5d4Sdrh **                                being inserted is removed.
9299cfcf5d4Sdrh **
9309cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
9319cfcf5d4Sdrh **
9321c92853dSdrh ** Which action to take is determined by the overrideError parameter.
9331c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
9341c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
9351c92853dSdrh ** for the constraint is used.
9369cfcf5d4Sdrh **
937aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
9389cfcf5d4Sdrh ** cursor number "base".  All indices of pTab must also have open
9399cfcf5d4Sdrh ** read/write cursors with cursor number base+i for the i-th cursor.
9409cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
9419cfcf5d4Sdrh ** cursors do not need to be open for indices where aIdxUsed[i]==0.
9429cfcf5d4Sdrh **
9439cfcf5d4Sdrh ** If the isUpdate flag is true, it means that the "base" cursor is
9449cfcf5d4Sdrh ** initially pointing to an entry that is being updated.  The isUpdate
9459cfcf5d4Sdrh ** flag causes extra code to be generated so that the "base" cursor
9469cfcf5d4Sdrh ** is still pointing at the same entry after the routine returns.
9479cfcf5d4Sdrh ** Without the isUpdate flag, the "base" cursor might be moved.
9489cfcf5d4Sdrh */
9494adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
9509cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
9519cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
9529cfcf5d4Sdrh   int base,           /* Index of a read/write cursor pointing at pTab */
9539cfcf5d4Sdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
954f0863fe5Sdrh   int rowidChng,      /* True if the record number will change */
955b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
9569cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
957b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
9589cfcf5d4Sdrh ){
9599cfcf5d4Sdrh   int i;
9609cfcf5d4Sdrh   Vdbe *v;
9619cfcf5d4Sdrh   int nCol;
9629cfcf5d4Sdrh   int onError;
9639cfcf5d4Sdrh   int addr;
9649cfcf5d4Sdrh   int extra;
9650ca3e24bSdrh   int iCur;
9660ca3e24bSdrh   Index *pIdx;
9670ca3e24bSdrh   int seenReplace = 0;
968cfe9a69fSdanielk1977   int jumpInst1=0, jumpInst2;
969f0863fe5Sdrh   int hasTwoRowids = (isUpdate && rowidChng);
9709cfcf5d4Sdrh 
9714adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
9729cfcf5d4Sdrh   assert( v!=0 );
973417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
9749cfcf5d4Sdrh   nCol = pTab->nCol;
9759cfcf5d4Sdrh 
9769cfcf5d4Sdrh   /* Test all NOT NULL constraints.
9779cfcf5d4Sdrh   */
9789cfcf5d4Sdrh   for(i=0; i<nCol; i++){
9790ca3e24bSdrh     if( i==pTab->iPKey ){
9800ca3e24bSdrh       continue;
9810ca3e24bSdrh     }
9829cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
9830ca3e24bSdrh     if( onError==OE_None ) continue;
9849cfcf5d4Sdrh     if( overrideError!=OE_Default ){
9859cfcf5d4Sdrh       onError = overrideError;
986a996e477Sdrh     }else if( onError==OE_Default ){
987a996e477Sdrh       onError = OE_Abort;
9889cfcf5d4Sdrh     }
9897977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
9909cfcf5d4Sdrh       onError = OE_Abort;
9919cfcf5d4Sdrh     }
9924adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
9934adee20fSdanielk1977     addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
994b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
995b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
9969cfcf5d4Sdrh     switch( onError ){
9971c92853dSdrh       case OE_Rollback:
9981c92853dSdrh       case OE_Abort:
9991c92853dSdrh       case OE_Fail: {
1000483750baSdrh         char *zMsg = 0;
10014adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
10024adee20fSdanielk1977         sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
100341743984Sdrh                         " may not be NULL", (char*)0);
10044adee20fSdanielk1977         sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
10059cfcf5d4Sdrh         break;
10069cfcf5d4Sdrh       }
10079cfcf5d4Sdrh       case OE_Ignore: {
1008f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
10094adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
10109cfcf5d4Sdrh         break;
10119cfcf5d4Sdrh       }
10129cfcf5d4Sdrh       case OE_Replace: {
10137977a17fSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
10144adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
10159cfcf5d4Sdrh         break;
10169cfcf5d4Sdrh       }
10179cfcf5d4Sdrh     }
1018d654be80Sdrh     sqlite3VdbeJumpHere(v, addr);
10199cfcf5d4Sdrh   }
10209cfcf5d4Sdrh 
10219cfcf5d4Sdrh   /* Test all CHECK constraints
10229cfcf5d4Sdrh   */
1023ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
10240cd2d4c9Sdrh   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
1025ffe07b2dSdrh     int allOk = sqlite3VdbeMakeLabel(v);
1026ffe07b2dSdrh     assert( pParse->ckOffset==0 );
1027ffe07b2dSdrh     pParse->ckOffset = nCol;
10286275b88bSdrh     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
1029ffe07b2dSdrh     assert( pParse->ckOffset==nCol );
1030ffe07b2dSdrh     pParse->ckOffset = 0;
1031aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
10322e06c67cSdrh     if( onError==OE_Ignore ){
1033aa01c7e2Sdrh       sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1034aa01c7e2Sdrh       sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1035aa01c7e2Sdrh     }else{
1036aa01c7e2Sdrh       sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1037aa01c7e2Sdrh     }
1038ffe07b2dSdrh     sqlite3VdbeResolveLabel(v, allOk);
1039ffe07b2dSdrh   }
1040ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
10419cfcf5d4Sdrh 
10420bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
10430bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
10440bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
10459cfcf5d4Sdrh   */
1046f0863fe5Sdrh   if( rowidChng ){
10470ca3e24bSdrh     onError = pTab->keyConf;
10480ca3e24bSdrh     if( overrideError!=OE_Default ){
10490ca3e24bSdrh       onError = overrideError;
1050a996e477Sdrh     }else if( onError==OE_Default ){
1051a996e477Sdrh       onError = OE_Abort;
10520ca3e24bSdrh     }
1053a0217ba7Sdrh 
105479b0c956Sdrh     if( isUpdate ){
10554adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
10564adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
10574adee20fSdanielk1977       jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
105879b0c956Sdrh     }
10594adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
10604adee20fSdanielk1977     jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
10610ca3e24bSdrh     switch( onError ){
1062a0217ba7Sdrh       default: {
1063a0217ba7Sdrh         onError = OE_Abort;
1064a0217ba7Sdrh         /* Fall thru into the next case */
1065a0217ba7Sdrh       }
10661c92853dSdrh       case OE_Rollback:
10671c92853dSdrh       case OE_Abort:
10681c92853dSdrh       case OE_Fail: {
10694adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1070701a0aebSdrh                          "PRIMARY KEY must be unique", P3_STATIC);
10710ca3e24bSdrh         break;
10720ca3e24bSdrh       }
10735383ae5cSdrh       case OE_Replace: {
107474161705Sdrh         sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
10755383ae5cSdrh         if( isUpdate ){
1076f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
10777cf6e4deSdrh           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
10785383ae5cSdrh         }
10795383ae5cSdrh         seenReplace = 1;
10805383ae5cSdrh         break;
10815383ae5cSdrh       }
10820ca3e24bSdrh       case OE_Ignore: {
10835383ae5cSdrh         assert( seenReplace==0 );
1084f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
10854adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
10860ca3e24bSdrh         break;
10870ca3e24bSdrh       }
10880ca3e24bSdrh     }
1089d654be80Sdrh     sqlite3VdbeJumpHere(v, jumpInst2);
1090f5905aa7Sdrh     if( isUpdate ){
1091d654be80Sdrh       sqlite3VdbeJumpHere(v, jumpInst1);
10924adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
10937cf6e4deSdrh       sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
10940ca3e24bSdrh     }
10950ca3e24bSdrh   }
10960bd1f4eaSdrh 
10970bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
10980bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
10990bd1f4eaSdrh   ** Add the new records to the indices as we go.
11000bd1f4eaSdrh   */
1101b2fe7d8cSdrh   extra = -1;
1102b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1103b2fe7d8cSdrh     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;  /* Skip unused indices */
11049cfcf5d4Sdrh     extra++;
1105b2fe7d8cSdrh 
1106b2fe7d8cSdrh     /* Create a key for accessing the index entry */
11074adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
11089cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
11099cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
11109cfcf5d4Sdrh       if( idx==pTab->iPKey ){
11114adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
11129cfcf5d4Sdrh       }else{
11134adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
11149cfcf5d4Sdrh       }
11159cfcf5d4Sdrh     }
11167f057c91Sdrh     jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
1117a37cdde0Sdanielk1977     sqlite3IndexAffinityStr(v, pIdx);
1118b2fe7d8cSdrh 
1119b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
11209cfcf5d4Sdrh     onError = pIdx->onError;
1121b2fe7d8cSdrh     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
11229cfcf5d4Sdrh     if( overrideError!=OE_Default ){
11239cfcf5d4Sdrh       onError = overrideError;
1124a996e477Sdrh     }else if( onError==OE_Default ){
1125a996e477Sdrh       onError = OE_Abort;
11269cfcf5d4Sdrh     }
11275383ae5cSdrh     if( seenReplace ){
11285383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
11295383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
11305383ae5cSdrh     }
11315383ae5cSdrh 
1132b2fe7d8cSdrh 
1133b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
1134f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
11354adee20fSdanielk1977     jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
1136b2fe7d8cSdrh 
1137b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1138b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1139b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
11409cfcf5d4Sdrh     switch( onError ){
11411c92853dSdrh       case OE_Rollback:
11421c92853dSdrh       case OE_Abort:
11431c92853dSdrh       case OE_Fail: {
114437ed48edSdrh         int j, n1, n2;
114537ed48edSdrh         char zErrMsg[200];
11465bb3eb9bSdrh         sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
11475bb3eb9bSdrh                          pIdx->nColumn>1 ? "columns " : "column ");
114837ed48edSdrh         n1 = strlen(zErrMsg);
114937ed48edSdrh         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
115037ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
115137ed48edSdrh           n2 = strlen(zCol);
115237ed48edSdrh           if( j>0 ){
11535bb3eb9bSdrh             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
115437ed48edSdrh             n1 += 2;
115537ed48edSdrh           }
115637ed48edSdrh           if( n1+n2>sizeof(zErrMsg)-30 ){
11575bb3eb9bSdrh             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
115837ed48edSdrh             n1 += 3;
115937ed48edSdrh             break;
116037ed48edSdrh           }else{
11615bb3eb9bSdrh             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
116237ed48edSdrh             n1 += n2;
116337ed48edSdrh           }
116437ed48edSdrh         }
11655bb3eb9bSdrh         sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
116637ed48edSdrh             pIdx->nColumn>1 ? " are not unique" : " is not unique");
11674adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
11689cfcf5d4Sdrh         break;
11699cfcf5d4Sdrh       }
11709cfcf5d4Sdrh       case OE_Ignore: {
11710ca3e24bSdrh         assert( seenReplace==0 );
1172f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
11734adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
11749cfcf5d4Sdrh         break;
11759cfcf5d4Sdrh       }
11769cfcf5d4Sdrh       case OE_Replace: {
11774adee20fSdanielk1977         sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
11789cfcf5d4Sdrh         if( isUpdate ){
1179f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
11807cf6e4deSdrh           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
11819cfcf5d4Sdrh         }
11820ca3e24bSdrh         seenReplace = 1;
11839cfcf5d4Sdrh         break;
11849cfcf5d4Sdrh       }
11859cfcf5d4Sdrh     }
11860bd1f4eaSdrh #if NULL_DISTINCT_FOR_UNIQUE
1187d654be80Sdrh     sqlite3VdbeJumpHere(v, jumpInst1);
11880bd1f4eaSdrh #endif
1189d654be80Sdrh     sqlite3VdbeJumpHere(v, jumpInst2);
11909cfcf5d4Sdrh   }
11919cfcf5d4Sdrh }
11920ca3e24bSdrh 
11930ca3e24bSdrh /*
11940ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
11954adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
11960ca3e24bSdrh ** The stack must contain keys for all active indices followed by data
1197f0863fe5Sdrh ** and the rowid for the new entry.  This routine creates the new
11980ca3e24bSdrh ** entries in all indices and in the main table.
11990ca3e24bSdrh **
1200b419a926Sdrh ** The arguments to this routine should be the same as the first six
12014adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
12020ca3e24bSdrh */
12034adee20fSdanielk1977 void sqlite3CompleteInsertion(
12040ca3e24bSdrh   Parse *pParse,      /* The parser context */
12050ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
12060ca3e24bSdrh   int base,           /* Index of a read/write cursor pointing at pTab */
12070ca3e24bSdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
1208f0863fe5Sdrh   int rowidChng,      /* True if the record number will change */
120970ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1210e4d90813Sdrh   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
1211e4d90813Sdrh   int appendBias      /* True if this is likely to be an append */
12120ca3e24bSdrh ){
12130ca3e24bSdrh   int i;
12140ca3e24bSdrh   Vdbe *v;
12150ca3e24bSdrh   int nIdx;
12160ca3e24bSdrh   Index *pIdx;
1217b28af71aSdanielk1977   int pik_flags;
12180ca3e24bSdrh 
12194adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
12200ca3e24bSdrh   assert( v!=0 );
1221417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
12220ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
12230ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
12240ca3e24bSdrh     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
1225f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
12260ca3e24bSdrh   }
12274adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
1228a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1229b84f96f8Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
123070ce3f0cSdrh   if( newIdx>=0 ){
12314adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
12324adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1233f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
123470ce3f0cSdrh   }
1235b84f96f8Sdanielk1977 #endif
12364794f735Sdrh   if( pParse->nested ){
12374794f735Sdrh     pik_flags = 0;
12384794f735Sdrh   }else{
123994eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
124094eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
12414794f735Sdrh   }
1242e4d90813Sdrh   if( appendBias ){
1243e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1244e4d90813Sdrh   }
1245f0863fe5Sdrh   sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
124694eb6a14Sdanielk1977   if( !pParse->nested ){
124794eb6a14Sdanielk1977     sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
124894eb6a14Sdanielk1977   }
1249b28af71aSdanielk1977 
1250f0863fe5Sdrh   if( isUpdate && rowidChng ){
12514adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
12520ca3e24bSdrh   }
12530ca3e24bSdrh }
1254cd44690aSdrh 
1255cd44690aSdrh /*
1256290c1948Sdrh ** Generate code that will open cursors for a table and for all
1257cd44690aSdrh ** indices of that table.  The "base" parameter is the cursor number used
1258cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1259cd44690aSdrh */
1260290c1948Sdrh void sqlite3OpenTableAndIndices(
1261290c1948Sdrh   Parse *pParse,   /* Parsing context */
1262290c1948Sdrh   Table *pTab,     /* Table to be opened */
1263290c1948Sdrh   int base,        /* Cursor number assigned to the table */
1264290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1265290c1948Sdrh ){
1266cd44690aSdrh   int i;
12674cbdda9eSdrh   int iDb;
1268cd44690aSdrh   Index *pIdx;
12694cbdda9eSdrh   Vdbe *v;
12704cbdda9eSdrh 
12714cbdda9eSdrh   if( IsVirtual(pTab) ) return;
12724cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
12734cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1274cd44690aSdrh   assert( v!=0 );
1275c00da105Sdanielk1977   sqlite3OpenTable(pParse, base, iDb, pTab, op);
1276cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1277b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1278da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
1279da184236Sdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
128029dda4aeSdrh     VdbeComment((v, "# %s", pIdx->zName));
1281b3bf556eSdanielk1977     sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
1282cd44690aSdrh   }
1283290c1948Sdrh   if( pParse->nTab<=base+i ){
1284290c1948Sdrh     pParse->nTab = base+i;
1285290c1948Sdrh   }
1286cd44690aSdrh }
12879d9cf229Sdrh 
128891c58e23Sdrh 
128991c58e23Sdrh #ifdef SQLITE_TEST
129091c58e23Sdrh /*
129191c58e23Sdrh ** The following global variable is incremented whenever the
129291c58e23Sdrh ** transfer optimization is used.  This is used for testing
129391c58e23Sdrh ** purposes only - to make sure the transfer optimization really
129491c58e23Sdrh ** is happening when it is suppose to.
129591c58e23Sdrh */
129691c58e23Sdrh int sqlite3_xferopt_count;
129791c58e23Sdrh #endif /* SQLITE_TEST */
129891c58e23Sdrh 
129991c58e23Sdrh 
13009d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
13019d9cf229Sdrh /*
13029d9cf229Sdrh ** Check to collation names to see if they are compatible.
13039d9cf229Sdrh */
13049d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
13059d9cf229Sdrh   if( z1==0 ){
13069d9cf229Sdrh     return z2==0;
13079d9cf229Sdrh   }
13089d9cf229Sdrh   if( z2==0 ){
13099d9cf229Sdrh     return 0;
13109d9cf229Sdrh   }
13119d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
13129d9cf229Sdrh }
13139d9cf229Sdrh 
13149d9cf229Sdrh 
13159d9cf229Sdrh /*
13169d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
13179d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
13189d9cf229Sdrh ** for a compatible index:
13199d9cf229Sdrh **
13209d9cf229Sdrh **    *   The index is over the same set of columns
13219d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
13229d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
13239d9cf229Sdrh **    *   The same collating sequence on each column
13249d9cf229Sdrh */
13259d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
13269d9cf229Sdrh   int i;
13279d9cf229Sdrh   assert( pDest && pSrc );
13289d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
13299d9cf229Sdrh   if( pDest->nColumn!=pSrc->nColumn ){
13309d9cf229Sdrh     return 0;   /* Different number of columns */
13319d9cf229Sdrh   }
13329d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
13339d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
13349d9cf229Sdrh   }
13359d9cf229Sdrh   for(i=0; i<pSrc->nColumn; i++){
13369d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
13379d9cf229Sdrh       return 0;   /* Different columns indexed */
13389d9cf229Sdrh     }
13399d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
13409d9cf229Sdrh       return 0;   /* Different sort orders */
13419d9cf229Sdrh     }
13429d9cf229Sdrh     if( pSrc->azColl[i]!=pDest->azColl[i] ){
13439d9cf229Sdrh       return 0;   /* Different sort orders */
13449d9cf229Sdrh     }
13459d9cf229Sdrh   }
13469d9cf229Sdrh 
13479d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
13489d9cf229Sdrh   return 1;
13499d9cf229Sdrh }
13509d9cf229Sdrh 
13519d9cf229Sdrh /*
13529d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
13539d9cf229Sdrh **
13549d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
13559d9cf229Sdrh **
13569d9cf229Sdrh ** This optimization is only attempted if
13579d9cf229Sdrh **
13589d9cf229Sdrh **    (1)  tab1 and tab2 have identical schemas including all the
13598103b7d2Sdrh **         same indices and constraints
13609d9cf229Sdrh **
13619d9cf229Sdrh **    (2)  tab1 and tab2 are different tables
13629d9cf229Sdrh **
13639d9cf229Sdrh **    (3)  There must be no triggers on tab1
13649d9cf229Sdrh **
13659d9cf229Sdrh **    (4)  The result set of the SELECT statement is "*"
13669d9cf229Sdrh **
13679d9cf229Sdrh **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
13689d9cf229Sdrh **         or LIMIT clause.
13699d9cf229Sdrh **
13709d9cf229Sdrh **    (6)  The SELECT statement is a simple (not a compound) select that
13719d9cf229Sdrh **         contains only tab2 in its FROM clause
13729d9cf229Sdrh **
13739d9cf229Sdrh ** This method for implementing the INSERT transfers raw records from
13749d9cf229Sdrh ** tab2 over to tab1.  The columns are not decoded.  Raw records from
13759d9cf229Sdrh ** the indices of tab2 are transfered to tab1 as well.  In so doing,
13769d9cf229Sdrh ** the resulting tab1 has much less fragmentation.
13779d9cf229Sdrh **
13789d9cf229Sdrh ** This routine returns TRUE if the optimization is attempted.  If any
13799d9cf229Sdrh ** of the conditions above fail so that the optimization should not
13809d9cf229Sdrh ** be attempted, then this routine returns FALSE.
13819d9cf229Sdrh */
13829d9cf229Sdrh static int xferOptimization(
13839d9cf229Sdrh   Parse *pParse,        /* Parser context */
13849d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
13859d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
13869d9cf229Sdrh   int onError,          /* How to handle constraint errors */
13879d9cf229Sdrh   int iDbDest           /* The database of pDest */
13889d9cf229Sdrh ){
13899d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
13909d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
13919d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
13929d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
13939d9cf229Sdrh   int i;                           /* Loop counter */
13949d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
13959d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
13969d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
13979d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
13989d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
13999d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
14009d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
14019d9cf229Sdrh   int counterMem;                  /* Memory register used by AUTOINC */
1402f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
14039d9cf229Sdrh 
14049d9cf229Sdrh   if( pSelect==0 ){
14059d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
14069d9cf229Sdrh   }
14079d9cf229Sdrh   if( pDest->pTrigger ){
14089d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
14099d9cf229Sdrh   }
14109d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
14119d9cf229Sdrh   if( pDest->isVirtual ){
14129d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
14139d9cf229Sdrh   }
14149d9cf229Sdrh #endif
14159d9cf229Sdrh   if( onError==OE_Default ){
14169d9cf229Sdrh     onError = OE_Abort;
14179d9cf229Sdrh   }
14189d9cf229Sdrh   if( onError!=OE_Abort && onError!=OE_Rollback ){
14199d9cf229Sdrh     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
14209d9cf229Sdrh   }
14219d9cf229Sdrh   if( pSelect->pSrc==0 ){
14229d9cf229Sdrh     return 0;   /* SELECT must have a FROM clause */
14239d9cf229Sdrh   }
14249d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
14259d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
14269d9cf229Sdrh   }
14279d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
14289d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
14299d9cf229Sdrh   }
14309d9cf229Sdrh   if( pSelect->pWhere ){
14319d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
14329d9cf229Sdrh   }
14339d9cf229Sdrh   if( pSelect->pOrderBy ){
14349d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
14359d9cf229Sdrh   }
14368103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
14378103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
14389d9cf229Sdrh   if( pSelect->pGroupBy ){
14399d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
14409d9cf229Sdrh   }
14419d9cf229Sdrh   if( pSelect->pLimit ){
14429d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
14439d9cf229Sdrh   }
14448103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
14459d9cf229Sdrh   if( pSelect->pPrior ){
14469d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
14479d9cf229Sdrh   }
14489d9cf229Sdrh   if( pSelect->isDistinct ){
14499d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
14509d9cf229Sdrh   }
14519d9cf229Sdrh   pEList = pSelect->pEList;
14529d9cf229Sdrh   assert( pEList!=0 );
14539d9cf229Sdrh   if( pEList->nExpr!=1 ){
14549d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
14559d9cf229Sdrh   }
14569d9cf229Sdrh   assert( pEList->a[0].pExpr );
14579d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
14589d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
14599d9cf229Sdrh   }
14609d9cf229Sdrh 
14619d9cf229Sdrh   /* At this point we have established that the statement is of the
14629d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
14639d9cf229Sdrh   ** we have to check the semantics.
14649d9cf229Sdrh   */
14659d9cf229Sdrh   pItem = pSelect->pSrc->a;
14669d9cf229Sdrh   pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
14679d9cf229Sdrh   if( pSrc==0 ){
14689d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
14699d9cf229Sdrh   }
14709d9cf229Sdrh   if( pSrc==pDest ){
14719d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
14729d9cf229Sdrh   }
14739d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
14749d9cf229Sdrh   if( pSrc->isVirtual ){
14759d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
14769d9cf229Sdrh   }
14779d9cf229Sdrh #endif
14789d9cf229Sdrh   if( pSrc->pSelect ){
14799d9cf229Sdrh     return 0;   /* tab2 may not be a view */
14809d9cf229Sdrh   }
14819d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
14829d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
14839d9cf229Sdrh   }
14849d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
14859d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
14869d9cf229Sdrh   }
14879d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
14889d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
14899d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
14909d9cf229Sdrh     }
14919d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
14929d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
14939d9cf229Sdrh     }
14949d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
14959d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
14969d9cf229Sdrh     }
14979d9cf229Sdrh   }
14989d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1499f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1500f33c9fadSdrh       destHasUniqueIdx = 1;
1501f33c9fadSdrh     }
15029d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
15039d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
15049d9cf229Sdrh     }
15059d9cf229Sdrh     if( pSrcIdx==0 ){
15069d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
15079d9cf229Sdrh     }
15089d9cf229Sdrh   }
15097fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1510fb658dedSdrh   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
15118103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
15128103b7d2Sdrh   }
15137fc2f41bSdrh #endif
15149d9cf229Sdrh 
15159d9cf229Sdrh   /* If we get this far, it means either:
15169d9cf229Sdrh   **
15179d9cf229Sdrh   **    *   We can always do the transfer if the table contains an
15189d9cf229Sdrh   **        an integer primary key
15199d9cf229Sdrh   **
15209d9cf229Sdrh   **    *   We can conditionally do the transfer if the destination
15219d9cf229Sdrh   **        table is empty.
15229d9cf229Sdrh   */
1523dd73521bSdrh #ifdef SQLITE_TEST
1524dd73521bSdrh   sqlite3_xferopt_count++;
1525dd73521bSdrh #endif
15269d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
15279d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
15289d9cf229Sdrh   iSrc = pParse->nTab++;
15299d9cf229Sdrh   iDest = pParse->nTab++;
15309d9cf229Sdrh   counterMem = autoIncBegin(pParse, iDbDest, pDest);
15319d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1532f33c9fadSdrh   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
1533bd36ba69Sdrh     /* If tables do not have an INTEGER PRIMARY KEY and there
1534bd36ba69Sdrh     ** are indices to be copied and the destination is not empty,
1535bd36ba69Sdrh     ** we have to disallow the transfer optimization because the
1536bd36ba69Sdrh     ** the rowids might change which will mess up indexing.
1537f33c9fadSdrh     **
1538f33c9fadSdrh     ** Or if the destination has a UNIQUE index and is not empty,
1539f33c9fadSdrh     ** we also disallow the transfer optimization because we cannot
1540f33c9fadSdrh     ** insure that all entries in the union of DEST and SRC will be
1541f33c9fadSdrh     ** unique.
15429d9cf229Sdrh     */
15439d9cf229Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
15449d9cf229Sdrh     emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
15459d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
15469d9cf229Sdrh   }else{
15479d9cf229Sdrh     emptyDestTest = 0;
15489d9cf229Sdrh   }
15499d9cf229Sdrh   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
15509d9cf229Sdrh   emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
155142242dedSdrh   if( pDest->iPKey>=0 ){
1552bd36ba69Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
15539d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
15549d9cf229Sdrh     addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
15559d9cf229Sdrh     sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
15569d9cf229Sdrh                       "PRIMARY KEY must be unique", P3_STATIC);
15579d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr2);
15589d9cf229Sdrh     autoIncStep(pParse, counterMem);
1559bd36ba69Sdrh   }else if( pDest->pIndex==0 ){
1560bd36ba69Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
156195bad4c7Sdrh   }else{
1562bd36ba69Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
156342242dedSdrh     assert( pDest->autoInc==0 );
156495bad4c7Sdrh   }
15659d9cf229Sdrh   sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
1566e4d90813Sdrh   sqlite3VdbeOp3(v, OP_Insert, iDest,
1567e4d90813Sdrh                     OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
15689d9cf229Sdrh                     pDest->zName, 0);
15699d9cf229Sdrh   sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
15709d9cf229Sdrh   autoIncEnd(pParse, iDbDest, pDest, counterMem);
15719d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
15729d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
15739d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
15749d9cf229Sdrh     }
15759d9cf229Sdrh     assert( pSrcIdx );
15769d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
15779d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
15789d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
15799d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
15809d9cf229Sdrh     VdbeComment((v, "# %s", pSrcIdx->zName));
15819d9cf229Sdrh     sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
15829d9cf229Sdrh                    (char*)pKey, P3_KEYINFO_HANDOFF);
15839d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
15849d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
15859d9cf229Sdrh     VdbeComment((v, "# %s", pDestIdx->zName));
15869d9cf229Sdrh     sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
15879d9cf229Sdrh                    (char*)pKey, P3_KEYINFO_HANDOFF);
15889d9cf229Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
15899d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
1590e4d90813Sdrh     sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
15919d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
15929d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
15939d9cf229Sdrh   }
15949d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
15959d9cf229Sdrh   sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
15969d9cf229Sdrh   sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
15979d9cf229Sdrh   if( emptyDestTest ){
15989d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
15999d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
16009d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
16019d9cf229Sdrh     return 0;
16029d9cf229Sdrh   }else{
16039d9cf229Sdrh     return 1;
16049d9cf229Sdrh   }
16059d9cf229Sdrh }
16069d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
1607