xref: /sqlite-3.40.0/src/insert.c (revision fb658ded)
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*fb658dedSdrh ** $Id: insert.c,v 1.176 2007/02/24 15:18:50 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19cce7d176Sdrh /*
203d1bfeaaSdanielk1977 ** Set P3 of the most recently inserted opcode to a column affinity
21a37cdde0Sdanielk1977 ** string for index pIdx. A column affinity string has one character
223d1bfeaaSdanielk1977 ** for each column in the table, according to the affinity of the column:
233d1bfeaaSdanielk1977 **
243d1bfeaaSdanielk1977 **  Character      Column affinity
253d1bfeaaSdanielk1977 **  ------------------------------
263eda040bSdrh **  'a'            TEXT
273eda040bSdrh **  'b'            NONE
283eda040bSdrh **  'c'            NUMERIC
293eda040bSdrh **  'd'            INTEGER
303eda040bSdrh **  'e'            REAL
313d1bfeaaSdanielk1977 */
32a37cdde0Sdanielk1977 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
33a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
34e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
35a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
36e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
37a37cdde0Sdanielk1977     **
38a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
39e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
40a37cdde0Sdanielk1977     ** up.
41a37cdde0Sdanielk1977     */
42a37cdde0Sdanielk1977     int n;
43a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
44a37cdde0Sdanielk1977     pIdx->zColAff = (char *)sqliteMalloc(pIdx->nColumn+1);
45a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
46a37cdde0Sdanielk1977       return;
47a37cdde0Sdanielk1977     }
48a37cdde0Sdanielk1977     for(n=0; n<pIdx->nColumn; n++){
49a37cdde0Sdanielk1977       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
50a37cdde0Sdanielk1977     }
51a37cdde0Sdanielk1977     pIdx->zColAff[pIdx->nColumn] = '\0';
52a37cdde0Sdanielk1977   }
533d1bfeaaSdanielk1977 
54956bc92cSdrh   sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
55a37cdde0Sdanielk1977 }
56a37cdde0Sdanielk1977 
57a37cdde0Sdanielk1977 /*
58a37cdde0Sdanielk1977 ** Set P3 of the most recently inserted opcode to a column affinity
59a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
60a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
61a37cdde0Sdanielk1977 ** column:
62a37cdde0Sdanielk1977 **
63a37cdde0Sdanielk1977 **  Character      Column affinity
64a37cdde0Sdanielk1977 **  ------------------------------
653eda040bSdrh **  'a'            TEXT
663eda040bSdrh **  'b'            NONE
673eda040bSdrh **  'c'            NUMERIC
683eda040bSdrh **  'd'            INTEGER
693eda040bSdrh **  'e'            REAL
70a37cdde0Sdanielk1977 */
71a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
723d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
733d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
743d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
753d1bfeaaSdanielk1977   **
763d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
773d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
783d1bfeaaSdanielk1977   */
793d1bfeaaSdanielk1977   if( !pTab->zColAff ){
803d1bfeaaSdanielk1977     char *zColAff;
813d1bfeaaSdanielk1977     int i;
823d1bfeaaSdanielk1977 
83a37cdde0Sdanielk1977     zColAff = (char *)sqliteMalloc(pTab->nCol+1);
843d1bfeaaSdanielk1977     if( !zColAff ){
85a37cdde0Sdanielk1977       return;
863d1bfeaaSdanielk1977     }
873d1bfeaaSdanielk1977 
883d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
89a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
903d1bfeaaSdanielk1977     }
913d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
923d1bfeaaSdanielk1977 
933d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
943d1bfeaaSdanielk1977   }
953d1bfeaaSdanielk1977 
96956bc92cSdrh   sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
973d1bfeaaSdanielk1977 }
983d1bfeaaSdanielk1977 
994d88778bSdanielk1977 /*
1004d88778bSdanielk1977 ** Return non-zero if SELECT statement p opens the table with rootpage
1014d88778bSdanielk1977 ** iTab in database iDb.  This is used to see if a statement of the form
1024d88778bSdanielk1977 ** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
1034d88778bSdanielk1977 ** table for the results of the SELECT.
1044d88778bSdanielk1977 **
1054d88778bSdanielk1977 ** No checking is done for sub-selects that are part of expressions.
1064d88778bSdanielk1977 */
107e501b89aSdanielk1977 static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
1084d88778bSdanielk1977   int i;
1094d88778bSdanielk1977   struct SrcList_item *pItem;
1104d88778bSdanielk1977   if( p->pSrc==0 ) return 0;
1114d88778bSdanielk1977   for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
1124d88778bSdanielk1977     if( pItem->pSelect ){
113da184236Sdanielk1977       if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
1144d88778bSdanielk1977     }else{
115da184236Sdanielk1977       if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
1164d88778bSdanielk1977     }
1174d88778bSdanielk1977   }
1184d88778bSdanielk1977   return 0;
1194d88778bSdanielk1977 }
1203d1bfeaaSdanielk1977 
1219d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1229d9cf229Sdrh /*
1239d9cf229Sdrh ** Write out code to initialize the autoincrement logic.  This code
1249d9cf229Sdrh ** looks up the current autoincrement value in the sqlite_sequence
1259d9cf229Sdrh ** table and stores that value in a memory cell.  Code generated by
1269d9cf229Sdrh ** autoIncStep() will keep that memory cell holding the largest
1279d9cf229Sdrh ** rowid value.  Code generated by autoIncEnd() will write the new
1289d9cf229Sdrh ** largest value of the counter back into the sqlite_sequence table.
1299d9cf229Sdrh **
1309d9cf229Sdrh ** This routine returns the index of the mem[] cell that contains
1319d9cf229Sdrh ** the maximum rowid counter.
1329d9cf229Sdrh **
1339d9cf229Sdrh ** Two memory cells are allocated.  The next memory cell after the
1349d9cf229Sdrh ** one returned holds the rowid in sqlite_sequence where we will
1359d9cf229Sdrh ** write back the revised maximum rowid.
1369d9cf229Sdrh */
1379d9cf229Sdrh static int autoIncBegin(
1389d9cf229Sdrh   Parse *pParse,      /* Parsing context */
1399d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
1409d9cf229Sdrh   Table *pTab         /* The table we are writing to */
1419d9cf229Sdrh ){
1429d9cf229Sdrh   int memId = 0;
1439d9cf229Sdrh   if( pTab->autoInc ){
1449d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
1459d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
1469d9cf229Sdrh     int iCur = pParse->nTab;
1479d9cf229Sdrh     int addr;
1489d9cf229Sdrh     assert( v );
1499d9cf229Sdrh     addr = sqlite3VdbeCurrentAddr(v);
1509d9cf229Sdrh     memId = pParse->nMem+1;
1519d9cf229Sdrh     pParse->nMem += 2;
1529d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
1539d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
1549d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
1559d9cf229Sdrh     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
1569d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
1579d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
1589d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
1599d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
1609d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
1619d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
1629d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
1639d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
1649d9cf229Sdrh   }
1659d9cf229Sdrh   return memId;
1669d9cf229Sdrh }
1679d9cf229Sdrh 
1689d9cf229Sdrh /*
1699d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
1709d9cf229Sdrh **
1719d9cf229Sdrh ** This routine should be called when the top of the stack holds a
1729d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
1739d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
1749d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
1759d9cf229Sdrh */
1769d9cf229Sdrh static void autoIncStep(Parse *pParse, int memId){
1779d9cf229Sdrh   if( memId>0 ){
1789d9cf229Sdrh     sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
1799d9cf229Sdrh   }
1809d9cf229Sdrh }
1819d9cf229Sdrh 
1829d9cf229Sdrh /*
1839d9cf229Sdrh ** After doing one or more inserts, the maximum rowid is stored
1849d9cf229Sdrh ** in mem[memId].  Generate code to write this value back into the
1859d9cf229Sdrh ** the sqlite_sequence table.
1869d9cf229Sdrh */
1879d9cf229Sdrh static void autoIncEnd(
1889d9cf229Sdrh   Parse *pParse,     /* The parsing context */
1899d9cf229Sdrh   int iDb,           /* Index of the database holding pTab */
1909d9cf229Sdrh   Table *pTab,       /* Table we are inserting into */
1919d9cf229Sdrh   int memId          /* Memory cell holding the maximum rowid */
1929d9cf229Sdrh ){
1939d9cf229Sdrh   if( pTab->autoInc ){
1949d9cf229Sdrh     int iCur = pParse->nTab;
1959d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
1969d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
1979d9cf229Sdrh     int addr;
1989d9cf229Sdrh     assert( v );
1999d9cf229Sdrh     addr = sqlite3VdbeCurrentAddr(v);
2009d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
2019d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
2029d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
2039d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2049d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
2059d9cf229Sdrh     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
2069d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
2079d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
2089d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Insert, iCur, 0);
2099d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
2109d9cf229Sdrh   }
2119d9cf229Sdrh }
2129d9cf229Sdrh #else
2139d9cf229Sdrh /*
2149d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
2159d9cf229Sdrh ** above are all no-ops
2169d9cf229Sdrh */
2179d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
2189d9cf229Sdrh # define autoIncStep(A,B)
2199d9cf229Sdrh # define autoIncEnd(A,B,C,D)
2209d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
2219d9cf229Sdrh 
2229d9cf229Sdrh 
2239d9cf229Sdrh /* Forward declaration */
2249d9cf229Sdrh static int xferOptimization(
2259d9cf229Sdrh   Parse *pParse,        /* Parser context */
2269d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
2279d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
2289d9cf229Sdrh   int onError,          /* How to handle constraint errors */
2299d9cf229Sdrh   int iDbDest           /* The database of pDest */
2309d9cf229Sdrh );
2319d9cf229Sdrh 
2323d1bfeaaSdanielk1977 /*
2331ccde15dSdrh ** This routine is call to handle SQL of the following forms:
234cce7d176Sdrh **
235cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
2361ccde15dSdrh **    insert into TABLE (IDLIST) select
237cce7d176Sdrh **
2381ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
2391ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
240967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
2411ccde15dSdrh **
2421ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
2431ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
2441ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
2451ccde15dSdrh ** data for the insert.
246142e30dfSdrh **
2479d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
248142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
249142e30dfSdrh ** once straight down through.  The template looks like this:
250142e30dfSdrh **
251142e30dfSdrh **         open write cursor to <table> and its indices
252142e30dfSdrh **         puts VALUES clause expressions onto the stack
253142e30dfSdrh **         write the resulting record into <table>
254142e30dfSdrh **         cleanup
255142e30dfSdrh **
2569d9cf229Sdrh ** The three remaining templates assume the statement is of the form
257142e30dfSdrh **
258142e30dfSdrh **   INSERT INTO <table> SELECT ...
259142e30dfSdrh **
2609d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
2619d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
2629d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
2639d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
2649d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
2659d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
2669d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
2679d9cf229Sdrh ** template.  This is the second template.
2689d9cf229Sdrh **
2699d9cf229Sdrh **         open a write cursor to <table>
2709d9cf229Sdrh **         open read cursor on <table2>
2719d9cf229Sdrh **         transfer all records in <table2> over to <table>
2729d9cf229Sdrh **         close cursors
2739d9cf229Sdrh **         foreach index on <table>
2749d9cf229Sdrh **           open a write cursor on the <table> index
2759d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
2769d9cf229Sdrh **           transfer all records from the read to the write cursors
2779d9cf229Sdrh **           close cursors
2789d9cf229Sdrh **         end foreach
2799d9cf229Sdrh **
2809d9cf229Sdrh ** The third template is for when the second template does not apply
2819d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
2829d9cf229Sdrh ** The generated code follows this template:
283142e30dfSdrh **
284142e30dfSdrh **         goto B
285142e30dfSdrh **      A: setup for the SELECT
2869d9cf229Sdrh **         loop over the rows in the SELECT
287142e30dfSdrh **           gosub C
288142e30dfSdrh **         end loop
289142e30dfSdrh **         cleanup after the SELECT
290142e30dfSdrh **         goto D
291142e30dfSdrh **      B: open write cursor to <table> and its indices
292142e30dfSdrh **         goto A
293142e30dfSdrh **      C: insert the select result into <table>
294142e30dfSdrh **         return
295142e30dfSdrh **      D: cleanup
296142e30dfSdrh **
2979d9cf229Sdrh ** The fourth template is used if the insert statement takes its
298142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
299142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
300142e30dfSdrh ** we have to use a intermediate table to store the results of
301142e30dfSdrh ** the select.  The template is like this:
302142e30dfSdrh **
303142e30dfSdrh **         goto B
304142e30dfSdrh **      A: setup for the SELECT
305142e30dfSdrh **         loop over the tables in the SELECT
306142e30dfSdrh **           gosub C
307142e30dfSdrh **         end loop
308142e30dfSdrh **         cleanup after the SELECT
309142e30dfSdrh **         goto D
310142e30dfSdrh **      C: insert the select result into the intermediate table
311142e30dfSdrh **         return
312142e30dfSdrh **      B: open a cursor to an intermediate table
313142e30dfSdrh **         goto A
314142e30dfSdrh **      D: open write cursor to <table> and its indices
315142e30dfSdrh **         loop over the intermediate table
316142e30dfSdrh **           transfer values form intermediate table into <table>
317142e30dfSdrh **         end the loop
318142e30dfSdrh **         cleanup
319cce7d176Sdrh */
3204adee20fSdanielk1977 void sqlite3Insert(
321cce7d176Sdrh   Parse *pParse,        /* Parser context */
322113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
323cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
3245974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
3259cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
3269cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
327cce7d176Sdrh ){
3285974a30fSdrh   Table *pTab;          /* The table to insert into */
329113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
330e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
3315974a30fSdrh   int i, j, idx;        /* Loop counters */
3325974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
3335974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
334967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
335cfe9a69fSdanielk1977   int base = 0;         /* VDBE Cursor number for pTab */
336cfe9a69fSdanielk1977   int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
3379bb575fdSdrh   sqlite3 *db;          /* The main database structure */
3384a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
3390ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
3404d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
341cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
342cfe9a69fSdanielk1977   int iSelectLoop = 0;  /* Address of code that implements the SELECT */
343cfe9a69fSdanielk1977   int iCleanup = 0;     /* Address of the cleanup code */
344cfe9a69fSdanielk1977   int iInsertBlock = 0; /* Address of the subroutine used to insert data */
345cfe9a69fSdanielk1977   int iCntMem = 0;      /* Memory cell used for the row counter */
346798da52cSdrh   int newIdx = -1;      /* Cursor for the NEW table */
3472958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
3482958a4e6Sdrh   int counterMem = 0;   /* Memory cell holding AUTOINCREMENT counter */
349da184236Sdanielk1977   int iDb;
350cce7d176Sdrh 
351798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
352798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
353dca76841Sdrh   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
354798da52cSdrh #endif
355c3f9bad2Sdanielk1977 
3569e12800dSdanielk1977   if( pParse->nErr || sqlite3MallocFailed() ){
3576f7adc8aSdrh     goto insert_cleanup;
3586f7adc8aSdrh   }
359ecdc7530Sdrh   db = pParse->db;
360daffd0e5Sdrh 
3611ccde15dSdrh   /* Locate the table into which we will be inserting new information.
3621ccde15dSdrh   */
363113088ecSdrh   assert( pTabList->nSrc==1 );
364113088ecSdrh   zTab = pTabList->a[0].zName;
365daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
3664adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
367c3f9bad2Sdanielk1977   if( pTab==0 ){
368c3f9bad2Sdanielk1977     goto insert_cleanup;
369c3f9bad2Sdanielk1977   }
370da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
371da184236Sdanielk1977   assert( iDb<db->nDb );
372da184236Sdanielk1977   pDb = &db->aDb[iDb];
3732958a4e6Sdrh   zDb = pDb->zName;
3744adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
3751962bda7Sdrh     goto insert_cleanup;
3761962bda7Sdrh   }
377c3f9bad2Sdanielk1977 
378b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
379b7f9164eSdrh   ** inserted into is a view
380b7f9164eSdrh   */
381b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
382dca76841Sdrh   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
383b7f9164eSdrh   isView = pTab->pSelect!=0;
384b7f9164eSdrh #else
385dca76841Sdrh # define triggers_exist 0
386b7f9164eSdrh # define isView 0
387b7f9164eSdrh #endif
388b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
389b7f9164eSdrh # undef isView
390b7f9164eSdrh # define isView 0
391b7f9164eSdrh #endif
392b7f9164eSdrh 
393c3f9bad2Sdanielk1977   /* Ensure that:
394c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
395c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
396c3f9bad2Sdanielk1977   */
397dca76841Sdrh   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
398c3f9bad2Sdanielk1977     goto insert_cleanup;
399c3f9bad2Sdanielk1977   }
40043617e9aSdrh   assert( pTab!=0 );
4011ccde15dSdrh 
402f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
403b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
404b3d24bf8Sdanielk1977   ** module table).
405f573c99bSdrh   */
406b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
407f573c99bSdrh     goto insert_cleanup;
408f573c99bSdrh   }
409f573c99bSdrh 
4101ccde15dSdrh   /* Allocate a VDBE
4111ccde15dSdrh   */
4124adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
4135974a30fSdrh   if( v==0 ) goto insert_cleanup;
4144794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
415da184236Sdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
4161ccde15dSdrh 
417c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
418dca76841Sdrh   if( triggers_exist ){
419c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
420f29ce559Sdanielk1977   }
421c3f9bad2Sdanielk1977 
4229d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
4239d9cf229Sdrh   /* If the statement is of the form
4249d9cf229Sdrh   **
4259d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
4269d9cf229Sdrh   **
4279d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
4289d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
4299d9cf229Sdrh   */
4309d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
4319d9cf229Sdrh     assert( !triggers_exist );
4329d9cf229Sdrh     assert( pList==0 );
4339d9cf229Sdrh     goto insert_cleanup;
4349d9cf229Sdrh   }
4359d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
4369d9cf229Sdrh 
4372958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
438f3388144Sdrh   ** sqlite_sequence table and store it in memory cell counterMem.  Also
439f3388144Sdrh   ** remember the rowid of the sqlite_sequence table entry in memory cell
440f3388144Sdrh   ** counterRowid.
4412958a4e6Sdrh   */
4429d9cf229Sdrh   counterMem = autoIncBegin(pParse, iDb, pTab);
4432958a4e6Sdrh 
4441ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
445142e30dfSdrh   ** is coming from a SELECT statement, then this step also generates
446142e30dfSdrh   ** all the code to implement the SELECT statement and invoke a subroutine
447142e30dfSdrh   ** to process each row of the result. (Template 2.) If the SELECT
448142e30dfSdrh   ** statement uses the the table that is being inserted into, then the
449142e30dfSdrh   ** subroutine is also coded here.  That subroutine stores the SELECT
450142e30dfSdrh   ** results in a temporary table. (Template 3.)
4511ccde15dSdrh   */
4525974a30fSdrh   if( pSelect ){
453142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
454142e30dfSdrh     */
455142e30dfSdrh     int rc, iInitCode;
4564adee20fSdanielk1977     iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
4574adee20fSdanielk1977     iSelectLoop = sqlite3VdbeCurrentAddr(v);
4584adee20fSdanielk1977     iInsertBlock = sqlite3VdbeMakeLabel(v);
459b3bce662Sdanielk1977 
460b3bce662Sdanielk1977     /* Resolve the expressions in the SELECT statement and execute it. */
461b3bce662Sdanielk1977     rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
4629e12800dSdanielk1977     if( rc || pParse->nErr || sqlite3MallocFailed() ){
4636f7adc8aSdrh       goto insert_cleanup;
4646f7adc8aSdrh     }
465b3bce662Sdanielk1977 
4664adee20fSdanielk1977     iCleanup = sqlite3VdbeMakeLabel(v);
4674adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
4685974a30fSdrh     assert( pSelect->pEList );
469967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
470142e30dfSdrh 
471142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
472142e30dfSdrh     ** should be written into a temporary table.  Set to FALSE if each
473142e30dfSdrh     ** row of the SELECT can be written directly into the result table.
474048c530cSdrh     **
475048c530cSdrh     ** A temp table must be used if the table being updated is also one
476048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
477048c530cSdrh     ** temp table in the case of row triggers.
478142e30dfSdrh     */
479da184236Sdanielk1977     if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
480048c530cSdrh       useTempTable = 1;
481048c530cSdrh     }
482142e30dfSdrh 
483142e30dfSdrh     if( useTempTable ){
484142e30dfSdrh       /* Generate the subroutine that SELECT calls to process each row of
485142e30dfSdrh       ** the result.  Store the result in a temporary table
486142e30dfSdrh       */
487142e30dfSdrh       srcTab = pParse->nTab++;
4884adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iInsertBlock);
4894adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
490f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
4914adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
492f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_Insert, srcTab, 0);
4934adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
494142e30dfSdrh 
495142e30dfSdrh       /* The following code runs first because the GOTO at the very top
496142e30dfSdrh       ** of the program jumps to it.  Create the temporary table, then jump
497142e30dfSdrh       ** back up and execute the SELECT code above.
498142e30dfSdrh       */
499d654be80Sdrh       sqlite3VdbeJumpHere(v, iInitCode);
500b9bb7c18Sdrh       sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
501b6f5452fSdrh       sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
5024adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
5034adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCleanup);
5045974a30fSdrh     }else{
505d654be80Sdrh       sqlite3VdbeJumpHere(v, iInitCode);
506142e30dfSdrh     }
507142e30dfSdrh   }else{
508142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
509142e30dfSdrh     ** clause
510142e30dfSdrh     */
511b3bce662Sdanielk1977     NameContext sNC;
512b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
513b3bce662Sdanielk1977     sNC.pParse = pParse;
5145974a30fSdrh     srcTab = -1;
515142e30dfSdrh     useTempTable = 0;
516147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
517e64e7b20Sdrh     for(i=0; i<nColumn; i++){
518b3bce662Sdanielk1977       if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
519b04a5d87Sdrh         goto insert_cleanup;
520b04a5d87Sdrh       }
521e64e7b20Sdrh     }
5225974a30fSdrh   }
5231ccde15dSdrh 
5241ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
5251ccde15dSdrh   ** of columns to be inserted into the table.
5261ccde15dSdrh   */
527147d0cccSdrh   if( pColumn==0 && nColumn && nColumn!=pTab->nCol ){
5284adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
529da93d238Sdrh        "table %S has %d columns but %d values were supplied",
530da93d238Sdrh        pTabList, 0, pTab->nCol, nColumn);
531cce7d176Sdrh     goto insert_cleanup;
532cce7d176Sdrh   }
533967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
5344adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
535cce7d176Sdrh     goto insert_cleanup;
536cce7d176Sdrh   }
5371ccde15dSdrh 
5381ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
5391ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
5401ccde15dSdrh   ** remember the column indices.
541c8392586Sdrh   **
542c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
543c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
544c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
545c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
546c8392586Sdrh   ** is appears in the original table.  (The index of the primary
547c8392586Sdrh   ** key in the original table is pTab->iPKey.)
5481ccde15dSdrh   */
549967e8b73Sdrh   if( pColumn ){
550967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
551967e8b73Sdrh       pColumn->a[i].idx = -1;
552cce7d176Sdrh     }
553967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
554cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
5554adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
556967e8b73Sdrh           pColumn->a[i].idx = j;
5574a32431cSdrh           if( j==pTab->iPKey ){
5589aa028daSdrh             keyColumn = i;
5594a32431cSdrh           }
560cce7d176Sdrh           break;
561cce7d176Sdrh         }
562cce7d176Sdrh       }
563cce7d176Sdrh       if( j>=pTab->nCol ){
5644adee20fSdanielk1977         if( sqlite3IsRowid(pColumn->a[i].zName) ){
565a0217ba7Sdrh           keyColumn = i;
566a0217ba7Sdrh         }else{
5674adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
568da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
569cce7d176Sdrh           pParse->nErr++;
570cce7d176Sdrh           goto insert_cleanup;
571cce7d176Sdrh         }
572cce7d176Sdrh       }
573cce7d176Sdrh     }
574a0217ba7Sdrh   }
5751ccde15dSdrh 
576aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
577c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
578c8392586Sdrh   ** in the original table definition.
5794a32431cSdrh   */
580147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
5814a32431cSdrh     keyColumn = pTab->iPKey;
5824a32431cSdrh   }
5834a32431cSdrh 
584142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
585142e30dfSdrh   */
586dca76841Sdrh   if( triggers_exist ){
5874adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
58884ac9d02Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
589f29ce559Sdanielk1977   }
590c3f9bad2Sdanielk1977 
591c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
5921ccde15dSdrh   */
593142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
594142e30dfSdrh     iCntMem = pParse->nMem++;
595d654be80Sdrh     sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
596c3f9bad2Sdanielk1977   }
597c3f9bad2Sdanielk1977 
598c3f9bad2Sdanielk1977   /* Open tables and indices if there are no row triggers */
599dca76841Sdrh   if( !triggers_exist ){
6005974a30fSdrh     base = pParse->nTab;
601290c1948Sdrh     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
602feeb1394Sdrh   }
603feeb1394Sdrh 
604142e30dfSdrh   /* If the data source is a temporary table, then we have to create
6051ccde15dSdrh   ** a loop because there might be multiple rows of data.  If the data
606142e30dfSdrh   ** source is a subroutine call from the SELECT statement, then we need
607142e30dfSdrh   ** to launch the SELECT statement processing.
6081ccde15dSdrh   */
609142e30dfSdrh   if( useTempTable ){
6104adee20fSdanielk1977     iBreak = sqlite3VdbeMakeLabel(v);
6114adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
6124adee20fSdanielk1977     iCont = sqlite3VdbeCurrentAddr(v);
613142e30dfSdrh   }else if( pSelect ){
6144adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
6154adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iInsertBlock);
616bed8690fSdrh   }
6171ccde15dSdrh 
6185cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
61970ce3f0cSdrh   */
6204adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
621dca76841Sdrh   if( triggers_exist & TRIGGER_BEFORE ){
622c3f9bad2Sdanielk1977 
62370ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
62470ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
62570ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
62670ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
62770ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
62870ce3f0cSdrh     */
62970ce3f0cSdrh     if( keyColumn<0 ){
6304adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
63170ce3f0cSdrh     }else if( useTempTable ){
6324adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
63370ce3f0cSdrh     }else{
634d6fe961eSdrh       assert( pSelect==0 );  /* Otherwise useTempTable is true */
6354adee20fSdanielk1977       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
6364adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
6374adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
6384adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
6394adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
64070ce3f0cSdrh     }
64170ce3f0cSdrh 
64270ce3f0cSdrh     /* Create the new column data
64370ce3f0cSdrh     */
644c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
645c3f9bad2Sdanielk1977       if( pColumn==0 ){
646c3f9bad2Sdanielk1977         j = i;
647c3f9bad2Sdanielk1977       }else{
648c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
649c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
650c3f9bad2Sdanielk1977         }
651c3f9bad2Sdanielk1977       }
652c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
6537977a17fSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
654142e30dfSdrh       }else if( useTempTable ){
6554adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
656c3f9bad2Sdanielk1977       }else{
657d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
65825303780Sdrh         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
659c3f9bad2Sdanielk1977       }
660c3f9bad2Sdanielk1977     }
6614adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
662a37cdde0Sdanielk1977 
663a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
664a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
665a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
666a37cdde0Sdanielk1977     ** table column affinities.
667a37cdde0Sdanielk1977     */
668a37cdde0Sdanielk1977     if( !isView ){
669a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
670a37cdde0Sdanielk1977     }
671f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
672c3f9bad2Sdanielk1977 
6735cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
674dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
675b2fe7d8cSdrh         newIdx, -1, onError, endOfLoop) ){
676f29ce559Sdanielk1977       goto insert_cleanup;
677f29ce559Sdanielk1977     }
67870ce3f0cSdrh   }
679c3f9bad2Sdanielk1977 
68070ce3f0cSdrh   /* If any triggers exists, the opening of tables and indices is deferred
68170ce3f0cSdrh   ** until now.
68270ce3f0cSdrh   */
683dca76841Sdrh   if( triggers_exist && !isView ){
684c3f9bad2Sdanielk1977     base = pParse->nTab;
685290c1948Sdrh     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
686c3f9bad2Sdanielk1977   }
687c3f9bad2Sdanielk1977 
6884a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
689f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
6904a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
691b419a926Sdrh   ** case the record number is the same as that column.
6921ccde15dSdrh   */
6935cf590c1Sdrh   if( !isView ){
6944cbdda9eSdrh     if( IsVirtual(pTab) ){
6954cbdda9eSdrh       /* The row that the VUpdate opcode will delete:  none */
6964cbdda9eSdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
6974cbdda9eSdrh     }
6984a32431cSdrh     if( keyColumn>=0 ){
699142e30dfSdrh       if( useTempTable ){
7004adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
701142e30dfSdrh       }else if( pSelect ){
7024adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
7034a32431cSdrh       }else{
7044adee20fSdanielk1977         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
70527a32783Sdrh       }
706f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
707e1e68f49Sdrh       ** to generate a unique primary key value.
708e1e68f49Sdrh       */
7094adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
7104adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
711f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
7124adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
7134cbdda9eSdrh     }else if( IsVirtual(pTab) ){
7144cbdda9eSdrh       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
7154a32431cSdrh     }else{
716f0863fe5Sdrh       sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
7174a32431cSdrh     }
7189d9cf229Sdrh     autoIncStep(pParse, counterMem);
7194a32431cSdrh 
720aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
7214a32431cSdrh     ** with the first column.
7224a32431cSdrh     */
723cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
7244a32431cSdrh       if( i==pTab->iPKey ){
7254a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
726aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
727aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
728aacc543eSdrh         ** taking up data space with information that will never be used. */
729f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
7304a32431cSdrh         continue;
7314a32431cSdrh       }
732967e8b73Sdrh       if( pColumn==0 ){
733cce7d176Sdrh         j = i;
734cce7d176Sdrh       }else{
735967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
736967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
737cce7d176Sdrh         }
738cce7d176Sdrh       }
739147d0cccSdrh       if( nColumn==0 || (pColumn && j>=pColumn->nId) ){
7407977a17fSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
741142e30dfSdrh       }else if( useTempTable ){
7424adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
743142e30dfSdrh       }else if( pSelect ){
74416ed8a64Sdrh         sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
745cce7d176Sdrh       }else{
7464adee20fSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr);
747cce7d176Sdrh       }
748cce7d176Sdrh     }
7491ccde15dSdrh 
7500ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
7510ca3e24bSdrh     ** do the insertion.
7524a32431cSdrh     */
7534cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
7544cbdda9eSdrh     if( IsVirtual(pTab) ){
755f9e7dda7Sdanielk1977       pParse->pVirtualLock = pTab;
7561f6eec54Sdanielk1977       sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
7574cbdda9eSdrh                      (const char*)pTab->pVtab, P3_VTAB);
7584cbdda9eSdrh     }else
7594cbdda9eSdrh #endif
7604cbdda9eSdrh     {
7614adee20fSdanielk1977       sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
762a0217ba7Sdrh                                      0, onError, endOfLoop);
7634adee20fSdanielk1977       sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
764dca76841Sdrh                             (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1);
7655cf590c1Sdrh     }
7664cbdda9eSdrh   }
7671bee3d7bSdrh 
768feeb1394Sdrh   /* Update the count of rows that are inserted
7691bee3d7bSdrh   */
770142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
77115007a99Sdrh     sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
7721bee3d7bSdrh   }
773c3f9bad2Sdanielk1977 
774dca76841Sdrh   if( triggers_exist ){
775c3f9bad2Sdanielk1977     /* Close all tables opened */
7765cf590c1Sdrh     if( !isView ){
7774adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, base, 0);
778c3f9bad2Sdanielk1977       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
7794adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
780c3f9bad2Sdanielk1977       }
781c3f9bad2Sdanielk1977     }
782c3f9bad2Sdanielk1977 
783c3f9bad2Sdanielk1977     /* Code AFTER triggers */
784dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
785dca76841Sdrh           newIdx, -1, onError, endOfLoop) ){
786f29ce559Sdanielk1977       goto insert_cleanup;
787f29ce559Sdanielk1977     }
788c3f9bad2Sdanielk1977   }
7891bee3d7bSdrh 
7901ccde15dSdrh   /* The bottom of the loop, if the data source is a SELECT statement
7911ccde15dSdrh   */
7924adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
793142e30dfSdrh   if( useTempTable ){
7944adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
7954adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iBreak);
7964adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
797142e30dfSdrh   }else if( pSelect ){
7984adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
7994adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Return, 0, 0);
8004adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iCleanup);
8016b56344dSdrh   }
802c3f9bad2Sdanielk1977 
8034cbdda9eSdrh   if( !triggers_exist && !IsVirtual(pTab) ){
804c3f9bad2Sdanielk1977     /* Close all tables opened */
8054adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Close, base, 0);
8066b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
8074adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
808cce7d176Sdrh     }
809c3f9bad2Sdanielk1977   }
810c3f9bad2Sdanielk1977 
811f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
812f3388144Sdrh   ** counter value in memory counterMem back into the sqlite_sequence
813f3388144Sdrh   ** table.
8142958a4e6Sdrh   */
8159d9cf229Sdrh   autoIncEnd(pParse, iDb, pTab, counterMem);
8162958a4e6Sdrh 
8171bee3d7bSdrh   /*
818e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
819e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
820e7de6f25Sdanielk1977   ** invoke the callback function.
8211bee3d7bSdrh   */
822cc6bd383Sdanielk1977   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
8234adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
8244adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
82522322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
826955de52cSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
8271bee3d7bSdrh   }
828cce7d176Sdrh 
829cce7d176Sdrh insert_cleanup:
8304adee20fSdanielk1977   sqlite3SrcListDelete(pTabList);
831d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
832d5d56523Sdanielk1977   sqlite3SelectDelete(pSelect);
8334adee20fSdanielk1977   sqlite3IdListDelete(pColumn);
834cce7d176Sdrh }
8359cfcf5d4Sdrh 
8369cfcf5d4Sdrh /*
8379cfcf5d4Sdrh ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
8389cfcf5d4Sdrh **
8399cfcf5d4Sdrh ** When this routine is called, the stack contains (from bottom to top)
8400ca3e24bSdrh ** the following values:
8410ca3e24bSdrh **
842f0863fe5Sdrh **    1.  The rowid of the row to be updated before the update.  This
843b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
844b419a926Sdrh **        change to the record number.
8450ca3e24bSdrh **
846f0863fe5Sdrh **    2.  The rowid of the row after the update.
8470ca3e24bSdrh **
8480ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
8490ca3e24bSdrh **
8500ca3e24bSdrh **    i.  Data from middle columns...
8510ca3e24bSdrh **
8520ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
8530ca3e24bSdrh **
854f0863fe5Sdrh ** The old rowid shown as entry (1) above is omitted unless both isUpdate
855f0863fe5Sdrh ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
856f0863fe5Sdrh ** INSERTs and rowidChng is true if the record number is being changed.
8570ca3e24bSdrh **
8580ca3e24bSdrh ** The code generated by this routine pushes additional entries onto
8590ca3e24bSdrh ** the stack which are the keys for new index entries for the new record.
8600ca3e24bSdrh ** The order of index keys is the same as the order of the indices on
8610ca3e24bSdrh ** the pTable->pIndex list.  A key is only created for index i if
8620ca3e24bSdrh ** aIdxUsed!=0 and aIdxUsed[i]!=0.
8639cfcf5d4Sdrh **
8649cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
8659cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
8661c92853dSdrh ** then the appropriate action is performed.  There are five possible
8671c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
8689cfcf5d4Sdrh **
8699cfcf5d4Sdrh **  Constraint type  Action       What Happens
8709cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
8711c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
87224b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
8739cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
8749cfcf5d4Sdrh **
8751c92853dSdrh **  any              ABORT        Back out changes from the current command
8761c92853dSdrh **                                only (do not do a complete rollback) then
87724b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
8781c92853dSdrh **                                with SQLITE_CONSTRAINT.
8791c92853dSdrh **
8801c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
8811c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
8821c92853dSdrh **                                transaction is not rolled back and any
8831c92853dSdrh **                                prior changes are retained.
8841c92853dSdrh **
8859cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
8869cfcf5d4Sdrh **                                the stack and there is an immediate jump
8879cfcf5d4Sdrh **                                to label ignoreDest.
8889cfcf5d4Sdrh **
8899cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
8909cfcf5d4Sdrh **                                value for that column.  If the default value
8919cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
8929cfcf5d4Sdrh **
8939cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
8949cfcf5d4Sdrh **                                being inserted is removed.
8959cfcf5d4Sdrh **
8969cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
8979cfcf5d4Sdrh **
8981c92853dSdrh ** Which action to take is determined by the overrideError parameter.
8991c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
9001c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
9011c92853dSdrh ** for the constraint is used.
9029cfcf5d4Sdrh **
903aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
9049cfcf5d4Sdrh ** cursor number "base".  All indices of pTab must also have open
9059cfcf5d4Sdrh ** read/write cursors with cursor number base+i for the i-th cursor.
9069cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
9079cfcf5d4Sdrh ** cursors do not need to be open for indices where aIdxUsed[i]==0.
9089cfcf5d4Sdrh **
9099cfcf5d4Sdrh ** If the isUpdate flag is true, it means that the "base" cursor is
9109cfcf5d4Sdrh ** initially pointing to an entry that is being updated.  The isUpdate
9119cfcf5d4Sdrh ** flag causes extra code to be generated so that the "base" cursor
9129cfcf5d4Sdrh ** is still pointing at the same entry after the routine returns.
9139cfcf5d4Sdrh ** Without the isUpdate flag, the "base" cursor might be moved.
9149cfcf5d4Sdrh */
9154adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
9169cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
9179cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
9189cfcf5d4Sdrh   int base,           /* Index of a read/write cursor pointing at pTab */
9199cfcf5d4Sdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
920f0863fe5Sdrh   int rowidChng,      /* True if the record number will change */
921b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
9229cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
923b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
9249cfcf5d4Sdrh ){
9259cfcf5d4Sdrh   int i;
9269cfcf5d4Sdrh   Vdbe *v;
9279cfcf5d4Sdrh   int nCol;
9289cfcf5d4Sdrh   int onError;
9299cfcf5d4Sdrh   int addr;
9309cfcf5d4Sdrh   int extra;
9310ca3e24bSdrh   int iCur;
9320ca3e24bSdrh   Index *pIdx;
9330ca3e24bSdrh   int seenReplace = 0;
934cfe9a69fSdanielk1977   int jumpInst1=0, jumpInst2;
935f0863fe5Sdrh   int hasTwoRowids = (isUpdate && rowidChng);
9369cfcf5d4Sdrh 
9374adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
9389cfcf5d4Sdrh   assert( v!=0 );
939417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
9409cfcf5d4Sdrh   nCol = pTab->nCol;
9419cfcf5d4Sdrh 
9429cfcf5d4Sdrh   /* Test all NOT NULL constraints.
9439cfcf5d4Sdrh   */
9449cfcf5d4Sdrh   for(i=0; i<nCol; i++){
9450ca3e24bSdrh     if( i==pTab->iPKey ){
9460ca3e24bSdrh       continue;
9470ca3e24bSdrh     }
9489cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
9490ca3e24bSdrh     if( onError==OE_None ) continue;
9509cfcf5d4Sdrh     if( overrideError!=OE_Default ){
9519cfcf5d4Sdrh       onError = overrideError;
952a996e477Sdrh     }else if( onError==OE_Default ){
953a996e477Sdrh       onError = OE_Abort;
9549cfcf5d4Sdrh     }
9557977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
9569cfcf5d4Sdrh       onError = OE_Abort;
9579cfcf5d4Sdrh     }
9584adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
9594adee20fSdanielk1977     addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
960b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
961b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
9629cfcf5d4Sdrh     switch( onError ){
9631c92853dSdrh       case OE_Rollback:
9641c92853dSdrh       case OE_Abort:
9651c92853dSdrh       case OE_Fail: {
966483750baSdrh         char *zMsg = 0;
9674adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
9684adee20fSdanielk1977         sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
96941743984Sdrh                         " may not be NULL", (char*)0);
9704adee20fSdanielk1977         sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
9719cfcf5d4Sdrh         break;
9729cfcf5d4Sdrh       }
9739cfcf5d4Sdrh       case OE_Ignore: {
974f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
9754adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
9769cfcf5d4Sdrh         break;
9779cfcf5d4Sdrh       }
9789cfcf5d4Sdrh       case OE_Replace: {
9797977a17fSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
9804adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
9819cfcf5d4Sdrh         break;
9829cfcf5d4Sdrh       }
9839cfcf5d4Sdrh     }
984d654be80Sdrh     sqlite3VdbeJumpHere(v, addr);
9859cfcf5d4Sdrh   }
9869cfcf5d4Sdrh 
9879cfcf5d4Sdrh   /* Test all CHECK constraints
9889cfcf5d4Sdrh   */
989ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
9900cd2d4c9Sdrh   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
991ffe07b2dSdrh     int allOk = sqlite3VdbeMakeLabel(v);
992ffe07b2dSdrh     assert( pParse->ckOffset==0 );
993ffe07b2dSdrh     pParse->ckOffset = nCol;
9946275b88bSdrh     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
995ffe07b2dSdrh     assert( pParse->ckOffset==nCol );
996ffe07b2dSdrh     pParse->ckOffset = 0;
997aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
998aa01c7e2Sdrh     if( onError==OE_Ignore || onError==OE_Replace ){
999aa01c7e2Sdrh       sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1000aa01c7e2Sdrh       sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1001aa01c7e2Sdrh     }else{
1002aa01c7e2Sdrh       sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1003aa01c7e2Sdrh     }
1004ffe07b2dSdrh     sqlite3VdbeResolveLabel(v, allOk);
1005ffe07b2dSdrh   }
1006ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
10079cfcf5d4Sdrh 
10080bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
10090bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
10100bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
10119cfcf5d4Sdrh   */
1012f0863fe5Sdrh   if( rowidChng ){
10130ca3e24bSdrh     onError = pTab->keyConf;
10140ca3e24bSdrh     if( overrideError!=OE_Default ){
10150ca3e24bSdrh       onError = overrideError;
1016a996e477Sdrh     }else if( onError==OE_Default ){
1017a996e477Sdrh       onError = OE_Abort;
10180ca3e24bSdrh     }
1019a0217ba7Sdrh 
102079b0c956Sdrh     if( isUpdate ){
10214adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
10224adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
10234adee20fSdanielk1977       jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
102479b0c956Sdrh     }
10254adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
10264adee20fSdanielk1977     jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
10270ca3e24bSdrh     switch( onError ){
1028a0217ba7Sdrh       default: {
1029a0217ba7Sdrh         onError = OE_Abort;
1030a0217ba7Sdrh         /* Fall thru into the next case */
1031a0217ba7Sdrh       }
10321c92853dSdrh       case OE_Rollback:
10331c92853dSdrh       case OE_Abort:
10341c92853dSdrh       case OE_Fail: {
10354adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1036701a0aebSdrh                          "PRIMARY KEY must be unique", P3_STATIC);
10370ca3e24bSdrh         break;
10380ca3e24bSdrh       }
10395383ae5cSdrh       case OE_Replace: {
104074161705Sdrh         sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
10415383ae5cSdrh         if( isUpdate ){
1042f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
10437cf6e4deSdrh           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
10445383ae5cSdrh         }
10455383ae5cSdrh         seenReplace = 1;
10465383ae5cSdrh         break;
10475383ae5cSdrh       }
10480ca3e24bSdrh       case OE_Ignore: {
10495383ae5cSdrh         assert( seenReplace==0 );
1050f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
10514adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
10520ca3e24bSdrh         break;
10530ca3e24bSdrh       }
10540ca3e24bSdrh     }
1055d654be80Sdrh     sqlite3VdbeJumpHere(v, jumpInst2);
1056f5905aa7Sdrh     if( isUpdate ){
1057d654be80Sdrh       sqlite3VdbeJumpHere(v, jumpInst1);
10584adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
10597cf6e4deSdrh       sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
10600ca3e24bSdrh     }
10610ca3e24bSdrh   }
10620bd1f4eaSdrh 
10630bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
10640bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
10650bd1f4eaSdrh   ** Add the new records to the indices as we go.
10660bd1f4eaSdrh   */
1067b2fe7d8cSdrh   extra = -1;
1068b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1069b2fe7d8cSdrh     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;  /* Skip unused indices */
10709cfcf5d4Sdrh     extra++;
1071b2fe7d8cSdrh 
1072b2fe7d8cSdrh     /* Create a key for accessing the index entry */
10734adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
10749cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
10759cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
10769cfcf5d4Sdrh       if( idx==pTab->iPKey ){
10774adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
10789cfcf5d4Sdrh       }else{
10794adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
10809cfcf5d4Sdrh       }
10819cfcf5d4Sdrh     }
10827f057c91Sdrh     jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
1083a37cdde0Sdanielk1977     sqlite3IndexAffinityStr(v, pIdx);
1084b2fe7d8cSdrh 
1085b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
10869cfcf5d4Sdrh     onError = pIdx->onError;
1087b2fe7d8cSdrh     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
10889cfcf5d4Sdrh     if( overrideError!=OE_Default ){
10899cfcf5d4Sdrh       onError = overrideError;
1090a996e477Sdrh     }else if( onError==OE_Default ){
1091a996e477Sdrh       onError = OE_Abort;
10929cfcf5d4Sdrh     }
10935383ae5cSdrh     if( seenReplace ){
10945383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
10955383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
10965383ae5cSdrh     }
10975383ae5cSdrh 
1098b2fe7d8cSdrh 
1099b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
1100f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
11014adee20fSdanielk1977     jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
1102b2fe7d8cSdrh 
1103b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1104b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1105b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
11069cfcf5d4Sdrh     switch( onError ){
11071c92853dSdrh       case OE_Rollback:
11081c92853dSdrh       case OE_Abort:
11091c92853dSdrh       case OE_Fail: {
111037ed48edSdrh         int j, n1, n2;
111137ed48edSdrh         char zErrMsg[200];
111237ed48edSdrh         strcpy(zErrMsg, pIdx->nColumn>1 ? "columns " : "column ");
111337ed48edSdrh         n1 = strlen(zErrMsg);
111437ed48edSdrh         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
111537ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
111637ed48edSdrh           n2 = strlen(zCol);
111737ed48edSdrh           if( j>0 ){
111837ed48edSdrh             strcpy(&zErrMsg[n1], ", ");
111937ed48edSdrh             n1 += 2;
112037ed48edSdrh           }
112137ed48edSdrh           if( n1+n2>sizeof(zErrMsg)-30 ){
112237ed48edSdrh             strcpy(&zErrMsg[n1], "...");
112337ed48edSdrh             n1 += 3;
112437ed48edSdrh             break;
112537ed48edSdrh           }else{
112637ed48edSdrh             strcpy(&zErrMsg[n1], zCol);
112737ed48edSdrh             n1 += n2;
112837ed48edSdrh           }
112937ed48edSdrh         }
113037ed48edSdrh         strcpy(&zErrMsg[n1],
113137ed48edSdrh             pIdx->nColumn>1 ? " are not unique" : " is not unique");
11324adee20fSdanielk1977         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
11339cfcf5d4Sdrh         break;
11349cfcf5d4Sdrh       }
11359cfcf5d4Sdrh       case OE_Ignore: {
11360ca3e24bSdrh         assert( seenReplace==0 );
1137f0863fe5Sdrh         sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
11384adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
11399cfcf5d4Sdrh         break;
11409cfcf5d4Sdrh       }
11419cfcf5d4Sdrh       case OE_Replace: {
11424adee20fSdanielk1977         sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
11439cfcf5d4Sdrh         if( isUpdate ){
1144f0863fe5Sdrh           sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
11457cf6e4deSdrh           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
11469cfcf5d4Sdrh         }
11470ca3e24bSdrh         seenReplace = 1;
11489cfcf5d4Sdrh         break;
11499cfcf5d4Sdrh       }
11509cfcf5d4Sdrh     }
11510bd1f4eaSdrh #if NULL_DISTINCT_FOR_UNIQUE
1152d654be80Sdrh     sqlite3VdbeJumpHere(v, jumpInst1);
11530bd1f4eaSdrh #endif
1154d654be80Sdrh     sqlite3VdbeJumpHere(v, jumpInst2);
11559cfcf5d4Sdrh   }
11569cfcf5d4Sdrh }
11570ca3e24bSdrh 
11580ca3e24bSdrh /*
11590ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
11604adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
11610ca3e24bSdrh ** The stack must contain keys for all active indices followed by data
1162f0863fe5Sdrh ** and the rowid for the new entry.  This routine creates the new
11630ca3e24bSdrh ** entries in all indices and in the main table.
11640ca3e24bSdrh **
1165b419a926Sdrh ** The arguments to this routine should be the same as the first six
11664adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
11670ca3e24bSdrh */
11684adee20fSdanielk1977 void sqlite3CompleteInsertion(
11690ca3e24bSdrh   Parse *pParse,      /* The parser context */
11700ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
11710ca3e24bSdrh   int base,           /* Index of a read/write cursor pointing at pTab */
11720ca3e24bSdrh   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
1173f0863fe5Sdrh   int rowidChng,      /* True if the record number will change */
117470ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
117570ce3f0cSdrh   int newIdx          /* Index of NEW table for triggers.  -1 if none */
11760ca3e24bSdrh ){
11770ca3e24bSdrh   int i;
11780ca3e24bSdrh   Vdbe *v;
11790ca3e24bSdrh   int nIdx;
11800ca3e24bSdrh   Index *pIdx;
1181b28af71aSdanielk1977   int pik_flags;
11820ca3e24bSdrh 
11834adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
11840ca3e24bSdrh   assert( v!=0 );
1185417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
11860ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
11870ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
11880ca3e24bSdrh     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
1189f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
11900ca3e24bSdrh   }
11914adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
1192a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1193b84f96f8Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
119470ce3f0cSdrh   if( newIdx>=0 ){
11954adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
11964adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1197f0863fe5Sdrh     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
119870ce3f0cSdrh   }
1199b84f96f8Sdanielk1977 #endif
12004794f735Sdrh   if( pParse->nested ){
12014794f735Sdrh     pik_flags = 0;
12024794f735Sdrh   }else{
120394eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
120494eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
12054794f735Sdrh   }
1206f0863fe5Sdrh   sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
120794eb6a14Sdanielk1977   if( !pParse->nested ){
120894eb6a14Sdanielk1977     sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
120994eb6a14Sdanielk1977   }
1210b28af71aSdanielk1977 
1211f0863fe5Sdrh   if( isUpdate && rowidChng ){
12124adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
12130ca3e24bSdrh   }
12140ca3e24bSdrh }
1215cd44690aSdrh 
1216cd44690aSdrh /*
1217290c1948Sdrh ** Generate code that will open cursors for a table and for all
1218cd44690aSdrh ** indices of that table.  The "base" parameter is the cursor number used
1219cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1220cd44690aSdrh */
1221290c1948Sdrh void sqlite3OpenTableAndIndices(
1222290c1948Sdrh   Parse *pParse,   /* Parsing context */
1223290c1948Sdrh   Table *pTab,     /* Table to be opened */
1224290c1948Sdrh   int base,        /* Cursor number assigned to the table */
1225290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1226290c1948Sdrh ){
1227cd44690aSdrh   int i;
12284cbdda9eSdrh   int iDb;
1229cd44690aSdrh   Index *pIdx;
12304cbdda9eSdrh   Vdbe *v;
12314cbdda9eSdrh 
12324cbdda9eSdrh   if( IsVirtual(pTab) ) return;
12334cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
12344cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1235cd44690aSdrh   assert( v!=0 );
1236c00da105Sdanielk1977   sqlite3OpenTable(pParse, base, iDb, pTab, op);
1237cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1238b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1239da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
1240da184236Sdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
124129dda4aeSdrh     VdbeComment((v, "# %s", pIdx->zName));
1242b3bf556eSdanielk1977     sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
1243cd44690aSdrh   }
1244290c1948Sdrh   if( pParse->nTab<=base+i ){
1245290c1948Sdrh     pParse->nTab = base+i;
1246290c1948Sdrh   }
1247cd44690aSdrh }
12489d9cf229Sdrh 
12499d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
12509d9cf229Sdrh /*
12519d9cf229Sdrh ** Check to collation names to see if they are compatible.
12529d9cf229Sdrh */
12539d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
12549d9cf229Sdrh   if( z1==0 ){
12559d9cf229Sdrh     return z2==0;
12569d9cf229Sdrh   }
12579d9cf229Sdrh   if( z2==0 ){
12589d9cf229Sdrh     return 0;
12599d9cf229Sdrh   }
12609d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
12619d9cf229Sdrh }
12629d9cf229Sdrh 
12639d9cf229Sdrh 
12649d9cf229Sdrh /*
12659d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
12669d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
12679d9cf229Sdrh ** for a compatible index:
12689d9cf229Sdrh **
12699d9cf229Sdrh **    *   The index is over the same set of columns
12709d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
12719d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
12729d9cf229Sdrh **    *   The same collating sequence on each column
12739d9cf229Sdrh */
12749d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
12759d9cf229Sdrh   int i;
12769d9cf229Sdrh   assert( pDest && pSrc );
12779d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
12789d9cf229Sdrh   if( pDest->nColumn!=pSrc->nColumn ){
12799d9cf229Sdrh     return 0;   /* Different number of columns */
12809d9cf229Sdrh   }
12819d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
12829d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
12839d9cf229Sdrh   }
12849d9cf229Sdrh   for(i=0; i<pSrc->nColumn; i++){
12859d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
12869d9cf229Sdrh       return 0;   /* Different columns indexed */
12879d9cf229Sdrh     }
12889d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
12899d9cf229Sdrh       return 0;   /* Different sort orders */
12909d9cf229Sdrh     }
12919d9cf229Sdrh     if( pSrc->azColl[i]!=pDest->azColl[i] ){
12929d9cf229Sdrh       return 0;   /* Different sort orders */
12939d9cf229Sdrh     }
12949d9cf229Sdrh   }
12959d9cf229Sdrh 
12969d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
12979d9cf229Sdrh   return 1;
12989d9cf229Sdrh }
12999d9cf229Sdrh 
1300dd73521bSdrh #ifdef SQLITE_TEST
1301dd73521bSdrh /*
1302dd73521bSdrh ** The following global variable is incremented whenever the
1303dd73521bSdrh ** transfer optimization is used.  This is used for testing
1304dd73521bSdrh ** purposes only - to make sure the transfer optimization really
1305dd73521bSdrh ** is happening when it is suppose to.
1306dd73521bSdrh */
1307dd73521bSdrh int sqlite3_xferopt_count;
1308dd73521bSdrh #endif /* SQLITE_TEST */
1309dd73521bSdrh 
13109d9cf229Sdrh /*
13119d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
13129d9cf229Sdrh **
13139d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
13149d9cf229Sdrh **
13159d9cf229Sdrh ** This optimization is only attempted if
13169d9cf229Sdrh **
13179d9cf229Sdrh **    (1)  tab1 and tab2 have identical schemas including all the
13188103b7d2Sdrh **         same indices and constraints
13199d9cf229Sdrh **
13209d9cf229Sdrh **    (2)  tab1 and tab2 are different tables
13219d9cf229Sdrh **
13229d9cf229Sdrh **    (3)  There must be no triggers on tab1
13239d9cf229Sdrh **
13249d9cf229Sdrh **    (4)  The result set of the SELECT statement is "*"
13259d9cf229Sdrh **
13269d9cf229Sdrh **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
13279d9cf229Sdrh **         or LIMIT clause.
13289d9cf229Sdrh **
13299d9cf229Sdrh **    (6)  The SELECT statement is a simple (not a compound) select that
13309d9cf229Sdrh **         contains only tab2 in its FROM clause
13319d9cf229Sdrh **
13329d9cf229Sdrh ** This method for implementing the INSERT transfers raw records from
13339d9cf229Sdrh ** tab2 over to tab1.  The columns are not decoded.  Raw records from
13349d9cf229Sdrh ** the indices of tab2 are transfered to tab1 as well.  In so doing,
13359d9cf229Sdrh ** the resulting tab1 has much less fragmentation.
13369d9cf229Sdrh **
13379d9cf229Sdrh ** This routine returns TRUE if the optimization is attempted.  If any
13389d9cf229Sdrh ** of the conditions above fail so that the optimization should not
13399d9cf229Sdrh ** be attempted, then this routine returns FALSE.
13409d9cf229Sdrh */
13419d9cf229Sdrh static int xferOptimization(
13429d9cf229Sdrh   Parse *pParse,        /* Parser context */
13439d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
13449d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
13459d9cf229Sdrh   int onError,          /* How to handle constraint errors */
13469d9cf229Sdrh   int iDbDest           /* The database of pDest */
13479d9cf229Sdrh ){
13489d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
13499d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
13509d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
13519d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
13529d9cf229Sdrh   int i;                           /* Loop counter */
13539d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
13549d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
13559d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
13569d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
13579d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
13589d9cf229Sdrh   int memRowid;                    /* A memcell containing a rowid from pSrc */
13599d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
13609d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
13619d9cf229Sdrh   int counterMem;                  /* Memory register used by AUTOINC */
13629d9cf229Sdrh 
13639d9cf229Sdrh   if( pSelect==0 ){
13649d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
13659d9cf229Sdrh   }
13669d9cf229Sdrh   if( pDest->pTrigger ){
13679d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
13689d9cf229Sdrh   }
13699d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
13709d9cf229Sdrh   if( pDest->isVirtual ){
13719d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
13729d9cf229Sdrh   }
13739d9cf229Sdrh #endif
13749d9cf229Sdrh   if( onError==OE_Default ){
13759d9cf229Sdrh     onError = OE_Abort;
13769d9cf229Sdrh   }
13779d9cf229Sdrh   if( onError!=OE_Abort && onError!=OE_Rollback ){
13789d9cf229Sdrh     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
13799d9cf229Sdrh   }
13809d9cf229Sdrh   if( pSelect->pSrc==0 ){
13819d9cf229Sdrh     return 0;   /* SELECT must have a FROM clause */
13829d9cf229Sdrh   }
13839d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
13849d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
13859d9cf229Sdrh   }
13869d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
13879d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
13889d9cf229Sdrh   }
13899d9cf229Sdrh   if( pSelect->pWhere ){
13909d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
13919d9cf229Sdrh   }
13929d9cf229Sdrh   if( pSelect->pOrderBy ){
13939d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
13949d9cf229Sdrh   }
13958103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
13968103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
13979d9cf229Sdrh   if( pSelect->pGroupBy ){
13989d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
13999d9cf229Sdrh   }
14009d9cf229Sdrh   if( pSelect->pLimit ){
14019d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
14029d9cf229Sdrh   }
14038103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
14049d9cf229Sdrh   if( pSelect->pPrior ){
14059d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
14069d9cf229Sdrh   }
14079d9cf229Sdrh   if( pSelect->isDistinct ){
14089d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
14099d9cf229Sdrh   }
14109d9cf229Sdrh   pEList = pSelect->pEList;
14119d9cf229Sdrh   assert( pEList!=0 );
14129d9cf229Sdrh   if( pEList->nExpr!=1 ){
14139d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
14149d9cf229Sdrh   }
14159d9cf229Sdrh   assert( pEList->a[0].pExpr );
14169d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
14179d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
14189d9cf229Sdrh   }
14199d9cf229Sdrh 
14209d9cf229Sdrh   /* At this point we have established that the statement is of the
14219d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
14229d9cf229Sdrh   ** we have to check the semantics.
14239d9cf229Sdrh   */
14249d9cf229Sdrh   pItem = pSelect->pSrc->a;
14259d9cf229Sdrh   pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
14269d9cf229Sdrh   if( pSrc==0 ){
14279d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
14289d9cf229Sdrh   }
14299d9cf229Sdrh   if( pSrc==pDest ){
14309d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
14319d9cf229Sdrh   }
14329d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
14339d9cf229Sdrh   if( pSrc->isVirtual ){
14349d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
14359d9cf229Sdrh   }
14369d9cf229Sdrh #endif
14379d9cf229Sdrh   if( pSrc->pSelect ){
14389d9cf229Sdrh     return 0;   /* tab2 may not be a view */
14399d9cf229Sdrh   }
14409d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
14419d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
14429d9cf229Sdrh   }
14439d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
14449d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
14459d9cf229Sdrh   }
14469d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
14479d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
14489d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
14499d9cf229Sdrh     }
14509d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
14519d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
14529d9cf229Sdrh     }
14539d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
14549d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
14559d9cf229Sdrh     }
14569d9cf229Sdrh   }
14579d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
14589d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
14599d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
14609d9cf229Sdrh     }
14619d9cf229Sdrh     if( pSrcIdx==0 ){
14629d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
14639d9cf229Sdrh     }
14649d9cf229Sdrh   }
1465*fb658dedSdrh   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
14668103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
14678103b7d2Sdrh   }
14689d9cf229Sdrh 
14699d9cf229Sdrh   /* If we get this far, it means either:
14709d9cf229Sdrh   **
14719d9cf229Sdrh   **    *   We can always do the transfer if the table contains an
14729d9cf229Sdrh   **        an integer primary key
14739d9cf229Sdrh   **
14749d9cf229Sdrh   **    *   We can conditionally do the transfer if the destination
14759d9cf229Sdrh   **        table is empty.
14769d9cf229Sdrh   */
1477dd73521bSdrh #ifdef SQLITE_TEST
1478dd73521bSdrh   sqlite3_xferopt_count++;
1479dd73521bSdrh #endif
14809d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
14819d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
14829d9cf229Sdrh   iSrc = pParse->nTab++;
14839d9cf229Sdrh   iDest = pParse->nTab++;
14849d9cf229Sdrh   counterMem = autoIncBegin(pParse, iDbDest, pDest);
14859d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
14869d9cf229Sdrh   if( pDest->iPKey<0 ){
14879d9cf229Sdrh     /* The tables do not have an INTEGER PRIMARY KEY so that
14889d9cf229Sdrh     ** transfer optimization is only allowed if the destination
14899d9cf229Sdrh     ** table is initially empty
14909d9cf229Sdrh     */
14919d9cf229Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
14929d9cf229Sdrh     emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
14939d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
14949d9cf229Sdrh   }else{
14959d9cf229Sdrh     emptyDestTest = 0;
14969d9cf229Sdrh   }
14979d9cf229Sdrh   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
14989d9cf229Sdrh   emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
14999d9cf229Sdrh   memRowid = pParse->nMem++;
15009d9cf229Sdrh   sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
15019d9cf229Sdrh   sqlite3VdbeAddOp(v, OP_MemStore, memRowid, 1);
15029d9cf229Sdrh   addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
15039d9cf229Sdrh   sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
15049d9cf229Sdrh   addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
15059d9cf229Sdrh   sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
15069d9cf229Sdrh                     "PRIMARY KEY must be unique", P3_STATIC);
15079d9cf229Sdrh   sqlite3VdbeJumpHere(v, addr2);
15089d9cf229Sdrh   autoIncStep(pParse, counterMem);
15099d9cf229Sdrh   sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
15109d9cf229Sdrh   sqlite3VdbeOp3(v, OP_Insert, iDest, OPFLAG_NCHANGE|OPFLAG_LASTROWID,
15119d9cf229Sdrh                     pDest->zName, 0);
15129d9cf229Sdrh   sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
15139d9cf229Sdrh   autoIncEnd(pParse, iDbDest, pDest, counterMem);
15149d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
15159d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
15169d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
15179d9cf229Sdrh     }
15189d9cf229Sdrh     assert( pSrcIdx );
15199d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
15209d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
15219d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
15229d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
15239d9cf229Sdrh     VdbeComment((v, "# %s", pSrcIdx->zName));
15249d9cf229Sdrh     sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
15259d9cf229Sdrh                    (char*)pKey, P3_KEYINFO_HANDOFF);
15269d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
15279d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
15289d9cf229Sdrh     VdbeComment((v, "# %s", pDestIdx->zName));
15299d9cf229Sdrh     sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
15309d9cf229Sdrh                    (char*)pKey, P3_KEYINFO_HANDOFF);
15319d9cf229Sdrh     addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
15329d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
15339d9cf229Sdrh     if( pDestIdx->onError!=OE_None ){
15349d9cf229Sdrh       sqlite3VdbeAddOp(v, OP_MemLoad, memRowid, 0);
15359d9cf229Sdrh       addr2 = sqlite3VdbeAddOp(v, OP_IsUnique, iDest, 0);
15369d9cf229Sdrh       sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
15379d9cf229Sdrh                     "UNIQUE constraint failed", P3_STATIC);
15389d9cf229Sdrh       sqlite3VdbeJumpHere(v, addr2);
15399d9cf229Sdrh     }
15409d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 0);
15419d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
15429d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
15439d9cf229Sdrh   }
15449d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
15459d9cf229Sdrh   sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
15469d9cf229Sdrh   sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
15479d9cf229Sdrh   if( emptyDestTest ){
15489d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
15499d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
15509d9cf229Sdrh     sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
15519d9cf229Sdrh     return 0;
15529d9cf229Sdrh   }else{
15539d9cf229Sdrh     return 1;
15549d9cf229Sdrh   }
15559d9cf229Sdrh }
15569d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
1557