xref: /sqlite-3.40.0/src/insert.c (revision 6ab3a2ec)
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*6ab3a2ecSdanielk1977 ** $Id: insert.c,v 1.257 2009/02/19 14:39:25 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);
48633e6d57Sdrh     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
49a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
50633e6d57Sdrh       db->mallocFailed = 1;
51a37cdde0Sdanielk1977       return;
52a37cdde0Sdanielk1977     }
53a37cdde0Sdanielk1977     for(n=0; n<pIdx->nColumn; n++){
54a37cdde0Sdanielk1977       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
55a37cdde0Sdanielk1977     }
562d401ab8Sdrh     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
572d401ab8Sdrh     pIdx->zColAff[n] = 0;
58a37cdde0Sdanielk1977   }
593d1bfeaaSdanielk1977 
6066a5167bSdrh   sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
61a37cdde0Sdanielk1977 }
62a37cdde0Sdanielk1977 
63a37cdde0Sdanielk1977 /*
6466a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
65a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
66a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
67a37cdde0Sdanielk1977 ** column:
68a37cdde0Sdanielk1977 **
69a37cdde0Sdanielk1977 **  Character      Column affinity
70a37cdde0Sdanielk1977 **  ------------------------------
713eda040bSdrh **  'a'            TEXT
723eda040bSdrh **  'b'            NONE
733eda040bSdrh **  'c'            NUMERIC
743eda040bSdrh **  'd'            INTEGER
753eda040bSdrh **  'e'            REAL
76a37cdde0Sdanielk1977 */
77a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
783d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
793d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
803d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
813d1bfeaaSdanielk1977   **
823d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
833d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
843d1bfeaaSdanielk1977   */
853d1bfeaaSdanielk1977   if( !pTab->zColAff ){
863d1bfeaaSdanielk1977     char *zColAff;
873d1bfeaaSdanielk1977     int i;
88abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
893d1bfeaaSdanielk1977 
90633e6d57Sdrh     zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
913d1bfeaaSdanielk1977     if( !zColAff ){
92633e6d57Sdrh       db->mallocFailed = 1;
93a37cdde0Sdanielk1977       return;
943d1bfeaaSdanielk1977     }
953d1bfeaaSdanielk1977 
963d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
97a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
983d1bfeaaSdanielk1977     }
993d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
1003d1bfeaaSdanielk1977 
1013d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1023d1bfeaaSdanielk1977   }
1033d1bfeaaSdanielk1977 
10466a5167bSdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
1053d1bfeaaSdanielk1977 }
1063d1bfeaaSdanielk1977 
1074d88778bSdanielk1977 /*
10848d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
10948d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
11048d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
11148d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
11248d1178aSdrh ** run without using temporary table for the results of the SELECT.
1134d88778bSdanielk1977 */
11448d1178aSdrh static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
1154d88778bSdanielk1977   int i;
11648d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
11748d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
11848d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
119ef0bea92Sdrh     assert( pOp!=0 );
120207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
12148d1178aSdrh       Index *pIndex;
122207872a4Sdanielk1977       int tnum = pOp->p2;
12348d1178aSdrh       if( tnum==pTab->tnum ){
12448d1178aSdrh         return 1;
12548d1178aSdrh       }
12648d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
12748d1178aSdrh         if( tnum==pIndex->tnum ){
12848d1178aSdrh           return 1;
12948d1178aSdrh         }
13048d1178aSdrh       }
13148d1178aSdrh     }
132543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1332dca4ac1Sdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
1342dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
13566a5167bSdrh       assert( pOp->p4type==P4_VTAB );
13648d1178aSdrh       return 1;
1374d88778bSdanielk1977     }
138543165efSdrh #endif
1394d88778bSdanielk1977   }
1404d88778bSdanielk1977   return 0;
1414d88778bSdanielk1977 }
1423d1bfeaaSdanielk1977 
1439d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1449d9cf229Sdrh /*
1459d9cf229Sdrh ** Write out code to initialize the autoincrement logic.  This code
1469d9cf229Sdrh ** looks up the current autoincrement value in the sqlite_sequence
1476a288a33Sdrh ** table and stores that value in a register.  Code generated by
1486a288a33Sdrh ** autoIncStep() will keep that register holding the largest
1499d9cf229Sdrh ** rowid value.  Code generated by autoIncEnd() will write the new
1509d9cf229Sdrh ** largest value of the counter back into the sqlite_sequence table.
1519d9cf229Sdrh **
1529d9cf229Sdrh ** This routine returns the index of the mem[] cell that contains
1539d9cf229Sdrh ** the maximum rowid counter.
1549d9cf229Sdrh **
1556a288a33Sdrh ** Three consecutive registers are allocated by this routine.  The
1566a288a33Sdrh ** first two hold the name of the target table and the maximum rowid
1576a288a33Sdrh ** inserted into the target table, respectively.
1586a288a33Sdrh ** The third holds the rowid in sqlite_sequence where we will
1596a288a33Sdrh ** write back the revised maximum rowid.  This routine returns the
1606a288a33Sdrh ** index of the second of these three registers.
1619d9cf229Sdrh */
1629d9cf229Sdrh static int autoIncBegin(
1639d9cf229Sdrh   Parse *pParse,      /* Parsing context */
1649d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
1659d9cf229Sdrh   Table *pTab         /* The table we are writing to */
1669d9cf229Sdrh ){
1676a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
1687d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
1699d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
1709d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
171*6ab3a2ecSdanielk1977     int iCur = pParse->nTab++;
1726a288a33Sdrh     int addr;               /* Address of the top of the loop */
1739d9cf229Sdrh     assert( v );
1746a288a33Sdrh     pParse->nMem++;         /* Holds name of table */
1756a288a33Sdrh     memId = ++pParse->nMem;
1766a288a33Sdrh     pParse->nMem++;
1779d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
1786a288a33Sdrh     addr = sqlite3VdbeCurrentAddr(v);
1791db639ceSdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
180c9ded4c6Sdrh     sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
1811db639ceSdrh     sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
1821db639ceSdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
18335573356Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
1846a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
1856a288a33Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
186c9ded4c6Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
1871db639ceSdrh     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
188c9ded4c6Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
18966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
1909d9cf229Sdrh   }
1919d9cf229Sdrh   return memId;
1929d9cf229Sdrh }
1939d9cf229Sdrh 
1949d9cf229Sdrh /*
1959d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
1969d9cf229Sdrh **
1979d9cf229Sdrh ** This routine should be called when the top of the stack holds a
1989d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
1999d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
2009d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
2019d9cf229Sdrh */
2026a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2039d9cf229Sdrh   if( memId>0 ){
2046a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2059d9cf229Sdrh   }
2069d9cf229Sdrh }
2079d9cf229Sdrh 
2089d9cf229Sdrh /*
2099d9cf229Sdrh ** After doing one or more inserts, the maximum rowid is stored
2106a288a33Sdrh ** in reg[memId].  Generate code to write this value back into the
2119d9cf229Sdrh ** the sqlite_sequence table.
2129d9cf229Sdrh */
2139d9cf229Sdrh static void autoIncEnd(
2149d9cf229Sdrh   Parse *pParse,     /* The parsing context */
2159d9cf229Sdrh   int iDb,           /* Index of the database holding pTab */
2169d9cf229Sdrh   Table *pTab,       /* Table we are inserting into */
2179d9cf229Sdrh   int memId          /* Memory cell holding the maximum rowid */
2189d9cf229Sdrh ){
2197d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
220*6ab3a2ecSdanielk1977     int iCur = pParse->nTab++;
2219d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
2229d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
2236a288a33Sdrh     int j1;
224a7a8e14bSdanielk1977     int iRec = ++pParse->nMem;    /* Memory cell used for record */
2256a288a33Sdrh 
2269d9cf229Sdrh     assert( v );
2279d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
2286a288a33Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
2296a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
2306a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
231a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
232a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
23335573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
2346a288a33Sdrh     sqlite3VdbeAddOp1(v, OP_Close, iCur);
2359d9cf229Sdrh   }
2369d9cf229Sdrh }
2379d9cf229Sdrh #else
2389d9cf229Sdrh /*
2399d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
2409d9cf229Sdrh ** above are all no-ops
2419d9cf229Sdrh */
2429d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
243287fb61cSdanielk1977 # define autoIncStep(A,B,C)
2449d9cf229Sdrh # define autoIncEnd(A,B,C,D)
2459d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
2469d9cf229Sdrh 
2479d9cf229Sdrh 
2489d9cf229Sdrh /* Forward declaration */
2499d9cf229Sdrh static int xferOptimization(
2509d9cf229Sdrh   Parse *pParse,        /* Parser context */
2519d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
2529d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
2539d9cf229Sdrh   int onError,          /* How to handle constraint errors */
2549d9cf229Sdrh   int iDbDest           /* The database of pDest */
2559d9cf229Sdrh );
2569d9cf229Sdrh 
2573d1bfeaaSdanielk1977 /*
2581ccde15dSdrh ** This routine is call to handle SQL of the following forms:
259cce7d176Sdrh **
260cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
2611ccde15dSdrh **    insert into TABLE (IDLIST) select
262cce7d176Sdrh **
2631ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
2641ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
265967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
2661ccde15dSdrh **
2671ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
2681ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
2691ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
2701ccde15dSdrh ** data for the insert.
271142e30dfSdrh **
2729d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
273142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
274e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
275e00ee6ebSdrh ** the "1st template"):
276142e30dfSdrh **
277142e30dfSdrh **         open write cursor to <table> and its indices
278142e30dfSdrh **         puts VALUES clause expressions onto the stack
279142e30dfSdrh **         write the resulting record into <table>
280142e30dfSdrh **         cleanup
281142e30dfSdrh **
2829d9cf229Sdrh ** The three remaining templates assume the statement is of the form
283142e30dfSdrh **
284142e30dfSdrh **   INSERT INTO <table> SELECT ...
285142e30dfSdrh **
2869d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
2879d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
2889d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
2899d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
2909d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
2919d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
2929d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
293e00ee6ebSdrh ** template.  This is the 2nd template.
2949d9cf229Sdrh **
2959d9cf229Sdrh **         open a write cursor to <table>
2969d9cf229Sdrh **         open read cursor on <table2>
2979d9cf229Sdrh **         transfer all records in <table2> over to <table>
2989d9cf229Sdrh **         close cursors
2999d9cf229Sdrh **         foreach index on <table>
3009d9cf229Sdrh **           open a write cursor on the <table> index
3019d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
3029d9cf229Sdrh **           transfer all records from the read to the write cursors
3039d9cf229Sdrh **           close cursors
3049d9cf229Sdrh **         end foreach
3059d9cf229Sdrh **
306e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
3079d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
3089d9cf229Sdrh ** The generated code follows this template:
309142e30dfSdrh **
310e00ee6ebSdrh **         EOF <- 0
311e00ee6ebSdrh **         X <- A
312142e30dfSdrh **         goto B
313142e30dfSdrh **      A: setup for the SELECT
3149d9cf229Sdrh **         loop over the rows in the SELECT
315e00ee6ebSdrh **           load values into registers R..R+n
316e00ee6ebSdrh **           yield X
317142e30dfSdrh **         end loop
318142e30dfSdrh **         cleanup after the SELECT
319e00ee6ebSdrh **         EOF <- 1
320e00ee6ebSdrh **         yield X
321142e30dfSdrh **         goto A
322e00ee6ebSdrh **      B: open write cursor to <table> and its indices
323e00ee6ebSdrh **      C: yield X
324e00ee6ebSdrh **         if EOF goto D
325e00ee6ebSdrh **         insert the select result into <table> from R..R+n
326e00ee6ebSdrh **         goto C
327142e30dfSdrh **      D: cleanup
328142e30dfSdrh **
329e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
330142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
331142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
332142e30dfSdrh ** we have to use a intermediate table to store the results of
333142e30dfSdrh ** the select.  The template is like this:
334142e30dfSdrh **
335e00ee6ebSdrh **         EOF <- 0
336e00ee6ebSdrh **         X <- A
337142e30dfSdrh **         goto B
338142e30dfSdrh **      A: setup for the SELECT
339142e30dfSdrh **         loop over the tables in the SELECT
340e00ee6ebSdrh **           load value into register R..R+n
341e00ee6ebSdrh **           yield X
342142e30dfSdrh **         end loop
343142e30dfSdrh **         cleanup after the SELECT
344e00ee6ebSdrh **         EOF <- 1
345e00ee6ebSdrh **         yield X
346e00ee6ebSdrh **         halt-error
347e00ee6ebSdrh **      B: open temp table
348e00ee6ebSdrh **      L: yield X
349e00ee6ebSdrh **         if EOF goto M
350e00ee6ebSdrh **         insert row from R..R+n into temp table
351e00ee6ebSdrh **         goto L
352e00ee6ebSdrh **      M: open write cursor to <table> and its indices
353e00ee6ebSdrh **         rewind temp table
354e00ee6ebSdrh **      C: loop over rows of intermediate table
355142e30dfSdrh **           transfer values form intermediate table into <table>
356e00ee6ebSdrh **         end loop
357e00ee6ebSdrh **      D: cleanup
358cce7d176Sdrh */
3594adee20fSdanielk1977 void sqlite3Insert(
360cce7d176Sdrh   Parse *pParse,        /* Parser context */
361113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
362cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
3635974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
3649cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
3659cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
366cce7d176Sdrh ){
3676a288a33Sdrh   sqlite3 *db;          /* The main database structure */
3686a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
369113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
370e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
3715974a30fSdrh   int i, j, idx;        /* Loop counters */
3725974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
3735974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
374967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
3756a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
37604adf416Sdrh   int baseCur = 0;      /* VDBE Cursor number for pTab */
3774a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
3780ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
3794d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
380cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
381e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
382e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
383e00ee6ebSdrh   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
3842eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
3856a288a33Sdrh   int newIdx = -1;      /* Cursor for the NEW pseudo-table */
3866a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
3872958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
388e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
389cce7d176Sdrh 
3906a288a33Sdrh   /* Register allocations */
3911bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
3926a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
3936a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
3946a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
3956a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
3966a288a33Sdrh   int regData;          /* register holding first column to insert */
3976a288a33Sdrh   int regRecord;        /* Holds the assemblied row record */
3981bd10f8aSdrh   int regEof = 0;       /* Register recording end of SELECT data */
399aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
4006a288a33Sdrh 
401034ca14fSdanielk1977 
402798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
403798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
404dca76841Sdrh   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
405798da52cSdrh #endif
406c3f9bad2Sdanielk1977 
40717435752Sdrh   db = pParse->db;
4081bd10f8aSdrh   memset(&dest, 0, sizeof(dest));
40917435752Sdrh   if( pParse->nErr || db->mallocFailed ){
4106f7adc8aSdrh     goto insert_cleanup;
4116f7adc8aSdrh   }
412daffd0e5Sdrh 
4131ccde15dSdrh   /* Locate the table into which we will be inserting new information.
4141ccde15dSdrh   */
415113088ecSdrh   assert( pTabList->nSrc==1 );
416113088ecSdrh   zTab = pTabList->a[0].zName;
417daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
4184adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
419c3f9bad2Sdanielk1977   if( pTab==0 ){
420c3f9bad2Sdanielk1977     goto insert_cleanup;
421c3f9bad2Sdanielk1977   }
422da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
423da184236Sdanielk1977   assert( iDb<db->nDb );
424da184236Sdanielk1977   pDb = &db->aDb[iDb];
4252958a4e6Sdrh   zDb = pDb->zName;
4264adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
4271962bda7Sdrh     goto insert_cleanup;
4281962bda7Sdrh   }
429c3f9bad2Sdanielk1977 
430b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
431b7f9164eSdrh   ** inserted into is a view
432b7f9164eSdrh   */
433b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
43462c14b34Sdanielk1977   triggers_exist = sqlite3TriggersExist(pTab, TK_INSERT, 0);
435b7f9164eSdrh   isView = pTab->pSelect!=0;
436b7f9164eSdrh #else
437dca76841Sdrh # define triggers_exist 0
438b7f9164eSdrh # define isView 0
439b7f9164eSdrh #endif
440b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
441b7f9164eSdrh # undef isView
442b7f9164eSdrh # define isView 0
443b7f9164eSdrh #endif
444b7f9164eSdrh 
445c3f9bad2Sdanielk1977   /* Ensure that:
446c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
447c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
448c3f9bad2Sdanielk1977   */
449dca76841Sdrh   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
450c3f9bad2Sdanielk1977     goto insert_cleanup;
451c3f9bad2Sdanielk1977   }
45243617e9aSdrh   assert( pTab!=0 );
4531ccde15dSdrh 
454f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
455b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
456b3d24bf8Sdanielk1977   ** module table).
457f573c99bSdrh   */
458b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
459f573c99bSdrh     goto insert_cleanup;
460f573c99bSdrh   }
461f573c99bSdrh 
4621ccde15dSdrh   /* Allocate a VDBE
4631ccde15dSdrh   */
4644adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
4655974a30fSdrh   if( v==0 ) goto insert_cleanup;
4664794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
467da184236Sdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
4681ccde15dSdrh 
469c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
470dca76841Sdrh   if( triggers_exist ){
471c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
472f29ce559Sdanielk1977   }
473c3f9bad2Sdanielk1977 
4749d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
4759d9cf229Sdrh   /* If the statement is of the form
4769d9cf229Sdrh   **
4779d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
4789d9cf229Sdrh   **
4799d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
4809d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
481e00ee6ebSdrh   **
482e00ee6ebSdrh   ** This is the 2nd template.
4839d9cf229Sdrh   */
4849d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
4859d9cf229Sdrh     assert( !triggers_exist );
4869d9cf229Sdrh     assert( pList==0 );
4879d9cf229Sdrh     goto insert_cleanup;
4889d9cf229Sdrh   }
4899d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
4909d9cf229Sdrh 
4912958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
4926a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
4932958a4e6Sdrh   */
4946a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
4952958a4e6Sdrh 
4961ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
497e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
498e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
499e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
5001ccde15dSdrh   */
5015974a30fSdrh   if( pSelect ){
502142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
503e00ee6ebSdrh     ** as a co-routine.  The code is common to both the 3rd and 4th
504e00ee6ebSdrh     ** templates:
505e00ee6ebSdrh     **
506e00ee6ebSdrh     **         EOF <- 0
507e00ee6ebSdrh     **         X <- A
508e00ee6ebSdrh     **         goto B
509e00ee6ebSdrh     **      A: setup for the SELECT
510e00ee6ebSdrh     **         loop over the tables in the SELECT
511e00ee6ebSdrh     **           load value into register R..R+n
512e00ee6ebSdrh     **           yield X
513e00ee6ebSdrh     **         end loop
514e00ee6ebSdrh     **         cleanup after the SELECT
515e00ee6ebSdrh     **         EOF <- 1
516e00ee6ebSdrh     **         yield X
517e00ee6ebSdrh     **         halt-error
518e00ee6ebSdrh     **
519e00ee6ebSdrh     ** On each invocation of the co-routine, it puts a single row of the
520e00ee6ebSdrh     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
521e00ee6ebSdrh     ** (These output registers are allocated by sqlite3Select().)  When
522e00ee6ebSdrh     ** the SELECT completes, it sets the EOF flag stored in regEof.
523142e30dfSdrh     */
524e00ee6ebSdrh     int rc, j1;
5251013c932Sdrh 
526e00ee6ebSdrh     regEof = ++pParse->nMem;
527e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
528e00ee6ebSdrh     VdbeComment((v, "SELECT eof flag"));
52992b01d53Sdrh     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
530e00ee6ebSdrh     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
53192b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
532e00ee6ebSdrh     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
533e00ee6ebSdrh     VdbeComment((v, "Jump over SELECT coroutine"));
534b3bce662Sdanielk1977 
535b3bce662Sdanielk1977     /* Resolve the expressions in the SELECT statement and execute it. */
5367d10d5a6Sdrh     rc = sqlite3Select(pParse, pSelect, &dest);
53717435752Sdrh     if( rc || pParse->nErr || db->mallocFailed ){
5386f7adc8aSdrh       goto insert_cleanup;
5396f7adc8aSdrh     }
540e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
54192b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
542e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
543e00ee6ebSdrh     VdbeComment((v, "End of SELECT coroutine"));
544e00ee6ebSdrh     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
545b3bce662Sdanielk1977 
5466a288a33Sdrh     regFromSelect = dest.iMem;
5475974a30fSdrh     assert( pSelect->pEList );
548967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
549e00ee6ebSdrh     assert( dest.nMem==nColumn );
550142e30dfSdrh 
551142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
552e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
553e00ee6ebSdrh     ** FALSE if each* row of the SELECT can be written directly into
554e00ee6ebSdrh     ** the destination table (template 3).
555048c530cSdrh     **
556048c530cSdrh     ** A temp table must be used if the table being updated is also one
557048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
558048c530cSdrh     ** temp table in the case of row triggers.
559142e30dfSdrh     */
560e00ee6ebSdrh     if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){
561048c530cSdrh       useTempTable = 1;
562048c530cSdrh     }
563142e30dfSdrh 
564142e30dfSdrh     if( useTempTable ){
565e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
566e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
567e00ee6ebSdrh       ** here is from the 4th template:
568e00ee6ebSdrh       **
569e00ee6ebSdrh       **      B: open temp table
570e00ee6ebSdrh       **      L: yield X
571e00ee6ebSdrh       **         if EOF goto M
572e00ee6ebSdrh       **         insert row from R..R+n into temp table
573e00ee6ebSdrh       **         goto L
574e00ee6ebSdrh       **      M: ...
575142e30dfSdrh       */
576e00ee6ebSdrh       int regRec;          /* Register to hold packed record */
577dc5ea5c7Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
578e00ee6ebSdrh       int addrTop;         /* Label "L" */
579e00ee6ebSdrh       int addrIf;          /* Address of jump to M */
580b7654111Sdrh 
581142e30dfSdrh       srcTab = pParse->nTab++;
582b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
583dc5ea5c7Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
584e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
58592b01d53Sdrh       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
586e00ee6ebSdrh       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
5871db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
588dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
589dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
590e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
591e00ee6ebSdrh       sqlite3VdbeJumpHere(v, addrIf);
592b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
593dc5ea5c7Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
594142e30dfSdrh     }
595142e30dfSdrh   }else{
596142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
597142e30dfSdrh     ** clause
598142e30dfSdrh     */
599b3bce662Sdanielk1977     NameContext sNC;
600b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
601b3bce662Sdanielk1977     sNC.pParse = pParse;
6025974a30fSdrh     srcTab = -1;
60348d1178aSdrh     assert( useTempTable==0 );
604147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
605e64e7b20Sdrh     for(i=0; i<nColumn; i++){
6067d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
607b04a5d87Sdrh         goto insert_cleanup;
608b04a5d87Sdrh       }
609e64e7b20Sdrh     }
6105974a30fSdrh   }
6111ccde15dSdrh 
6121ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
6131ccde15dSdrh   ** of columns to be inserted into the table.
6141ccde15dSdrh   */
615034ca14fSdanielk1977   if( IsVirtual(pTab) ){
616034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
617034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
618034ca14fSdanielk1977     }
619034ca14fSdanielk1977   }
620034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
6214adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
622da93d238Sdrh        "table %S has %d columns but %d values were supplied",
623da93d238Sdrh        pTabList, 0, pTab->nCol, nColumn);
624cce7d176Sdrh     goto insert_cleanup;
625cce7d176Sdrh   }
626967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
6274adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
628cce7d176Sdrh     goto insert_cleanup;
629cce7d176Sdrh   }
6301ccde15dSdrh 
6311ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
6321ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
6331ccde15dSdrh   ** remember the column indices.
634c8392586Sdrh   **
635c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
636c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
637c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
638c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
639c8392586Sdrh   ** is appears in the original table.  (The index of the primary
640c8392586Sdrh   ** key in the original table is pTab->iPKey.)
6411ccde15dSdrh   */
642967e8b73Sdrh   if( pColumn ){
643967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
644967e8b73Sdrh       pColumn->a[i].idx = -1;
645cce7d176Sdrh     }
646967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
647cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
6484adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
649967e8b73Sdrh           pColumn->a[i].idx = j;
6504a32431cSdrh           if( j==pTab->iPKey ){
6519aa028daSdrh             keyColumn = i;
6524a32431cSdrh           }
653cce7d176Sdrh           break;
654cce7d176Sdrh         }
655cce7d176Sdrh       }
656cce7d176Sdrh       if( j>=pTab->nCol ){
6574adee20fSdanielk1977         if( sqlite3IsRowid(pColumn->a[i].zName) ){
658a0217ba7Sdrh           keyColumn = i;
659a0217ba7Sdrh         }else{
6604adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
661da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
662cce7d176Sdrh           pParse->nErr++;
663cce7d176Sdrh           goto insert_cleanup;
664cce7d176Sdrh         }
665cce7d176Sdrh       }
666cce7d176Sdrh     }
667a0217ba7Sdrh   }
6681ccde15dSdrh 
669aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
670c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
671c8392586Sdrh   ** in the original table definition.
6724a32431cSdrh   */
673147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
6744a32431cSdrh     keyColumn = pTab->iPKey;
6754a32431cSdrh   }
6764a32431cSdrh 
677142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
678142e30dfSdrh   */
679dca76841Sdrh   if( triggers_exist ){
680cd3e8f7cSdanielk1977     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
68166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
682f29ce559Sdanielk1977   }
683c3f9bad2Sdanielk1977 
684c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
6851ccde15dSdrh   */
686142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
6876a288a33Sdrh     regRowCount = ++pParse->nMem;
6886a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
689c3f9bad2Sdanielk1977   }
690c3f9bad2Sdanielk1977 
691e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
692e448dc4aSdanielk1977   if( !isView ){
693aa9b8963Sdrh     int nIdx;
694aa9b8963Sdrh 
69504adf416Sdrh     baseCur = pParse->nTab;
69604adf416Sdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
6975c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
698aa9b8963Sdrh     if( aRegIdx==0 ){
699aa9b8963Sdrh       goto insert_cleanup;
700aa9b8963Sdrh     }
701aa9b8963Sdrh     for(i=0; i<nIdx; i++){
702aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
703aa9b8963Sdrh     }
704feeb1394Sdrh   }
705feeb1394Sdrh 
706e00ee6ebSdrh   /* This is the top of the main insertion loop */
707142e30dfSdrh   if( useTempTable ){
708e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
709e00ee6ebSdrh     ** following pseudocode (template 4):
710e00ee6ebSdrh     **
711e00ee6ebSdrh     **         rewind temp table
712e00ee6ebSdrh     **      C: loop over rows of intermediate table
713e00ee6ebSdrh     **           transfer values form intermediate table into <table>
714e00ee6ebSdrh     **         end loop
715e00ee6ebSdrh     **      D: ...
716e00ee6ebSdrh     */
717e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
718e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
719142e30dfSdrh   }else if( pSelect ){
720e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
721e00ee6ebSdrh     ** following pseudocode (template 3):
722e00ee6ebSdrh     **
723e00ee6ebSdrh     **      C: yield X
724e00ee6ebSdrh     **         if EOF goto D
725e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
726e00ee6ebSdrh     **         goto C
727e00ee6ebSdrh     **      D: ...
728e00ee6ebSdrh     */
72992b01d53Sdrh     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
730e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
731bed8690fSdrh   }
7321ccde15dSdrh 
7336a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
7346a288a33Sdrh   ** the content of the new row, and the assemblied row record.
7356a288a33Sdrh   */
7366a288a33Sdrh   regRecord = ++pParse->nMem;
7376a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
7386a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
7396a288a33Sdrh   if( IsVirtual(pTab) ){
7406a288a33Sdrh     regRowid++;
7416a288a33Sdrh     pParse->nMem++;
7426a288a33Sdrh   }
7436a288a33Sdrh   regData = regRowid+1;
7446a288a33Sdrh 
7455cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
74670ce3f0cSdrh   */
7474adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
748dca76841Sdrh   if( triggers_exist & TRIGGER_BEFORE ){
749dc5ea5c7Sdrh     int regTrigRowid;
7502d401ab8Sdrh     int regCols;
7512d401ab8Sdrh     int regRec;
752c3f9bad2Sdanielk1977 
75370ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
75470ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
75570ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
75670ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
75770ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
75870ce3f0cSdrh     */
759dc5ea5c7Sdrh     regTrigRowid = sqlite3GetTempReg(pParse);
76070ce3f0cSdrh     if( keyColumn<0 ){
761dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
76270ce3f0cSdrh     }else if( useTempTable ){
763dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
76470ce3f0cSdrh     }else{
7656a288a33Sdrh       int j1;
766d6fe961eSdrh       assert( pSelect==0 );  /* Otherwise useTempTable is true */
767dc5ea5c7Sdrh       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
768dc5ea5c7Sdrh       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
769dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
7706a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
771dc5ea5c7Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
77270ce3f0cSdrh     }
77370ce3f0cSdrh 
774034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
775034ca14fSdanielk1977     ** this block would have to account for hidden column.
776034ca14fSdanielk1977     */
777034ca14fSdanielk1977     assert(!IsVirtual(pTab));
778034ca14fSdanielk1977 
77970ce3f0cSdrh     /* Create the new column data
78070ce3f0cSdrh     */
7812d401ab8Sdrh     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
782c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
783c3f9bad2Sdanielk1977       if( pColumn==0 ){
784c3f9bad2Sdanielk1977         j = i;
785c3f9bad2Sdanielk1977       }else{
786c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
787c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
788c3f9bad2Sdanielk1977         }
789c3f9bad2Sdanielk1977       }
790c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
7912d401ab8Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
792142e30dfSdrh       }else if( useTempTable ){
7932d401ab8Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i);
794c3f9bad2Sdanielk1977       }else{
795d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
7962d401ab8Sdrh         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
797c3f9bad2Sdanielk1977       }
798c3f9bad2Sdanielk1977     }
7992d401ab8Sdrh     regRec = sqlite3GetTempReg(pParse);
8001db639ceSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
801a37cdde0Sdanielk1977 
802a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
803a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
804a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
805a37cdde0Sdanielk1977     ** table column affinities.
806a37cdde0Sdanielk1977     */
807a37cdde0Sdanielk1977     if( !isView ){
808a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
809a37cdde0Sdanielk1977     }
810dc5ea5c7Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regTrigRowid);
8112d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRec);
812dc5ea5c7Sdrh     sqlite3ReleaseTempReg(pParse, regTrigRowid);
8132d401ab8Sdrh     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
814c3f9bad2Sdanielk1977 
8155cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
816dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
8178f2c54e6Sdanielk1977         newIdx, -1, onError, endOfLoop, 0, 0) ){
818f29ce559Sdanielk1977       goto insert_cleanup;
819f29ce559Sdanielk1977     }
82070ce3f0cSdrh   }
821c3f9bad2Sdanielk1977 
8224a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
823f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
8244a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
825b419a926Sdrh   ** case the record number is the same as that column.
8261ccde15dSdrh   */
8275cf590c1Sdrh   if( !isView ){
8284cbdda9eSdrh     if( IsVirtual(pTab) ){
8294cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
8306a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
8314cbdda9eSdrh     }
8324a32431cSdrh     if( keyColumn>=0 ){
833142e30dfSdrh       if( useTempTable ){
8346a288a33Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
835142e30dfSdrh       }else if( pSelect ){
836b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
8374a32431cSdrh       }else{
838e4d90813Sdrh         VdbeOp *pOp;
8391db639ceSdrh         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
840e4d90813Sdrh         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
841bb50e7adSdanielk1977         if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
842e4d90813Sdrh           appendFlag = 1;
843e4d90813Sdrh           pOp->opcode = OP_NewRowid;
84404adf416Sdrh           pOp->p1 = baseCur;
8456a288a33Sdrh           pOp->p2 = regRowid;
8466a288a33Sdrh           pOp->p3 = regAutoinc;
847e4d90813Sdrh         }
84827a32783Sdrh       }
849f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
850e1e68f49Sdrh       ** to generate a unique primary key value.
851e1e68f49Sdrh       */
852e4d90813Sdrh       if( !appendFlag ){
8531db639ceSdrh         int j1;
854bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
8551db639ceSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
85604adf416Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
8571db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
858bb50e7adSdanielk1977         }else{
859bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
860bb50e7adSdanielk1977           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
861bb50e7adSdanielk1977         }
8623c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
863e4d90813Sdrh       }
8644cbdda9eSdrh     }else if( IsVirtual(pTab) ){
8656a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
8664a32431cSdrh     }else{
86704adf416Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
868e4d90813Sdrh       appendFlag = 1;
8694a32431cSdrh     }
8706a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
8714a32431cSdrh 
872aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
8734a32431cSdrh     ** with the first column.
8744a32431cSdrh     */
875034ca14fSdanielk1977     nHidden = 0;
876cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
8776a288a33Sdrh       int iRegStore = regRowid+1+i;
8784a32431cSdrh       if( i==pTab->iPKey ){
8794a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
880aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
881aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
882aacc543eSdrh         ** taking up data space with information that will never be used. */
8834c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
8844a32431cSdrh         continue;
8854a32431cSdrh       }
886967e8b73Sdrh       if( pColumn==0 ){
887034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
888034ca14fSdanielk1977           assert( IsVirtual(pTab) );
889034ca14fSdanielk1977           j = -1;
890034ca14fSdanielk1977           nHidden++;
891034ca14fSdanielk1977         }else{
892034ca14fSdanielk1977           j = i - nHidden;
893034ca14fSdanielk1977         }
894cce7d176Sdrh       }else{
895967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
896967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
897cce7d176Sdrh         }
898cce7d176Sdrh       }
899034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
900287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
901142e30dfSdrh       }else if( useTempTable ){
902287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
903142e30dfSdrh       }else if( pSelect ){
904b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
905cce7d176Sdrh       }else{
906287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
907cce7d176Sdrh       }
908cce7d176Sdrh     }
9091ccde15dSdrh 
9100ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
9110ca3e24bSdrh     ** do the insertion.
9124a32431cSdrh     */
9134cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
9144cbdda9eSdrh     if( IsVirtual(pTab) ){
9154f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
9166a288a33Sdrh       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
91766a5167bSdrh                      (const char*)pTab->pVtab, P4_VTAB);
9184cbdda9eSdrh     }else
9194cbdda9eSdrh #endif
9204cbdda9eSdrh     {
92104adf416Sdrh       sqlite3GenerateConstraintChecks(
92204adf416Sdrh           pParse,
92304adf416Sdrh           pTab,
92404adf416Sdrh           baseCur,
92504adf416Sdrh           regIns,
92604adf416Sdrh           aRegIdx,
92704adf416Sdrh           keyColumn>=0,
92804adf416Sdrh           0,
92904adf416Sdrh           onError,
93004adf416Sdrh           endOfLoop
93104adf416Sdrh       );
93204adf416Sdrh       sqlite3CompleteInsertion(
93304adf416Sdrh           pParse,
93404adf416Sdrh           pTab,
93504adf416Sdrh           baseCur,
93604adf416Sdrh           regIns,
93704adf416Sdrh           aRegIdx,
93804adf416Sdrh           0,
939e4d90813Sdrh           (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
94004adf416Sdrh           appendFlag
94104adf416Sdrh        );
9425cf590c1Sdrh     }
9434cbdda9eSdrh   }
9441bee3d7bSdrh 
945feeb1394Sdrh   /* Update the count of rows that are inserted
9461bee3d7bSdrh   */
947142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
9486a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
9491bee3d7bSdrh   }
950c3f9bad2Sdanielk1977 
951dca76841Sdrh   if( triggers_exist ){
952c3f9bad2Sdanielk1977     /* Code AFTER triggers */
953dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
9548f2c54e6Sdanielk1977           newIdx, -1, onError, endOfLoop, 0, 0) ){
955f29ce559Sdanielk1977       goto insert_cleanup;
956f29ce559Sdanielk1977     }
957c3f9bad2Sdanielk1977   }
9581bee3d7bSdrh 
959e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
960e00ee6ebSdrh   ** is a SELECT statement.
9611ccde15dSdrh   */
9624adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
963142e30dfSdrh   if( useTempTable ){
964e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
965e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
9662eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
967142e30dfSdrh   }else if( pSelect ){
968e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
969e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
9706b56344dSdrh   }
971c3f9bad2Sdanielk1977 
972e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
973c3f9bad2Sdanielk1977     /* Close all tables opened */
9742eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
9756b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
9762eb95377Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
977cce7d176Sdrh     }
978c3f9bad2Sdanielk1977   }
979c3f9bad2Sdanielk1977 
980f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
9816a288a33Sdrh   ** counter value in memory regAutoinc back into the sqlite_sequence
982f3388144Sdrh   ** table.
9832958a4e6Sdrh   */
9846a288a33Sdrh   autoIncEnd(pParse, iDb, pTab, regAutoinc);
9852958a4e6Sdrh 
9861bee3d7bSdrh   /*
987e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
988e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
989e7de6f25Sdanielk1977   ** invoke the callback function.
9901bee3d7bSdrh   */
991cc6bd383Sdanielk1977   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
9926a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
99322322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
99410fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
9951bee3d7bSdrh   }
996cce7d176Sdrh 
997cce7d176Sdrh insert_cleanup:
998633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
999633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1000633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1001633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1002633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1003cce7d176Sdrh }
10049cfcf5d4Sdrh 
10059cfcf5d4Sdrh /*
10066a288a33Sdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
10079cfcf5d4Sdrh **
100804adf416Sdrh ** The input is a range of consecutive registers as follows:
10090ca3e24bSdrh **
1010f0863fe5Sdrh **    1.  The rowid of the row to be updated before the update.  This
1011b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
1012a05a722fSdrh **        change to the record number or writing to a virtual table.
10130ca3e24bSdrh **
1014f0863fe5Sdrh **    2.  The rowid of the row after the update.
10150ca3e24bSdrh **
10160ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
10170ca3e24bSdrh **
10180ca3e24bSdrh **    i.  Data from middle columns...
10190ca3e24bSdrh **
10200ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
10210ca3e24bSdrh **
102204adf416Sdrh ** The regRowid parameter is the index of the register containing (2).
102304adf416Sdrh **
1024f0863fe5Sdrh ** The old rowid shown as entry (1) above is omitted unless both isUpdate
1025f0863fe5Sdrh ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
1026a05a722fSdrh ** INSERTs.  RowidChng means that the new rowid is explicitly specified by
1027a05a722fSdrh ** the update or insert statement.  If rowidChng is false, it means that
1028a05a722fSdrh ** the rowid is computed automatically in an insert or that the rowid value
1029a05a722fSdrh ** is not modified by the update.
10300ca3e24bSdrh **
1031aa9b8963Sdrh ** The code generated by this routine store new index entries into
1032aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1033aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1034aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
1035aa9b8963Sdrh ** attached to the table.
10369cfcf5d4Sdrh **
10379cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
10389cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
10391c92853dSdrh ** then the appropriate action is performed.  There are five possible
10401c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
10419cfcf5d4Sdrh **
10429cfcf5d4Sdrh **  Constraint type  Action       What Happens
10439cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
10441c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
104524b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
10469cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
10479cfcf5d4Sdrh **
10481c92853dSdrh **  any              ABORT        Back out changes from the current command
10491c92853dSdrh **                                only (do not do a complete rollback) then
105024b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
10511c92853dSdrh **                                with SQLITE_CONSTRAINT.
10521c92853dSdrh **
10531c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
10541c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
10551c92853dSdrh **                                transaction is not rolled back and any
10561c92853dSdrh **                                prior changes are retained.
10571c92853dSdrh **
10589cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
10599cfcf5d4Sdrh **                                the stack and there is an immediate jump
10609cfcf5d4Sdrh **                                to label ignoreDest.
10619cfcf5d4Sdrh **
10629cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
10639cfcf5d4Sdrh **                                value for that column.  If the default value
10649cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
10659cfcf5d4Sdrh **
10669cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
10679cfcf5d4Sdrh **                                being inserted is removed.
10689cfcf5d4Sdrh **
10699cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
10709cfcf5d4Sdrh **
10711c92853dSdrh ** Which action to take is determined by the overrideError parameter.
10721c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
10731c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
10741c92853dSdrh ** for the constraint is used.
10759cfcf5d4Sdrh **
1076aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
107704adf416Sdrh ** cursor number "baseCur".  All indices of pTab must also have open
107804adf416Sdrh ** read/write cursors with cursor number baseCur+i for the i-th cursor.
10799cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
1080aa9b8963Sdrh ** cursors do not need to be open for indices where aRegIdx[i]==0.
10819cfcf5d4Sdrh */
10824adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
10839cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
10849cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
108504adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
108604adf416Sdrh   int regRowid,       /* Index of the range of input registers */
1087aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1088a05a722fSdrh   int rowidChng,      /* True if the rowid might collide with existing entry */
1089b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
10909cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
1091b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
10929cfcf5d4Sdrh ){
10939cfcf5d4Sdrh   int i;
10949cfcf5d4Sdrh   Vdbe *v;
10959cfcf5d4Sdrh   int nCol;
10969cfcf5d4Sdrh   int onError;
10971bd10f8aSdrh   int j1;             /* Addresss of jump instruction */
10981bd10f8aSdrh   int j2 = 0, j3;     /* Addresses of jump instructions */
109904adf416Sdrh   int regData;        /* Register containing first data column */
11000ca3e24bSdrh   int iCur;
11010ca3e24bSdrh   Index *pIdx;
11020ca3e24bSdrh   int seenReplace = 0;
1103f0863fe5Sdrh   int hasTwoRowids = (isUpdate && rowidChng);
11049cfcf5d4Sdrh 
11054adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
11069cfcf5d4Sdrh   assert( v!=0 );
1107417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
11089cfcf5d4Sdrh   nCol = pTab->nCol;
1109aa9b8963Sdrh   regData = regRowid + 1;
1110aa9b8963Sdrh 
111104adf416Sdrh 
11129cfcf5d4Sdrh   /* Test all NOT NULL constraints.
11139cfcf5d4Sdrh   */
11149cfcf5d4Sdrh   for(i=0; i<nCol; i++){
11150ca3e24bSdrh     if( i==pTab->iPKey ){
11160ca3e24bSdrh       continue;
11170ca3e24bSdrh     }
11189cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
11190ca3e24bSdrh     if( onError==OE_None ) continue;
11209cfcf5d4Sdrh     if( overrideError!=OE_Default ){
11219cfcf5d4Sdrh       onError = overrideError;
1122a996e477Sdrh     }else if( onError==OE_Default ){
1123a996e477Sdrh       onError = OE_Abort;
11249cfcf5d4Sdrh     }
11257977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
11269cfcf5d4Sdrh       onError = OE_Abort;
11279cfcf5d4Sdrh     }
1128aa9b8963Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
1129b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1130b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
11319cfcf5d4Sdrh     switch( onError ){
11321c92853dSdrh       case OE_Rollback:
11331c92853dSdrh       case OE_Abort:
11341c92853dSdrh       case OE_Fail: {
1135f089aa45Sdrh         char *zMsg;
113666a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1137f089aa45Sdrh         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
1138f089aa45Sdrh                               pTab->zName, pTab->aCol[i].zName);
113966a5167bSdrh         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
11409cfcf5d4Sdrh         break;
11419cfcf5d4Sdrh       }
11429cfcf5d4Sdrh       case OE_Ignore: {
114366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
11449cfcf5d4Sdrh         break;
11459cfcf5d4Sdrh       }
11469cfcf5d4Sdrh       case OE_Replace: {
114704adf416Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
11489cfcf5d4Sdrh         break;
11499cfcf5d4Sdrh       }
11509cfcf5d4Sdrh     }
1151aa9b8963Sdrh     sqlite3VdbeJumpHere(v, j1);
11529cfcf5d4Sdrh   }
11539cfcf5d4Sdrh 
11549cfcf5d4Sdrh   /* Test all CHECK constraints
11559cfcf5d4Sdrh   */
1156ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
11570cd2d4c9Sdrh   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
1158ffe07b2dSdrh     int allOk = sqlite3VdbeMakeLabel(v);
1159aa9b8963Sdrh     pParse->ckBase = regData;
116035573356Sdrh     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
1161aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
11622e06c67cSdrh     if( onError==OE_Ignore ){
116366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1164aa01c7e2Sdrh     }else{
116566a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1166aa01c7e2Sdrh     }
1167ffe07b2dSdrh     sqlite3VdbeResolveLabel(v, allOk);
1168ffe07b2dSdrh   }
1169ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
11709cfcf5d4Sdrh 
11710bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
11720bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
11730bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
11749cfcf5d4Sdrh   */
1175f0863fe5Sdrh   if( rowidChng ){
11760ca3e24bSdrh     onError = pTab->keyConf;
11770ca3e24bSdrh     if( overrideError!=OE_Default ){
11780ca3e24bSdrh       onError = overrideError;
1179a996e477Sdrh     }else if( onError==OE_Default ){
1180a996e477Sdrh       onError = OE_Abort;
11810ca3e24bSdrh     }
1182a0217ba7Sdrh 
118360a713c6Sdrh     if( onError!=OE_Replace || pTab->pIndex ){
118479b0c956Sdrh       if( isUpdate ){
1185892d3179Sdrh         j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
118679b0c956Sdrh       }
118704adf416Sdrh       j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
11880ca3e24bSdrh       switch( onError ){
1189a0217ba7Sdrh         default: {
1190a0217ba7Sdrh           onError = OE_Abort;
1191a0217ba7Sdrh           /* Fall thru into the next case */
1192a0217ba7Sdrh         }
11931c92853dSdrh         case OE_Rollback:
11941c92853dSdrh         case OE_Abort:
11951c92853dSdrh         case OE_Fail: {
119666a5167bSdrh           sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
119766a5167bSdrh                            "PRIMARY KEY must be unique", P4_STATIC);
11980ca3e24bSdrh           break;
11990ca3e24bSdrh         }
12005383ae5cSdrh         case OE_Replace: {
12012d401ab8Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
12025383ae5cSdrh           seenReplace = 1;
12035383ae5cSdrh           break;
12045383ae5cSdrh         }
12050ca3e24bSdrh         case OE_Ignore: {
12065383ae5cSdrh           assert( seenReplace==0 );
120766a5167bSdrh           sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
12080ca3e24bSdrh           break;
12090ca3e24bSdrh         }
12100ca3e24bSdrh       }
1211aa9b8963Sdrh       sqlite3VdbeJumpHere(v, j3);
1212f5905aa7Sdrh       if( isUpdate ){
1213aa9b8963Sdrh         sqlite3VdbeJumpHere(v, j2);
1214a05a722fSdrh       }
12150ca3e24bSdrh     }
12160ca3e24bSdrh   }
12170bd1f4eaSdrh 
12180bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
12190bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
12200bd1f4eaSdrh   ** Add the new records to the indices as we go.
12210bd1f4eaSdrh   */
1222b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
12232d401ab8Sdrh     int regIdx;
12242d401ab8Sdrh     int regR;
12252d401ab8Sdrh 
1226aa9b8963Sdrh     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
1227b2fe7d8cSdrh 
1228b2fe7d8cSdrh     /* Create a key for accessing the index entry */
12292d401ab8Sdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
12309cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
12319cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
12329cfcf5d4Sdrh       if( idx==pTab->iPKey ){
12332d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
12349cfcf5d4Sdrh       }else{
12352d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
12369cfcf5d4Sdrh       }
12379cfcf5d4Sdrh     }
12382d401ab8Sdrh     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
12391db639ceSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
1240a37cdde0Sdanielk1977     sqlite3IndexAffinityStr(v, pIdx);
1241da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
12422d401ab8Sdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
1243b2fe7d8cSdrh 
1244b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
12459cfcf5d4Sdrh     onError = pIdx->onError;
1246b2fe7d8cSdrh     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
12479cfcf5d4Sdrh     if( overrideError!=OE_Default ){
12489cfcf5d4Sdrh       onError = overrideError;
1249a996e477Sdrh     }else if( onError==OE_Default ){
1250a996e477Sdrh       onError = OE_Abort;
12519cfcf5d4Sdrh     }
12525383ae5cSdrh     if( seenReplace ){
12535383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
12545383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
12555383ae5cSdrh     }
12565383ae5cSdrh 
1257b2fe7d8cSdrh 
1258b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
12592d401ab8Sdrh     j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
12602d401ab8Sdrh     regR = sqlite3GetTempReg(pParse);
12612d401ab8Sdrh     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
12622d401ab8Sdrh     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
12631fc4129dSshane                            regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
1264a9e852b6Smlcreech                            P4_INT32);
1265b2fe7d8cSdrh 
1266b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1267b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1268b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
12699cfcf5d4Sdrh     switch( onError ){
12701c92853dSdrh       case OE_Rollback:
12711c92853dSdrh       case OE_Abort:
12721c92853dSdrh       case OE_Fail: {
127337ed48edSdrh         int j, n1, n2;
127437ed48edSdrh         char zErrMsg[200];
127500e13613Sdanielk1977         sqlite3_snprintf(ArraySize(zErrMsg), zErrMsg,
12765bb3eb9bSdrh                          pIdx->nColumn>1 ? "columns " : "column ");
1277ea678832Sdrh         n1 = sqlite3Strlen30(zErrMsg);
127800e13613Sdanielk1977         for(j=0; j<pIdx->nColumn && n1<ArraySize(zErrMsg)-30; j++){
127937ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1280ea678832Sdrh           n2 = sqlite3Strlen30(zCol);
128137ed48edSdrh           if( j>0 ){
128200e13613Sdanielk1977             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], ", ");
128337ed48edSdrh             n1 += 2;
128437ed48edSdrh           }
128500e13613Sdanielk1977           if( n1+n2>ArraySize(zErrMsg)-30 ){
128600e13613Sdanielk1977             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "...");
128737ed48edSdrh             n1 += 3;
128837ed48edSdrh             break;
128937ed48edSdrh           }else{
129000e13613Sdanielk1977             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
129137ed48edSdrh             n1 += n2;
129237ed48edSdrh           }
129337ed48edSdrh         }
129400e13613Sdanielk1977         sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1],
129537ed48edSdrh             pIdx->nColumn>1 ? " are not unique" : " is not unique");
129666a5167bSdrh         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
12979cfcf5d4Sdrh         break;
12989cfcf5d4Sdrh       }
12999cfcf5d4Sdrh       case OE_Ignore: {
13000ca3e24bSdrh         assert( seenReplace==0 );
130166a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
13029cfcf5d4Sdrh         break;
13039cfcf5d4Sdrh       }
13049cfcf5d4Sdrh       case OE_Replace: {
13052d401ab8Sdrh         sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
13060ca3e24bSdrh         seenReplace = 1;
13079cfcf5d4Sdrh         break;
13089cfcf5d4Sdrh       }
13099cfcf5d4Sdrh     }
1310aa9b8963Sdrh     sqlite3VdbeJumpHere(v, j2);
13112d401ab8Sdrh     sqlite3VdbeJumpHere(v, j3);
13122d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regR);
13139cfcf5d4Sdrh   }
13149cfcf5d4Sdrh }
13150ca3e24bSdrh 
13160ca3e24bSdrh /*
13170ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
13184adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
131904adf416Sdrh ** A consecutive range of registers starting at regRowid contains the
132004adf416Sdrh ** rowid and the content to be inserted.
13210ca3e24bSdrh **
1322b419a926Sdrh ** The arguments to this routine should be the same as the first six
13234adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
13240ca3e24bSdrh */
13254adee20fSdanielk1977 void sqlite3CompleteInsertion(
13260ca3e24bSdrh   Parse *pParse,      /* The parser context */
13270ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
132804adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
132904adf416Sdrh   int regRowid,       /* Range of content */
1330aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
133170ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1332e4d90813Sdrh   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
1333e4d90813Sdrh   int appendBias      /* True if this is likely to be an append */
13340ca3e24bSdrh ){
13350ca3e24bSdrh   int i;
13360ca3e24bSdrh   Vdbe *v;
13370ca3e24bSdrh   int nIdx;
13380ca3e24bSdrh   Index *pIdx;
13391bd10f8aSdrh   u8 pik_flags;
134004adf416Sdrh   int regData;
1341b7654111Sdrh   int regRec;
13420ca3e24bSdrh 
13434adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
13440ca3e24bSdrh   assert( v!=0 );
1345417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
13460ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
13470ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
1348aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
134904adf416Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
13500ca3e24bSdrh   }
135104adf416Sdrh   regData = regRowid + 1;
1352b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
13531db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1354a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1355da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
1356b84f96f8Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
135770ce3f0cSdrh   if( newIdx>=0 ){
1358b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
135970ce3f0cSdrh   }
1360b84f96f8Sdanielk1977 #endif
13614794f735Sdrh   if( pParse->nested ){
13624794f735Sdrh     pik_flags = 0;
13634794f735Sdrh   }else{
136494eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
136594eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
13664794f735Sdrh   }
1367e4d90813Sdrh   if( appendBias ){
1368e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1369e4d90813Sdrh   }
1370b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
137194eb6a14Sdanielk1977   if( !pParse->nested ){
137266a5167bSdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
137394eb6a14Sdanielk1977   }
1374b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
13750ca3e24bSdrh }
1376cd44690aSdrh 
1377cd44690aSdrh /*
1378290c1948Sdrh ** Generate code that will open cursors for a table and for all
137904adf416Sdrh ** indices of that table.  The "baseCur" parameter is the cursor number used
1380cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1381aa9b8963Sdrh **
1382aa9b8963Sdrh ** Return the number of indices on the table.
1383cd44690aSdrh */
1384aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1385290c1948Sdrh   Parse *pParse,   /* Parsing context */
1386290c1948Sdrh   Table *pTab,     /* Table to be opened */
138704adf416Sdrh   int baseCur,     /* Cursor number assigned to the table */
1388290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1389290c1948Sdrh ){
1390cd44690aSdrh   int i;
13914cbdda9eSdrh   int iDb;
1392cd44690aSdrh   Index *pIdx;
13934cbdda9eSdrh   Vdbe *v;
13944cbdda9eSdrh 
1395aa9b8963Sdrh   if( IsVirtual(pTab) ) return 0;
13964cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
13974cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1398cd44690aSdrh   assert( v!=0 );
139904adf416Sdrh   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
1400cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1401b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1402da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
140304adf416Sdrh     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
140466a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1405207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1406cd44690aSdrh   }
140704adf416Sdrh   if( pParse->nTab<=baseCur+i ){
140804adf416Sdrh     pParse->nTab = baseCur+i;
1409290c1948Sdrh   }
1410aa9b8963Sdrh   return i-1;
1411cd44690aSdrh }
14129d9cf229Sdrh 
141391c58e23Sdrh 
141491c58e23Sdrh #ifdef SQLITE_TEST
141591c58e23Sdrh /*
141691c58e23Sdrh ** The following global variable is incremented whenever the
141791c58e23Sdrh ** transfer optimization is used.  This is used for testing
141891c58e23Sdrh ** purposes only - to make sure the transfer optimization really
141991c58e23Sdrh ** is happening when it is suppose to.
142091c58e23Sdrh */
142191c58e23Sdrh int sqlite3_xferopt_count;
142291c58e23Sdrh #endif /* SQLITE_TEST */
142391c58e23Sdrh 
142491c58e23Sdrh 
14259d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
14269d9cf229Sdrh /*
14279d9cf229Sdrh ** Check to collation names to see if they are compatible.
14289d9cf229Sdrh */
14299d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
14309d9cf229Sdrh   if( z1==0 ){
14319d9cf229Sdrh     return z2==0;
14329d9cf229Sdrh   }
14339d9cf229Sdrh   if( z2==0 ){
14349d9cf229Sdrh     return 0;
14359d9cf229Sdrh   }
14369d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
14379d9cf229Sdrh }
14389d9cf229Sdrh 
14399d9cf229Sdrh 
14409d9cf229Sdrh /*
14419d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
14429d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
14439d9cf229Sdrh ** for a compatible index:
14449d9cf229Sdrh **
14459d9cf229Sdrh **    *   The index is over the same set of columns
14469d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
14479d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
14489d9cf229Sdrh **    *   The same collating sequence on each column
14499d9cf229Sdrh */
14509d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
14519d9cf229Sdrh   int i;
14529d9cf229Sdrh   assert( pDest && pSrc );
14539d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
14549d9cf229Sdrh   if( pDest->nColumn!=pSrc->nColumn ){
14559d9cf229Sdrh     return 0;   /* Different number of columns */
14569d9cf229Sdrh   }
14579d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
14589d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
14599d9cf229Sdrh   }
14609d9cf229Sdrh   for(i=0; i<pSrc->nColumn; i++){
14619d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
14629d9cf229Sdrh       return 0;   /* Different columns indexed */
14639d9cf229Sdrh     }
14649d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
14659d9cf229Sdrh       return 0;   /* Different sort orders */
14669d9cf229Sdrh     }
14679d9cf229Sdrh     if( pSrc->azColl[i]!=pDest->azColl[i] ){
146860a713c6Sdrh       return 0;   /* Different collating sequences */
14699d9cf229Sdrh     }
14709d9cf229Sdrh   }
14719d9cf229Sdrh 
14729d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
14739d9cf229Sdrh   return 1;
14749d9cf229Sdrh }
14759d9cf229Sdrh 
14769d9cf229Sdrh /*
14779d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
14789d9cf229Sdrh **
14799d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
14809d9cf229Sdrh **
14819d9cf229Sdrh ** This optimization is only attempted if
14829d9cf229Sdrh **
14839d9cf229Sdrh **    (1)  tab1 and tab2 have identical schemas including all the
14848103b7d2Sdrh **         same indices and constraints
14859d9cf229Sdrh **
14869d9cf229Sdrh **    (2)  tab1 and tab2 are different tables
14879d9cf229Sdrh **
14889d9cf229Sdrh **    (3)  There must be no triggers on tab1
14899d9cf229Sdrh **
14909d9cf229Sdrh **    (4)  The result set of the SELECT statement is "*"
14919d9cf229Sdrh **
14929d9cf229Sdrh **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
14939d9cf229Sdrh **         or LIMIT clause.
14949d9cf229Sdrh **
14959d9cf229Sdrh **    (6)  The SELECT statement is a simple (not a compound) select that
14969d9cf229Sdrh **         contains only tab2 in its FROM clause
14979d9cf229Sdrh **
14989d9cf229Sdrh ** This method for implementing the INSERT transfers raw records from
14999d9cf229Sdrh ** tab2 over to tab1.  The columns are not decoded.  Raw records from
15009d9cf229Sdrh ** the indices of tab2 are transfered to tab1 as well.  In so doing,
15019d9cf229Sdrh ** the resulting tab1 has much less fragmentation.
15029d9cf229Sdrh **
15039d9cf229Sdrh ** This routine returns TRUE if the optimization is attempted.  If any
15049d9cf229Sdrh ** of the conditions above fail so that the optimization should not
15059d9cf229Sdrh ** be attempted, then this routine returns FALSE.
15069d9cf229Sdrh */
15079d9cf229Sdrh static int xferOptimization(
15089d9cf229Sdrh   Parse *pParse,        /* Parser context */
15099d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
15109d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
15119d9cf229Sdrh   int onError,          /* How to handle constraint errors */
15129d9cf229Sdrh   int iDbDest           /* The database of pDest */
15139d9cf229Sdrh ){
15149d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
15159d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
15169d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
15179d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
15189d9cf229Sdrh   int i;                           /* Loop counter */
15199d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
15209d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
15219d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
15229d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
15239d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
15249d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
15259d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
15266a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1527f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1528b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
15299d9cf229Sdrh 
15309d9cf229Sdrh   if( pSelect==0 ){
15319d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
15329d9cf229Sdrh   }
15339d9cf229Sdrh   if( pDest->pTrigger ){
15349d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
15359d9cf229Sdrh   }
15369d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
15377d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
15389d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
15399d9cf229Sdrh   }
15409d9cf229Sdrh #endif
15419d9cf229Sdrh   if( onError==OE_Default ){
15429d9cf229Sdrh     onError = OE_Abort;
15439d9cf229Sdrh   }
15449d9cf229Sdrh   if( onError!=OE_Abort && onError!=OE_Rollback ){
15459d9cf229Sdrh     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
15469d9cf229Sdrh   }
15475ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
15489d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
15499d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
15509d9cf229Sdrh   }
15519d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
15529d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
15539d9cf229Sdrh   }
15549d9cf229Sdrh   if( pSelect->pWhere ){
15559d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
15569d9cf229Sdrh   }
15579d9cf229Sdrh   if( pSelect->pOrderBy ){
15589d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
15599d9cf229Sdrh   }
15608103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
15618103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
15629d9cf229Sdrh   if( pSelect->pGroupBy ){
15639d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
15649d9cf229Sdrh   }
15659d9cf229Sdrh   if( pSelect->pLimit ){
15669d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
15679d9cf229Sdrh   }
15688103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
15699d9cf229Sdrh   if( pSelect->pPrior ){
15709d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
15719d9cf229Sdrh   }
15727d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
15739d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
15749d9cf229Sdrh   }
15759d9cf229Sdrh   pEList = pSelect->pEList;
15769d9cf229Sdrh   assert( pEList!=0 );
15779d9cf229Sdrh   if( pEList->nExpr!=1 ){
15789d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
15799d9cf229Sdrh   }
15809d9cf229Sdrh   assert( pEList->a[0].pExpr );
15819d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
15829d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
15839d9cf229Sdrh   }
15849d9cf229Sdrh 
15859d9cf229Sdrh   /* At this point we have established that the statement is of the
15869d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
15879d9cf229Sdrh   ** we have to check the semantics.
15889d9cf229Sdrh   */
15899d9cf229Sdrh   pItem = pSelect->pSrc->a;
1590ca424114Sdrh   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
15919d9cf229Sdrh   if( pSrc==0 ){
15929d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
15939d9cf229Sdrh   }
15949d9cf229Sdrh   if( pSrc==pDest ){
15959d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
15969d9cf229Sdrh   }
15979d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
15987d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
15999d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
16009d9cf229Sdrh   }
16019d9cf229Sdrh #endif
16029d9cf229Sdrh   if( pSrc->pSelect ){
16039d9cf229Sdrh     return 0;   /* tab2 may not be a view */
16049d9cf229Sdrh   }
16059d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
16069d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
16079d9cf229Sdrh   }
16089d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
16099d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
16109d9cf229Sdrh   }
16119d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
16129d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
16139d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
16149d9cf229Sdrh     }
16159d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
16169d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
16179d9cf229Sdrh     }
16189d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
16199d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
16209d9cf229Sdrh     }
16219d9cf229Sdrh   }
16229d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1623f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1624f33c9fadSdrh       destHasUniqueIdx = 1;
1625f33c9fadSdrh     }
16269d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
16279d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
16289d9cf229Sdrh     }
16299d9cf229Sdrh     if( pSrcIdx==0 ){
16309d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
16319d9cf229Sdrh     }
16329d9cf229Sdrh   }
16337fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1634fb658dedSdrh   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
16358103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
16368103b7d2Sdrh   }
16377fc2f41bSdrh #endif
16389d9cf229Sdrh 
16399d9cf229Sdrh   /* If we get this far, it means either:
16409d9cf229Sdrh   **
16419d9cf229Sdrh   **    *   We can always do the transfer if the table contains an
16429d9cf229Sdrh   **        an integer primary key
16439d9cf229Sdrh   **
16449d9cf229Sdrh   **    *   We can conditionally do the transfer if the destination
16459d9cf229Sdrh   **        table is empty.
16469d9cf229Sdrh   */
1647dd73521bSdrh #ifdef SQLITE_TEST
1648dd73521bSdrh   sqlite3_xferopt_count++;
1649dd73521bSdrh #endif
16509d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
16519d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1652f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
16539d9cf229Sdrh   iSrc = pParse->nTab++;
16549d9cf229Sdrh   iDest = pParse->nTab++;
16556a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
16569d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1657f33c9fadSdrh   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
1658bd36ba69Sdrh     /* If tables do not have an INTEGER PRIMARY KEY and there
1659bd36ba69Sdrh     ** are indices to be copied and the destination is not empty,
1660bd36ba69Sdrh     ** we have to disallow the transfer optimization because the
1661bd36ba69Sdrh     ** the rowids might change which will mess up indexing.
1662f33c9fadSdrh     **
1663f33c9fadSdrh     ** Or if the destination has a UNIQUE index and is not empty,
1664f33c9fadSdrh     ** we also disallow the transfer optimization because we cannot
1665f33c9fadSdrh     ** insure that all entries in the union of DEST and SRC will be
1666f33c9fadSdrh     ** unique.
16679d9cf229Sdrh     */
166866a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
166966a5167bSdrh     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
16709d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
16719d9cf229Sdrh   }else{
16729d9cf229Sdrh     emptyDestTest = 0;
16739d9cf229Sdrh   }
16749d9cf229Sdrh   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
167566a5167bSdrh   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1676b7654111Sdrh   regData = sqlite3GetTempReg(pParse);
1677b7654111Sdrh   regRowid = sqlite3GetTempReg(pParse);
167842242dedSdrh   if( pDest->iPKey>=0 ){
1679b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1680b7654111Sdrh     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
168166a5167bSdrh     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
168266a5167bSdrh                       "PRIMARY KEY must be unique", P4_STATIC);
16839d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr2);
1684b7654111Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
1685bd36ba69Sdrh   }else if( pDest->pIndex==0 ){
1686b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
168795bad4c7Sdrh   }else{
1688b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
16897d10d5a6Sdrh     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
169095bad4c7Sdrh   }
1691b7654111Sdrh   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1692b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1693b7654111Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
16941f4aa337Sdanielk1977   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
169566a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
16966a288a33Sdrh   autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
16979d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
16989d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
16999d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
17009d9cf229Sdrh     }
17019d9cf229Sdrh     assert( pSrcIdx );
170266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
170366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
17049d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1705207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1706207872a4Sdanielk1977                       (char*)pKey, P4_KEYINFO_HANDOFF);
1707d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
17089d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1709207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
171066a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1711207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
171266a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1713b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1714b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
171566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
17169d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
17179d9cf229Sdrh   }
17189d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
1719b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
1720b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
172166a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
172266a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
17239d9cf229Sdrh   if( emptyDestTest ){
172466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
17259d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
172666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
17279d9cf229Sdrh     return 0;
17289d9cf229Sdrh   }else{
17299d9cf229Sdrh     return 1;
17309d9cf229Sdrh   }
17319d9cf229Sdrh }
17329d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
1733f39d9588Sdrh 
1734f39d9588Sdrh /* Make sure "isView" gets undefined in case this file becomes part of
1735f39d9588Sdrh ** the amalgamation - so that subsequent files do not see isView as a
1736f39d9588Sdrh ** macro. */
1737f39d9588Sdrh #undef isView
1738