xref: /sqlite-3.40.0/src/insert.c (revision bb50e7ad)
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*bb50e7adSdanielk1977 ** $Id: insert.c,v 1.244 2008/07/04 10:56:08 danielk1977 Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19cce7d176Sdrh /*
2066a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
21a37cdde0Sdanielk1977 ** string for index pIdx. A column affinity string has one character
223d1bfeaaSdanielk1977 ** for each column in the table, according to the affinity of the column:
233d1bfeaaSdanielk1977 **
243d1bfeaaSdanielk1977 **  Character      Column affinity
253d1bfeaaSdanielk1977 **  ------------------------------
263eda040bSdrh **  'a'            TEXT
273eda040bSdrh **  'b'            NONE
283eda040bSdrh **  'c'            NUMERIC
293eda040bSdrh **  'd'            INTEGER
303eda040bSdrh **  'e'            REAL
312d401ab8Sdrh **
322d401ab8Sdrh ** An extra 'b' is appended to the end of the string to cover the
332d401ab8Sdrh ** rowid that appears as the last column in every index.
343d1bfeaaSdanielk1977 */
35a37cdde0Sdanielk1977 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
36a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
37e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
38a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
39e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
40a37cdde0Sdanielk1977     **
41a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
42e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
43a37cdde0Sdanielk1977     ** up.
44a37cdde0Sdanielk1977     */
45a37cdde0Sdanielk1977     int n;
46a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
47abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
485c070538Sdrh     pIdx->zColAff = (char *)sqlite3DbMallocRaw(db, pIdx->nColumn+2);
49a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
50a37cdde0Sdanielk1977       return;
51a37cdde0Sdanielk1977     }
52a37cdde0Sdanielk1977     for(n=0; n<pIdx->nColumn; n++){
53a37cdde0Sdanielk1977       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
54a37cdde0Sdanielk1977     }
552d401ab8Sdrh     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
562d401ab8Sdrh     pIdx->zColAff[n] = 0;
57a37cdde0Sdanielk1977   }
583d1bfeaaSdanielk1977 
5966a5167bSdrh   sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
60a37cdde0Sdanielk1977 }
61a37cdde0Sdanielk1977 
62a37cdde0Sdanielk1977 /*
6366a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
64a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
65a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
66a37cdde0Sdanielk1977 ** column:
67a37cdde0Sdanielk1977 **
68a37cdde0Sdanielk1977 **  Character      Column affinity
69a37cdde0Sdanielk1977 **  ------------------------------
703eda040bSdrh **  'a'            TEXT
713eda040bSdrh **  'b'            NONE
723eda040bSdrh **  'c'            NUMERIC
733eda040bSdrh **  'd'            INTEGER
743eda040bSdrh **  'e'            REAL
75a37cdde0Sdanielk1977 */
76a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
773d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
783d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
793d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
803d1bfeaaSdanielk1977   **
813d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
823d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
833d1bfeaaSdanielk1977   */
843d1bfeaaSdanielk1977   if( !pTab->zColAff ){
853d1bfeaaSdanielk1977     char *zColAff;
863d1bfeaaSdanielk1977     int i;
87abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
883d1bfeaaSdanielk1977 
895c070538Sdrh     zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1);
903d1bfeaaSdanielk1977     if( !zColAff ){
91a37cdde0Sdanielk1977       return;
923d1bfeaaSdanielk1977     }
933d1bfeaaSdanielk1977 
943d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
95a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
963d1bfeaaSdanielk1977     }
973d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
983d1bfeaaSdanielk1977 
993d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1003d1bfeaaSdanielk1977   }
1013d1bfeaaSdanielk1977 
10266a5167bSdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
1033d1bfeaaSdanielk1977 }
1043d1bfeaaSdanielk1977 
1054d88778bSdanielk1977 /*
10648d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
10748d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
10848d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
10948d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
11048d1178aSdrh ** run without using temporary table for the results of the SELECT.
1114d88778bSdanielk1977 */
11248d1178aSdrh static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
1134d88778bSdanielk1977   int i;
11448d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
11548d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
11648d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
117ef0bea92Sdrh     assert( pOp!=0 );
118207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
11948d1178aSdrh       Index *pIndex;
120207872a4Sdanielk1977       int tnum = pOp->p2;
12148d1178aSdrh       if( tnum==pTab->tnum ){
12248d1178aSdrh         return 1;
12348d1178aSdrh       }
12448d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
12548d1178aSdrh         if( tnum==pIndex->tnum ){
12648d1178aSdrh           return 1;
12748d1178aSdrh         }
12848d1178aSdrh       }
12948d1178aSdrh     }
130543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1312dca4ac1Sdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
1322dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
13366a5167bSdrh       assert( pOp->p4type==P4_VTAB );
13448d1178aSdrh       return 1;
1354d88778bSdanielk1977     }
136543165efSdrh #endif
1374d88778bSdanielk1977   }
1384d88778bSdanielk1977   return 0;
1394d88778bSdanielk1977 }
1403d1bfeaaSdanielk1977 
1419d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1429d9cf229Sdrh /*
1439d9cf229Sdrh ** Write out code to initialize the autoincrement logic.  This code
1449d9cf229Sdrh ** looks up the current autoincrement value in the sqlite_sequence
1456a288a33Sdrh ** table and stores that value in a register.  Code generated by
1466a288a33Sdrh ** autoIncStep() will keep that register holding the largest
1479d9cf229Sdrh ** rowid value.  Code generated by autoIncEnd() will write the new
1489d9cf229Sdrh ** largest value of the counter back into the sqlite_sequence table.
1499d9cf229Sdrh **
1509d9cf229Sdrh ** This routine returns the index of the mem[] cell that contains
1519d9cf229Sdrh ** the maximum rowid counter.
1529d9cf229Sdrh **
1536a288a33Sdrh ** Three consecutive registers are allocated by this routine.  The
1546a288a33Sdrh ** first two hold the name of the target table and the maximum rowid
1556a288a33Sdrh ** inserted into the target table, respectively.
1566a288a33Sdrh ** The third holds the rowid in sqlite_sequence where we will
1576a288a33Sdrh ** write back the revised maximum rowid.  This routine returns the
1586a288a33Sdrh ** index of the second of these three registers.
1599d9cf229Sdrh */
1609d9cf229Sdrh static int autoIncBegin(
1619d9cf229Sdrh   Parse *pParse,      /* Parsing context */
1629d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
1639d9cf229Sdrh   Table *pTab         /* The table we are writing to */
1649d9cf229Sdrh ){
1656a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
1669d9cf229Sdrh   if( pTab->autoInc ){
1679d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
1689d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
1699d9cf229Sdrh     int iCur = pParse->nTab;
1706a288a33Sdrh     int addr;               /* Address of the top of the loop */
1719d9cf229Sdrh     assert( v );
1726a288a33Sdrh     pParse->nMem++;         /* Holds name of table */
1736a288a33Sdrh     memId = ++pParse->nMem;
1746a288a33Sdrh     pParse->nMem++;
1759d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
1766a288a33Sdrh     addr = sqlite3VdbeCurrentAddr(v);
1771db639ceSdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
178c9ded4c6Sdrh     sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
1791db639ceSdrh     sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
1801db639ceSdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
18135573356Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
1826a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
1836a288a33Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
184c9ded4c6Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
1851db639ceSdrh     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
186c9ded4c6Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
18766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
1889d9cf229Sdrh   }
1899d9cf229Sdrh   return memId;
1909d9cf229Sdrh }
1919d9cf229Sdrh 
1929d9cf229Sdrh /*
1939d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
1949d9cf229Sdrh **
1959d9cf229Sdrh ** This routine should be called when the top of the stack holds a
1969d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
1979d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
1989d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
1999d9cf229Sdrh */
2006a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2019d9cf229Sdrh   if( memId>0 ){
2026a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2039d9cf229Sdrh   }
2049d9cf229Sdrh }
2059d9cf229Sdrh 
2069d9cf229Sdrh /*
2079d9cf229Sdrh ** After doing one or more inserts, the maximum rowid is stored
2086a288a33Sdrh ** in reg[memId].  Generate code to write this value back into the
2099d9cf229Sdrh ** the sqlite_sequence table.
2109d9cf229Sdrh */
2119d9cf229Sdrh static void autoIncEnd(
2129d9cf229Sdrh   Parse *pParse,     /* The parsing context */
2139d9cf229Sdrh   int iDb,           /* Index of the database holding pTab */
2149d9cf229Sdrh   Table *pTab,       /* Table we are inserting into */
2159d9cf229Sdrh   int memId          /* Memory cell holding the maximum rowid */
2169d9cf229Sdrh ){
2179d9cf229Sdrh   if( pTab->autoInc ){
2189d9cf229Sdrh     int iCur = pParse->nTab;
2199d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
2209d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
2216a288a33Sdrh     int j1;
222a7a8e14bSdanielk1977     int iRec = ++pParse->nMem;    /* Memory cell used for record */
2236a288a33Sdrh 
2249d9cf229Sdrh     assert( v );
2259d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
2266a288a33Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
2276a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
2286a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
229a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
230a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
23135573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
2326a288a33Sdrh     sqlite3VdbeAddOp1(v, OP_Close, iCur);
2339d9cf229Sdrh   }
2349d9cf229Sdrh }
2359d9cf229Sdrh #else
2369d9cf229Sdrh /*
2379d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
2389d9cf229Sdrh ** above are all no-ops
2399d9cf229Sdrh */
2409d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
241287fb61cSdanielk1977 # define autoIncStep(A,B,C)
2429d9cf229Sdrh # define autoIncEnd(A,B,C,D)
2439d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
2449d9cf229Sdrh 
2459d9cf229Sdrh 
2469d9cf229Sdrh /* Forward declaration */
2479d9cf229Sdrh static int xferOptimization(
2489d9cf229Sdrh   Parse *pParse,        /* Parser context */
2499d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
2509d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
2519d9cf229Sdrh   int onError,          /* How to handle constraint errors */
2529d9cf229Sdrh   int iDbDest           /* The database of pDest */
2539d9cf229Sdrh );
2549d9cf229Sdrh 
2553d1bfeaaSdanielk1977 /*
2561ccde15dSdrh ** This routine is call to handle SQL of the following forms:
257cce7d176Sdrh **
258cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
2591ccde15dSdrh **    insert into TABLE (IDLIST) select
260cce7d176Sdrh **
2611ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
2621ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
263967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
2641ccde15dSdrh **
2651ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
2661ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
2671ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
2681ccde15dSdrh ** data for the insert.
269142e30dfSdrh **
2709d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
271142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
272e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
273e00ee6ebSdrh ** the "1st template"):
274142e30dfSdrh **
275142e30dfSdrh **         open write cursor to <table> and its indices
276142e30dfSdrh **         puts VALUES clause expressions onto the stack
277142e30dfSdrh **         write the resulting record into <table>
278142e30dfSdrh **         cleanup
279142e30dfSdrh **
2809d9cf229Sdrh ** The three remaining templates assume the statement is of the form
281142e30dfSdrh **
282142e30dfSdrh **   INSERT INTO <table> SELECT ...
283142e30dfSdrh **
2849d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
2859d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
2869d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
2879d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
2889d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
2899d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
2909d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
291e00ee6ebSdrh ** template.  This is the 2nd template.
2929d9cf229Sdrh **
2939d9cf229Sdrh **         open a write cursor to <table>
2949d9cf229Sdrh **         open read cursor on <table2>
2959d9cf229Sdrh **         transfer all records in <table2> over to <table>
2969d9cf229Sdrh **         close cursors
2979d9cf229Sdrh **         foreach index on <table>
2989d9cf229Sdrh **           open a write cursor on the <table> index
2999d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
3009d9cf229Sdrh **           transfer all records from the read to the write cursors
3019d9cf229Sdrh **           close cursors
3029d9cf229Sdrh **         end foreach
3039d9cf229Sdrh **
304e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
3059d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
3069d9cf229Sdrh ** The generated code follows this template:
307142e30dfSdrh **
308e00ee6ebSdrh **         EOF <- 0
309e00ee6ebSdrh **         X <- A
310142e30dfSdrh **         goto B
311142e30dfSdrh **      A: setup for the SELECT
3129d9cf229Sdrh **         loop over the rows in the SELECT
313e00ee6ebSdrh **           load values into registers R..R+n
314e00ee6ebSdrh **           yield X
315142e30dfSdrh **         end loop
316142e30dfSdrh **         cleanup after the SELECT
317e00ee6ebSdrh **         EOF <- 1
318e00ee6ebSdrh **         yield X
319142e30dfSdrh **         goto A
320e00ee6ebSdrh **      B: open write cursor to <table> and its indices
321e00ee6ebSdrh **      C: yield X
322e00ee6ebSdrh **         if EOF goto D
323e00ee6ebSdrh **         insert the select result into <table> from R..R+n
324e00ee6ebSdrh **         goto C
325142e30dfSdrh **      D: cleanup
326142e30dfSdrh **
327e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
328142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
329142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
330142e30dfSdrh ** we have to use a intermediate table to store the results of
331142e30dfSdrh ** the select.  The template is like this:
332142e30dfSdrh **
333e00ee6ebSdrh **         EOF <- 0
334e00ee6ebSdrh **         X <- A
335142e30dfSdrh **         goto B
336142e30dfSdrh **      A: setup for the SELECT
337142e30dfSdrh **         loop over the tables in the SELECT
338e00ee6ebSdrh **           load value into register R..R+n
339e00ee6ebSdrh **           yield X
340142e30dfSdrh **         end loop
341142e30dfSdrh **         cleanup after the SELECT
342e00ee6ebSdrh **         EOF <- 1
343e00ee6ebSdrh **         yield X
344e00ee6ebSdrh **         halt-error
345e00ee6ebSdrh **      B: open temp table
346e00ee6ebSdrh **      L: yield X
347e00ee6ebSdrh **         if EOF goto M
348e00ee6ebSdrh **         insert row from R..R+n into temp table
349e00ee6ebSdrh **         goto L
350e00ee6ebSdrh **      M: open write cursor to <table> and its indices
351e00ee6ebSdrh **         rewind temp table
352e00ee6ebSdrh **      C: loop over rows of intermediate table
353142e30dfSdrh **           transfer values form intermediate table into <table>
354e00ee6ebSdrh **         end loop
355e00ee6ebSdrh **      D: cleanup
356cce7d176Sdrh */
3574adee20fSdanielk1977 void sqlite3Insert(
358cce7d176Sdrh   Parse *pParse,        /* Parser context */
359113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
360cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
3615974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
3629cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
3639cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
364cce7d176Sdrh ){
3656a288a33Sdrh   sqlite3 *db;          /* The main database structure */
3666a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
367113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
368e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
3695974a30fSdrh   int i, j, idx;        /* Loop counters */
3705974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
3715974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
372967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
3736a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
37404adf416Sdrh   int baseCur = 0;      /* VDBE Cursor number for pTab */
3754a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
3760ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
3774d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
378cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
379e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
380e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
381e00ee6ebSdrh   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
3822eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
3836a288a33Sdrh   int newIdx = -1;      /* Cursor for the NEW pseudo-table */
3846a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
3852958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
386e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
387cce7d176Sdrh 
3886a288a33Sdrh   /* Register allocations */
3896a288a33Sdrh   int regFromSelect;    /* Base register for data coming from SELECT */
3906a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
3916a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
3926a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
3936a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
3946a288a33Sdrh   int regData;          /* register holding first column to insert */
3956a288a33Sdrh   int regRecord;        /* Holds the assemblied row record */
396e00ee6ebSdrh   int regEof;           /* Register recording end of SELECT data */
397aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
3986a288a33Sdrh 
399034ca14fSdanielk1977 
400798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
401798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
402dca76841Sdrh   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
403798da52cSdrh #endif
404c3f9bad2Sdanielk1977 
40517435752Sdrh   db = pParse->db;
40617435752Sdrh   if( pParse->nErr || db->mallocFailed ){
4076f7adc8aSdrh     goto insert_cleanup;
4086f7adc8aSdrh   }
409daffd0e5Sdrh 
4101ccde15dSdrh   /* Locate the table into which we will be inserting new information.
4111ccde15dSdrh   */
412113088ecSdrh   assert( pTabList->nSrc==1 );
413113088ecSdrh   zTab = pTabList->a[0].zName;
414daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
4154adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
416c3f9bad2Sdanielk1977   if( pTab==0 ){
417c3f9bad2Sdanielk1977     goto insert_cleanup;
418c3f9bad2Sdanielk1977   }
419da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
420da184236Sdanielk1977   assert( iDb<db->nDb );
421da184236Sdanielk1977   pDb = &db->aDb[iDb];
4222958a4e6Sdrh   zDb = pDb->zName;
4234adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
4241962bda7Sdrh     goto insert_cleanup;
4251962bda7Sdrh   }
426c3f9bad2Sdanielk1977 
427b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
428b7f9164eSdrh   ** inserted into is a view
429b7f9164eSdrh   */
430b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
431dca76841Sdrh   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
432b7f9164eSdrh   isView = pTab->pSelect!=0;
433b7f9164eSdrh #else
434dca76841Sdrh # define triggers_exist 0
435b7f9164eSdrh # define isView 0
436b7f9164eSdrh #endif
437b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
438b7f9164eSdrh # undef isView
439b7f9164eSdrh # define isView 0
440b7f9164eSdrh #endif
441b7f9164eSdrh 
442c3f9bad2Sdanielk1977   /* Ensure that:
443c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
444c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
445c3f9bad2Sdanielk1977   */
446dca76841Sdrh   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
447c3f9bad2Sdanielk1977     goto insert_cleanup;
448c3f9bad2Sdanielk1977   }
44943617e9aSdrh   assert( pTab!=0 );
4501ccde15dSdrh 
451f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
452b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
453b3d24bf8Sdanielk1977   ** module table).
454f573c99bSdrh   */
455b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
456f573c99bSdrh     goto insert_cleanup;
457f573c99bSdrh   }
458f573c99bSdrh 
4591ccde15dSdrh   /* Allocate a VDBE
4601ccde15dSdrh   */
4614adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
4625974a30fSdrh   if( v==0 ) goto insert_cleanup;
4634794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
464da184236Sdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
4651ccde15dSdrh 
466c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
467dca76841Sdrh   if( triggers_exist ){
468c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
469f29ce559Sdanielk1977   }
470c3f9bad2Sdanielk1977 
4719d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
4729d9cf229Sdrh   /* If the statement is of the form
4739d9cf229Sdrh   **
4749d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
4759d9cf229Sdrh   **
4769d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
4779d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
478e00ee6ebSdrh   **
479e00ee6ebSdrh   ** This is the 2nd template.
4809d9cf229Sdrh   */
4819d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
4829d9cf229Sdrh     assert( !triggers_exist );
4839d9cf229Sdrh     assert( pList==0 );
4849d9cf229Sdrh     goto insert_cleanup;
4859d9cf229Sdrh   }
4869d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
4879d9cf229Sdrh 
4882958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
4896a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
4902958a4e6Sdrh   */
4916a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
4922958a4e6Sdrh 
4931ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
494e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
495e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
496e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
4971ccde15dSdrh   */
4985974a30fSdrh   if( pSelect ){
499142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
500e00ee6ebSdrh     ** as a co-routine.  The code is common to both the 3rd and 4th
501e00ee6ebSdrh     ** templates:
502e00ee6ebSdrh     **
503e00ee6ebSdrh     **         EOF <- 0
504e00ee6ebSdrh     **         X <- A
505e00ee6ebSdrh     **         goto B
506e00ee6ebSdrh     **      A: setup for the SELECT
507e00ee6ebSdrh     **         loop over the tables in the SELECT
508e00ee6ebSdrh     **           load value into register R..R+n
509e00ee6ebSdrh     **           yield X
510e00ee6ebSdrh     **         end loop
511e00ee6ebSdrh     **         cleanup after the SELECT
512e00ee6ebSdrh     **         EOF <- 1
513e00ee6ebSdrh     **         yield X
514e00ee6ebSdrh     **         halt-error
515e00ee6ebSdrh     **
516e00ee6ebSdrh     ** On each invocation of the co-routine, it puts a single row of the
517e00ee6ebSdrh     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
518e00ee6ebSdrh     ** (These output registers are allocated by sqlite3Select().)  When
519e00ee6ebSdrh     ** the SELECT completes, it sets the EOF flag stored in regEof.
520142e30dfSdrh     */
521e00ee6ebSdrh     int rc, j1;
5221013c932Sdrh 
523e00ee6ebSdrh     regEof = ++pParse->nMem;
524e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
525e00ee6ebSdrh     VdbeComment((v, "SELECT eof flag"));
52692b01d53Sdrh     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
527e00ee6ebSdrh     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
52892b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
529e00ee6ebSdrh     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
530e00ee6ebSdrh     VdbeComment((v, "Jump over SELECT coroutine"));
531b3bce662Sdanielk1977 
532b3bce662Sdanielk1977     /* Resolve the expressions in the SELECT statement and execute it. */
5336c8c8ce0Sdanielk1977     rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
53417435752Sdrh     if( rc || pParse->nErr || db->mallocFailed ){
5356f7adc8aSdrh       goto insert_cleanup;
5366f7adc8aSdrh     }
537e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
53892b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
539e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
540e00ee6ebSdrh     VdbeComment((v, "End of SELECT coroutine"));
541e00ee6ebSdrh     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
542b3bce662Sdanielk1977 
5436a288a33Sdrh     regFromSelect = dest.iMem;
5445974a30fSdrh     assert( pSelect->pEList );
545967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
546e00ee6ebSdrh     assert( dest.nMem==nColumn );
547142e30dfSdrh 
548142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
549e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
550e00ee6ebSdrh     ** FALSE if each* row of the SELECT can be written directly into
551e00ee6ebSdrh     ** the destination table (template 3).
552048c530cSdrh     **
553048c530cSdrh     ** A temp table must be used if the table being updated is also one
554048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
555048c530cSdrh     ** temp table in the case of row triggers.
556142e30dfSdrh     */
557e00ee6ebSdrh     if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){
558048c530cSdrh       useTempTable = 1;
559048c530cSdrh     }
560142e30dfSdrh 
561142e30dfSdrh     if( useTempTable ){
562e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
563e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
564e00ee6ebSdrh       ** here is from the 4th template:
565e00ee6ebSdrh       **
566e00ee6ebSdrh       **      B: open temp table
567e00ee6ebSdrh       **      L: yield X
568e00ee6ebSdrh       **         if EOF goto M
569e00ee6ebSdrh       **         insert row from R..R+n into temp table
570e00ee6ebSdrh       **         goto L
571e00ee6ebSdrh       **      M: ...
572142e30dfSdrh       */
573e00ee6ebSdrh       int regRec;      /* Register to hold packed record */
574e00ee6ebSdrh       int regRowid;    /* Register to hold temp table ROWID */
575e00ee6ebSdrh       int addrTop;     /* Label "L" */
576e00ee6ebSdrh       int addrIf;      /* Address of jump to M */
577b7654111Sdrh 
578142e30dfSdrh       srcTab = pParse->nTab++;
579b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
580b7654111Sdrh       regRowid = sqlite3GetTempReg(pParse);
581e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
58292b01d53Sdrh       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
583e00ee6ebSdrh       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
5841db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
585b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid);
586b7654111Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid);
587e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
588e00ee6ebSdrh       sqlite3VdbeJumpHere(v, addrIf);
589b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
590b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRowid);
591142e30dfSdrh     }
592142e30dfSdrh   }else{
593142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
594142e30dfSdrh     ** clause
595142e30dfSdrh     */
596b3bce662Sdanielk1977     NameContext sNC;
597b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
598b3bce662Sdanielk1977     sNC.pParse = pParse;
5995974a30fSdrh     srcTab = -1;
60048d1178aSdrh     assert( useTempTable==0 );
601147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
602e64e7b20Sdrh     for(i=0; i<nColumn; i++){
603b3bce662Sdanielk1977       if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
604b04a5d87Sdrh         goto insert_cleanup;
605b04a5d87Sdrh       }
606e64e7b20Sdrh     }
6075974a30fSdrh   }
6081ccde15dSdrh 
6091ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
6101ccde15dSdrh   ** of columns to be inserted into the table.
6111ccde15dSdrh   */
612034ca14fSdanielk1977   if( IsVirtual(pTab) ){
613034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
614034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
615034ca14fSdanielk1977     }
616034ca14fSdanielk1977   }
617034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
6184adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
619da93d238Sdrh        "table %S has %d columns but %d values were supplied",
620da93d238Sdrh        pTabList, 0, pTab->nCol, nColumn);
621cce7d176Sdrh     goto insert_cleanup;
622cce7d176Sdrh   }
623967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
6244adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
625cce7d176Sdrh     goto insert_cleanup;
626cce7d176Sdrh   }
6271ccde15dSdrh 
6281ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
6291ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
6301ccde15dSdrh   ** remember the column indices.
631c8392586Sdrh   **
632c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
633c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
634c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
635c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
636c8392586Sdrh   ** is appears in the original table.  (The index of the primary
637c8392586Sdrh   ** key in the original table is pTab->iPKey.)
6381ccde15dSdrh   */
639967e8b73Sdrh   if( pColumn ){
640967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
641967e8b73Sdrh       pColumn->a[i].idx = -1;
642cce7d176Sdrh     }
643967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
644cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
6454adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
646967e8b73Sdrh           pColumn->a[i].idx = j;
6474a32431cSdrh           if( j==pTab->iPKey ){
6489aa028daSdrh             keyColumn = i;
6494a32431cSdrh           }
650cce7d176Sdrh           break;
651cce7d176Sdrh         }
652cce7d176Sdrh       }
653cce7d176Sdrh       if( j>=pTab->nCol ){
6544adee20fSdanielk1977         if( sqlite3IsRowid(pColumn->a[i].zName) ){
655a0217ba7Sdrh           keyColumn = i;
656a0217ba7Sdrh         }else{
6574adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
658da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
659cce7d176Sdrh           pParse->nErr++;
660cce7d176Sdrh           goto insert_cleanup;
661cce7d176Sdrh         }
662cce7d176Sdrh       }
663cce7d176Sdrh     }
664a0217ba7Sdrh   }
6651ccde15dSdrh 
666aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
667c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
668c8392586Sdrh   ** in the original table definition.
6694a32431cSdrh   */
670147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
6714a32431cSdrh     keyColumn = pTab->iPKey;
6724a32431cSdrh   }
6734a32431cSdrh 
674142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
675142e30dfSdrh   */
676dca76841Sdrh   if( triggers_exist ){
677cd3e8f7cSdanielk1977     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
67866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
679f29ce559Sdanielk1977   }
680c3f9bad2Sdanielk1977 
681c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
6821ccde15dSdrh   */
683142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
6846a288a33Sdrh     regRowCount = ++pParse->nMem;
6856a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
686c3f9bad2Sdanielk1977   }
687c3f9bad2Sdanielk1977 
688e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
689e448dc4aSdanielk1977   if( !isView ){
690aa9b8963Sdrh     int nIdx;
691aa9b8963Sdrh     int i;
692aa9b8963Sdrh 
69304adf416Sdrh     baseCur = pParse->nTab;
69404adf416Sdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
6955c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
696aa9b8963Sdrh     if( aRegIdx==0 ){
697aa9b8963Sdrh       goto insert_cleanup;
698aa9b8963Sdrh     }
699aa9b8963Sdrh     for(i=0; i<nIdx; i++){
700aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
701aa9b8963Sdrh     }
702feeb1394Sdrh   }
703feeb1394Sdrh 
704e00ee6ebSdrh   /* This is the top of the main insertion loop */
705142e30dfSdrh   if( useTempTable ){
706e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
707e00ee6ebSdrh     ** following pseudocode (template 4):
708e00ee6ebSdrh     **
709e00ee6ebSdrh     **         rewind temp table
710e00ee6ebSdrh     **      C: loop over rows of intermediate table
711e00ee6ebSdrh     **           transfer values form intermediate table into <table>
712e00ee6ebSdrh     **         end loop
713e00ee6ebSdrh     **      D: ...
714e00ee6ebSdrh     */
715e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
716e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
717142e30dfSdrh   }else if( pSelect ){
718e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
719e00ee6ebSdrh     ** following pseudocode (template 3):
720e00ee6ebSdrh     **
721e00ee6ebSdrh     **      C: yield X
722e00ee6ebSdrh     **         if EOF goto D
723e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
724e00ee6ebSdrh     **         goto C
725e00ee6ebSdrh     **      D: ...
726e00ee6ebSdrh     */
72792b01d53Sdrh     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
728e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
729bed8690fSdrh   }
7301ccde15dSdrh 
7316a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
7326a288a33Sdrh   ** the content of the new row, and the assemblied row record.
7336a288a33Sdrh   */
7346a288a33Sdrh   regRecord = ++pParse->nMem;
7356a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
7366a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
7376a288a33Sdrh   if( IsVirtual(pTab) ){
7386a288a33Sdrh     regRowid++;
7396a288a33Sdrh     pParse->nMem++;
7406a288a33Sdrh   }
7416a288a33Sdrh   regData = regRowid+1;
7426a288a33Sdrh 
7435cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
74470ce3f0cSdrh   */
7454adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
746dca76841Sdrh   if( triggers_exist & TRIGGER_BEFORE ){
7472d401ab8Sdrh     int regRowid;
7482d401ab8Sdrh     int regCols;
7492d401ab8Sdrh     int regRec;
750c3f9bad2Sdanielk1977 
75170ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
75270ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
75370ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
75470ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
75570ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
75670ce3f0cSdrh     */
7572d401ab8Sdrh     regRowid = sqlite3GetTempReg(pParse);
75870ce3f0cSdrh     if( keyColumn<0 ){
7592d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
76070ce3f0cSdrh     }else if( useTempTable ){
7612d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
76270ce3f0cSdrh     }else{
7636a288a33Sdrh       int j1;
764d6fe961eSdrh       assert( pSelect==0 );  /* Otherwise useTempTable is true */
7652d401ab8Sdrh       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
7662d401ab8Sdrh       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
7672d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
7686a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
7692d401ab8Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
77070ce3f0cSdrh     }
77170ce3f0cSdrh 
772034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
773034ca14fSdanielk1977     ** this block would have to account for hidden column.
774034ca14fSdanielk1977     */
775034ca14fSdanielk1977     assert(!IsVirtual(pTab));
776034ca14fSdanielk1977 
77770ce3f0cSdrh     /* Create the new column data
77870ce3f0cSdrh     */
7792d401ab8Sdrh     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
780c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
781c3f9bad2Sdanielk1977       if( pColumn==0 ){
782c3f9bad2Sdanielk1977         j = i;
783c3f9bad2Sdanielk1977       }else{
784c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
785c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
786c3f9bad2Sdanielk1977         }
787c3f9bad2Sdanielk1977       }
788c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
7892d401ab8Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
790142e30dfSdrh       }else if( useTempTable ){
7912d401ab8Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i);
792c3f9bad2Sdanielk1977       }else{
793d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
7942d401ab8Sdrh         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
795c3f9bad2Sdanielk1977       }
796c3f9bad2Sdanielk1977     }
7972d401ab8Sdrh     regRec = sqlite3GetTempReg(pParse);
7981db639ceSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
799a37cdde0Sdanielk1977 
800a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
801a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
802a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
803a37cdde0Sdanielk1977     ** table column affinities.
804a37cdde0Sdanielk1977     */
805a37cdde0Sdanielk1977     if( !isView ){
806a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
807a37cdde0Sdanielk1977     }
8082d401ab8Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
8092d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRec);
8102d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRowid);
8112d401ab8Sdrh     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
812c3f9bad2Sdanielk1977 
8135cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
814dca76841Sdrh     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
8158f2c54e6Sdanielk1977         newIdx, -1, onError, endOfLoop, 0, 0) ){
816f29ce559Sdanielk1977       goto insert_cleanup;
817f29ce559Sdanielk1977     }
81870ce3f0cSdrh   }
819c3f9bad2Sdanielk1977 
8204a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
821f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
8224a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
823b419a926Sdrh   ** case the record number is the same as that column.
8241ccde15dSdrh   */
8255cf590c1Sdrh   if( !isView ){
8264cbdda9eSdrh     if( IsVirtual(pTab) ){
8274cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
8286a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
8294cbdda9eSdrh     }
8304a32431cSdrh     if( keyColumn>=0 ){
831142e30dfSdrh       if( useTempTable ){
8326a288a33Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
833142e30dfSdrh       }else if( pSelect ){
834b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
8354a32431cSdrh       }else{
836e4d90813Sdrh         VdbeOp *pOp;
8371db639ceSdrh         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
838e4d90813Sdrh         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
839*bb50e7adSdanielk1977         if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
840e4d90813Sdrh           appendFlag = 1;
841e4d90813Sdrh           pOp->opcode = OP_NewRowid;
84204adf416Sdrh           pOp->p1 = baseCur;
8436a288a33Sdrh           pOp->p2 = regRowid;
8446a288a33Sdrh           pOp->p3 = regAutoinc;
845e4d90813Sdrh         }
84627a32783Sdrh       }
847f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
848e1e68f49Sdrh       ** to generate a unique primary key value.
849e1e68f49Sdrh       */
850e4d90813Sdrh       if( !appendFlag ){
8511db639ceSdrh         int j1;
852*bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
8531db639ceSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
85404adf416Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
8551db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
856*bb50e7adSdanielk1977         }else{
857*bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
858*bb50e7adSdanielk1977           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
859*bb50e7adSdanielk1977         }
8603c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
861e4d90813Sdrh       }
8624cbdda9eSdrh     }else if( IsVirtual(pTab) ){
8636a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
8644a32431cSdrh     }else{
86504adf416Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
866e4d90813Sdrh       appendFlag = 1;
8674a32431cSdrh     }
8686a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
8694a32431cSdrh 
870aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
8714a32431cSdrh     ** with the first column.
8724a32431cSdrh     */
873034ca14fSdanielk1977     nHidden = 0;
874cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
8756a288a33Sdrh       int iRegStore = regRowid+1+i;
8764a32431cSdrh       if( i==pTab->iPKey ){
8774a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
878aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
879aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
880aacc543eSdrh         ** taking up data space with information that will never be used. */
8814c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
8824a32431cSdrh         continue;
8834a32431cSdrh       }
884967e8b73Sdrh       if( pColumn==0 ){
885034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
886034ca14fSdanielk1977           assert( IsVirtual(pTab) );
887034ca14fSdanielk1977           j = -1;
888034ca14fSdanielk1977           nHidden++;
889034ca14fSdanielk1977         }else{
890034ca14fSdanielk1977           j = i - nHidden;
891034ca14fSdanielk1977         }
892cce7d176Sdrh       }else{
893967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
894967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
895cce7d176Sdrh         }
896cce7d176Sdrh       }
897034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
898287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
899142e30dfSdrh       }else if( useTempTable ){
900287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
901142e30dfSdrh       }else if( pSelect ){
902b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
903cce7d176Sdrh       }else{
904287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
905cce7d176Sdrh       }
906cce7d176Sdrh     }
9071ccde15dSdrh 
9080ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
9090ca3e24bSdrh     ** do the insertion.
9104a32431cSdrh     */
9114cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
9124cbdda9eSdrh     if( IsVirtual(pTab) ){
9134f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
9146a288a33Sdrh       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
91566a5167bSdrh                      (const char*)pTab->pVtab, P4_VTAB);
9164cbdda9eSdrh     }else
9174cbdda9eSdrh #endif
9184cbdda9eSdrh     {
91904adf416Sdrh       sqlite3GenerateConstraintChecks(
92004adf416Sdrh           pParse,
92104adf416Sdrh           pTab,
92204adf416Sdrh           baseCur,
92304adf416Sdrh           regIns,
92404adf416Sdrh           aRegIdx,
92504adf416Sdrh           keyColumn>=0,
92604adf416Sdrh           0,
92704adf416Sdrh           onError,
92804adf416Sdrh           endOfLoop
92904adf416Sdrh       );
93004adf416Sdrh       sqlite3CompleteInsertion(
93104adf416Sdrh           pParse,
93204adf416Sdrh           pTab,
93304adf416Sdrh           baseCur,
93404adf416Sdrh           regIns,
93504adf416Sdrh           aRegIdx,
93604adf416Sdrh           0,
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);
99366a5167bSdrh     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
9941bee3d7bSdrh   }
995cce7d176Sdrh 
996cce7d176Sdrh insert_cleanup:
9974adee20fSdanielk1977   sqlite3SrcListDelete(pTabList);
998d5d56523Sdanielk1977   sqlite3ExprListDelete(pList);
999d5d56523Sdanielk1977   sqlite3SelectDelete(pSelect);
10004adee20fSdanielk1977   sqlite3IdListDelete(pColumn);
1001aa9b8963Sdrh   sqlite3_free(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: {
1133483750baSdrh         char *zMsg = 0;
113466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
11354adee20fSdanielk1977         sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
113641743984Sdrh                         " may not be NULL", (char*)0);
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,
12617209c697Sdrh                            regR, (char*)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];
12735bb3eb9bSdrh         sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
12745bb3eb9bSdrh                          pIdx->nColumn>1 ? "columns " : "column ");
127537ed48edSdrh         n1 = strlen(zErrMsg);
127637ed48edSdrh         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
127737ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
127837ed48edSdrh           n2 = strlen(zCol);
127937ed48edSdrh           if( j>0 ){
12805bb3eb9bSdrh             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
128137ed48edSdrh             n1 += 2;
128237ed48edSdrh           }
128337ed48edSdrh           if( n1+n2>sizeof(zErrMsg)-30 ){
12845bb3eb9bSdrh             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
128537ed48edSdrh             n1 += 3;
128637ed48edSdrh             break;
128737ed48edSdrh           }else{
12885bb3eb9bSdrh             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
128937ed48edSdrh             n1 += n2;
129037ed48edSdrh           }
129137ed48edSdrh         }
12925bb3eb9bSdrh         sqlite3_snprintf(sizeof(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 */
1329f0863fe5Sdrh   int rowidChng,      /* True if the record number will change */
133070ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1331e4d90813Sdrh   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
1332e4d90813Sdrh   int appendBias      /* True if this is likely to be an append */
13330ca3e24bSdrh ){
13340ca3e24bSdrh   int i;
13350ca3e24bSdrh   Vdbe *v;
13360ca3e24bSdrh   int nIdx;
13370ca3e24bSdrh   Index *pIdx;
1338b28af71aSdanielk1977   int pik_flags;
133904adf416Sdrh   int regData;
1340b7654111Sdrh   int regRec;
13410ca3e24bSdrh 
13424adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
13430ca3e24bSdrh   assert( v!=0 );
1344417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
13450ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
13460ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
1347aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
134804adf416Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
13490ca3e24bSdrh   }
135004adf416Sdrh   regData = regRowid + 1;
1351b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
13521db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1353a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1354da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
1355b84f96f8Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
135670ce3f0cSdrh   if( newIdx>=0 ){
1357b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
135870ce3f0cSdrh   }
1359b84f96f8Sdanielk1977 #endif
13604794f735Sdrh   if( pParse->nested ){
13614794f735Sdrh     pik_flags = 0;
13624794f735Sdrh   }else{
136394eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
136494eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
13654794f735Sdrh   }
1366e4d90813Sdrh   if( appendBias ){
1367e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1368e4d90813Sdrh   }
1369b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
137094eb6a14Sdanielk1977   if( !pParse->nested ){
137166a5167bSdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
137294eb6a14Sdanielk1977   }
1373b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
13740ca3e24bSdrh }
1375cd44690aSdrh 
1376cd44690aSdrh /*
1377290c1948Sdrh ** Generate code that will open cursors for a table and for all
137804adf416Sdrh ** indices of that table.  The "baseCur" parameter is the cursor number used
1379cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1380aa9b8963Sdrh **
1381aa9b8963Sdrh ** Return the number of indices on the table.
1382cd44690aSdrh */
1383aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1384290c1948Sdrh   Parse *pParse,   /* Parsing context */
1385290c1948Sdrh   Table *pTab,     /* Table to be opened */
138604adf416Sdrh   int baseCur,        /* Cursor number assigned to the table */
1387290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1388290c1948Sdrh ){
1389cd44690aSdrh   int i;
13904cbdda9eSdrh   int iDb;
1391cd44690aSdrh   Index *pIdx;
13924cbdda9eSdrh   Vdbe *v;
13934cbdda9eSdrh 
1394aa9b8963Sdrh   if( IsVirtual(pTab) ) return 0;
13954cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
13964cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1397cd44690aSdrh   assert( v!=0 );
139804adf416Sdrh   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
1399cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1400b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1401da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
140204adf416Sdrh     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
140366a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1404207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1405cd44690aSdrh   }
140604adf416Sdrh   if( pParse->nTab<=baseCur+i ){
140704adf416Sdrh     pParse->nTab = baseCur+i;
1408290c1948Sdrh   }
1409aa9b8963Sdrh   return i-1;
1410cd44690aSdrh }
14119d9cf229Sdrh 
141291c58e23Sdrh 
141391c58e23Sdrh #ifdef SQLITE_TEST
141491c58e23Sdrh /*
141591c58e23Sdrh ** The following global variable is incremented whenever the
141691c58e23Sdrh ** transfer optimization is used.  This is used for testing
141791c58e23Sdrh ** purposes only - to make sure the transfer optimization really
141891c58e23Sdrh ** is happening when it is suppose to.
141991c58e23Sdrh */
142091c58e23Sdrh int sqlite3_xferopt_count;
142191c58e23Sdrh #endif /* SQLITE_TEST */
142291c58e23Sdrh 
142391c58e23Sdrh 
14249d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
14259d9cf229Sdrh /*
14269d9cf229Sdrh ** Check to collation names to see if they are compatible.
14279d9cf229Sdrh */
14289d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
14299d9cf229Sdrh   if( z1==0 ){
14309d9cf229Sdrh     return z2==0;
14319d9cf229Sdrh   }
14329d9cf229Sdrh   if( z2==0 ){
14339d9cf229Sdrh     return 0;
14349d9cf229Sdrh   }
14359d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
14369d9cf229Sdrh }
14379d9cf229Sdrh 
14389d9cf229Sdrh 
14399d9cf229Sdrh /*
14409d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
14419d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
14429d9cf229Sdrh ** for a compatible index:
14439d9cf229Sdrh **
14449d9cf229Sdrh **    *   The index is over the same set of columns
14459d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
14469d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
14479d9cf229Sdrh **    *   The same collating sequence on each column
14489d9cf229Sdrh */
14499d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
14509d9cf229Sdrh   int i;
14519d9cf229Sdrh   assert( pDest && pSrc );
14529d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
14539d9cf229Sdrh   if( pDest->nColumn!=pSrc->nColumn ){
14549d9cf229Sdrh     return 0;   /* Different number of columns */
14559d9cf229Sdrh   }
14569d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
14579d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
14589d9cf229Sdrh   }
14599d9cf229Sdrh   for(i=0; i<pSrc->nColumn; i++){
14609d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
14619d9cf229Sdrh       return 0;   /* Different columns indexed */
14629d9cf229Sdrh     }
14639d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
14649d9cf229Sdrh       return 0;   /* Different sort orders */
14659d9cf229Sdrh     }
14669d9cf229Sdrh     if( pSrc->azColl[i]!=pDest->azColl[i] ){
146760a713c6Sdrh       return 0;   /* Different collating sequences */
14689d9cf229Sdrh     }
14699d9cf229Sdrh   }
14709d9cf229Sdrh 
14719d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
14729d9cf229Sdrh   return 1;
14739d9cf229Sdrh }
14749d9cf229Sdrh 
14759d9cf229Sdrh /*
14769d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
14779d9cf229Sdrh **
14789d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
14799d9cf229Sdrh **
14809d9cf229Sdrh ** This optimization is only attempted if
14819d9cf229Sdrh **
14829d9cf229Sdrh **    (1)  tab1 and tab2 have identical schemas including all the
14838103b7d2Sdrh **         same indices and constraints
14849d9cf229Sdrh **
14859d9cf229Sdrh **    (2)  tab1 and tab2 are different tables
14869d9cf229Sdrh **
14879d9cf229Sdrh **    (3)  There must be no triggers on tab1
14889d9cf229Sdrh **
14899d9cf229Sdrh **    (4)  The result set of the SELECT statement is "*"
14909d9cf229Sdrh **
14919d9cf229Sdrh **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
14929d9cf229Sdrh **         or LIMIT clause.
14939d9cf229Sdrh **
14949d9cf229Sdrh **    (6)  The SELECT statement is a simple (not a compound) select that
14959d9cf229Sdrh **         contains only tab2 in its FROM clause
14969d9cf229Sdrh **
14979d9cf229Sdrh ** This method for implementing the INSERT transfers raw records from
14989d9cf229Sdrh ** tab2 over to tab1.  The columns are not decoded.  Raw records from
14999d9cf229Sdrh ** the indices of tab2 are transfered to tab1 as well.  In so doing,
15009d9cf229Sdrh ** the resulting tab1 has much less fragmentation.
15019d9cf229Sdrh **
15029d9cf229Sdrh ** This routine returns TRUE if the optimization is attempted.  If any
15039d9cf229Sdrh ** of the conditions above fail so that the optimization should not
15049d9cf229Sdrh ** be attempted, then this routine returns FALSE.
15059d9cf229Sdrh */
15069d9cf229Sdrh static int xferOptimization(
15079d9cf229Sdrh   Parse *pParse,        /* Parser context */
15089d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
15099d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
15109d9cf229Sdrh   int onError,          /* How to handle constraint errors */
15119d9cf229Sdrh   int iDbDest           /* The database of pDest */
15129d9cf229Sdrh ){
15139d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
15149d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
15159d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
15169d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
15179d9cf229Sdrh   int i;                           /* Loop counter */
15189d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
15199d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
15209d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
15219d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
15229d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
15239d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
15249d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
15256a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1526f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1527b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
15289d9cf229Sdrh 
15299d9cf229Sdrh   if( pSelect==0 ){
15309d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
15319d9cf229Sdrh   }
15329d9cf229Sdrh   if( pDest->pTrigger ){
15339d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
15349d9cf229Sdrh   }
15359d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
15369d9cf229Sdrh   if( pDest->isVirtual ){
15379d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
15389d9cf229Sdrh   }
15399d9cf229Sdrh #endif
15409d9cf229Sdrh   if( onError==OE_Default ){
15419d9cf229Sdrh     onError = OE_Abort;
15429d9cf229Sdrh   }
15439d9cf229Sdrh   if( onError!=OE_Abort && onError!=OE_Rollback ){
15449d9cf229Sdrh     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
15459d9cf229Sdrh   }
15465ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
15479d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
15489d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
15499d9cf229Sdrh   }
15509d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
15519d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
15529d9cf229Sdrh   }
15539d9cf229Sdrh   if( pSelect->pWhere ){
15549d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
15559d9cf229Sdrh   }
15569d9cf229Sdrh   if( pSelect->pOrderBy ){
15579d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
15589d9cf229Sdrh   }
15598103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
15608103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
15619d9cf229Sdrh   if( pSelect->pGroupBy ){
15629d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
15639d9cf229Sdrh   }
15649d9cf229Sdrh   if( pSelect->pLimit ){
15659d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
15669d9cf229Sdrh   }
15678103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
15689d9cf229Sdrh   if( pSelect->pPrior ){
15699d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
15709d9cf229Sdrh   }
15719d9cf229Sdrh   if( pSelect->isDistinct ){
15729d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
15739d9cf229Sdrh   }
15749d9cf229Sdrh   pEList = pSelect->pEList;
15759d9cf229Sdrh   assert( pEList!=0 );
15769d9cf229Sdrh   if( pEList->nExpr!=1 ){
15779d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
15789d9cf229Sdrh   }
15799d9cf229Sdrh   assert( pEList->a[0].pExpr );
15809d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
15819d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
15829d9cf229Sdrh   }
15839d9cf229Sdrh 
15849d9cf229Sdrh   /* At this point we have established that the statement is of the
15859d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
15869d9cf229Sdrh   ** we have to check the semantics.
15879d9cf229Sdrh   */
15889d9cf229Sdrh   pItem = pSelect->pSrc->a;
1589ca424114Sdrh   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
15909d9cf229Sdrh   if( pSrc==0 ){
15919d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
15929d9cf229Sdrh   }
15939d9cf229Sdrh   if( pSrc==pDest ){
15949d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
15959d9cf229Sdrh   }
15969d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
15979d9cf229Sdrh   if( pSrc->isVirtual ){
15989d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
15999d9cf229Sdrh   }
16009d9cf229Sdrh #endif
16019d9cf229Sdrh   if( pSrc->pSelect ){
16029d9cf229Sdrh     return 0;   /* tab2 may not be a view */
16039d9cf229Sdrh   }
16049d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
16059d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
16069d9cf229Sdrh   }
16079d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
16089d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
16099d9cf229Sdrh   }
16109d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
16119d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
16129d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
16139d9cf229Sdrh     }
16149d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
16159d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
16169d9cf229Sdrh     }
16179d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
16189d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
16199d9cf229Sdrh     }
16209d9cf229Sdrh   }
16219d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1622f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1623f33c9fadSdrh       destHasUniqueIdx = 1;
1624f33c9fadSdrh     }
16259d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
16269d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
16279d9cf229Sdrh     }
16289d9cf229Sdrh     if( pSrcIdx==0 ){
16299d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
16309d9cf229Sdrh     }
16319d9cf229Sdrh   }
16327fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1633fb658dedSdrh   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
16348103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
16358103b7d2Sdrh   }
16367fc2f41bSdrh #endif
16379d9cf229Sdrh 
16389d9cf229Sdrh   /* If we get this far, it means either:
16399d9cf229Sdrh   **
16409d9cf229Sdrh   **    *   We can always do the transfer if the table contains an
16419d9cf229Sdrh   **        an integer primary key
16429d9cf229Sdrh   **
16439d9cf229Sdrh   **    *   We can conditionally do the transfer if the destination
16449d9cf229Sdrh   **        table is empty.
16459d9cf229Sdrh   */
1646dd73521bSdrh #ifdef SQLITE_TEST
1647dd73521bSdrh   sqlite3_xferopt_count++;
1648dd73521bSdrh #endif
16499d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
16509d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1651f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
16529d9cf229Sdrh   iSrc = pParse->nTab++;
16539d9cf229Sdrh   iDest = pParse->nTab++;
16546a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
16559d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1656f33c9fadSdrh   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
1657bd36ba69Sdrh     /* If tables do not have an INTEGER PRIMARY KEY and there
1658bd36ba69Sdrh     ** are indices to be copied and the destination is not empty,
1659bd36ba69Sdrh     ** we have to disallow the transfer optimization because the
1660bd36ba69Sdrh     ** the rowids might change which will mess up indexing.
1661f33c9fadSdrh     **
1662f33c9fadSdrh     ** Or if the destination has a UNIQUE index and is not empty,
1663f33c9fadSdrh     ** we also disallow the transfer optimization because we cannot
1664f33c9fadSdrh     ** insure that all entries in the union of DEST and SRC will be
1665f33c9fadSdrh     ** unique.
16669d9cf229Sdrh     */
166766a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
166866a5167bSdrh     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
16699d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
16709d9cf229Sdrh   }else{
16719d9cf229Sdrh     emptyDestTest = 0;
16729d9cf229Sdrh   }
16739d9cf229Sdrh   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
167466a5167bSdrh   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1675b7654111Sdrh   regData = sqlite3GetTempReg(pParse);
1676b7654111Sdrh   regRowid = sqlite3GetTempReg(pParse);
167742242dedSdrh   if( pDest->iPKey>=0 ){
1678b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1679b7654111Sdrh     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
168066a5167bSdrh     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
168166a5167bSdrh                       "PRIMARY KEY must be unique", P4_STATIC);
16829d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr2);
1683b7654111Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
1684bd36ba69Sdrh   }else if( pDest->pIndex==0 ){
1685b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
168695bad4c7Sdrh   }else{
1687b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
168842242dedSdrh     assert( pDest->autoInc==0 );
168995bad4c7Sdrh   }
1690b7654111Sdrh   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1691b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1692b7654111Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
16931f4aa337Sdanielk1977   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
169466a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
16956a288a33Sdrh   autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
16969d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
16979d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
16989d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
16999d9cf229Sdrh     }
17009d9cf229Sdrh     assert( pSrcIdx );
170166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
170266a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
17039d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1704207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1705207872a4Sdanielk1977                       (char*)pKey, P4_KEYINFO_HANDOFF);
1706d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
17079d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1708207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
170966a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1710207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
171166a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1712b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1713b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
171466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
17159d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
17169d9cf229Sdrh   }
17179d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
1718b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
1719b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
172066a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
172166a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
17229d9cf229Sdrh   if( emptyDestTest ){
172366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
17249d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
172566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
17269d9cf229Sdrh     return 0;
17279d9cf229Sdrh   }else{
17289d9cf229Sdrh     return 1;
17299d9cf229Sdrh   }
17309d9cf229Sdrh }
17319d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
1732f39d9588Sdrh 
1733f39d9588Sdrh /* Make sure "isView" gets undefined in case this file becomes part of
1734f39d9588Sdrh ** the amalgamation - so that subsequent files do not see isView as a
1735f39d9588Sdrh ** macro. */
1736f39d9588Sdrh #undef isView
1737