xref: /sqlite-3.40.0/src/insert.c (revision dc5ea5c7)
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*dc5ea5c7Sdrh ** $Id: insert.c,v 1.254 2008/12/10 17:20:00 drh 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];
1719d9cf229Sdrh     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 ){
2209d9cf229Sdrh     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 */
3916a288a33Sdrh   int regFromSelect;    /* 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 */
398e00ee6ebSdrh   int regEof;           /* 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;
40817435752Sdrh   if( pParse->nErr || db->mallocFailed ){
4096f7adc8aSdrh     goto insert_cleanup;
4106f7adc8aSdrh   }
411daffd0e5Sdrh 
4121ccde15dSdrh   /* Locate the table into which we will be inserting new information.
4131ccde15dSdrh   */
414113088ecSdrh   assert( pTabList->nSrc==1 );
415113088ecSdrh   zTab = pTabList->a[0].zName;
416daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
4174adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
418c3f9bad2Sdanielk1977   if( pTab==0 ){
419c3f9bad2Sdanielk1977     goto insert_cleanup;
420c3f9bad2Sdanielk1977   }
421da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
422da184236Sdanielk1977   assert( iDb<db->nDb );
423da184236Sdanielk1977   pDb = &db->aDb[iDb];
4242958a4e6Sdrh   zDb = pDb->zName;
4254adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
4261962bda7Sdrh     goto insert_cleanup;
4271962bda7Sdrh   }
428c3f9bad2Sdanielk1977 
429b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
430b7f9164eSdrh   ** inserted into is a view
431b7f9164eSdrh   */
432b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
43362c14b34Sdanielk1977   triggers_exist = sqlite3TriggersExist(pTab, TK_INSERT, 0);
434b7f9164eSdrh   isView = pTab->pSelect!=0;
435b7f9164eSdrh #else
436dca76841Sdrh # define triggers_exist 0
437b7f9164eSdrh # define isView 0
438b7f9164eSdrh #endif
439b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
440b7f9164eSdrh # undef isView
441b7f9164eSdrh # define isView 0
442b7f9164eSdrh #endif
443b7f9164eSdrh 
444c3f9bad2Sdanielk1977   /* Ensure that:
445c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
446c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
447c3f9bad2Sdanielk1977   */
448dca76841Sdrh   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
449c3f9bad2Sdanielk1977     goto insert_cleanup;
450c3f9bad2Sdanielk1977   }
45143617e9aSdrh   assert( pTab!=0 );
4521ccde15dSdrh 
453f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
454b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
455b3d24bf8Sdanielk1977   ** module table).
456f573c99bSdrh   */
457b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
458f573c99bSdrh     goto insert_cleanup;
459f573c99bSdrh   }
460f573c99bSdrh 
4611ccde15dSdrh   /* Allocate a VDBE
4621ccde15dSdrh   */
4634adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
4645974a30fSdrh   if( v==0 ) goto insert_cleanup;
4654794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
466da184236Sdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
4671ccde15dSdrh 
468c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
469dca76841Sdrh   if( triggers_exist ){
470c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
471f29ce559Sdanielk1977   }
472c3f9bad2Sdanielk1977 
4739d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
4749d9cf229Sdrh   /* If the statement is of the form
4759d9cf229Sdrh   **
4769d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
4779d9cf229Sdrh   **
4789d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
4799d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
480e00ee6ebSdrh   **
481e00ee6ebSdrh   ** This is the 2nd template.
4829d9cf229Sdrh   */
4839d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
4849d9cf229Sdrh     assert( !triggers_exist );
4859d9cf229Sdrh     assert( pList==0 );
4869d9cf229Sdrh     goto insert_cleanup;
4879d9cf229Sdrh   }
4889d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
4899d9cf229Sdrh 
4902958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
4916a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
4922958a4e6Sdrh   */
4936a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
4942958a4e6Sdrh 
4951ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
496e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
497e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
498e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
4991ccde15dSdrh   */
5005974a30fSdrh   if( pSelect ){
501142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
502e00ee6ebSdrh     ** as a co-routine.  The code is common to both the 3rd and 4th
503e00ee6ebSdrh     ** templates:
504e00ee6ebSdrh     **
505e00ee6ebSdrh     **         EOF <- 0
506e00ee6ebSdrh     **         X <- A
507e00ee6ebSdrh     **         goto B
508e00ee6ebSdrh     **      A: setup for the SELECT
509e00ee6ebSdrh     **         loop over the tables in the SELECT
510e00ee6ebSdrh     **           load value into register R..R+n
511e00ee6ebSdrh     **           yield X
512e00ee6ebSdrh     **         end loop
513e00ee6ebSdrh     **         cleanup after the SELECT
514e00ee6ebSdrh     **         EOF <- 1
515e00ee6ebSdrh     **         yield X
516e00ee6ebSdrh     **         halt-error
517e00ee6ebSdrh     **
518e00ee6ebSdrh     ** On each invocation of the co-routine, it puts a single row of the
519e00ee6ebSdrh     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
520e00ee6ebSdrh     ** (These output registers are allocated by sqlite3Select().)  When
521e00ee6ebSdrh     ** the SELECT completes, it sets the EOF flag stored in regEof.
522142e30dfSdrh     */
523e00ee6ebSdrh     int rc, j1;
5241013c932Sdrh 
525e00ee6ebSdrh     regEof = ++pParse->nMem;
526e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
527e00ee6ebSdrh     VdbeComment((v, "SELECT eof flag"));
52892b01d53Sdrh     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
529e00ee6ebSdrh     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
53092b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
531e00ee6ebSdrh     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
532e00ee6ebSdrh     VdbeComment((v, "Jump over SELECT coroutine"));
533b3bce662Sdanielk1977 
534b3bce662Sdanielk1977     /* Resolve the expressions in the SELECT statement and execute it. */
5357d10d5a6Sdrh     rc = sqlite3Select(pParse, pSelect, &dest);
53617435752Sdrh     if( rc || pParse->nErr || db->mallocFailed ){
5376f7adc8aSdrh       goto insert_cleanup;
5386f7adc8aSdrh     }
539e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
54092b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
541e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
542e00ee6ebSdrh     VdbeComment((v, "End of SELECT coroutine"));
543e00ee6ebSdrh     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
544b3bce662Sdanielk1977 
5456a288a33Sdrh     regFromSelect = dest.iMem;
5465974a30fSdrh     assert( pSelect->pEList );
547967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
548e00ee6ebSdrh     assert( dest.nMem==nColumn );
549142e30dfSdrh 
550142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
551e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
552e00ee6ebSdrh     ** FALSE if each* row of the SELECT can be written directly into
553e00ee6ebSdrh     ** the destination table (template 3).
554048c530cSdrh     **
555048c530cSdrh     ** A temp table must be used if the table being updated is also one
556048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
557048c530cSdrh     ** temp table in the case of row triggers.
558142e30dfSdrh     */
559e00ee6ebSdrh     if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){
560048c530cSdrh       useTempTable = 1;
561048c530cSdrh     }
562142e30dfSdrh 
563142e30dfSdrh     if( useTempTable ){
564e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
565e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
566e00ee6ebSdrh       ** here is from the 4th template:
567e00ee6ebSdrh       **
568e00ee6ebSdrh       **      B: open temp table
569e00ee6ebSdrh       **      L: yield X
570e00ee6ebSdrh       **         if EOF goto M
571e00ee6ebSdrh       **         insert row from R..R+n into temp table
572e00ee6ebSdrh       **         goto L
573e00ee6ebSdrh       **      M: ...
574142e30dfSdrh       */
575e00ee6ebSdrh       int regRec;          /* Register to hold packed record */
576*dc5ea5c7Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
577e00ee6ebSdrh       int addrTop;         /* Label "L" */
578e00ee6ebSdrh       int addrIf;          /* Address of jump to M */
579b7654111Sdrh 
580142e30dfSdrh       srcTab = pParse->nTab++;
581b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
582*dc5ea5c7Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
583e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
58492b01d53Sdrh       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
585e00ee6ebSdrh       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
5861db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
587*dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
588*dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
589e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
590e00ee6ebSdrh       sqlite3VdbeJumpHere(v, addrIf);
591b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
592*dc5ea5c7Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
593142e30dfSdrh     }
594142e30dfSdrh   }else{
595142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
596142e30dfSdrh     ** clause
597142e30dfSdrh     */
598b3bce662Sdanielk1977     NameContext sNC;
599b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
600b3bce662Sdanielk1977     sNC.pParse = pParse;
6015974a30fSdrh     srcTab = -1;
60248d1178aSdrh     assert( useTempTable==0 );
603147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
604e64e7b20Sdrh     for(i=0; i<nColumn; i++){
6057d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
606b04a5d87Sdrh         goto insert_cleanup;
607b04a5d87Sdrh       }
608e64e7b20Sdrh     }
6095974a30fSdrh   }
6101ccde15dSdrh 
6111ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
6121ccde15dSdrh   ** of columns to be inserted into the table.
6131ccde15dSdrh   */
614034ca14fSdanielk1977   if( IsVirtual(pTab) ){
615034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
616034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
617034ca14fSdanielk1977     }
618034ca14fSdanielk1977   }
619034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
6204adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
621da93d238Sdrh        "table %S has %d columns but %d values were supplied",
622da93d238Sdrh        pTabList, 0, pTab->nCol, nColumn);
623cce7d176Sdrh     goto insert_cleanup;
624cce7d176Sdrh   }
625967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
6264adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
627cce7d176Sdrh     goto insert_cleanup;
628cce7d176Sdrh   }
6291ccde15dSdrh 
6301ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
6311ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
6321ccde15dSdrh   ** remember the column indices.
633c8392586Sdrh   **
634c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
635c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
636c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
637c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
638c8392586Sdrh   ** is appears in the original table.  (The index of the primary
639c8392586Sdrh   ** key in the original table is pTab->iPKey.)
6401ccde15dSdrh   */
641967e8b73Sdrh   if( pColumn ){
642967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
643967e8b73Sdrh       pColumn->a[i].idx = -1;
644cce7d176Sdrh     }
645967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
646cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
6474adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
648967e8b73Sdrh           pColumn->a[i].idx = j;
6494a32431cSdrh           if( j==pTab->iPKey ){
6509aa028daSdrh             keyColumn = i;
6514a32431cSdrh           }
652cce7d176Sdrh           break;
653cce7d176Sdrh         }
654cce7d176Sdrh       }
655cce7d176Sdrh       if( j>=pTab->nCol ){
6564adee20fSdanielk1977         if( sqlite3IsRowid(pColumn->a[i].zName) ){
657a0217ba7Sdrh           keyColumn = i;
658a0217ba7Sdrh         }else{
6594adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
660da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
661cce7d176Sdrh           pParse->nErr++;
662cce7d176Sdrh           goto insert_cleanup;
663cce7d176Sdrh         }
664cce7d176Sdrh       }
665cce7d176Sdrh     }
666a0217ba7Sdrh   }
6671ccde15dSdrh 
668aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
669c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
670c8392586Sdrh   ** in the original table definition.
6714a32431cSdrh   */
672147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
6734a32431cSdrh     keyColumn = pTab->iPKey;
6744a32431cSdrh   }
6754a32431cSdrh 
676142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
677142e30dfSdrh   */
678dca76841Sdrh   if( triggers_exist ){
679cd3e8f7cSdanielk1977     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
68066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
681f29ce559Sdanielk1977   }
682c3f9bad2Sdanielk1977 
683c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
6841ccde15dSdrh   */
685142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
6866a288a33Sdrh     regRowCount = ++pParse->nMem;
6876a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
688c3f9bad2Sdanielk1977   }
689c3f9bad2Sdanielk1977 
690e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
691e448dc4aSdanielk1977   if( !isView ){
692aa9b8963Sdrh     int nIdx;
693aa9b8963Sdrh 
69404adf416Sdrh     baseCur = pParse->nTab;
69504adf416Sdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
6965c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
697aa9b8963Sdrh     if( aRegIdx==0 ){
698aa9b8963Sdrh       goto insert_cleanup;
699aa9b8963Sdrh     }
700aa9b8963Sdrh     for(i=0; i<nIdx; i++){
701aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
702aa9b8963Sdrh     }
703feeb1394Sdrh   }
704feeb1394Sdrh 
705e00ee6ebSdrh   /* This is the top of the main insertion loop */
706142e30dfSdrh   if( useTempTable ){
707e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
708e00ee6ebSdrh     ** following pseudocode (template 4):
709e00ee6ebSdrh     **
710e00ee6ebSdrh     **         rewind temp table
711e00ee6ebSdrh     **      C: loop over rows of intermediate table
712e00ee6ebSdrh     **           transfer values form intermediate table into <table>
713e00ee6ebSdrh     **         end loop
714e00ee6ebSdrh     **      D: ...
715e00ee6ebSdrh     */
716e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
717e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
718142e30dfSdrh   }else if( pSelect ){
719e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
720e00ee6ebSdrh     ** following pseudocode (template 3):
721e00ee6ebSdrh     **
722e00ee6ebSdrh     **      C: yield X
723e00ee6ebSdrh     **         if EOF goto D
724e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
725e00ee6ebSdrh     **         goto C
726e00ee6ebSdrh     **      D: ...
727e00ee6ebSdrh     */
72892b01d53Sdrh     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
729e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
730bed8690fSdrh   }
7311ccde15dSdrh 
7326a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
7336a288a33Sdrh   ** the content of the new row, and the assemblied row record.
7346a288a33Sdrh   */
7356a288a33Sdrh   regRecord = ++pParse->nMem;
7366a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
7376a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
7386a288a33Sdrh   if( IsVirtual(pTab) ){
7396a288a33Sdrh     regRowid++;
7406a288a33Sdrh     pParse->nMem++;
7416a288a33Sdrh   }
7426a288a33Sdrh   regData = regRowid+1;
7436a288a33Sdrh 
7445cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
74570ce3f0cSdrh   */
7464adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
747dca76841Sdrh   if( triggers_exist & TRIGGER_BEFORE ){
748*dc5ea5c7Sdrh     int regTrigRowid;
7492d401ab8Sdrh     int regCols;
7502d401ab8Sdrh     int regRec;
751c3f9bad2Sdanielk1977 
75270ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
75370ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
75470ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
75570ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
75670ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
75770ce3f0cSdrh     */
758*dc5ea5c7Sdrh     regTrigRowid = sqlite3GetTempReg(pParse);
75970ce3f0cSdrh     if( keyColumn<0 ){
760*dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
76170ce3f0cSdrh     }else if( useTempTable ){
762*dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
76370ce3f0cSdrh     }else{
7646a288a33Sdrh       int j1;
765d6fe961eSdrh       assert( pSelect==0 );  /* Otherwise useTempTable is true */
766*dc5ea5c7Sdrh       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
767*dc5ea5c7Sdrh       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
768*dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
7696a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
770*dc5ea5c7Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
77170ce3f0cSdrh     }
77270ce3f0cSdrh 
773034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
774034ca14fSdanielk1977     ** this block would have to account for hidden column.
775034ca14fSdanielk1977     */
776034ca14fSdanielk1977     assert(!IsVirtual(pTab));
777034ca14fSdanielk1977 
77870ce3f0cSdrh     /* Create the new column data
77970ce3f0cSdrh     */
7802d401ab8Sdrh     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
781c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
782c3f9bad2Sdanielk1977       if( pColumn==0 ){
783c3f9bad2Sdanielk1977         j = i;
784c3f9bad2Sdanielk1977       }else{
785c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
786c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
787c3f9bad2Sdanielk1977         }
788c3f9bad2Sdanielk1977       }
789c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
7902d401ab8Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
791142e30dfSdrh       }else if( useTempTable ){
7922d401ab8Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i);
793c3f9bad2Sdanielk1977       }else{
794d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
7952d401ab8Sdrh         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
796c3f9bad2Sdanielk1977       }
797c3f9bad2Sdanielk1977     }
7982d401ab8Sdrh     regRec = sqlite3GetTempReg(pParse);
7991db639ceSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
800a37cdde0Sdanielk1977 
801a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
802a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
803a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
804a37cdde0Sdanielk1977     ** table column affinities.
805a37cdde0Sdanielk1977     */
806a37cdde0Sdanielk1977     if( !isView ){
807a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
808a37cdde0Sdanielk1977     }
809*dc5ea5c7Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regTrigRowid);
8102d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRec);
811*dc5ea5c7Sdrh     sqlite3ReleaseTempReg(pParse, regTrigRowid);
8122d401ab8Sdrh     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
813c3f9bad2Sdanielk1977 
8145cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
815dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
8168f2c54e6Sdanielk1977         newIdx, -1, onError, endOfLoop, 0, 0) ){
817f29ce559Sdanielk1977       goto insert_cleanup;
818f29ce559Sdanielk1977     }
81970ce3f0cSdrh   }
820c3f9bad2Sdanielk1977 
8214a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
822f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
8234a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
824b419a926Sdrh   ** case the record number is the same as that column.
8251ccde15dSdrh   */
8265cf590c1Sdrh   if( !isView ){
8274cbdda9eSdrh     if( IsVirtual(pTab) ){
8284cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
8296a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
8304cbdda9eSdrh     }
8314a32431cSdrh     if( keyColumn>=0 ){
832142e30dfSdrh       if( useTempTable ){
8336a288a33Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
834142e30dfSdrh       }else if( pSelect ){
835b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
8364a32431cSdrh       }else{
837e4d90813Sdrh         VdbeOp *pOp;
8381db639ceSdrh         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
839e4d90813Sdrh         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
840bb50e7adSdanielk1977         if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
841e4d90813Sdrh           appendFlag = 1;
842e4d90813Sdrh           pOp->opcode = OP_NewRowid;
84304adf416Sdrh           pOp->p1 = baseCur;
8446a288a33Sdrh           pOp->p2 = regRowid;
8456a288a33Sdrh           pOp->p3 = regAutoinc;
846e4d90813Sdrh         }
84727a32783Sdrh       }
848f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
849e1e68f49Sdrh       ** to generate a unique primary key value.
850e1e68f49Sdrh       */
851e4d90813Sdrh       if( !appendFlag ){
8521db639ceSdrh         int j1;
853bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
8541db639ceSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
85504adf416Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
8561db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
857bb50e7adSdanielk1977         }else{
858bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
859bb50e7adSdanielk1977           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
860bb50e7adSdanielk1977         }
8613c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
862e4d90813Sdrh       }
8634cbdda9eSdrh     }else if( IsVirtual(pTab) ){
8646a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
8654a32431cSdrh     }else{
86604adf416Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
867e4d90813Sdrh       appendFlag = 1;
8684a32431cSdrh     }
8696a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
8704a32431cSdrh 
871aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
8724a32431cSdrh     ** with the first column.
8734a32431cSdrh     */
874034ca14fSdanielk1977     nHidden = 0;
875cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
8766a288a33Sdrh       int iRegStore = regRowid+1+i;
8774a32431cSdrh       if( i==pTab->iPKey ){
8784a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
879aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
880aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
881aacc543eSdrh         ** taking up data space with information that will never be used. */
8824c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
8834a32431cSdrh         continue;
8844a32431cSdrh       }
885967e8b73Sdrh       if( pColumn==0 ){
886034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
887034ca14fSdanielk1977           assert( IsVirtual(pTab) );
888034ca14fSdanielk1977           j = -1;
889034ca14fSdanielk1977           nHidden++;
890034ca14fSdanielk1977         }else{
891034ca14fSdanielk1977           j = i - nHidden;
892034ca14fSdanielk1977         }
893cce7d176Sdrh       }else{
894967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
895967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
896cce7d176Sdrh         }
897cce7d176Sdrh       }
898034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
899287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
900142e30dfSdrh       }else if( useTempTable ){
901287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
902142e30dfSdrh       }else if( pSelect ){
903b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
904cce7d176Sdrh       }else{
905287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
906cce7d176Sdrh       }
907cce7d176Sdrh     }
9081ccde15dSdrh 
9090ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
9100ca3e24bSdrh     ** do the insertion.
9114a32431cSdrh     */
9124cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
9134cbdda9eSdrh     if( IsVirtual(pTab) ){
9144f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
9156a288a33Sdrh       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
91666a5167bSdrh                      (const char*)pTab->pVtab, P4_VTAB);
9174cbdda9eSdrh     }else
9184cbdda9eSdrh #endif
9194cbdda9eSdrh     {
92004adf416Sdrh       sqlite3GenerateConstraintChecks(
92104adf416Sdrh           pParse,
92204adf416Sdrh           pTab,
92304adf416Sdrh           baseCur,
92404adf416Sdrh           regIns,
92504adf416Sdrh           aRegIdx,
92604adf416Sdrh           keyColumn>=0,
92704adf416Sdrh           0,
92804adf416Sdrh           onError,
92904adf416Sdrh           endOfLoop
93004adf416Sdrh       );
93104adf416Sdrh       sqlite3CompleteInsertion(
93204adf416Sdrh           pParse,
93304adf416Sdrh           pTab,
93404adf416Sdrh           baseCur,
93504adf416Sdrh           regIns,
93604adf416Sdrh           aRegIdx,
93704adf416Sdrh           0,
938e4d90813Sdrh           (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
93904adf416Sdrh           appendFlag
94004adf416Sdrh        );
9415cf590c1Sdrh     }
9424cbdda9eSdrh   }
9431bee3d7bSdrh 
944feeb1394Sdrh   /* Update the count of rows that are inserted
9451bee3d7bSdrh   */
946142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
9476a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
9481bee3d7bSdrh   }
949c3f9bad2Sdanielk1977 
950dca76841Sdrh   if( triggers_exist ){
951c3f9bad2Sdanielk1977     /* Code AFTER triggers */
952dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
9538f2c54e6Sdanielk1977           newIdx, -1, onError, endOfLoop, 0, 0) ){
954f29ce559Sdanielk1977       goto insert_cleanup;
955f29ce559Sdanielk1977     }
956c3f9bad2Sdanielk1977   }
9571bee3d7bSdrh 
958e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
959e00ee6ebSdrh   ** is a SELECT statement.
9601ccde15dSdrh   */
9614adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
962142e30dfSdrh   if( useTempTable ){
963e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
964e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
9652eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
966142e30dfSdrh   }else if( pSelect ){
967e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
968e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
9696b56344dSdrh   }
970c3f9bad2Sdanielk1977 
971e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
972c3f9bad2Sdanielk1977     /* Close all tables opened */
9732eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
9746b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
9752eb95377Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
976cce7d176Sdrh     }
977c3f9bad2Sdanielk1977   }
978c3f9bad2Sdanielk1977 
979f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
9806a288a33Sdrh   ** counter value in memory regAutoinc back into the sqlite_sequence
981f3388144Sdrh   ** table.
9822958a4e6Sdrh   */
9836a288a33Sdrh   autoIncEnd(pParse, iDb, pTab, regAutoinc);
9842958a4e6Sdrh 
9851bee3d7bSdrh   /*
986e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
987e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
988e7de6f25Sdanielk1977   ** invoke the callback function.
9891bee3d7bSdrh   */
990cc6bd383Sdanielk1977   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
9916a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
99222322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
99310fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
9941bee3d7bSdrh   }
995cce7d176Sdrh 
996cce7d176Sdrh insert_cleanup:
997633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
998633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
999633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1000633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1001633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1002cce7d176Sdrh }
10039cfcf5d4Sdrh 
10049cfcf5d4Sdrh /*
10056a288a33Sdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
10069cfcf5d4Sdrh **
100704adf416Sdrh ** The input is a range of consecutive registers as follows:
10080ca3e24bSdrh **
1009f0863fe5Sdrh **    1.  The rowid of the row to be updated before the update.  This
1010b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
1011a05a722fSdrh **        change to the record number or writing to a virtual table.
10120ca3e24bSdrh **
1013f0863fe5Sdrh **    2.  The rowid of the row after the update.
10140ca3e24bSdrh **
10150ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
10160ca3e24bSdrh **
10170ca3e24bSdrh **    i.  Data from middle columns...
10180ca3e24bSdrh **
10190ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
10200ca3e24bSdrh **
102104adf416Sdrh ** The regRowid parameter is the index of the register containing (2).
102204adf416Sdrh **
1023f0863fe5Sdrh ** The old rowid shown as entry (1) above is omitted unless both isUpdate
1024f0863fe5Sdrh ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
1025a05a722fSdrh ** INSERTs.  RowidChng means that the new rowid is explicitly specified by
1026a05a722fSdrh ** the update or insert statement.  If rowidChng is false, it means that
1027a05a722fSdrh ** the rowid is computed automatically in an insert or that the rowid value
1028a05a722fSdrh ** is not modified by the update.
10290ca3e24bSdrh **
1030aa9b8963Sdrh ** The code generated by this routine store new index entries into
1031aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1032aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1033aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
1034aa9b8963Sdrh ** attached to the table.
10359cfcf5d4Sdrh **
10369cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
10379cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
10381c92853dSdrh ** then the appropriate action is performed.  There are five possible
10391c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
10409cfcf5d4Sdrh **
10419cfcf5d4Sdrh **  Constraint type  Action       What Happens
10429cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
10431c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
104424b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
10459cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
10469cfcf5d4Sdrh **
10471c92853dSdrh **  any              ABORT        Back out changes from the current command
10481c92853dSdrh **                                only (do not do a complete rollback) then
104924b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
10501c92853dSdrh **                                with SQLITE_CONSTRAINT.
10511c92853dSdrh **
10521c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
10531c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
10541c92853dSdrh **                                transaction is not rolled back and any
10551c92853dSdrh **                                prior changes are retained.
10561c92853dSdrh **
10579cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
10589cfcf5d4Sdrh **                                the stack and there is an immediate jump
10599cfcf5d4Sdrh **                                to label ignoreDest.
10609cfcf5d4Sdrh **
10619cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
10629cfcf5d4Sdrh **                                value for that column.  If the default value
10639cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
10649cfcf5d4Sdrh **
10659cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
10669cfcf5d4Sdrh **                                being inserted is removed.
10679cfcf5d4Sdrh **
10689cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
10699cfcf5d4Sdrh **
10701c92853dSdrh ** Which action to take is determined by the overrideError parameter.
10711c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
10721c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
10731c92853dSdrh ** for the constraint is used.
10749cfcf5d4Sdrh **
1075aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
107604adf416Sdrh ** cursor number "baseCur".  All indices of pTab must also have open
107704adf416Sdrh ** read/write cursors with cursor number baseCur+i for the i-th cursor.
10789cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
1079aa9b8963Sdrh ** cursors do not need to be open for indices where aRegIdx[i]==0.
10809cfcf5d4Sdrh */
10814adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
10829cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
10839cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
108404adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
108504adf416Sdrh   int regRowid,       /* Index of the range of input registers */
1086aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1087a05a722fSdrh   int rowidChng,      /* True if the rowid might collide with existing entry */
1088b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
10899cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
1090b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
10919cfcf5d4Sdrh ){
10929cfcf5d4Sdrh   int i;
10939cfcf5d4Sdrh   Vdbe *v;
10949cfcf5d4Sdrh   int nCol;
10959cfcf5d4Sdrh   int onError;
1096a05a722fSdrh   int j1, j2, j3;     /* Addresses of jump instructions */
109704adf416Sdrh   int regData;        /* Register containing first data column */
10980ca3e24bSdrh   int iCur;
10990ca3e24bSdrh   Index *pIdx;
11000ca3e24bSdrh   int seenReplace = 0;
1101f0863fe5Sdrh   int hasTwoRowids = (isUpdate && rowidChng);
11029cfcf5d4Sdrh 
11034adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
11049cfcf5d4Sdrh   assert( v!=0 );
1105417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
11069cfcf5d4Sdrh   nCol = pTab->nCol;
1107aa9b8963Sdrh   regData = regRowid + 1;
1108aa9b8963Sdrh 
110904adf416Sdrh 
11109cfcf5d4Sdrh   /* Test all NOT NULL constraints.
11119cfcf5d4Sdrh   */
11129cfcf5d4Sdrh   for(i=0; i<nCol; i++){
11130ca3e24bSdrh     if( i==pTab->iPKey ){
11140ca3e24bSdrh       continue;
11150ca3e24bSdrh     }
11169cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
11170ca3e24bSdrh     if( onError==OE_None ) continue;
11189cfcf5d4Sdrh     if( overrideError!=OE_Default ){
11199cfcf5d4Sdrh       onError = overrideError;
1120a996e477Sdrh     }else if( onError==OE_Default ){
1121a996e477Sdrh       onError = OE_Abort;
11229cfcf5d4Sdrh     }
11237977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
11249cfcf5d4Sdrh       onError = OE_Abort;
11259cfcf5d4Sdrh     }
1126aa9b8963Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
1127b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1128b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
11299cfcf5d4Sdrh     switch( onError ){
11301c92853dSdrh       case OE_Rollback:
11311c92853dSdrh       case OE_Abort:
11321c92853dSdrh       case OE_Fail: {
1133f089aa45Sdrh         char *zMsg;
113466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1135f089aa45Sdrh         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
1136f089aa45Sdrh                               pTab->zName, pTab->aCol[i].zName);
113766a5167bSdrh         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
11389cfcf5d4Sdrh         break;
11399cfcf5d4Sdrh       }
11409cfcf5d4Sdrh       case OE_Ignore: {
114166a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
11429cfcf5d4Sdrh         break;
11439cfcf5d4Sdrh       }
11449cfcf5d4Sdrh       case OE_Replace: {
114504adf416Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
11469cfcf5d4Sdrh         break;
11479cfcf5d4Sdrh       }
11489cfcf5d4Sdrh     }
1149aa9b8963Sdrh     sqlite3VdbeJumpHere(v, j1);
11509cfcf5d4Sdrh   }
11519cfcf5d4Sdrh 
11529cfcf5d4Sdrh   /* Test all CHECK constraints
11539cfcf5d4Sdrh   */
1154ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
11550cd2d4c9Sdrh   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
1156ffe07b2dSdrh     int allOk = sqlite3VdbeMakeLabel(v);
1157aa9b8963Sdrh     pParse->ckBase = regData;
115835573356Sdrh     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
1159aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
11602e06c67cSdrh     if( onError==OE_Ignore ){
116166a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1162aa01c7e2Sdrh     }else{
116366a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1164aa01c7e2Sdrh     }
1165ffe07b2dSdrh     sqlite3VdbeResolveLabel(v, allOk);
1166ffe07b2dSdrh   }
1167ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
11689cfcf5d4Sdrh 
11690bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
11700bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
11710bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
11729cfcf5d4Sdrh   */
1173f0863fe5Sdrh   if( rowidChng ){
11740ca3e24bSdrh     onError = pTab->keyConf;
11750ca3e24bSdrh     if( overrideError!=OE_Default ){
11760ca3e24bSdrh       onError = overrideError;
1177a996e477Sdrh     }else if( onError==OE_Default ){
1178a996e477Sdrh       onError = OE_Abort;
11790ca3e24bSdrh     }
1180a0217ba7Sdrh 
118160a713c6Sdrh     if( onError!=OE_Replace || pTab->pIndex ){
118279b0c956Sdrh       if( isUpdate ){
1183892d3179Sdrh         j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
118479b0c956Sdrh       }
118504adf416Sdrh       j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
11860ca3e24bSdrh       switch( onError ){
1187a0217ba7Sdrh         default: {
1188a0217ba7Sdrh           onError = OE_Abort;
1189a0217ba7Sdrh           /* Fall thru into the next case */
1190a0217ba7Sdrh         }
11911c92853dSdrh         case OE_Rollback:
11921c92853dSdrh         case OE_Abort:
11931c92853dSdrh         case OE_Fail: {
119466a5167bSdrh           sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
119566a5167bSdrh                            "PRIMARY KEY must be unique", P4_STATIC);
11960ca3e24bSdrh           break;
11970ca3e24bSdrh         }
11985383ae5cSdrh         case OE_Replace: {
11992d401ab8Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
12005383ae5cSdrh           seenReplace = 1;
12015383ae5cSdrh           break;
12025383ae5cSdrh         }
12030ca3e24bSdrh         case OE_Ignore: {
12045383ae5cSdrh           assert( seenReplace==0 );
120566a5167bSdrh           sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
12060ca3e24bSdrh           break;
12070ca3e24bSdrh         }
12080ca3e24bSdrh       }
1209aa9b8963Sdrh       sqlite3VdbeJumpHere(v, j3);
1210f5905aa7Sdrh       if( isUpdate ){
1211aa9b8963Sdrh         sqlite3VdbeJumpHere(v, j2);
1212a05a722fSdrh       }
12130ca3e24bSdrh     }
12140ca3e24bSdrh   }
12150bd1f4eaSdrh 
12160bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
12170bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
12180bd1f4eaSdrh   ** Add the new records to the indices as we go.
12190bd1f4eaSdrh   */
1220b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
12212d401ab8Sdrh     int regIdx;
12222d401ab8Sdrh     int regR;
12232d401ab8Sdrh 
1224aa9b8963Sdrh     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
1225b2fe7d8cSdrh 
1226b2fe7d8cSdrh     /* Create a key for accessing the index entry */
12272d401ab8Sdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
12289cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
12299cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
12309cfcf5d4Sdrh       if( idx==pTab->iPKey ){
12312d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
12329cfcf5d4Sdrh       }else{
12332d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
12349cfcf5d4Sdrh       }
12359cfcf5d4Sdrh     }
12362d401ab8Sdrh     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
12371db639ceSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
1238a37cdde0Sdanielk1977     sqlite3IndexAffinityStr(v, pIdx);
1239da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
12402d401ab8Sdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
1241b2fe7d8cSdrh 
1242b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
12439cfcf5d4Sdrh     onError = pIdx->onError;
1244b2fe7d8cSdrh     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
12459cfcf5d4Sdrh     if( overrideError!=OE_Default ){
12469cfcf5d4Sdrh       onError = overrideError;
1247a996e477Sdrh     }else if( onError==OE_Default ){
1248a996e477Sdrh       onError = OE_Abort;
12499cfcf5d4Sdrh     }
12505383ae5cSdrh     if( seenReplace ){
12515383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
12525383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
12535383ae5cSdrh     }
12545383ae5cSdrh 
1255b2fe7d8cSdrh 
1256b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
12572d401ab8Sdrh     j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
12582d401ab8Sdrh     regR = sqlite3GetTempReg(pParse);
12592d401ab8Sdrh     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
12602d401ab8Sdrh     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
12611fc4129dSshane                            regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
1262a9e852b6Smlcreech                            P4_INT32);
1263b2fe7d8cSdrh 
1264b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1265b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1266b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
12679cfcf5d4Sdrh     switch( onError ){
12681c92853dSdrh       case OE_Rollback:
12691c92853dSdrh       case OE_Abort:
12701c92853dSdrh       case OE_Fail: {
127137ed48edSdrh         int j, n1, n2;
127237ed48edSdrh         char zErrMsg[200];
127300e13613Sdanielk1977         sqlite3_snprintf(ArraySize(zErrMsg), zErrMsg,
12745bb3eb9bSdrh                          pIdx->nColumn>1 ? "columns " : "column ");
127537ed48edSdrh         n1 = strlen(zErrMsg);
127600e13613Sdanielk1977         for(j=0; j<pIdx->nColumn && n1<ArraySize(zErrMsg)-30; j++){
127737ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
127837ed48edSdrh           n2 = strlen(zCol);
127937ed48edSdrh           if( j>0 ){
128000e13613Sdanielk1977             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], ", ");
128137ed48edSdrh             n1 += 2;
128237ed48edSdrh           }
128300e13613Sdanielk1977           if( n1+n2>ArraySize(zErrMsg)-30 ){
128400e13613Sdanielk1977             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "...");
128537ed48edSdrh             n1 += 3;
128637ed48edSdrh             break;
128737ed48edSdrh           }else{
128800e13613Sdanielk1977             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
128937ed48edSdrh             n1 += n2;
129037ed48edSdrh           }
129137ed48edSdrh         }
129200e13613Sdanielk1977         sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1],
129337ed48edSdrh             pIdx->nColumn>1 ? " are not unique" : " is not unique");
129466a5167bSdrh         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
12959cfcf5d4Sdrh         break;
12969cfcf5d4Sdrh       }
12979cfcf5d4Sdrh       case OE_Ignore: {
12980ca3e24bSdrh         assert( seenReplace==0 );
129966a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
13009cfcf5d4Sdrh         break;
13019cfcf5d4Sdrh       }
13029cfcf5d4Sdrh       case OE_Replace: {
13032d401ab8Sdrh         sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
13040ca3e24bSdrh         seenReplace = 1;
13059cfcf5d4Sdrh         break;
13069cfcf5d4Sdrh       }
13079cfcf5d4Sdrh     }
1308aa9b8963Sdrh     sqlite3VdbeJumpHere(v, j2);
13092d401ab8Sdrh     sqlite3VdbeJumpHere(v, j3);
13102d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regR);
13119cfcf5d4Sdrh   }
13129cfcf5d4Sdrh }
13130ca3e24bSdrh 
13140ca3e24bSdrh /*
13150ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
13164adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
131704adf416Sdrh ** A consecutive range of registers starting at regRowid contains the
131804adf416Sdrh ** rowid and the content to be inserted.
13190ca3e24bSdrh **
1320b419a926Sdrh ** The arguments to this routine should be the same as the first six
13214adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
13220ca3e24bSdrh */
13234adee20fSdanielk1977 void sqlite3CompleteInsertion(
13240ca3e24bSdrh   Parse *pParse,      /* The parser context */
13250ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
132604adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
132704adf416Sdrh   int regRowid,       /* Range of content */
1328aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
132970ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1330e4d90813Sdrh   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
1331e4d90813Sdrh   int appendBias      /* True if this is likely to be an append */
13320ca3e24bSdrh ){
13330ca3e24bSdrh   int i;
13340ca3e24bSdrh   Vdbe *v;
13350ca3e24bSdrh   int nIdx;
13360ca3e24bSdrh   Index *pIdx;
1337b28af71aSdanielk1977   int pik_flags;
133804adf416Sdrh   int regData;
1339b7654111Sdrh   int regRec;
13400ca3e24bSdrh 
13414adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
13420ca3e24bSdrh   assert( v!=0 );
1343417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
13440ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
13450ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
1346aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
134704adf416Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
13480ca3e24bSdrh   }
134904adf416Sdrh   regData = regRowid + 1;
1350b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
13511db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1352a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1353da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
1354b84f96f8Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
135570ce3f0cSdrh   if( newIdx>=0 ){
1356b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
135770ce3f0cSdrh   }
1358b84f96f8Sdanielk1977 #endif
13594794f735Sdrh   if( pParse->nested ){
13604794f735Sdrh     pik_flags = 0;
13614794f735Sdrh   }else{
136294eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
136394eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
13644794f735Sdrh   }
1365e4d90813Sdrh   if( appendBias ){
1366e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1367e4d90813Sdrh   }
1368b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
136994eb6a14Sdanielk1977   if( !pParse->nested ){
137066a5167bSdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
137194eb6a14Sdanielk1977   }
1372b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
13730ca3e24bSdrh }
1374cd44690aSdrh 
1375cd44690aSdrh /*
1376290c1948Sdrh ** Generate code that will open cursors for a table and for all
137704adf416Sdrh ** indices of that table.  The "baseCur" parameter is the cursor number used
1378cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1379aa9b8963Sdrh **
1380aa9b8963Sdrh ** Return the number of indices on the table.
1381cd44690aSdrh */
1382aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1383290c1948Sdrh   Parse *pParse,   /* Parsing context */
1384290c1948Sdrh   Table *pTab,     /* Table to be opened */
138504adf416Sdrh   int baseCur,     /* Cursor number assigned to the table */
1386290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1387290c1948Sdrh ){
1388cd44690aSdrh   int i;
13894cbdda9eSdrh   int iDb;
1390cd44690aSdrh   Index *pIdx;
13914cbdda9eSdrh   Vdbe *v;
13924cbdda9eSdrh 
1393aa9b8963Sdrh   if( IsVirtual(pTab) ) return 0;
13944cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
13954cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1396cd44690aSdrh   assert( v!=0 );
139704adf416Sdrh   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
1398cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1399b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1400da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
140104adf416Sdrh     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
140266a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1403207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1404cd44690aSdrh   }
140504adf416Sdrh   if( pParse->nTab<=baseCur+i ){
140604adf416Sdrh     pParse->nTab = baseCur+i;
1407290c1948Sdrh   }
1408aa9b8963Sdrh   return i-1;
1409cd44690aSdrh }
14109d9cf229Sdrh 
141191c58e23Sdrh 
141291c58e23Sdrh #ifdef SQLITE_TEST
141391c58e23Sdrh /*
141491c58e23Sdrh ** The following global variable is incremented whenever the
141591c58e23Sdrh ** transfer optimization is used.  This is used for testing
141691c58e23Sdrh ** purposes only - to make sure the transfer optimization really
141791c58e23Sdrh ** is happening when it is suppose to.
141891c58e23Sdrh */
141991c58e23Sdrh int sqlite3_xferopt_count;
142091c58e23Sdrh #endif /* SQLITE_TEST */
142191c58e23Sdrh 
142291c58e23Sdrh 
14239d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
14249d9cf229Sdrh /*
14259d9cf229Sdrh ** Check to collation names to see if they are compatible.
14269d9cf229Sdrh */
14279d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
14289d9cf229Sdrh   if( z1==0 ){
14299d9cf229Sdrh     return z2==0;
14309d9cf229Sdrh   }
14319d9cf229Sdrh   if( z2==0 ){
14329d9cf229Sdrh     return 0;
14339d9cf229Sdrh   }
14349d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
14359d9cf229Sdrh }
14369d9cf229Sdrh 
14379d9cf229Sdrh 
14389d9cf229Sdrh /*
14399d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
14409d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
14419d9cf229Sdrh ** for a compatible index:
14429d9cf229Sdrh **
14439d9cf229Sdrh **    *   The index is over the same set of columns
14449d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
14459d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
14469d9cf229Sdrh **    *   The same collating sequence on each column
14479d9cf229Sdrh */
14489d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
14499d9cf229Sdrh   int i;
14509d9cf229Sdrh   assert( pDest && pSrc );
14519d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
14529d9cf229Sdrh   if( pDest->nColumn!=pSrc->nColumn ){
14539d9cf229Sdrh     return 0;   /* Different number of columns */
14549d9cf229Sdrh   }
14559d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
14569d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
14579d9cf229Sdrh   }
14589d9cf229Sdrh   for(i=0; i<pSrc->nColumn; i++){
14599d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
14609d9cf229Sdrh       return 0;   /* Different columns indexed */
14619d9cf229Sdrh     }
14629d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
14639d9cf229Sdrh       return 0;   /* Different sort orders */
14649d9cf229Sdrh     }
14659d9cf229Sdrh     if( pSrc->azColl[i]!=pDest->azColl[i] ){
146660a713c6Sdrh       return 0;   /* Different collating sequences */
14679d9cf229Sdrh     }
14689d9cf229Sdrh   }
14699d9cf229Sdrh 
14709d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
14719d9cf229Sdrh   return 1;
14729d9cf229Sdrh }
14739d9cf229Sdrh 
14749d9cf229Sdrh /*
14759d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
14769d9cf229Sdrh **
14779d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
14789d9cf229Sdrh **
14799d9cf229Sdrh ** This optimization is only attempted if
14809d9cf229Sdrh **
14819d9cf229Sdrh **    (1)  tab1 and tab2 have identical schemas including all the
14828103b7d2Sdrh **         same indices and constraints
14839d9cf229Sdrh **
14849d9cf229Sdrh **    (2)  tab1 and tab2 are different tables
14859d9cf229Sdrh **
14869d9cf229Sdrh **    (3)  There must be no triggers on tab1
14879d9cf229Sdrh **
14889d9cf229Sdrh **    (4)  The result set of the SELECT statement is "*"
14899d9cf229Sdrh **
14909d9cf229Sdrh **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
14919d9cf229Sdrh **         or LIMIT clause.
14929d9cf229Sdrh **
14939d9cf229Sdrh **    (6)  The SELECT statement is a simple (not a compound) select that
14949d9cf229Sdrh **         contains only tab2 in its FROM clause
14959d9cf229Sdrh **
14969d9cf229Sdrh ** This method for implementing the INSERT transfers raw records from
14979d9cf229Sdrh ** tab2 over to tab1.  The columns are not decoded.  Raw records from
14989d9cf229Sdrh ** the indices of tab2 are transfered to tab1 as well.  In so doing,
14999d9cf229Sdrh ** the resulting tab1 has much less fragmentation.
15009d9cf229Sdrh **
15019d9cf229Sdrh ** This routine returns TRUE if the optimization is attempted.  If any
15029d9cf229Sdrh ** of the conditions above fail so that the optimization should not
15039d9cf229Sdrh ** be attempted, then this routine returns FALSE.
15049d9cf229Sdrh */
15059d9cf229Sdrh static int xferOptimization(
15069d9cf229Sdrh   Parse *pParse,        /* Parser context */
15079d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
15089d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
15099d9cf229Sdrh   int onError,          /* How to handle constraint errors */
15109d9cf229Sdrh   int iDbDest           /* The database of pDest */
15119d9cf229Sdrh ){
15129d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
15139d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
15149d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
15159d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
15169d9cf229Sdrh   int i;                           /* Loop counter */
15179d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
15189d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
15199d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
15209d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
15219d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
15229d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
15239d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
15246a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1525f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1526b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
15279d9cf229Sdrh 
15289d9cf229Sdrh   if( pSelect==0 ){
15299d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
15309d9cf229Sdrh   }
15319d9cf229Sdrh   if( pDest->pTrigger ){
15329d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
15339d9cf229Sdrh   }
15349d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
15357d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
15369d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
15379d9cf229Sdrh   }
15389d9cf229Sdrh #endif
15399d9cf229Sdrh   if( onError==OE_Default ){
15409d9cf229Sdrh     onError = OE_Abort;
15419d9cf229Sdrh   }
15429d9cf229Sdrh   if( onError!=OE_Abort && onError!=OE_Rollback ){
15439d9cf229Sdrh     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
15449d9cf229Sdrh   }
15455ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
15469d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
15479d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
15489d9cf229Sdrh   }
15499d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
15509d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
15519d9cf229Sdrh   }
15529d9cf229Sdrh   if( pSelect->pWhere ){
15539d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
15549d9cf229Sdrh   }
15559d9cf229Sdrh   if( pSelect->pOrderBy ){
15569d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
15579d9cf229Sdrh   }
15588103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
15598103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
15609d9cf229Sdrh   if( pSelect->pGroupBy ){
15619d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
15629d9cf229Sdrh   }
15639d9cf229Sdrh   if( pSelect->pLimit ){
15649d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
15659d9cf229Sdrh   }
15668103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
15679d9cf229Sdrh   if( pSelect->pPrior ){
15689d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
15699d9cf229Sdrh   }
15707d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
15719d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
15729d9cf229Sdrh   }
15739d9cf229Sdrh   pEList = pSelect->pEList;
15749d9cf229Sdrh   assert( pEList!=0 );
15759d9cf229Sdrh   if( pEList->nExpr!=1 ){
15769d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
15779d9cf229Sdrh   }
15789d9cf229Sdrh   assert( pEList->a[0].pExpr );
15799d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
15809d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
15819d9cf229Sdrh   }
15829d9cf229Sdrh 
15839d9cf229Sdrh   /* At this point we have established that the statement is of the
15849d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
15859d9cf229Sdrh   ** we have to check the semantics.
15869d9cf229Sdrh   */
15879d9cf229Sdrh   pItem = pSelect->pSrc->a;
1588ca424114Sdrh   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
15899d9cf229Sdrh   if( pSrc==0 ){
15909d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
15919d9cf229Sdrh   }
15929d9cf229Sdrh   if( pSrc==pDest ){
15939d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
15949d9cf229Sdrh   }
15959d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
15967d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
15979d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
15989d9cf229Sdrh   }
15999d9cf229Sdrh #endif
16009d9cf229Sdrh   if( pSrc->pSelect ){
16019d9cf229Sdrh     return 0;   /* tab2 may not be a view */
16029d9cf229Sdrh   }
16039d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
16049d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
16059d9cf229Sdrh   }
16069d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
16079d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
16089d9cf229Sdrh   }
16099d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
16109d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
16119d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
16129d9cf229Sdrh     }
16139d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
16149d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
16159d9cf229Sdrh     }
16169d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
16179d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
16189d9cf229Sdrh     }
16199d9cf229Sdrh   }
16209d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1621f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1622f33c9fadSdrh       destHasUniqueIdx = 1;
1623f33c9fadSdrh     }
16249d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
16259d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
16269d9cf229Sdrh     }
16279d9cf229Sdrh     if( pSrcIdx==0 ){
16289d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
16299d9cf229Sdrh     }
16309d9cf229Sdrh   }
16317fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1632fb658dedSdrh   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
16338103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
16348103b7d2Sdrh   }
16357fc2f41bSdrh #endif
16369d9cf229Sdrh 
16379d9cf229Sdrh   /* If we get this far, it means either:
16389d9cf229Sdrh   **
16399d9cf229Sdrh   **    *   We can always do the transfer if the table contains an
16409d9cf229Sdrh   **        an integer primary key
16419d9cf229Sdrh   **
16429d9cf229Sdrh   **    *   We can conditionally do the transfer if the destination
16439d9cf229Sdrh   **        table is empty.
16449d9cf229Sdrh   */
1645dd73521bSdrh #ifdef SQLITE_TEST
1646dd73521bSdrh   sqlite3_xferopt_count++;
1647dd73521bSdrh #endif
16489d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
16499d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1650f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
16519d9cf229Sdrh   iSrc = pParse->nTab++;
16529d9cf229Sdrh   iDest = pParse->nTab++;
16536a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
16549d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1655f33c9fadSdrh   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
1656bd36ba69Sdrh     /* If tables do not have an INTEGER PRIMARY KEY and there
1657bd36ba69Sdrh     ** are indices to be copied and the destination is not empty,
1658bd36ba69Sdrh     ** we have to disallow the transfer optimization because the
1659bd36ba69Sdrh     ** the rowids might change which will mess up indexing.
1660f33c9fadSdrh     **
1661f33c9fadSdrh     ** Or if the destination has a UNIQUE index and is not empty,
1662f33c9fadSdrh     ** we also disallow the transfer optimization because we cannot
1663f33c9fadSdrh     ** insure that all entries in the union of DEST and SRC will be
1664f33c9fadSdrh     ** unique.
16659d9cf229Sdrh     */
166666a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
166766a5167bSdrh     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
16689d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
16699d9cf229Sdrh   }else{
16709d9cf229Sdrh     emptyDestTest = 0;
16719d9cf229Sdrh   }
16729d9cf229Sdrh   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
167366a5167bSdrh   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1674b7654111Sdrh   regData = sqlite3GetTempReg(pParse);
1675b7654111Sdrh   regRowid = sqlite3GetTempReg(pParse);
167642242dedSdrh   if( pDest->iPKey>=0 ){
1677b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1678b7654111Sdrh     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
167966a5167bSdrh     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
168066a5167bSdrh                       "PRIMARY KEY must be unique", P4_STATIC);
16819d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr2);
1682b7654111Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
1683bd36ba69Sdrh   }else if( pDest->pIndex==0 ){
1684b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
168595bad4c7Sdrh   }else{
1686b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
16877d10d5a6Sdrh     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
168895bad4c7Sdrh   }
1689b7654111Sdrh   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1690b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1691b7654111Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
16921f4aa337Sdanielk1977   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
169366a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
16946a288a33Sdrh   autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
16959d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
16969d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
16979d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
16989d9cf229Sdrh     }
16999d9cf229Sdrh     assert( pSrcIdx );
170066a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
170166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
17029d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1703207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1704207872a4Sdanielk1977                       (char*)pKey, P4_KEYINFO_HANDOFF);
1705d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
17069d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1707207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
170866a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1709207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
171066a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1711b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1712b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
171366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
17149d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
17159d9cf229Sdrh   }
17169d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
1717b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
1718b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
171966a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
172066a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
17219d9cf229Sdrh   if( emptyDestTest ){
172266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
17239d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
172466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
17259d9cf229Sdrh     return 0;
17269d9cf229Sdrh   }else{
17279d9cf229Sdrh     return 1;
17289d9cf229Sdrh   }
17299d9cf229Sdrh }
17309d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
1731f39d9588Sdrh 
1732f39d9588Sdrh /* Make sure "isView" gets undefined in case this file becomes part of
1733f39d9588Sdrh ** the amalgamation - so that subsequent files do not see isView as a
1734f39d9588Sdrh ** macro. */
1735f39d9588Sdrh #undef isView
1736