xref: /sqlite-3.40.0/src/insert.c (revision cd3e8f7c)
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*cd3e8f7cSdanielk1977 ** $Id: insert.c,v 1.233 2008/03/25 09:47:35 danielk1977 Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19cce7d176Sdrh /*
2066a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
21a37cdde0Sdanielk1977 ** string for index pIdx. A column affinity string has one character
223d1bfeaaSdanielk1977 ** for each column in the table, according to the affinity of the column:
233d1bfeaaSdanielk1977 **
243d1bfeaaSdanielk1977 **  Character      Column affinity
253d1bfeaaSdanielk1977 **  ------------------------------
263eda040bSdrh **  'a'            TEXT
273eda040bSdrh **  'b'            NONE
283eda040bSdrh **  'c'            NUMERIC
293eda040bSdrh **  'd'            INTEGER
303eda040bSdrh **  'e'            REAL
312d401ab8Sdrh **
322d401ab8Sdrh ** An extra 'b' is appended to the end of the string to cover the
332d401ab8Sdrh ** rowid that appears as the last column in every index.
343d1bfeaaSdanielk1977 */
35a37cdde0Sdanielk1977 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
36a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
37e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
38a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
39e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
40a37cdde0Sdanielk1977     **
41a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
42e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
43a37cdde0Sdanielk1977     ** up.
44a37cdde0Sdanielk1977     */
45a37cdde0Sdanielk1977     int n;
46a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
47abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
482d401ab8Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+2);
49a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
50a37cdde0Sdanielk1977       return;
51a37cdde0Sdanielk1977     }
52a37cdde0Sdanielk1977     for(n=0; n<pIdx->nColumn; n++){
53a37cdde0Sdanielk1977       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
54a37cdde0Sdanielk1977     }
552d401ab8Sdrh     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
562d401ab8Sdrh     pIdx->zColAff[n] = 0;
57a37cdde0Sdanielk1977   }
583d1bfeaaSdanielk1977 
5966a5167bSdrh   sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
60a37cdde0Sdanielk1977 }
61a37cdde0Sdanielk1977 
62a37cdde0Sdanielk1977 /*
6366a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
64a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
65a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
66a37cdde0Sdanielk1977 ** column:
67a37cdde0Sdanielk1977 **
68a37cdde0Sdanielk1977 **  Character      Column affinity
69a37cdde0Sdanielk1977 **  ------------------------------
703eda040bSdrh **  'a'            TEXT
713eda040bSdrh **  'b'            NONE
723eda040bSdrh **  'c'            NUMERIC
733eda040bSdrh **  'd'            INTEGER
743eda040bSdrh **  'e'            REAL
75a37cdde0Sdanielk1977 */
76a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
773d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
783d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
793d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
803d1bfeaaSdanielk1977   **
813d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
823d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
833d1bfeaaSdanielk1977   */
843d1bfeaaSdanielk1977   if( !pTab->zColAff ){
853d1bfeaaSdanielk1977     char *zColAff;
863d1bfeaaSdanielk1977     int i;
87abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
883d1bfeaaSdanielk1977 
8917435752Sdrh     zColAff = (char *)sqlite3DbMallocZero(db, pTab->nCol+1);
903d1bfeaaSdanielk1977     if( !zColAff ){
91a37cdde0Sdanielk1977       return;
923d1bfeaaSdanielk1977     }
933d1bfeaaSdanielk1977 
943d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
95a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
963d1bfeaaSdanielk1977     }
973d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
983d1bfeaaSdanielk1977 
993d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1003d1bfeaaSdanielk1977   }
1013d1bfeaaSdanielk1977 
10266a5167bSdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
1033d1bfeaaSdanielk1977 }
1043d1bfeaaSdanielk1977 
1054d88778bSdanielk1977 /*
10648d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
10748d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
10848d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
10948d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
11048d1178aSdrh ** run without using temporary table for the results of the SELECT.
1114d88778bSdanielk1977 */
11248d1178aSdrh static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
1134d88778bSdanielk1977   int i;
11448d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
11548d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
11648d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
117ef0bea92Sdrh     assert( pOp!=0 );
118207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
11948d1178aSdrh       Index *pIndex;
120207872a4Sdanielk1977       int tnum = pOp->p2;
12148d1178aSdrh       if( tnum==pTab->tnum ){
12248d1178aSdrh         return 1;
12348d1178aSdrh       }
12448d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
12548d1178aSdrh         if( tnum==pIndex->tnum ){
12648d1178aSdrh           return 1;
12748d1178aSdrh         }
12848d1178aSdrh       }
12948d1178aSdrh     }
130543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1312dca4ac1Sdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
1322dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
13366a5167bSdrh       assert( pOp->p4type==P4_VTAB );
13448d1178aSdrh       return 1;
1354d88778bSdanielk1977     }
136543165efSdrh #endif
1374d88778bSdanielk1977   }
1384d88778bSdanielk1977   return 0;
1394d88778bSdanielk1977 }
1403d1bfeaaSdanielk1977 
1419d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1429d9cf229Sdrh /*
1439d9cf229Sdrh ** Write out code to initialize the autoincrement logic.  This code
1449d9cf229Sdrh ** looks up the current autoincrement value in the sqlite_sequence
1456a288a33Sdrh ** table and stores that value in a register.  Code generated by
1466a288a33Sdrh ** autoIncStep() will keep that register holding the largest
1479d9cf229Sdrh ** rowid value.  Code generated by autoIncEnd() will write the new
1489d9cf229Sdrh ** largest value of the counter back into the sqlite_sequence table.
1499d9cf229Sdrh **
1509d9cf229Sdrh ** This routine returns the index of the mem[] cell that contains
1519d9cf229Sdrh ** the maximum rowid counter.
1529d9cf229Sdrh **
1536a288a33Sdrh ** Three consecutive registers are allocated by this routine.  The
1546a288a33Sdrh ** first two hold the name of the target table and the maximum rowid
1556a288a33Sdrh ** inserted into the target table, respectively.
1566a288a33Sdrh ** The third holds the rowid in sqlite_sequence where we will
1576a288a33Sdrh ** write back the revised maximum rowid.  This routine returns the
1586a288a33Sdrh ** index of the second of these three registers.
1599d9cf229Sdrh */
1609d9cf229Sdrh static int autoIncBegin(
1619d9cf229Sdrh   Parse *pParse,      /* Parsing context */
1629d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
1639d9cf229Sdrh   Table *pTab         /* The table we are writing to */
1649d9cf229Sdrh ){
1656a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
1669d9cf229Sdrh   if( pTab->autoInc ){
1679d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
1689d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
1699d9cf229Sdrh     int iCur = pParse->nTab;
1706a288a33Sdrh     int addr;               /* Address of the top of the loop */
1719d9cf229Sdrh     assert( v );
1726a288a33Sdrh     pParse->nMem++;         /* Holds name of table */
1736a288a33Sdrh     memId = ++pParse->nMem;
1746a288a33Sdrh     pParse->nMem++;
1759d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
1766a288a33Sdrh     addr = sqlite3VdbeCurrentAddr(v);
1771db639ceSdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
1786a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+8);
1791db639ceSdrh     sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
1801db639ceSdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
18135573356Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
1826a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
1836a288a33Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
1846a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+8);
1851db639ceSdrh     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
18666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
1879d9cf229Sdrh   }
1889d9cf229Sdrh   return memId;
1899d9cf229Sdrh }
1909d9cf229Sdrh 
1919d9cf229Sdrh /*
1929d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
1939d9cf229Sdrh **
1949d9cf229Sdrh ** This routine should be called when the top of the stack holds a
1959d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
1969d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
1979d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
1989d9cf229Sdrh */
1996a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2009d9cf229Sdrh   if( memId>0 ){
2016a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2029d9cf229Sdrh   }
2039d9cf229Sdrh }
2049d9cf229Sdrh 
2059d9cf229Sdrh /*
2069d9cf229Sdrh ** After doing one or more inserts, the maximum rowid is stored
2076a288a33Sdrh ** in reg[memId].  Generate code to write this value back into the
2089d9cf229Sdrh ** the sqlite_sequence table.
2099d9cf229Sdrh */
2109d9cf229Sdrh static void autoIncEnd(
2119d9cf229Sdrh   Parse *pParse,     /* The parsing context */
2129d9cf229Sdrh   int iDb,           /* Index of the database holding pTab */
2139d9cf229Sdrh   Table *pTab,       /* Table we are inserting into */
2149d9cf229Sdrh   int memId          /* Memory cell holding the maximum rowid */
2159d9cf229Sdrh ){
2169d9cf229Sdrh   if( pTab->autoInc ){
2179d9cf229Sdrh     int iCur = pParse->nTab;
2189d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
2199d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
2206a288a33Sdrh     int j1;
221a7a8e14bSdanielk1977     int iRec = ++pParse->nMem;    /* Memory cell used for record */
2226a288a33Sdrh 
2239d9cf229Sdrh     assert( v );
2249d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
2256a288a33Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
2266a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
2276a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
228a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
229a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
23035573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
2316a288a33Sdrh     sqlite3VdbeAddOp1(v, OP_Close, iCur);
2329d9cf229Sdrh   }
2339d9cf229Sdrh }
2349d9cf229Sdrh #else
2359d9cf229Sdrh /*
2369d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
2379d9cf229Sdrh ** above are all no-ops
2389d9cf229Sdrh */
2399d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
240287fb61cSdanielk1977 # define autoIncStep(A,B,C)
2419d9cf229Sdrh # define autoIncEnd(A,B,C,D)
2429d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
2439d9cf229Sdrh 
2449d9cf229Sdrh 
2459d9cf229Sdrh /* Forward declaration */
2469d9cf229Sdrh static int xferOptimization(
2479d9cf229Sdrh   Parse *pParse,        /* Parser context */
2489d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
2499d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
2509d9cf229Sdrh   int onError,          /* How to handle constraint errors */
2519d9cf229Sdrh   int iDbDest           /* The database of pDest */
2529d9cf229Sdrh );
2539d9cf229Sdrh 
2543d1bfeaaSdanielk1977 /*
2551ccde15dSdrh ** This routine is call to handle SQL of the following forms:
256cce7d176Sdrh **
257cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
2581ccde15dSdrh **    insert into TABLE (IDLIST) select
259cce7d176Sdrh **
2601ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
2611ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
262967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
2631ccde15dSdrh **
2641ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
2651ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
2661ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
2671ccde15dSdrh ** data for the insert.
268142e30dfSdrh **
2699d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
270142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
271142e30dfSdrh ** once straight down through.  The template looks like this:
272142e30dfSdrh **
273142e30dfSdrh **         open write cursor to <table> and its indices
274142e30dfSdrh **         puts VALUES clause expressions onto the stack
275142e30dfSdrh **         write the resulting record into <table>
276142e30dfSdrh **         cleanup
277142e30dfSdrh **
2789d9cf229Sdrh ** The three remaining templates assume the statement is of the form
279142e30dfSdrh **
280142e30dfSdrh **   INSERT INTO <table> SELECT ...
281142e30dfSdrh **
2829d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
2839d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
2849d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
2859d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
2869d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
2879d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
2889d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
2899d9cf229Sdrh ** template.  This is the second template.
2909d9cf229Sdrh **
2919d9cf229Sdrh **         open a write cursor to <table>
2929d9cf229Sdrh **         open read cursor on <table2>
2939d9cf229Sdrh **         transfer all records in <table2> over to <table>
2949d9cf229Sdrh **         close cursors
2959d9cf229Sdrh **         foreach index on <table>
2969d9cf229Sdrh **           open a write cursor on the <table> index
2979d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
2989d9cf229Sdrh **           transfer all records from the read to the write cursors
2999d9cf229Sdrh **           close cursors
3009d9cf229Sdrh **         end foreach
3019d9cf229Sdrh **
3029d9cf229Sdrh ** The third template is for when the second template does not apply
3039d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
3049d9cf229Sdrh ** The generated code follows this template:
305142e30dfSdrh **
306142e30dfSdrh **         goto B
307142e30dfSdrh **      A: setup for the SELECT
3089d9cf229Sdrh **         loop over the rows in the SELECT
309142e30dfSdrh **           gosub C
310142e30dfSdrh **         end loop
311142e30dfSdrh **         cleanup after the SELECT
312142e30dfSdrh **         goto D
313142e30dfSdrh **      B: open write cursor to <table> and its indices
314142e30dfSdrh **         goto A
315142e30dfSdrh **      C: insert the select result into <table>
316142e30dfSdrh **         return
317142e30dfSdrh **      D: cleanup
318142e30dfSdrh **
3199d9cf229Sdrh ** The fourth template is used if the insert statement takes its
320142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
321142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
322142e30dfSdrh ** we have to use a intermediate table to store the results of
323142e30dfSdrh ** the select.  The template is like this:
324142e30dfSdrh **
325142e30dfSdrh **         goto B
326142e30dfSdrh **      A: setup for the SELECT
327142e30dfSdrh **         loop over the tables in the SELECT
328142e30dfSdrh **           gosub C
329142e30dfSdrh **         end loop
330142e30dfSdrh **         cleanup after the SELECT
331142e30dfSdrh **         goto D
332142e30dfSdrh **      C: insert the select result into the intermediate table
333142e30dfSdrh **         return
334142e30dfSdrh **      B: open a cursor to an intermediate table
335142e30dfSdrh **         goto A
336142e30dfSdrh **      D: open write cursor to <table> and its indices
337142e30dfSdrh **         loop over the intermediate table
338142e30dfSdrh **           transfer values form intermediate table into <table>
339142e30dfSdrh **         end the loop
340142e30dfSdrh **         cleanup
341cce7d176Sdrh */
3424adee20fSdanielk1977 void sqlite3Insert(
343cce7d176Sdrh   Parse *pParse,        /* Parser context */
344113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
345cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
3465974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
3479cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
3489cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
349cce7d176Sdrh ){
3506a288a33Sdrh   sqlite3 *db;          /* The main database structure */
3516a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
352113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
353e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
3545974a30fSdrh   int i, j, idx;        /* Loop counters */
3555974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
3565974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
357967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
3586a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
35904adf416Sdrh   int baseCur = 0;      /* VDBE Cursor number for pTab */
3604a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
3610ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
3624d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
363cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
3646a288a33Sdrh   int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
365cfe9a69fSdanielk1977   int iSelectLoop = 0;  /* Address of code that implements the SELECT */
366cfe9a69fSdanielk1977   int iCleanup = 0;     /* Address of the cleanup code */
367cfe9a69fSdanielk1977   int iInsertBlock = 0; /* Address of the subroutine used to insert data */
3686a288a33Sdrh   int newIdx = -1;      /* Cursor for the NEW pseudo-table */
3696a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
3702958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
371e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
372cce7d176Sdrh 
3736a288a33Sdrh   /* Register allocations */
3746a288a33Sdrh   int regFromSelect;    /* Base register for data coming from SELECT */
3756a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
3766a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
3776a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
3786a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
3796a288a33Sdrh   int regData;          /* register holding first column to insert */
3806a288a33Sdrh   int regRecord;        /* Holds the assemblied row record */
381aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
3826a288a33Sdrh 
383034ca14fSdanielk1977 
384798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
385798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
386dca76841Sdrh   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
387798da52cSdrh #endif
388c3f9bad2Sdanielk1977 
38917435752Sdrh   db = pParse->db;
39017435752Sdrh   if( pParse->nErr || db->mallocFailed ){
3916f7adc8aSdrh     goto insert_cleanup;
3926f7adc8aSdrh   }
393daffd0e5Sdrh 
3941ccde15dSdrh   /* Locate the table into which we will be inserting new information.
3951ccde15dSdrh   */
396113088ecSdrh   assert( pTabList->nSrc==1 );
397113088ecSdrh   zTab = pTabList->a[0].zName;
398daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
3994adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
400c3f9bad2Sdanielk1977   if( pTab==0 ){
401c3f9bad2Sdanielk1977     goto insert_cleanup;
402c3f9bad2Sdanielk1977   }
403da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
404da184236Sdanielk1977   assert( iDb<db->nDb );
405da184236Sdanielk1977   pDb = &db->aDb[iDb];
4062958a4e6Sdrh   zDb = pDb->zName;
4074adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
4081962bda7Sdrh     goto insert_cleanup;
4091962bda7Sdrh   }
410c3f9bad2Sdanielk1977 
411b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
412b7f9164eSdrh   ** inserted into is a view
413b7f9164eSdrh   */
414b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
415dca76841Sdrh   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
416b7f9164eSdrh   isView = pTab->pSelect!=0;
417b7f9164eSdrh #else
418dca76841Sdrh # define triggers_exist 0
419b7f9164eSdrh # define isView 0
420b7f9164eSdrh #endif
421b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
422b7f9164eSdrh # undef isView
423b7f9164eSdrh # define isView 0
424b7f9164eSdrh #endif
425b7f9164eSdrh 
426c3f9bad2Sdanielk1977   /* Ensure that:
427c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
428c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
429c3f9bad2Sdanielk1977   */
430dca76841Sdrh   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
431c3f9bad2Sdanielk1977     goto insert_cleanup;
432c3f9bad2Sdanielk1977   }
43343617e9aSdrh   assert( pTab!=0 );
4341ccde15dSdrh 
435f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
436b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
437b3d24bf8Sdanielk1977   ** module table).
438f573c99bSdrh   */
439b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
440f573c99bSdrh     goto insert_cleanup;
441f573c99bSdrh   }
442f573c99bSdrh 
4431ccde15dSdrh   /* Allocate a VDBE
4441ccde15dSdrh   */
4454adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
4465974a30fSdrh   if( v==0 ) goto insert_cleanup;
4474794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
448da184236Sdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
4491ccde15dSdrh 
450c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
451dca76841Sdrh   if( triggers_exist ){
452c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
453f29ce559Sdanielk1977   }
454c3f9bad2Sdanielk1977 
4559d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
4569d9cf229Sdrh   /* If the statement is of the form
4579d9cf229Sdrh   **
4589d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
4599d9cf229Sdrh   **
4609d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
4619d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
4629d9cf229Sdrh   */
4639d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
4649d9cf229Sdrh     assert( !triggers_exist );
4659d9cf229Sdrh     assert( pList==0 );
4669d9cf229Sdrh     goto insert_cleanup;
4679d9cf229Sdrh   }
4689d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
4699d9cf229Sdrh 
4702958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
4716a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
4722958a4e6Sdrh   */
4736a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
4742958a4e6Sdrh 
4751ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
476142e30dfSdrh   ** is coming from a SELECT statement, then this step also generates
477142e30dfSdrh   ** all the code to implement the SELECT statement and invoke a subroutine
478142e30dfSdrh   ** to process each row of the result. (Template 2.) If the SELECT
479142e30dfSdrh   ** statement uses the the table that is being inserted into, then the
480142e30dfSdrh   ** subroutine is also coded here.  That subroutine stores the SELECT
481142e30dfSdrh   ** results in a temporary table. (Template 3.)
4821ccde15dSdrh   */
4835974a30fSdrh   if( pSelect ){
484142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
485142e30dfSdrh     */
4861013c932Sdrh     SelectDest dest;
487142e30dfSdrh     int rc, iInitCode;
4881013c932Sdrh 
48966a5167bSdrh     iInitCode = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
4904adee20fSdanielk1977     iSelectLoop = sqlite3VdbeCurrentAddr(v);
4914adee20fSdanielk1977     iInsertBlock = sqlite3VdbeMakeLabel(v);
4921013c932Sdrh     sqlite3SelectDestInit(&dest, SRT_Subroutine, iInsertBlock);
493b3bce662Sdanielk1977 
494b3bce662Sdanielk1977     /* Resolve the expressions in the SELECT statement and execute it. */
4956c8c8ce0Sdanielk1977     rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
49617435752Sdrh     if( rc || pParse->nErr || db->mallocFailed ){
4976f7adc8aSdrh       goto insert_cleanup;
4986f7adc8aSdrh     }
499b3bce662Sdanielk1977 
5006a288a33Sdrh     regFromSelect = dest.iMem;
5014adee20fSdanielk1977     iCleanup = sqlite3VdbeMakeLabel(v);
50266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, iCleanup);
5035974a30fSdrh     assert( pSelect->pEList );
504967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
505142e30dfSdrh 
506142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
507142e30dfSdrh     ** should be written into a temporary table.  Set to FALSE if each
508142e30dfSdrh     ** row of the SELECT can be written directly into the result table.
509048c530cSdrh     **
510048c530cSdrh     ** A temp table must be used if the table being updated is also one
511048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
512048c530cSdrh     ** temp table in the case of row triggers.
513142e30dfSdrh     */
51448d1178aSdrh     if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
515048c530cSdrh       useTempTable = 1;
516048c530cSdrh     }
517142e30dfSdrh 
518142e30dfSdrh     if( useTempTable ){
519142e30dfSdrh       /* Generate the subroutine that SELECT calls to process each row of
520142e30dfSdrh       ** the result.  Store the result in a temporary table
521142e30dfSdrh       */
522b7654111Sdrh       int regRec, regRowid;
523b7654111Sdrh 
524142e30dfSdrh       srcTab = pParse->nTab++;
525b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
526b7654111Sdrh       regRowid = sqlite3GetTempReg(pParse);
5274adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iInsertBlock);
5281db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
529b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid);
530b7654111Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid);
53166a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
532b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
533b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRowid);
534142e30dfSdrh 
535142e30dfSdrh       /* The following code runs first because the GOTO at the very top
536142e30dfSdrh       ** of the program jumps to it.  Create the temporary table, then jump
537142e30dfSdrh       ** back up and execute the SELECT code above.
538142e30dfSdrh       */
539d654be80Sdrh       sqlite3VdbeJumpHere(v, iInitCode);
540*cd3e8f7cSdanielk1977       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
54166a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
5424adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCleanup);
5435974a30fSdrh     }else{
544d654be80Sdrh       sqlite3VdbeJumpHere(v, iInitCode);
545142e30dfSdrh     }
546142e30dfSdrh   }else{
547142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
548142e30dfSdrh     ** clause
549142e30dfSdrh     */
550b3bce662Sdanielk1977     NameContext sNC;
551b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
552b3bce662Sdanielk1977     sNC.pParse = pParse;
5535974a30fSdrh     srcTab = -1;
55448d1178aSdrh     assert( useTempTable==0 );
555147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
556e64e7b20Sdrh     for(i=0; i<nColumn; i++){
557b3bce662Sdanielk1977       if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
558b04a5d87Sdrh         goto insert_cleanup;
559b04a5d87Sdrh       }
560e64e7b20Sdrh     }
5615974a30fSdrh   }
5621ccde15dSdrh 
5631ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
5641ccde15dSdrh   ** of columns to be inserted into the table.
5651ccde15dSdrh   */
566034ca14fSdanielk1977   if( IsVirtual(pTab) ){
567034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
568034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
569034ca14fSdanielk1977     }
570034ca14fSdanielk1977   }
571034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
5724adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
573da93d238Sdrh        "table %S has %d columns but %d values were supplied",
574da93d238Sdrh        pTabList, 0, pTab->nCol, nColumn);
575cce7d176Sdrh     goto insert_cleanup;
576cce7d176Sdrh   }
577967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
5784adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
579cce7d176Sdrh     goto insert_cleanup;
580cce7d176Sdrh   }
5811ccde15dSdrh 
5821ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
5831ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
5841ccde15dSdrh   ** remember the column indices.
585c8392586Sdrh   **
586c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
587c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
588c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
589c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
590c8392586Sdrh   ** is appears in the original table.  (The index of the primary
591c8392586Sdrh   ** key in the original table is pTab->iPKey.)
5921ccde15dSdrh   */
593967e8b73Sdrh   if( pColumn ){
594967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
595967e8b73Sdrh       pColumn->a[i].idx = -1;
596cce7d176Sdrh     }
597967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
598cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
5994adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
600967e8b73Sdrh           pColumn->a[i].idx = j;
6014a32431cSdrh           if( j==pTab->iPKey ){
6029aa028daSdrh             keyColumn = i;
6034a32431cSdrh           }
604cce7d176Sdrh           break;
605cce7d176Sdrh         }
606cce7d176Sdrh       }
607cce7d176Sdrh       if( j>=pTab->nCol ){
6084adee20fSdanielk1977         if( sqlite3IsRowid(pColumn->a[i].zName) ){
609a0217ba7Sdrh           keyColumn = i;
610a0217ba7Sdrh         }else{
6114adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
612da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
613cce7d176Sdrh           pParse->nErr++;
614cce7d176Sdrh           goto insert_cleanup;
615cce7d176Sdrh         }
616cce7d176Sdrh       }
617cce7d176Sdrh     }
618a0217ba7Sdrh   }
6191ccde15dSdrh 
620aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
621c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
622c8392586Sdrh   ** in the original table definition.
6234a32431cSdrh   */
624147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
6254a32431cSdrh     keyColumn = pTab->iPKey;
6264a32431cSdrh   }
6274a32431cSdrh 
628142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
629142e30dfSdrh   */
630dca76841Sdrh   if( triggers_exist ){
631*cd3e8f7cSdanielk1977     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
63266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
633f29ce559Sdanielk1977   }
634c3f9bad2Sdanielk1977 
635c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
6361ccde15dSdrh   */
637142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
6386a288a33Sdrh     regRowCount = ++pParse->nMem;
6396a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
640c3f9bad2Sdanielk1977   }
641c3f9bad2Sdanielk1977 
642e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
643e448dc4aSdanielk1977   if( !isView ){
644aa9b8963Sdrh     int nIdx;
645aa9b8963Sdrh     int i;
646aa9b8963Sdrh 
64704adf416Sdrh     baseCur = pParse->nTab;
64804adf416Sdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
649aa9b8963Sdrh     aRegIdx = sqlite3DbMallocZero(db, sizeof(int)*(nIdx+1));
650aa9b8963Sdrh     if( aRegIdx==0 ){
651aa9b8963Sdrh       goto insert_cleanup;
652aa9b8963Sdrh     }
653aa9b8963Sdrh     for(i=0; i<nIdx; i++){
654aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
655aa9b8963Sdrh     }
656feeb1394Sdrh   }
657feeb1394Sdrh 
658142e30dfSdrh   /* If the data source is a temporary table, then we have to create
6591ccde15dSdrh   ** a loop because there might be multiple rows of data.  If the data
660142e30dfSdrh   ** source is a subroutine call from the SELECT statement, then we need
661142e30dfSdrh   ** to launch the SELECT statement processing.
6621ccde15dSdrh   */
663142e30dfSdrh   if( useTempTable ){
6644adee20fSdanielk1977     iBreak = sqlite3VdbeMakeLabel(v);
66566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Rewind, srcTab, iBreak);
6664adee20fSdanielk1977     iCont = sqlite3VdbeCurrentAddr(v);
667142e30dfSdrh   }else if( pSelect ){
66866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
6694adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iInsertBlock);
670bed8690fSdrh   }
6711ccde15dSdrh 
6726a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
6736a288a33Sdrh   ** the content of the new row, and the assemblied row record.
6746a288a33Sdrh   */
6756a288a33Sdrh   regRecord = ++pParse->nMem;
6766a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
6776a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
6786a288a33Sdrh   if( IsVirtual(pTab) ){
6796a288a33Sdrh     regRowid++;
6806a288a33Sdrh     pParse->nMem++;
6816a288a33Sdrh   }
6826a288a33Sdrh   regData = regRowid+1;
6836a288a33Sdrh 
6845cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
68570ce3f0cSdrh   */
6864adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
687dca76841Sdrh   if( triggers_exist & TRIGGER_BEFORE ){
6882d401ab8Sdrh     int regRowid;
6892d401ab8Sdrh     int regCols;
6902d401ab8Sdrh     int regRec;
691c3f9bad2Sdanielk1977 
69270ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
69370ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
69470ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
69570ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
69670ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
69770ce3f0cSdrh     */
6982d401ab8Sdrh     regRowid = sqlite3GetTempReg(pParse);
69970ce3f0cSdrh     if( keyColumn<0 ){
7002d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
70170ce3f0cSdrh     }else if( useTempTable ){
7022d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
70370ce3f0cSdrh     }else{
7046a288a33Sdrh       int j1;
705d6fe961eSdrh       assert( pSelect==0 );  /* Otherwise useTempTable is true */
7062d401ab8Sdrh       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
7072d401ab8Sdrh       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
7082d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
7096a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
7102d401ab8Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
71170ce3f0cSdrh     }
71270ce3f0cSdrh 
713034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
714034ca14fSdanielk1977     ** this block would have to account for hidden column.
715034ca14fSdanielk1977     */
716034ca14fSdanielk1977     assert(!IsVirtual(pTab));
717034ca14fSdanielk1977 
71870ce3f0cSdrh     /* Create the new column data
71970ce3f0cSdrh     */
7202d401ab8Sdrh     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
721c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
722c3f9bad2Sdanielk1977       if( pColumn==0 ){
723c3f9bad2Sdanielk1977         j = i;
724c3f9bad2Sdanielk1977       }else{
725c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
726c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
727c3f9bad2Sdanielk1977         }
728c3f9bad2Sdanielk1977       }
729c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
7302d401ab8Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
731142e30dfSdrh       }else if( useTempTable ){
7322d401ab8Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i);
733c3f9bad2Sdanielk1977       }else{
734d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
7352d401ab8Sdrh         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
736c3f9bad2Sdanielk1977       }
737c3f9bad2Sdanielk1977     }
7382d401ab8Sdrh     regRec = sqlite3GetTempReg(pParse);
7391db639ceSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
740a37cdde0Sdanielk1977 
741a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
742a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
743a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
744a37cdde0Sdanielk1977     ** table column affinities.
745a37cdde0Sdanielk1977     */
746a37cdde0Sdanielk1977     if( !isView ){
747a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
748a37cdde0Sdanielk1977     }
7492d401ab8Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
7502d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRec);
7512d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRowid);
7522d401ab8Sdrh     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
753c3f9bad2Sdanielk1977 
7545cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
755dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
7568f2c54e6Sdanielk1977         newIdx, -1, onError, endOfLoop, 0, 0) ){
757f29ce559Sdanielk1977       goto insert_cleanup;
758f29ce559Sdanielk1977     }
75970ce3f0cSdrh   }
760c3f9bad2Sdanielk1977 
7614a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
762f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
7634a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
764b419a926Sdrh   ** case the record number is the same as that column.
7651ccde15dSdrh   */
7665cf590c1Sdrh   if( !isView ){
7674cbdda9eSdrh     if( IsVirtual(pTab) ){
7684cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
7696a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
7704cbdda9eSdrh     }
7714a32431cSdrh     if( keyColumn>=0 ){
772142e30dfSdrh       if( useTempTable ){
7736a288a33Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
774142e30dfSdrh       }else if( pSelect ){
775b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
7764a32431cSdrh       }else{
777e4d90813Sdrh         VdbeOp *pOp;
7781db639ceSdrh         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
779e4d90813Sdrh         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
78001256832Sdanielk1977         if( pOp && pOp->opcode==OP_Null ){
781e4d90813Sdrh           appendFlag = 1;
782e4d90813Sdrh           pOp->opcode = OP_NewRowid;
78304adf416Sdrh           pOp->p1 = baseCur;
7846a288a33Sdrh           pOp->p2 = regRowid;
7856a288a33Sdrh           pOp->p3 = regAutoinc;
786e4d90813Sdrh         }
78727a32783Sdrh       }
788f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
789e1e68f49Sdrh       ** to generate a unique primary key value.
790e1e68f49Sdrh       */
791e4d90813Sdrh       if( !appendFlag ){
7921db639ceSdrh         int j1;
7931db639ceSdrh         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
79404adf416Sdrh         sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
7951db639ceSdrh         sqlite3VdbeJumpHere(v, j1);
7963c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
797e4d90813Sdrh       }
7984cbdda9eSdrh     }else if( IsVirtual(pTab) ){
7996a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
8004a32431cSdrh     }else{
80104adf416Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
802e4d90813Sdrh       appendFlag = 1;
8034a32431cSdrh     }
8046a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
8054a32431cSdrh 
806aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
8074a32431cSdrh     ** with the first column.
8084a32431cSdrh     */
809034ca14fSdanielk1977     nHidden = 0;
810cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
8116a288a33Sdrh       int iRegStore = regRowid+1+i;
8124a32431cSdrh       if( i==pTab->iPKey ){
8134a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
814aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
815aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
816aacc543eSdrh         ** taking up data space with information that will never be used. */
8174c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
8184a32431cSdrh         continue;
8194a32431cSdrh       }
820967e8b73Sdrh       if( pColumn==0 ){
821034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
822034ca14fSdanielk1977           assert( IsVirtual(pTab) );
823034ca14fSdanielk1977           j = -1;
824034ca14fSdanielk1977           nHidden++;
825034ca14fSdanielk1977         }else{
826034ca14fSdanielk1977           j = i - nHidden;
827034ca14fSdanielk1977         }
828cce7d176Sdrh       }else{
829967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
830967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
831cce7d176Sdrh         }
832cce7d176Sdrh       }
833034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
834287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
835142e30dfSdrh       }else if( useTempTable ){
836287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
837142e30dfSdrh       }else if( pSelect ){
838b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
839cce7d176Sdrh       }else{
840287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
841cce7d176Sdrh       }
842cce7d176Sdrh     }
8431ccde15dSdrh 
8440ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
8450ca3e24bSdrh     ** do the insertion.
8464a32431cSdrh     */
8474cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
8484cbdda9eSdrh     if( IsVirtual(pTab) ){
849f9e7dda7Sdanielk1977       pParse->pVirtualLock = pTab;
8506a288a33Sdrh       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
85166a5167bSdrh                      (const char*)pTab->pVtab, P4_VTAB);
8524cbdda9eSdrh     }else
8534cbdda9eSdrh #endif
8544cbdda9eSdrh     {
85504adf416Sdrh       sqlite3GenerateConstraintChecks(
85604adf416Sdrh           pParse,
85704adf416Sdrh           pTab,
85804adf416Sdrh           baseCur,
85904adf416Sdrh           regIns,
86004adf416Sdrh           aRegIdx,
86104adf416Sdrh           keyColumn>=0,
86204adf416Sdrh           0,
86304adf416Sdrh           onError,
86404adf416Sdrh           endOfLoop
86504adf416Sdrh       );
86604adf416Sdrh       sqlite3CompleteInsertion(
86704adf416Sdrh           pParse,
86804adf416Sdrh           pTab,
86904adf416Sdrh           baseCur,
87004adf416Sdrh           regIns,
87104adf416Sdrh           aRegIdx,
87204adf416Sdrh           0,
87304adf416Sdrh           0,
874e4d90813Sdrh           (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
87504adf416Sdrh           appendFlag
87604adf416Sdrh        );
8775cf590c1Sdrh     }
8784cbdda9eSdrh   }
8791bee3d7bSdrh 
880feeb1394Sdrh   /* Update the count of rows that are inserted
8811bee3d7bSdrh   */
882142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
8836a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
8841bee3d7bSdrh   }
885c3f9bad2Sdanielk1977 
886dca76841Sdrh   if( triggers_exist ){
887c3f9bad2Sdanielk1977     /* Code AFTER triggers */
888dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
8898f2c54e6Sdanielk1977           newIdx, -1, onError, endOfLoop, 0, 0) ){
890f29ce559Sdanielk1977       goto insert_cleanup;
891f29ce559Sdanielk1977     }
892c3f9bad2Sdanielk1977   }
8931bee3d7bSdrh 
8941ccde15dSdrh   /* The bottom of the loop, if the data source is a SELECT statement
8951ccde15dSdrh   */
8964adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
897142e30dfSdrh   if( useTempTable ){
89866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, iCont);
8994adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iBreak);
90066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, srcTab, 0);
901142e30dfSdrh   }else if( pSelect ){
90266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
9034adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, iCleanup);
9046b56344dSdrh   }
905c3f9bad2Sdanielk1977 
906e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
907c3f9bad2Sdanielk1977     /* Close all tables opened */
90804adf416Sdrh     sqlite3VdbeAddOp2(v, OP_Close, baseCur, 0);
9096b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
91004adf416Sdrh       sqlite3VdbeAddOp2(v, OP_Close, idx+baseCur, 0);
911cce7d176Sdrh     }
912c3f9bad2Sdanielk1977   }
913c3f9bad2Sdanielk1977 
914f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
9156a288a33Sdrh   ** counter value in memory regAutoinc back into the sqlite_sequence
916f3388144Sdrh   ** table.
9172958a4e6Sdrh   */
9186a288a33Sdrh   autoIncEnd(pParse, iDb, pTab, regAutoinc);
9192958a4e6Sdrh 
9201bee3d7bSdrh   /*
921e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
922e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
923e7de6f25Sdanielk1977   ** invoke the callback function.
9241bee3d7bSdrh   */
925cc6bd383Sdanielk1977   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
9266a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
92722322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
92866a5167bSdrh     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
9291bee3d7bSdrh   }
930cce7d176Sdrh 
931cce7d176Sdrh insert_cleanup:
9324adee20fSdanielk1977   sqlite3SrcListDelete(pTabList);
933d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
934d5d56523Sdanielk1977   sqlite3SelectDelete(pSelect);
9354adee20fSdanielk1977   sqlite3IdListDelete(pColumn);
936aa9b8963Sdrh   sqlite3_free(aRegIdx);
937cce7d176Sdrh }
9389cfcf5d4Sdrh 
9399cfcf5d4Sdrh /*
9406a288a33Sdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
9419cfcf5d4Sdrh **
94204adf416Sdrh ** The input is a range of consecutive registers as follows:
9430ca3e24bSdrh **
944f0863fe5Sdrh **    1.  The rowid of the row to be updated before the update.  This
945b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
946a05a722fSdrh **        change to the record number or writing to a virtual table.
9470ca3e24bSdrh **
948f0863fe5Sdrh **    2.  The rowid of the row after the update.
9490ca3e24bSdrh **
9500ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
9510ca3e24bSdrh **
9520ca3e24bSdrh **    i.  Data from middle columns...
9530ca3e24bSdrh **
9540ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
9550ca3e24bSdrh **
95604adf416Sdrh ** The regRowid parameter is the index of the register containing (2).
95704adf416Sdrh **
958f0863fe5Sdrh ** The old rowid shown as entry (1) above is omitted unless both isUpdate
959f0863fe5Sdrh ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
960a05a722fSdrh ** INSERTs.  RowidChng means that the new rowid is explicitly specified by
961a05a722fSdrh ** the update or insert statement.  If rowidChng is false, it means that
962a05a722fSdrh ** the rowid is computed automatically in an insert or that the rowid value
963a05a722fSdrh ** is not modified by the update.
9640ca3e24bSdrh **
965aa9b8963Sdrh ** The code generated by this routine store new index entries into
966aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
967aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
968aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
969aa9b8963Sdrh ** attached to the table.
9709cfcf5d4Sdrh **
9719cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
9729cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
9731c92853dSdrh ** then the appropriate action is performed.  There are five possible
9741c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
9759cfcf5d4Sdrh **
9769cfcf5d4Sdrh **  Constraint type  Action       What Happens
9779cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
9781c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
97924b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
9809cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
9819cfcf5d4Sdrh **
9821c92853dSdrh **  any              ABORT        Back out changes from the current command
9831c92853dSdrh **                                only (do not do a complete rollback) then
98424b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
9851c92853dSdrh **                                with SQLITE_CONSTRAINT.
9861c92853dSdrh **
9871c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
9881c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
9891c92853dSdrh **                                transaction is not rolled back and any
9901c92853dSdrh **                                prior changes are retained.
9911c92853dSdrh **
9929cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
9939cfcf5d4Sdrh **                                the stack and there is an immediate jump
9949cfcf5d4Sdrh **                                to label ignoreDest.
9959cfcf5d4Sdrh **
9969cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
9979cfcf5d4Sdrh **                                value for that column.  If the default value
9989cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
9999cfcf5d4Sdrh **
10009cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
10019cfcf5d4Sdrh **                                being inserted is removed.
10029cfcf5d4Sdrh **
10039cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
10049cfcf5d4Sdrh **
10051c92853dSdrh ** Which action to take is determined by the overrideError parameter.
10061c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
10071c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
10081c92853dSdrh ** for the constraint is used.
10099cfcf5d4Sdrh **
1010aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
101104adf416Sdrh ** cursor number "baseCur".  All indices of pTab must also have open
101204adf416Sdrh ** read/write cursors with cursor number baseCur+i for the i-th cursor.
10139cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
1014aa9b8963Sdrh ** cursors do not need to be open for indices where aRegIdx[i]==0.
10159cfcf5d4Sdrh */
10164adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
10179cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
10189cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
101904adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
102004adf416Sdrh   int regRowid,       /* Index of the range of input registers */
1021aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1022a05a722fSdrh   int rowidChng,      /* True if the rowid might collide with existing entry */
1023b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
10249cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
1025b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
10269cfcf5d4Sdrh ){
10279cfcf5d4Sdrh   int i;
10289cfcf5d4Sdrh   Vdbe *v;
10299cfcf5d4Sdrh   int nCol;
10309cfcf5d4Sdrh   int onError;
1031a05a722fSdrh   int j1, j2, j3;     /* Addresses of jump instructions */
103204adf416Sdrh   int regData;        /* Register containing first data column */
10330ca3e24bSdrh   int iCur;
10340ca3e24bSdrh   Index *pIdx;
10350ca3e24bSdrh   int seenReplace = 0;
1036f0863fe5Sdrh   int hasTwoRowids = (isUpdate && rowidChng);
10379cfcf5d4Sdrh 
10384adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
10399cfcf5d4Sdrh   assert( v!=0 );
1040417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
10419cfcf5d4Sdrh   nCol = pTab->nCol;
1042aa9b8963Sdrh   regData = regRowid + 1;
1043aa9b8963Sdrh 
104404adf416Sdrh 
10459cfcf5d4Sdrh   /* Test all NOT NULL constraints.
10469cfcf5d4Sdrh   */
10479cfcf5d4Sdrh   for(i=0; i<nCol; i++){
10480ca3e24bSdrh     if( i==pTab->iPKey ){
10490ca3e24bSdrh       continue;
10500ca3e24bSdrh     }
10519cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
10520ca3e24bSdrh     if( onError==OE_None ) continue;
10539cfcf5d4Sdrh     if( overrideError!=OE_Default ){
10549cfcf5d4Sdrh       onError = overrideError;
1055a996e477Sdrh     }else if( onError==OE_Default ){
1056a996e477Sdrh       onError = OE_Abort;
10579cfcf5d4Sdrh     }
10587977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
10599cfcf5d4Sdrh       onError = OE_Abort;
10609cfcf5d4Sdrh     }
1061aa9b8963Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
1062b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1063b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
10649cfcf5d4Sdrh     switch( onError ){
10651c92853dSdrh       case OE_Rollback:
10661c92853dSdrh       case OE_Abort:
10671c92853dSdrh       case OE_Fail: {
1068483750baSdrh         char *zMsg = 0;
106966a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
10704adee20fSdanielk1977         sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
107141743984Sdrh                         " may not be NULL", (char*)0);
107266a5167bSdrh         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
10739cfcf5d4Sdrh         break;
10749cfcf5d4Sdrh       }
10759cfcf5d4Sdrh       case OE_Ignore: {
107666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
10779cfcf5d4Sdrh         break;
10789cfcf5d4Sdrh       }
10799cfcf5d4Sdrh       case OE_Replace: {
108004adf416Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
10819cfcf5d4Sdrh         break;
10829cfcf5d4Sdrh       }
10839cfcf5d4Sdrh     }
1084aa9b8963Sdrh     sqlite3VdbeJumpHere(v, j1);
10859cfcf5d4Sdrh   }
10869cfcf5d4Sdrh 
10879cfcf5d4Sdrh   /* Test all CHECK constraints
10889cfcf5d4Sdrh   */
1089ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
10900cd2d4c9Sdrh   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
1091ffe07b2dSdrh     int allOk = sqlite3VdbeMakeLabel(v);
1092aa9b8963Sdrh     pParse->ckBase = regData;
109335573356Sdrh     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
1094aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
10952e06c67cSdrh     if( onError==OE_Ignore ){
109666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1097aa01c7e2Sdrh     }else{
109866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1099aa01c7e2Sdrh     }
1100ffe07b2dSdrh     sqlite3VdbeResolveLabel(v, allOk);
1101ffe07b2dSdrh   }
1102ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
11039cfcf5d4Sdrh 
11040bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
11050bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
11060bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
11079cfcf5d4Sdrh   */
1108f0863fe5Sdrh   if( rowidChng ){
11090ca3e24bSdrh     onError = pTab->keyConf;
11100ca3e24bSdrh     if( overrideError!=OE_Default ){
11110ca3e24bSdrh       onError = overrideError;
1112a996e477Sdrh     }else if( onError==OE_Default ){
1113a996e477Sdrh       onError = OE_Abort;
11140ca3e24bSdrh     }
1115a0217ba7Sdrh 
111660a713c6Sdrh     if( onError!=OE_Replace || pTab->pIndex ){
111779b0c956Sdrh       if( isUpdate ){
1118892d3179Sdrh         j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
111979b0c956Sdrh       }
112004adf416Sdrh       j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
11210ca3e24bSdrh       switch( onError ){
1122a0217ba7Sdrh         default: {
1123a0217ba7Sdrh           onError = OE_Abort;
1124a0217ba7Sdrh           /* Fall thru into the next case */
1125a0217ba7Sdrh         }
11261c92853dSdrh         case OE_Rollback:
11271c92853dSdrh         case OE_Abort:
11281c92853dSdrh         case OE_Fail: {
112966a5167bSdrh           sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
113066a5167bSdrh                            "PRIMARY KEY must be unique", P4_STATIC);
11310ca3e24bSdrh           break;
11320ca3e24bSdrh         }
11335383ae5cSdrh         case OE_Replace: {
11342d401ab8Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
11355383ae5cSdrh           seenReplace = 1;
11365383ae5cSdrh           break;
11375383ae5cSdrh         }
11380ca3e24bSdrh         case OE_Ignore: {
11395383ae5cSdrh           assert( seenReplace==0 );
114066a5167bSdrh           sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
11410ca3e24bSdrh           break;
11420ca3e24bSdrh         }
11430ca3e24bSdrh       }
1144aa9b8963Sdrh       sqlite3VdbeJumpHere(v, j3);
1145f5905aa7Sdrh       if( isUpdate ){
1146aa9b8963Sdrh         sqlite3VdbeJumpHere(v, j2);
1147a05a722fSdrh       }
11480ca3e24bSdrh     }
11490ca3e24bSdrh   }
11500bd1f4eaSdrh 
11510bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
11520bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
11530bd1f4eaSdrh   ** Add the new records to the indices as we go.
11540bd1f4eaSdrh   */
1155b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
11562d401ab8Sdrh     int regIdx;
11572d401ab8Sdrh     int regR;
11582d401ab8Sdrh 
1159aa9b8963Sdrh     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
1160b2fe7d8cSdrh 
1161b2fe7d8cSdrh     /* Create a key for accessing the index entry */
11622d401ab8Sdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
11639cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
11649cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
11659cfcf5d4Sdrh       if( idx==pTab->iPKey ){
11662d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
11679cfcf5d4Sdrh       }else{
11682d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
11699cfcf5d4Sdrh       }
11709cfcf5d4Sdrh     }
11712d401ab8Sdrh     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
11721db639ceSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
1173a37cdde0Sdanielk1977     sqlite3IndexAffinityStr(v, pIdx);
11742d401ab8Sdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
1175b2fe7d8cSdrh 
1176b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
11779cfcf5d4Sdrh     onError = pIdx->onError;
1178b2fe7d8cSdrh     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
11799cfcf5d4Sdrh     if( overrideError!=OE_Default ){
11809cfcf5d4Sdrh       onError = overrideError;
1181a996e477Sdrh     }else if( onError==OE_Default ){
1182a996e477Sdrh       onError = OE_Abort;
11839cfcf5d4Sdrh     }
11845383ae5cSdrh     if( seenReplace ){
11855383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
11865383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
11875383ae5cSdrh     }
11885383ae5cSdrh 
1189b2fe7d8cSdrh 
1190b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
11912d401ab8Sdrh     j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
11922d401ab8Sdrh     regR = sqlite3GetTempReg(pParse);
11932d401ab8Sdrh     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
11942d401ab8Sdrh     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
1195a9e852b6Smlcreech                            regR, (char*)(sqlite3_intptr_t)aRegIdx[iCur],
1196a9e852b6Smlcreech                            P4_INT32);
1197b2fe7d8cSdrh 
1198b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1199b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1200b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
12019cfcf5d4Sdrh     switch( onError ){
12021c92853dSdrh       case OE_Rollback:
12031c92853dSdrh       case OE_Abort:
12041c92853dSdrh       case OE_Fail: {
120537ed48edSdrh         int j, n1, n2;
120637ed48edSdrh         char zErrMsg[200];
12075bb3eb9bSdrh         sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
12085bb3eb9bSdrh                          pIdx->nColumn>1 ? "columns " : "column ");
120937ed48edSdrh         n1 = strlen(zErrMsg);
121037ed48edSdrh         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
121137ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
121237ed48edSdrh           n2 = strlen(zCol);
121337ed48edSdrh           if( j>0 ){
12145bb3eb9bSdrh             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
121537ed48edSdrh             n1 += 2;
121637ed48edSdrh           }
121737ed48edSdrh           if( n1+n2>sizeof(zErrMsg)-30 ){
12185bb3eb9bSdrh             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
121937ed48edSdrh             n1 += 3;
122037ed48edSdrh             break;
122137ed48edSdrh           }else{
12225bb3eb9bSdrh             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
122337ed48edSdrh             n1 += n2;
122437ed48edSdrh           }
122537ed48edSdrh         }
12265bb3eb9bSdrh         sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
122737ed48edSdrh             pIdx->nColumn>1 ? " are not unique" : " is not unique");
122866a5167bSdrh         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
12299cfcf5d4Sdrh         break;
12309cfcf5d4Sdrh       }
12319cfcf5d4Sdrh       case OE_Ignore: {
12320ca3e24bSdrh         assert( seenReplace==0 );
123366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
12349cfcf5d4Sdrh         break;
12359cfcf5d4Sdrh       }
12369cfcf5d4Sdrh       case OE_Replace: {
12372d401ab8Sdrh         sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
12380ca3e24bSdrh         seenReplace = 1;
12399cfcf5d4Sdrh         break;
12409cfcf5d4Sdrh       }
12419cfcf5d4Sdrh     }
1242aa9b8963Sdrh     sqlite3VdbeJumpHere(v, j2);
12432d401ab8Sdrh     sqlite3VdbeJumpHere(v, j3);
12442d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regR);
12459cfcf5d4Sdrh   }
12469cfcf5d4Sdrh }
12470ca3e24bSdrh 
12480ca3e24bSdrh /*
12490ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
12504adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
125104adf416Sdrh ** A consecutive range of registers starting at regRowid contains the
125204adf416Sdrh ** rowid and the content to be inserted.
12530ca3e24bSdrh **
1254b419a926Sdrh ** The arguments to this routine should be the same as the first six
12554adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
12560ca3e24bSdrh */
12574adee20fSdanielk1977 void sqlite3CompleteInsertion(
12580ca3e24bSdrh   Parse *pParse,      /* The parser context */
12590ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
126004adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
126104adf416Sdrh   int regRowid,       /* Range of content */
1262aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1263f0863fe5Sdrh   int rowidChng,      /* True if the record number will change */
126470ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1265e4d90813Sdrh   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
1266e4d90813Sdrh   int appendBias      /* True if this is likely to be an append */
12670ca3e24bSdrh ){
12680ca3e24bSdrh   int i;
12690ca3e24bSdrh   Vdbe *v;
12700ca3e24bSdrh   int nIdx;
12710ca3e24bSdrh   Index *pIdx;
1272b28af71aSdanielk1977   int pik_flags;
127304adf416Sdrh   int regData;
1274b7654111Sdrh   int regRec;
12750ca3e24bSdrh 
12764adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
12770ca3e24bSdrh   assert( v!=0 );
1278417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
12790ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
12800ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
1281aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
128204adf416Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
12830ca3e24bSdrh   }
128404adf416Sdrh   regData = regRowid + 1;
1285b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
12861db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1287a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1288b84f96f8Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
128970ce3f0cSdrh   if( newIdx>=0 ){
1290b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
129170ce3f0cSdrh   }
1292b84f96f8Sdanielk1977 #endif
12934794f735Sdrh   if( pParse->nested ){
12944794f735Sdrh     pik_flags = 0;
12954794f735Sdrh   }else{
129694eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
129794eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
12984794f735Sdrh   }
1299e4d90813Sdrh   if( appendBias ){
1300e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1301e4d90813Sdrh   }
1302b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
130394eb6a14Sdanielk1977   if( !pParse->nested ){
130466a5167bSdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
130594eb6a14Sdanielk1977   }
1306b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
13070ca3e24bSdrh }
1308cd44690aSdrh 
1309cd44690aSdrh /*
1310290c1948Sdrh ** Generate code that will open cursors for a table and for all
131104adf416Sdrh ** indices of that table.  The "baseCur" parameter is the cursor number used
1312cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1313aa9b8963Sdrh **
1314aa9b8963Sdrh ** Return the number of indices on the table.
1315cd44690aSdrh */
1316aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1317290c1948Sdrh   Parse *pParse,   /* Parsing context */
1318290c1948Sdrh   Table *pTab,     /* Table to be opened */
131904adf416Sdrh   int baseCur,        /* Cursor number assigned to the table */
1320290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1321290c1948Sdrh ){
1322cd44690aSdrh   int i;
13234cbdda9eSdrh   int iDb;
1324cd44690aSdrh   Index *pIdx;
13254cbdda9eSdrh   Vdbe *v;
13264cbdda9eSdrh 
1327aa9b8963Sdrh   if( IsVirtual(pTab) ) return 0;
13284cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
13294cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1330cd44690aSdrh   assert( v!=0 );
133104adf416Sdrh   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
1332cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1333b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1334da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
133504adf416Sdrh     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
133666a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1337207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1338cd44690aSdrh   }
133904adf416Sdrh   if( pParse->nTab<=baseCur+i ){
134004adf416Sdrh     pParse->nTab = baseCur+i;
1341290c1948Sdrh   }
1342aa9b8963Sdrh   return i-1;
1343cd44690aSdrh }
13449d9cf229Sdrh 
134591c58e23Sdrh 
134691c58e23Sdrh #ifdef SQLITE_TEST
134791c58e23Sdrh /*
134891c58e23Sdrh ** The following global variable is incremented whenever the
134991c58e23Sdrh ** transfer optimization is used.  This is used for testing
135091c58e23Sdrh ** purposes only - to make sure the transfer optimization really
135191c58e23Sdrh ** is happening when it is suppose to.
135291c58e23Sdrh */
135391c58e23Sdrh int sqlite3_xferopt_count;
135491c58e23Sdrh #endif /* SQLITE_TEST */
135591c58e23Sdrh 
135691c58e23Sdrh 
13579d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
13589d9cf229Sdrh /*
13599d9cf229Sdrh ** Check to collation names to see if they are compatible.
13609d9cf229Sdrh */
13619d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
13629d9cf229Sdrh   if( z1==0 ){
13639d9cf229Sdrh     return z2==0;
13649d9cf229Sdrh   }
13659d9cf229Sdrh   if( z2==0 ){
13669d9cf229Sdrh     return 0;
13679d9cf229Sdrh   }
13689d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
13699d9cf229Sdrh }
13709d9cf229Sdrh 
13719d9cf229Sdrh 
13729d9cf229Sdrh /*
13739d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
13749d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
13759d9cf229Sdrh ** for a compatible index:
13769d9cf229Sdrh **
13779d9cf229Sdrh **    *   The index is over the same set of columns
13789d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
13799d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
13809d9cf229Sdrh **    *   The same collating sequence on each column
13819d9cf229Sdrh */
13829d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
13839d9cf229Sdrh   int i;
13849d9cf229Sdrh   assert( pDest && pSrc );
13859d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
13869d9cf229Sdrh   if( pDest->nColumn!=pSrc->nColumn ){
13879d9cf229Sdrh     return 0;   /* Different number of columns */
13889d9cf229Sdrh   }
13899d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
13909d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
13919d9cf229Sdrh   }
13929d9cf229Sdrh   for(i=0; i<pSrc->nColumn; i++){
13939d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
13949d9cf229Sdrh       return 0;   /* Different columns indexed */
13959d9cf229Sdrh     }
13969d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
13979d9cf229Sdrh       return 0;   /* Different sort orders */
13989d9cf229Sdrh     }
13999d9cf229Sdrh     if( pSrc->azColl[i]!=pDest->azColl[i] ){
140060a713c6Sdrh       return 0;   /* Different collating sequences */
14019d9cf229Sdrh     }
14029d9cf229Sdrh   }
14039d9cf229Sdrh 
14049d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
14059d9cf229Sdrh   return 1;
14069d9cf229Sdrh }
14079d9cf229Sdrh 
14089d9cf229Sdrh /*
14099d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
14109d9cf229Sdrh **
14119d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
14129d9cf229Sdrh **
14139d9cf229Sdrh ** This optimization is only attempted if
14149d9cf229Sdrh **
14159d9cf229Sdrh **    (1)  tab1 and tab2 have identical schemas including all the
14168103b7d2Sdrh **         same indices and constraints
14179d9cf229Sdrh **
14189d9cf229Sdrh **    (2)  tab1 and tab2 are different tables
14199d9cf229Sdrh **
14209d9cf229Sdrh **    (3)  There must be no triggers on tab1
14219d9cf229Sdrh **
14229d9cf229Sdrh **    (4)  The result set of the SELECT statement is "*"
14239d9cf229Sdrh **
14249d9cf229Sdrh **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
14259d9cf229Sdrh **         or LIMIT clause.
14269d9cf229Sdrh **
14279d9cf229Sdrh **    (6)  The SELECT statement is a simple (not a compound) select that
14289d9cf229Sdrh **         contains only tab2 in its FROM clause
14299d9cf229Sdrh **
14309d9cf229Sdrh ** This method for implementing the INSERT transfers raw records from
14319d9cf229Sdrh ** tab2 over to tab1.  The columns are not decoded.  Raw records from
14329d9cf229Sdrh ** the indices of tab2 are transfered to tab1 as well.  In so doing,
14339d9cf229Sdrh ** the resulting tab1 has much less fragmentation.
14349d9cf229Sdrh **
14359d9cf229Sdrh ** This routine returns TRUE if the optimization is attempted.  If any
14369d9cf229Sdrh ** of the conditions above fail so that the optimization should not
14379d9cf229Sdrh ** be attempted, then this routine returns FALSE.
14389d9cf229Sdrh */
14399d9cf229Sdrh static int xferOptimization(
14409d9cf229Sdrh   Parse *pParse,        /* Parser context */
14419d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
14429d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
14439d9cf229Sdrh   int onError,          /* How to handle constraint errors */
14449d9cf229Sdrh   int iDbDest           /* The database of pDest */
14459d9cf229Sdrh ){
14469d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
14479d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
14489d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
14499d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
14509d9cf229Sdrh   int i;                           /* Loop counter */
14519d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
14529d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
14539d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
14549d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
14559d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
14569d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
14579d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
14586a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1459f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1460b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
14619d9cf229Sdrh 
14629d9cf229Sdrh   if( pSelect==0 ){
14639d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
14649d9cf229Sdrh   }
14659d9cf229Sdrh   if( pDest->pTrigger ){
14669d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
14679d9cf229Sdrh   }
14689d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
14699d9cf229Sdrh   if( pDest->isVirtual ){
14709d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
14719d9cf229Sdrh   }
14729d9cf229Sdrh #endif
14739d9cf229Sdrh   if( onError==OE_Default ){
14749d9cf229Sdrh     onError = OE_Abort;
14759d9cf229Sdrh   }
14769d9cf229Sdrh   if( onError!=OE_Abort && onError!=OE_Rollback ){
14779d9cf229Sdrh     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
14789d9cf229Sdrh   }
14795ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
14809d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
14819d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
14829d9cf229Sdrh   }
14839d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
14849d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
14859d9cf229Sdrh   }
14869d9cf229Sdrh   if( pSelect->pWhere ){
14879d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
14889d9cf229Sdrh   }
14899d9cf229Sdrh   if( pSelect->pOrderBy ){
14909d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
14919d9cf229Sdrh   }
14928103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
14938103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
14949d9cf229Sdrh   if( pSelect->pGroupBy ){
14959d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
14969d9cf229Sdrh   }
14979d9cf229Sdrh   if( pSelect->pLimit ){
14989d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
14999d9cf229Sdrh   }
15008103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
15019d9cf229Sdrh   if( pSelect->pPrior ){
15029d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
15039d9cf229Sdrh   }
15049d9cf229Sdrh   if( pSelect->isDistinct ){
15059d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
15069d9cf229Sdrh   }
15079d9cf229Sdrh   pEList = pSelect->pEList;
15089d9cf229Sdrh   assert( pEList!=0 );
15099d9cf229Sdrh   if( pEList->nExpr!=1 ){
15109d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
15119d9cf229Sdrh   }
15129d9cf229Sdrh   assert( pEList->a[0].pExpr );
15139d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
15149d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
15159d9cf229Sdrh   }
15169d9cf229Sdrh 
15179d9cf229Sdrh   /* At this point we have established that the statement is of the
15189d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
15199d9cf229Sdrh   ** we have to check the semantics.
15209d9cf229Sdrh   */
15219d9cf229Sdrh   pItem = pSelect->pSrc->a;
1522ca424114Sdrh   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
15239d9cf229Sdrh   if( pSrc==0 ){
15249d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
15259d9cf229Sdrh   }
15269d9cf229Sdrh   if( pSrc==pDest ){
15279d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
15289d9cf229Sdrh   }
15299d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
15309d9cf229Sdrh   if( pSrc->isVirtual ){
15319d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
15329d9cf229Sdrh   }
15339d9cf229Sdrh #endif
15349d9cf229Sdrh   if( pSrc->pSelect ){
15359d9cf229Sdrh     return 0;   /* tab2 may not be a view */
15369d9cf229Sdrh   }
15379d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
15389d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
15399d9cf229Sdrh   }
15409d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
15419d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
15429d9cf229Sdrh   }
15439d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
15449d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
15459d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
15469d9cf229Sdrh     }
15479d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
15489d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
15499d9cf229Sdrh     }
15509d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
15519d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
15529d9cf229Sdrh     }
15539d9cf229Sdrh   }
15549d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1555f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1556f33c9fadSdrh       destHasUniqueIdx = 1;
1557f33c9fadSdrh     }
15589d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
15599d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
15609d9cf229Sdrh     }
15619d9cf229Sdrh     if( pSrcIdx==0 ){
15629d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
15639d9cf229Sdrh     }
15649d9cf229Sdrh   }
15657fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1566fb658dedSdrh   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
15678103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
15688103b7d2Sdrh   }
15697fc2f41bSdrh #endif
15709d9cf229Sdrh 
15719d9cf229Sdrh   /* If we get this far, it means either:
15729d9cf229Sdrh   **
15739d9cf229Sdrh   **    *   We can always do the transfer if the table contains an
15749d9cf229Sdrh   **        an integer primary key
15759d9cf229Sdrh   **
15769d9cf229Sdrh   **    *   We can conditionally do the transfer if the destination
15779d9cf229Sdrh   **        table is empty.
15789d9cf229Sdrh   */
1579dd73521bSdrh #ifdef SQLITE_TEST
1580dd73521bSdrh   sqlite3_xferopt_count++;
1581dd73521bSdrh #endif
15829d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
15839d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1584f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
15859d9cf229Sdrh   iSrc = pParse->nTab++;
15869d9cf229Sdrh   iDest = pParse->nTab++;
15876a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
15889d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1589f33c9fadSdrh   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
1590bd36ba69Sdrh     /* If tables do not have an INTEGER PRIMARY KEY and there
1591bd36ba69Sdrh     ** are indices to be copied and the destination is not empty,
1592bd36ba69Sdrh     ** we have to disallow the transfer optimization because the
1593bd36ba69Sdrh     ** the rowids might change which will mess up indexing.
1594f33c9fadSdrh     **
1595f33c9fadSdrh     ** Or if the destination has a UNIQUE index and is not empty,
1596f33c9fadSdrh     ** we also disallow the transfer optimization because we cannot
1597f33c9fadSdrh     ** insure that all entries in the union of DEST and SRC will be
1598f33c9fadSdrh     ** unique.
15999d9cf229Sdrh     */
160066a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
160166a5167bSdrh     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
16029d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
16039d9cf229Sdrh   }else{
16049d9cf229Sdrh     emptyDestTest = 0;
16059d9cf229Sdrh   }
16069d9cf229Sdrh   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
160766a5167bSdrh   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1608b7654111Sdrh   regData = sqlite3GetTempReg(pParse);
1609b7654111Sdrh   regRowid = sqlite3GetTempReg(pParse);
161042242dedSdrh   if( pDest->iPKey>=0 ){
1611b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1612b7654111Sdrh     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
161366a5167bSdrh     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
161466a5167bSdrh                       "PRIMARY KEY must be unique", P4_STATIC);
16159d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr2);
1616b7654111Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
1617bd36ba69Sdrh   }else if( pDest->pIndex==0 ){
1618b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
161995bad4c7Sdrh   }else{
1620b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
162142242dedSdrh     assert( pDest->autoInc==0 );
162295bad4c7Sdrh   }
1623b7654111Sdrh   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1624b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1625b7654111Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
16261f4aa337Sdanielk1977   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
162766a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
16286a288a33Sdrh   autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
16299d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
16309d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
16319d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
16329d9cf229Sdrh     }
16339d9cf229Sdrh     assert( pSrcIdx );
163466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
163566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
16369d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1637207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1638207872a4Sdanielk1977                       (char*)pKey, P4_KEYINFO_HANDOFF);
1639d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
16409d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1641207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
164266a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1643207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
164466a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1645b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1646b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
164766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
16489d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
16499d9cf229Sdrh   }
16509d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
1651b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
1652b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
165366a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
165466a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
16559d9cf229Sdrh   if( emptyDestTest ){
165666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
16579d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
165866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
16599d9cf229Sdrh     return 0;
16609d9cf229Sdrh   }else{
16619d9cf229Sdrh     return 1;
16629d9cf229Sdrh   }
16639d9cf229Sdrh }
16649d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
1665f39d9588Sdrh 
1666f39d9588Sdrh /* Make sure "isView" gets undefined in case this file becomes part of
1667f39d9588Sdrh ** the amalgamation - so that subsequent files do not see isView as a
1668f39d9588Sdrh ** macro. */
1669f39d9588Sdrh #undef isView
1670