000001  /*
000002  ** 2001 September 15
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  ** This file contains C code routines that are called by the parser
000013  ** to handle INSERT statements in SQLite.
000014  */
000015  #include "sqliteInt.h"
000016  
000017  /*
000018  ** Generate code that will 
000019  **
000020  **   (1) acquire a lock for table pTab then
000021  **   (2) open pTab as cursor iCur.
000022  **
000023  ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
000024  ** for that table that is actually opened.
000025  */
000026  void sqlite3OpenTable(
000027    Parse *pParse,  /* Generate code into this VDBE */
000028    int iCur,       /* The cursor number of the table */
000029    int iDb,        /* The database index in sqlite3.aDb[] */
000030    Table *pTab,    /* The table to be opened */
000031    int opcode      /* OP_OpenRead or OP_OpenWrite */
000032  ){
000033    Vdbe *v;
000034    assert( !IsVirtual(pTab) );
000035    v = sqlite3GetVdbe(pParse);
000036    assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
000037    sqlite3TableLock(pParse, iDb, pTab->tnum, 
000038                     (opcode==OP_OpenWrite)?1:0, pTab->zName);
000039    if( HasRowid(pTab) ){
000040      sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
000041      VdbeComment((v, "%s", pTab->zName));
000042    }else{
000043      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
000044      assert( pPk!=0 );
000045      assert( pPk->tnum==pTab->tnum );
000046      sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
000047      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
000048      VdbeComment((v, "%s", pTab->zName));
000049    }
000050  }
000051  
000052  /*
000053  ** Return a pointer to the column affinity string associated with index
000054  ** pIdx. A column affinity string has one character for each column in 
000055  ** the table, according to the affinity of the column:
000056  **
000057  **  Character      Column affinity
000058  **  ------------------------------
000059  **  'A'            BLOB
000060  **  'B'            TEXT
000061  **  'C'            NUMERIC
000062  **  'D'            INTEGER
000063  **  'F'            REAL
000064  **
000065  ** An extra 'D' is appended to the end of the string to cover the
000066  ** rowid that appears as the last column in every index.
000067  **
000068  ** Memory for the buffer containing the column index affinity string
000069  ** is managed along with the rest of the Index structure. It will be
000070  ** released when sqlite3DeleteIndex() is called.
000071  */
000072  const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
000073    if( !pIdx->zColAff ){
000074      /* The first time a column affinity string for a particular index is
000075      ** required, it is allocated and populated here. It is then stored as
000076      ** a member of the Index structure for subsequent use.
000077      **
000078      ** The column affinity string will eventually be deleted by
000079      ** sqliteDeleteIndex() when the Index structure itself is cleaned
000080      ** up.
000081      */
000082      int n;
000083      Table *pTab = pIdx->pTable;
000084      pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
000085      if( !pIdx->zColAff ){
000086        sqlite3OomFault(db);
000087        return 0;
000088      }
000089      for(n=0; n<pIdx->nColumn; n++){
000090        i16 x = pIdx->aiColumn[n];
000091        if( x>=0 ){
000092          pIdx->zColAff[n] = pTab->aCol[x].affinity;
000093        }else if( x==XN_ROWID ){
000094          pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
000095        }else{
000096          char aff;
000097          assert( x==XN_EXPR );
000098          assert( pIdx->aColExpr!=0 );
000099          aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
000100          if( aff==0 ) aff = SQLITE_AFF_BLOB;
000101          pIdx->zColAff[n] = aff;
000102        }
000103      }
000104      pIdx->zColAff[n] = 0;
000105    }
000106   
000107    return pIdx->zColAff;
000108  }
000109  
000110  /*
000111  ** Compute the affinity string for table pTab, if it has not already been
000112  ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
000113  **
000114  ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
000115  ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
000116  ** for register iReg and following.  Or if affinities exists and iReg==0,
000117  ** then just set the P4 operand of the previous opcode (which should  be
000118  ** an OP_MakeRecord) to the affinity string.
000119  **
000120  ** A column affinity string has one character per column:
000121  **
000122  **  Character      Column affinity
000123  **  ------------------------------
000124  **  'A'            BLOB
000125  **  'B'            TEXT
000126  **  'C'            NUMERIC
000127  **  'D'            INTEGER
000128  **  'E'            REAL
000129  */
000130  void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
000131    int i;
000132    char *zColAff = pTab->zColAff;
000133    if( zColAff==0 ){
000134      sqlite3 *db = sqlite3VdbeDb(v);
000135      zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
000136      if( !zColAff ){
000137        sqlite3OomFault(db);
000138        return;
000139      }
000140  
000141      for(i=0; i<pTab->nCol; i++){
000142        zColAff[i] = pTab->aCol[i].affinity;
000143      }
000144      do{
000145        zColAff[i--] = 0;
000146      }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
000147      pTab->zColAff = zColAff;
000148    }
000149    assert( zColAff!=0 );
000150    i = sqlite3Strlen30NN(zColAff);
000151    if( i ){
000152      if( iReg ){
000153        sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
000154      }else{
000155        sqlite3VdbeChangeP4(v, -1, zColAff, i);
000156      }
000157    }
000158  }
000159  
000160  /*
000161  ** Return non-zero if the table pTab in database iDb or any of its indices
000162  ** have been opened at any point in the VDBE program. This is used to see if 
000163  ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
000164  ** run without using a temporary table for the results of the SELECT. 
000165  */
000166  static int readsTable(Parse *p, int iDb, Table *pTab){
000167    Vdbe *v = sqlite3GetVdbe(p);
000168    int i;
000169    int iEnd = sqlite3VdbeCurrentAddr(v);
000170  #ifndef SQLITE_OMIT_VIRTUALTABLE
000171    VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
000172  #endif
000173  
000174    for(i=1; i<iEnd; i++){
000175      VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
000176      assert( pOp!=0 );
000177      if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
000178        Index *pIndex;
000179        int tnum = pOp->p2;
000180        if( tnum==pTab->tnum ){
000181          return 1;
000182        }
000183        for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
000184          if( tnum==pIndex->tnum ){
000185            return 1;
000186          }
000187        }
000188      }
000189  #ifndef SQLITE_OMIT_VIRTUALTABLE
000190      if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
000191        assert( pOp->p4.pVtab!=0 );
000192        assert( pOp->p4type==P4_VTAB );
000193        return 1;
000194      }
000195  #endif
000196    }
000197    return 0;
000198  }
000199  
000200  #ifndef SQLITE_OMIT_AUTOINCREMENT
000201  /*
000202  ** Locate or create an AutoincInfo structure associated with table pTab
000203  ** which is in database iDb.  Return the register number for the register
000204  ** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
000205  ** table.  (Also return zero when doing a VACUUM since we do not want to
000206  ** update the AUTOINCREMENT counters during a VACUUM.)
000207  **
000208  ** There is at most one AutoincInfo structure per table even if the
000209  ** same table is autoincremented multiple times due to inserts within
000210  ** triggers.  A new AutoincInfo structure is created if this is the
000211  ** first use of table pTab.  On 2nd and subsequent uses, the original
000212  ** AutoincInfo structure is used.
000213  **
000214  ** Four consecutive registers are allocated:
000215  **
000216  **   (1)  The name of the pTab table.
000217  **   (2)  The maximum ROWID of pTab.
000218  **   (3)  The rowid in sqlite_sequence of pTab
000219  **   (4)  The original value of the max ROWID in pTab, or NULL if none
000220  **
000221  ** The 2nd register is the one that is returned.  That is all the
000222  ** insert routine needs to know about.
000223  */
000224  static int autoIncBegin(
000225    Parse *pParse,      /* Parsing context */
000226    int iDb,            /* Index of the database holding pTab */
000227    Table *pTab         /* The table we are writing to */
000228  ){
000229    int memId = 0;      /* Register holding maximum rowid */
000230    assert( pParse->db->aDb[iDb].pSchema!=0 );
000231    if( (pTab->tabFlags & TF_Autoincrement)!=0
000232     && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
000233    ){
000234      Parse *pToplevel = sqlite3ParseToplevel(pParse);
000235      AutoincInfo *pInfo;
000236      Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
000237  
000238      /* Verify that the sqlite_sequence table exists and is an ordinary
000239      ** rowid table with exactly two columns.
000240      ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
000241      if( pSeqTab==0
000242       || !HasRowid(pSeqTab)
000243       || IsVirtual(pSeqTab)
000244       || pSeqTab->nCol!=2
000245      ){
000246        pParse->nErr++;
000247        pParse->rc = SQLITE_CORRUPT_SEQUENCE;
000248        return 0;
000249      }
000250  
000251      pInfo = pToplevel->pAinc;
000252      while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
000253      if( pInfo==0 ){
000254        pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
000255        if( pInfo==0 ) return 0;
000256        pInfo->pNext = pToplevel->pAinc;
000257        pToplevel->pAinc = pInfo;
000258        pInfo->pTab = pTab;
000259        pInfo->iDb = iDb;
000260        pToplevel->nMem++;                  /* Register to hold name of table */
000261        pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
000262        pToplevel->nMem +=2;       /* Rowid in sqlite_sequence + orig max val */
000263      }
000264      memId = pInfo->regCtr;
000265    }
000266    return memId;
000267  }
000268  
000269  /*
000270  ** This routine generates code that will initialize all of the
000271  ** register used by the autoincrement tracker.  
000272  */
000273  void sqlite3AutoincrementBegin(Parse *pParse){
000274    AutoincInfo *p;            /* Information about an AUTOINCREMENT */
000275    sqlite3 *db = pParse->db;  /* The database connection */
000276    Db *pDb;                   /* Database only autoinc table */
000277    int memId;                 /* Register holding max rowid */
000278    Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
000279  
000280    /* This routine is never called during trigger-generation.  It is
000281    ** only called from the top-level */
000282    assert( pParse->pTriggerTab==0 );
000283    assert( sqlite3IsToplevel(pParse) );
000284  
000285    assert( v );   /* We failed long ago if this is not so */
000286    for(p = pParse->pAinc; p; p = p->pNext){
000287      static const int iLn = VDBE_OFFSET_LINENO(2);
000288      static const VdbeOpList autoInc[] = {
000289        /* 0  */ {OP_Null,    0,  0, 0},
000290        /* 1  */ {OP_Rewind,  0, 10, 0},
000291        /* 2  */ {OP_Column,  0,  0, 0},
000292        /* 3  */ {OP_Ne,      0,  9, 0},
000293        /* 4  */ {OP_Rowid,   0,  0, 0},
000294        /* 5  */ {OP_Column,  0,  1, 0},
000295        /* 6  */ {OP_AddImm,  0,  0, 0},
000296        /* 7  */ {OP_Copy,    0,  0, 0},
000297        /* 8  */ {OP_Goto,    0, 11, 0},
000298        /* 9  */ {OP_Next,    0,  2, 0},
000299        /* 10 */ {OP_Integer, 0,  0, 0},
000300        /* 11 */ {OP_Close,   0,  0, 0} 
000301      };
000302      VdbeOp *aOp;
000303      pDb = &db->aDb[p->iDb];
000304      memId = p->regCtr;
000305      assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
000306      sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
000307      sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
000308      aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
000309      if( aOp==0 ) break;
000310      aOp[0].p2 = memId;
000311      aOp[0].p3 = memId+2;
000312      aOp[2].p3 = memId;
000313      aOp[3].p1 = memId-1;
000314      aOp[3].p3 = memId;
000315      aOp[3].p5 = SQLITE_JUMPIFNULL;
000316      aOp[4].p2 = memId+1;
000317      aOp[5].p3 = memId;
000318      aOp[6].p1 = memId;
000319      aOp[7].p2 = memId+2;
000320      aOp[7].p1 = memId;
000321      aOp[10].p2 = memId;
000322      if( pParse->nTab==0 ) pParse->nTab = 1;
000323    }
000324  }
000325  
000326  /*
000327  ** Update the maximum rowid for an autoincrement calculation.
000328  **
000329  ** This routine should be called when the regRowid register holds a
000330  ** new rowid that is about to be inserted.  If that new rowid is
000331  ** larger than the maximum rowid in the memId memory cell, then the
000332  ** memory cell is updated.
000333  */
000334  static void autoIncStep(Parse *pParse, int memId, int regRowid){
000335    if( memId>0 ){
000336      sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
000337    }
000338  }
000339  
000340  /*
000341  ** This routine generates the code needed to write autoincrement
000342  ** maximum rowid values back into the sqlite_sequence register.
000343  ** Every statement that might do an INSERT into an autoincrement
000344  ** table (either directly or through triggers) needs to call this
000345  ** routine just before the "exit" code.
000346  */
000347  static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
000348    AutoincInfo *p;
000349    Vdbe *v = pParse->pVdbe;
000350    sqlite3 *db = pParse->db;
000351  
000352    assert( v );
000353    for(p = pParse->pAinc; p; p = p->pNext){
000354      static const int iLn = VDBE_OFFSET_LINENO(2);
000355      static const VdbeOpList autoIncEnd[] = {
000356        /* 0 */ {OP_NotNull,     0, 2, 0},
000357        /* 1 */ {OP_NewRowid,    0, 0, 0},
000358        /* 2 */ {OP_MakeRecord,  0, 2, 0},
000359        /* 3 */ {OP_Insert,      0, 0, 0},
000360        /* 4 */ {OP_Close,       0, 0, 0}
000361      };
000362      VdbeOp *aOp;
000363      Db *pDb = &db->aDb[p->iDb];
000364      int iRec;
000365      int memId = p->regCtr;
000366  
000367      iRec = sqlite3GetTempReg(pParse);
000368      assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
000369      sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
000370      VdbeCoverage(v);
000371      sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
000372      aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
000373      if( aOp==0 ) break;
000374      aOp[0].p1 = memId+1;
000375      aOp[1].p2 = memId+1;
000376      aOp[2].p1 = memId-1;
000377      aOp[2].p3 = iRec;
000378      aOp[3].p2 = iRec;
000379      aOp[3].p3 = memId+1;
000380      aOp[3].p5 = OPFLAG_APPEND;
000381      sqlite3ReleaseTempReg(pParse, iRec);
000382    }
000383  }
000384  void sqlite3AutoincrementEnd(Parse *pParse){
000385    if( pParse->pAinc ) autoIncrementEnd(pParse);
000386  }
000387  #else
000388  /*
000389  ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
000390  ** above are all no-ops
000391  */
000392  # define autoIncBegin(A,B,C) (0)
000393  # define autoIncStep(A,B,C)
000394  #endif /* SQLITE_OMIT_AUTOINCREMENT */
000395  
000396  
000397  /* Forward declaration */
000398  static int xferOptimization(
000399    Parse *pParse,        /* Parser context */
000400    Table *pDest,         /* The table we are inserting into */
000401    Select *pSelect,      /* A SELECT statement to use as the data source */
000402    int onError,          /* How to handle constraint errors */
000403    int iDbDest           /* The database of pDest */
000404  );
000405  
000406  /*
000407  ** This routine is called to handle SQL of the following forms:
000408  **
000409  **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
000410  **    insert into TABLE (IDLIST) select
000411  **    insert into TABLE (IDLIST) default values
000412  **
000413  ** The IDLIST following the table name is always optional.  If omitted,
000414  ** then a list of all (non-hidden) columns for the table is substituted.
000415  ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
000416  ** is omitted.
000417  **
000418  ** For the pSelect parameter holds the values to be inserted for the
000419  ** first two forms shown above.  A VALUES clause is really just short-hand
000420  ** for a SELECT statement that omits the FROM clause and everything else
000421  ** that follows.  If the pSelect parameter is NULL, that means that the
000422  ** DEFAULT VALUES form of the INSERT statement is intended.
000423  **
000424  ** The code generated follows one of four templates.  For a simple
000425  ** insert with data coming from a single-row VALUES clause, the code executes
000426  ** once straight down through.  Pseudo-code follows (we call this
000427  ** the "1st template"):
000428  **
000429  **         open write cursor to <table> and its indices
000430  **         put VALUES clause expressions into registers
000431  **         write the resulting record into <table>
000432  **         cleanup
000433  **
000434  ** The three remaining templates assume the statement is of the form
000435  **
000436  **   INSERT INTO <table> SELECT ...
000437  **
000438  ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
000439  ** in other words if the SELECT pulls all columns from a single table
000440  ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
000441  ** if <table2> and <table1> are distinct tables but have identical
000442  ** schemas, including all the same indices, then a special optimization
000443  ** is invoked that copies raw records from <table2> over to <table1>.
000444  ** See the xferOptimization() function for the implementation of this
000445  ** template.  This is the 2nd template.
000446  **
000447  **         open a write cursor to <table>
000448  **         open read cursor on <table2>
000449  **         transfer all records in <table2> over to <table>
000450  **         close cursors
000451  **         foreach index on <table>
000452  **           open a write cursor on the <table> index
000453  **           open a read cursor on the corresponding <table2> index
000454  **           transfer all records from the read to the write cursors
000455  **           close cursors
000456  **         end foreach
000457  **
000458  ** The 3rd template is for when the second template does not apply
000459  ** and the SELECT clause does not read from <table> at any time.
000460  ** The generated code follows this template:
000461  **
000462  **         X <- A
000463  **         goto B
000464  **      A: setup for the SELECT
000465  **         loop over the rows in the SELECT
000466  **           load values into registers R..R+n
000467  **           yield X
000468  **         end loop
000469  **         cleanup after the SELECT
000470  **         end-coroutine X
000471  **      B: open write cursor to <table> and its indices
000472  **      C: yield X, at EOF goto D
000473  **         insert the select result into <table> from R..R+n
000474  **         goto C
000475  **      D: cleanup
000476  **
000477  ** The 4th template is used if the insert statement takes its
000478  ** values from a SELECT but the data is being inserted into a table
000479  ** that is also read as part of the SELECT.  In the third form,
000480  ** we have to use an intermediate table to store the results of
000481  ** the select.  The template is like this:
000482  **
000483  **         X <- A
000484  **         goto B
000485  **      A: setup for the SELECT
000486  **         loop over the tables in the SELECT
000487  **           load value into register R..R+n
000488  **           yield X
000489  **         end loop
000490  **         cleanup after the SELECT
000491  **         end co-routine R
000492  **      B: open temp table
000493  **      L: yield X, at EOF goto M
000494  **         insert row from R..R+n into temp table
000495  **         goto L
000496  **      M: open write cursor to <table> and its indices
000497  **         rewind temp table
000498  **      C: loop over rows of intermediate table
000499  **           transfer values form intermediate table into <table>
000500  **         end loop
000501  **      D: cleanup
000502  */
000503  void sqlite3Insert(
000504    Parse *pParse,        /* Parser context */
000505    SrcList *pTabList,    /* Name of table into which we are inserting */
000506    Select *pSelect,      /* A SELECT statement to use as the data source */
000507    IdList *pColumn,      /* Column names corresponding to IDLIST. */
000508    int onError,          /* How to handle constraint errors */
000509    Upsert *pUpsert       /* ON CONFLICT clauses for upsert, or NULL */
000510  ){
000511    sqlite3 *db;          /* The main database structure */
000512    Table *pTab;          /* The table to insert into.  aka TABLE */
000513    int i, j;             /* Loop counters */
000514    Vdbe *v;              /* Generate code into this virtual machine */
000515    Index *pIdx;          /* For looping over indices of the table */
000516    int nColumn;          /* Number of columns in the data */
000517    int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
000518    int iDataCur = 0;     /* VDBE cursor that is the main data repository */
000519    int iIdxCur = 0;      /* First index cursor */
000520    int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
000521    int endOfLoop;        /* Label for the end of the insertion loop */
000522    int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
000523    int addrInsTop = 0;   /* Jump to label "D" */
000524    int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
000525    SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
000526    int iDb;              /* Index of database holding TABLE */
000527    u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
000528    u8 appendFlag = 0;    /* True if the insert is likely to be an append */
000529    u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
000530    u8 bIdListInOrder;    /* True if IDLIST is in table order */
000531    ExprList *pList = 0;  /* List of VALUES() to be inserted  */
000532  
000533    /* Register allocations */
000534    int regFromSelect = 0;/* Base register for data coming from SELECT */
000535    int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
000536    int regRowCount = 0;  /* Memory cell used for the row counter */
000537    int regIns;           /* Block of regs holding rowid+data being inserted */
000538    int regRowid;         /* registers holding insert rowid */
000539    int regData;          /* register holding first column to insert */
000540    int *aRegIdx = 0;     /* One register allocated to each index */
000541  
000542  #ifndef SQLITE_OMIT_TRIGGER
000543    int isView;                 /* True if attempting to insert into a view */
000544    Trigger *pTrigger;          /* List of triggers on pTab, if required */
000545    int tmask;                  /* Mask of trigger times */
000546  #endif
000547  
000548    db = pParse->db;
000549    if( pParse->nErr || db->mallocFailed ){
000550      goto insert_cleanup;
000551    }
000552    dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
000553  
000554    /* If the Select object is really just a simple VALUES() list with a
000555    ** single row (the common case) then keep that one row of values
000556    ** and discard the other (unused) parts of the pSelect object
000557    */
000558    if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
000559      pList = pSelect->pEList;
000560      pSelect->pEList = 0;
000561      sqlite3SelectDelete(db, pSelect);
000562      pSelect = 0;
000563    }
000564  
000565    /* Locate the table into which we will be inserting new information.
000566    */
000567    assert( pTabList->nSrc==1 );
000568    pTab = sqlite3SrcListLookup(pParse, pTabList);
000569    if( pTab==0 ){
000570      goto insert_cleanup;
000571    }
000572    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
000573    assert( iDb<db->nDb );
000574    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
000575                         db->aDb[iDb].zDbSName) ){
000576      goto insert_cleanup;
000577    }
000578    withoutRowid = !HasRowid(pTab);
000579  
000580    /* Figure out if we have any triggers and if the table being
000581    ** inserted into is a view
000582    */
000583  #ifndef SQLITE_OMIT_TRIGGER
000584    pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
000585    isView = pTab->pSelect!=0;
000586  #else
000587  # define pTrigger 0
000588  # define tmask 0
000589  # define isView 0
000590  #endif
000591  #ifdef SQLITE_OMIT_VIEW
000592  # undef isView
000593  # define isView 0
000594  #endif
000595    assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
000596  
000597    /* If pTab is really a view, make sure it has been initialized.
000598    ** ViewGetColumnNames() is a no-op if pTab is not a view.
000599    */
000600    if( sqlite3ViewGetColumnNames(pParse, pTab) ){
000601      goto insert_cleanup;
000602    }
000603  
000604    /* Cannot insert into a read-only table.
000605    */
000606    if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
000607      goto insert_cleanup;
000608    }
000609  
000610    /* Allocate a VDBE
000611    */
000612    v = sqlite3GetVdbe(pParse);
000613    if( v==0 ) goto insert_cleanup;
000614    if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
000615    sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
000616  
000617  #ifndef SQLITE_OMIT_XFER_OPT
000618    /* If the statement is of the form
000619    **
000620    **       INSERT INTO <table1> SELECT * FROM <table2>;
000621    **
000622    ** Then special optimizations can be applied that make the transfer
000623    ** very fast and which reduce fragmentation of indices.
000624    **
000625    ** This is the 2nd template.
000626    */
000627    if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
000628      assert( !pTrigger );
000629      assert( pList==0 );
000630      goto insert_end;
000631    }
000632  #endif /* SQLITE_OMIT_XFER_OPT */
000633  
000634    /* If this is an AUTOINCREMENT table, look up the sequence number in the
000635    ** sqlite_sequence table and store it in memory cell regAutoinc.
000636    */
000637    regAutoinc = autoIncBegin(pParse, iDb, pTab);
000638  
000639    /* Allocate registers for holding the rowid of the new row,
000640    ** the content of the new row, and the assembled row record.
000641    */
000642    regRowid = regIns = pParse->nMem+1;
000643    pParse->nMem += pTab->nCol + 1;
000644    if( IsVirtual(pTab) ){
000645      regRowid++;
000646      pParse->nMem++;
000647    }
000648    regData = regRowid+1;
000649  
000650    /* If the INSERT statement included an IDLIST term, then make sure
000651    ** all elements of the IDLIST really are columns of the table and 
000652    ** remember the column indices.
000653    **
000654    ** If the table has an INTEGER PRIMARY KEY column and that column
000655    ** is named in the IDLIST, then record in the ipkColumn variable
000656    ** the index into IDLIST of the primary key column.  ipkColumn is
000657    ** the index of the primary key as it appears in IDLIST, not as
000658    ** is appears in the original table.  (The index of the INTEGER
000659    ** PRIMARY KEY in the original table is pTab->iPKey.)
000660    */
000661    bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
000662    if( pColumn ){
000663      for(i=0; i<pColumn->nId; i++){
000664        pColumn->a[i].idx = -1;
000665      }
000666      for(i=0; i<pColumn->nId; i++){
000667        for(j=0; j<pTab->nCol; j++){
000668          if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
000669            pColumn->a[i].idx = j;
000670            if( i!=j ) bIdListInOrder = 0;
000671            if( j==pTab->iPKey ){
000672              ipkColumn = i;  assert( !withoutRowid );
000673            }
000674            break;
000675          }
000676        }
000677        if( j>=pTab->nCol ){
000678          if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
000679            ipkColumn = i;
000680            bIdListInOrder = 0;
000681          }else{
000682            sqlite3ErrorMsg(pParse, "table %S has no column named %s",
000683                pTabList, 0, pColumn->a[i].zName);
000684            pParse->checkSchema = 1;
000685            goto insert_cleanup;
000686          }
000687        }
000688      }
000689    }
000690  
000691    /* Figure out how many columns of data are supplied.  If the data
000692    ** is coming from a SELECT statement, then generate a co-routine that
000693    ** produces a single row of the SELECT on each invocation.  The
000694    ** co-routine is the common header to the 3rd and 4th templates.
000695    */
000696    if( pSelect ){
000697      /* Data is coming from a SELECT or from a multi-row VALUES clause.
000698      ** Generate a co-routine to run the SELECT. */
000699      int regYield;       /* Register holding co-routine entry-point */
000700      int addrTop;        /* Top of the co-routine */
000701      int rc;             /* Result code */
000702  
000703      regYield = ++pParse->nMem;
000704      addrTop = sqlite3VdbeCurrentAddr(v) + 1;
000705      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
000706      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
000707      dest.iSdst = bIdListInOrder ? regData : 0;
000708      dest.nSdst = pTab->nCol;
000709      rc = sqlite3Select(pParse, pSelect, &dest);
000710      regFromSelect = dest.iSdst;
000711      if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
000712      sqlite3VdbeEndCoroutine(v, regYield);
000713      sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
000714      assert( pSelect->pEList );
000715      nColumn = pSelect->pEList->nExpr;
000716  
000717      /* Set useTempTable to TRUE if the result of the SELECT statement
000718      ** should be written into a temporary table (template 4).  Set to
000719      ** FALSE if each output row of the SELECT can be written directly into
000720      ** the destination table (template 3).
000721      **
000722      ** A temp table must be used if the table being updated is also one
000723      ** of the tables being read by the SELECT statement.  Also use a 
000724      ** temp table in the case of row triggers.
000725      */
000726      if( pTrigger || readsTable(pParse, iDb, pTab) ){
000727        useTempTable = 1;
000728      }
000729  
000730      if( useTempTable ){
000731        /* Invoke the coroutine to extract information from the SELECT
000732        ** and add it to a transient table srcTab.  The code generated
000733        ** here is from the 4th template:
000734        **
000735        **      B: open temp table
000736        **      L: yield X, goto M at EOF
000737        **         insert row from R..R+n into temp table
000738        **         goto L
000739        **      M: ...
000740        */
000741        int regRec;          /* Register to hold packed record */
000742        int regTempRowid;    /* Register to hold temp table ROWID */
000743        int addrL;           /* Label "L" */
000744  
000745        srcTab = pParse->nTab++;
000746        regRec = sqlite3GetTempReg(pParse);
000747        regTempRowid = sqlite3GetTempReg(pParse);
000748        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
000749        addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
000750        sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
000751        sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
000752        sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
000753        sqlite3VdbeGoto(v, addrL);
000754        sqlite3VdbeJumpHere(v, addrL);
000755        sqlite3ReleaseTempReg(pParse, regRec);
000756        sqlite3ReleaseTempReg(pParse, regTempRowid);
000757      }
000758    }else{
000759      /* This is the case if the data for the INSERT is coming from a 
000760      ** single-row VALUES clause
000761      */
000762      NameContext sNC;
000763      memset(&sNC, 0, sizeof(sNC));
000764      sNC.pParse = pParse;
000765      srcTab = -1;
000766      assert( useTempTable==0 );
000767      if( pList ){
000768        nColumn = pList->nExpr;
000769        if( sqlite3ResolveExprListNames(&sNC, pList) ){
000770          goto insert_cleanup;
000771        }
000772      }else{
000773        nColumn = 0;
000774      }
000775    }
000776  
000777    /* If there is no IDLIST term but the table has an integer primary
000778    ** key, the set the ipkColumn variable to the integer primary key 
000779    ** column index in the original table definition.
000780    */
000781    if( pColumn==0 && nColumn>0 ){
000782      ipkColumn = pTab->iPKey;
000783    }
000784  
000785    /* Make sure the number of columns in the source data matches the number
000786    ** of columns to be inserted into the table.
000787    */
000788    for(i=0; i<pTab->nCol; i++){
000789      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
000790    }
000791    if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
000792      sqlite3ErrorMsg(pParse, 
000793         "table %S has %d columns but %d values were supplied",
000794         pTabList, 0, pTab->nCol-nHidden, nColumn);
000795      goto insert_cleanup;
000796    }
000797    if( pColumn!=0 && nColumn!=pColumn->nId ){
000798      sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
000799      goto insert_cleanup;
000800    }
000801      
000802    /* Initialize the count of rows to be inserted
000803    */
000804    if( (db->flags & SQLITE_CountRows)!=0
000805     && !pParse->nested
000806     && !pParse->pTriggerTab
000807    ){
000808      regRowCount = ++pParse->nMem;
000809      sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
000810    }
000811  
000812    /* If this is not a view, open the table and and all indices */
000813    if( !isView ){
000814      int nIdx;
000815      nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
000816                                        &iDataCur, &iIdxCur);
000817      aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
000818      if( aRegIdx==0 ){
000819        goto insert_cleanup;
000820      }
000821      for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
000822        assert( pIdx );
000823        aRegIdx[i] = ++pParse->nMem;
000824        pParse->nMem += pIdx->nColumn;
000825      }
000826    }
000827  #ifndef SQLITE_OMIT_UPSERT
000828    if( pUpsert ){
000829      if( IsVirtual(pTab) ){
000830        sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
000831                pTab->zName);
000832        goto insert_cleanup;
000833      }
000834      pTabList->a[0].iCursor = iDataCur;
000835      pUpsert->pUpsertSrc = pTabList;
000836      pUpsert->regData = regData;
000837      pUpsert->iDataCur = iDataCur;
000838      pUpsert->iIdxCur = iIdxCur;
000839      if( pUpsert->pUpsertTarget ){
000840        sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
000841      }
000842    }
000843  #endif
000844  
000845  
000846    /* This is the top of the main insertion loop */
000847    if( useTempTable ){
000848      /* This block codes the top of loop only.  The complete loop is the
000849      ** following pseudocode (template 4):
000850      **
000851      **         rewind temp table, if empty goto D
000852      **      C: loop over rows of intermediate table
000853      **           transfer values form intermediate table into <table>
000854      **         end loop
000855      **      D: ...
000856      */
000857      addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
000858      addrCont = sqlite3VdbeCurrentAddr(v);
000859    }else if( pSelect ){
000860      /* This block codes the top of loop only.  The complete loop is the
000861      ** following pseudocode (template 3):
000862      **
000863      **      C: yield X, at EOF goto D
000864      **         insert the select result into <table> from R..R+n
000865      **         goto C
000866      **      D: ...
000867      */
000868      addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
000869      VdbeCoverage(v);
000870    }
000871  
000872    /* Run the BEFORE and INSTEAD OF triggers, if there are any
000873    */
000874    endOfLoop = sqlite3VdbeMakeLabel(pParse);
000875    if( tmask & TRIGGER_BEFORE ){
000876      int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
000877  
000878      /* build the NEW.* reference row.  Note that if there is an INTEGER
000879      ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
000880      ** translated into a unique ID for the row.  But on a BEFORE trigger,
000881      ** we do not know what the unique ID will be (because the insert has
000882      ** not happened yet) so we substitute a rowid of -1
000883      */
000884      if( ipkColumn<0 ){
000885        sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
000886      }else{
000887        int addr1;
000888        assert( !withoutRowid );
000889        if( useTempTable ){
000890          sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
000891        }else{
000892          assert( pSelect==0 );  /* Otherwise useTempTable is true */
000893          sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
000894        }
000895        addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
000896        sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
000897        sqlite3VdbeJumpHere(v, addr1);
000898        sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
000899      }
000900  
000901      /* Cannot have triggers on a virtual table. If it were possible,
000902      ** this block would have to account for hidden column.
000903      */
000904      assert( !IsVirtual(pTab) );
000905  
000906      /* Create the new column data
000907      */
000908      for(i=j=0; i<pTab->nCol; i++){
000909        if( pColumn ){
000910          for(j=0; j<pColumn->nId; j++){
000911            if( pColumn->a[j].idx==i ) break;
000912          }
000913        }
000914        if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
000915              || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
000916          sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
000917        }else if( useTempTable ){
000918          sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
000919        }else{
000920          assert( pSelect==0 ); /* Otherwise useTempTable is true */
000921          sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
000922        }
000923        if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
000924      }
000925  
000926      /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
000927      ** do not attempt any conversions before assembling the record.
000928      ** If this is a real table, attempt conversions as required by the
000929      ** table column affinities.
000930      */
000931      if( !isView ){
000932        sqlite3TableAffinity(v, pTab, regCols+1);
000933      }
000934  
000935      /* Fire BEFORE or INSTEAD OF triggers */
000936      sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
000937          pTab, regCols-pTab->nCol-1, onError, endOfLoop);
000938  
000939      sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
000940    }
000941  
000942    /* Compute the content of the next row to insert into a range of
000943    ** registers beginning at regIns.
000944    */
000945    if( !isView ){
000946      if( IsVirtual(pTab) ){
000947        /* The row that the VUpdate opcode will delete: none */
000948        sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
000949      }
000950      if( ipkColumn>=0 ){
000951        if( useTempTable ){
000952          sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
000953        }else if( pSelect ){
000954          sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
000955        }else{
000956          Expr *pIpk = pList->a[ipkColumn].pExpr;
000957          if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
000958            sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
000959            appendFlag = 1;
000960          }else{
000961            sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
000962          }
000963        }
000964        /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
000965        ** to generate a unique primary key value.
000966        */
000967        if( !appendFlag ){
000968          int addr1;
000969          if( !IsVirtual(pTab) ){
000970            addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
000971            sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
000972            sqlite3VdbeJumpHere(v, addr1);
000973          }else{
000974            addr1 = sqlite3VdbeCurrentAddr(v);
000975            sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
000976          }
000977          sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
000978        }
000979      }else if( IsVirtual(pTab) || withoutRowid ){
000980        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
000981      }else{
000982        sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
000983        appendFlag = 1;
000984      }
000985      autoIncStep(pParse, regAutoinc, regRowid);
000986  
000987      /* Compute data for all columns of the new entry, beginning
000988      ** with the first column.
000989      */
000990      nHidden = 0;
000991      for(i=0; i<pTab->nCol; i++){
000992        int iRegStore = regRowid+1+i;
000993        if( i==pTab->iPKey ){
000994          /* The value of the INTEGER PRIMARY KEY column is always a NULL.
000995          ** Whenever this column is read, the rowid will be substituted
000996          ** in its place.  Hence, fill this column with a NULL to avoid
000997          ** taking up data space with information that will never be used.
000998          ** As there may be shallow copies of this value, make it a soft-NULL */
000999          sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
001000          continue;
001001        }
001002        if( pColumn==0 ){
001003          if( IsHiddenColumn(&pTab->aCol[i]) ){
001004            j = -1;
001005            nHidden++;
001006          }else{
001007            j = i - nHidden;
001008          }
001009        }else{
001010          for(j=0; j<pColumn->nId; j++){
001011            if( pColumn->a[j].idx==i ) break;
001012          }
001013        }
001014        if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
001015          sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
001016        }else if( useTempTable ){
001017          sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
001018        }else if( pSelect ){
001019          if( regFromSelect!=regData ){
001020            sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
001021          }
001022        }else{
001023          sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
001024        }
001025      }
001026  
001027      /* Generate code to check constraints and generate index keys and
001028      ** do the insertion.
001029      */
001030  #ifndef SQLITE_OMIT_VIRTUALTABLE
001031      if( IsVirtual(pTab) ){
001032        const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
001033        sqlite3VtabMakeWritable(pParse, pTab);
001034        sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
001035        sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
001036        sqlite3MayAbort(pParse);
001037      }else
001038  #endif
001039      {
001040        int isReplace;    /* Set to true if constraints may cause a replace */
001041        int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
001042        sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
001043            regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
001044        );
001045        sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
001046  
001047        /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
001048        ** constraints or (b) there are no triggers and this table is not a
001049        ** parent table in a foreign key constraint. It is safe to set the
001050        ** flag in the second case as if any REPLACE constraint is hit, an
001051        ** OP_Delete or OP_IdxDelete instruction will be executed on each 
001052        ** cursor that is disturbed. And these instructions both clear the
001053        ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
001054        ** functionality.  */
001055        bUseSeek = (isReplace==0 || (pTrigger==0 &&
001056            ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
001057        ));
001058        sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
001059            regIns, aRegIdx, 0, appendFlag, bUseSeek
001060        );
001061      }
001062    }
001063  
001064    /* Update the count of rows that are inserted
001065    */
001066    if( regRowCount ){
001067      sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
001068    }
001069  
001070    if( pTrigger ){
001071      /* Code AFTER triggers */
001072      sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
001073          pTab, regData-2-pTab->nCol, onError, endOfLoop);
001074    }
001075  
001076    /* The bottom of the main insertion loop, if the data source
001077    ** is a SELECT statement.
001078    */
001079    sqlite3VdbeResolveLabel(v, endOfLoop);
001080    if( useTempTable ){
001081      sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
001082      sqlite3VdbeJumpHere(v, addrInsTop);
001083      sqlite3VdbeAddOp1(v, OP_Close, srcTab);
001084    }else if( pSelect ){
001085      sqlite3VdbeGoto(v, addrCont);
001086      sqlite3VdbeJumpHere(v, addrInsTop);
001087    }
001088  
001089  insert_end:
001090    /* Update the sqlite_sequence table by storing the content of the
001091    ** maximum rowid counter values recorded while inserting into
001092    ** autoincrement tables.
001093    */
001094    if( pParse->nested==0 && pParse->pTriggerTab==0 ){
001095      sqlite3AutoincrementEnd(pParse);
001096    }
001097  
001098    /*
001099    ** Return the number of rows inserted. If this routine is 
001100    ** generating code because of a call to sqlite3NestedParse(), do not
001101    ** invoke the callback function.
001102    */
001103    if( regRowCount ){
001104      sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
001105      sqlite3VdbeSetNumCols(v, 1);
001106      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
001107    }
001108  
001109  insert_cleanup:
001110    sqlite3SrcListDelete(db, pTabList);
001111    sqlite3ExprListDelete(db, pList);
001112    sqlite3UpsertDelete(db, pUpsert);
001113    sqlite3SelectDelete(db, pSelect);
001114    sqlite3IdListDelete(db, pColumn);
001115    sqlite3DbFree(db, aRegIdx);
001116  }
001117  
001118  /* Make sure "isView" and other macros defined above are undefined. Otherwise
001119  ** they may interfere with compilation of other functions in this file
001120  ** (or in another file, if this file becomes part of the amalgamation).  */
001121  #ifdef isView
001122   #undef isView
001123  #endif
001124  #ifdef pTrigger
001125   #undef pTrigger
001126  #endif
001127  #ifdef tmask
001128   #undef tmask
001129  #endif
001130  
001131  /*
001132  ** Meanings of bits in of pWalker->eCode for 
001133  ** sqlite3ExprReferencesUpdatedColumn()
001134  */
001135  #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
001136  #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
001137  
001138  /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
001139  *  Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
001140  ** expression node references any of the
001141  ** columns that are being modifed by an UPDATE statement.
001142  */
001143  static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
001144    if( pExpr->op==TK_COLUMN ){
001145      assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
001146      if( pExpr->iColumn>=0 ){
001147        if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
001148          pWalker->eCode |= CKCNSTRNT_COLUMN;
001149        }
001150      }else{
001151        pWalker->eCode |= CKCNSTRNT_ROWID;
001152      }
001153    }
001154    return WRC_Continue;
001155  }
001156  
001157  /*
001158  ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
001159  ** only columns that are modified by the UPDATE are those for which
001160  ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
001161  **
001162  ** Return true if CHECK constraint pExpr uses any of the
001163  ** changing columns (or the rowid if it is changing).  In other words,
001164  ** return true if this CHECK constraint must be validated for
001165  ** the new row in the UPDATE statement.
001166  **
001167  ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
001168  ** The operation of this routine is the same - return true if an only if
001169  ** the expression uses one or more of columns identified by the second and
001170  ** third arguments.
001171  */
001172  int sqlite3ExprReferencesUpdatedColumn(
001173    Expr *pExpr,    /* The expression to be checked */
001174    int *aiChng,    /* aiChng[x]>=0 if column x changed by the UPDATE */
001175    int chngRowid   /* True if UPDATE changes the rowid */
001176  ){
001177    Walker w;
001178    memset(&w, 0, sizeof(w));
001179    w.eCode = 0;
001180    w.xExprCallback = checkConstraintExprNode;
001181    w.u.aiCol = aiChng;
001182    sqlite3WalkExpr(&w, pExpr);
001183    if( !chngRowid ){
001184      testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
001185      w.eCode &= ~CKCNSTRNT_ROWID;
001186    }
001187    testcase( w.eCode==0 );
001188    testcase( w.eCode==CKCNSTRNT_COLUMN );
001189    testcase( w.eCode==CKCNSTRNT_ROWID );
001190    testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
001191    return w.eCode!=0;
001192  }
001193  
001194  /*
001195  ** Generate code to do constraint checks prior to an INSERT or an UPDATE
001196  ** on table pTab.
001197  **
001198  ** The regNewData parameter is the first register in a range that contains
001199  ** the data to be inserted or the data after the update.  There will be
001200  ** pTab->nCol+1 registers in this range.  The first register (the one
001201  ** that regNewData points to) will contain the new rowid, or NULL in the
001202  ** case of a WITHOUT ROWID table.  The second register in the range will
001203  ** contain the content of the first table column.  The third register will
001204  ** contain the content of the second table column.  And so forth.
001205  **
001206  ** The regOldData parameter is similar to regNewData except that it contains
001207  ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
001208  ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
001209  ** checking regOldData for zero.
001210  **
001211  ** For an UPDATE, the pkChng boolean is true if the true primary key (the
001212  ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
001213  ** might be modified by the UPDATE.  If pkChng is false, then the key of
001214  ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
001215  **
001216  ** For an INSERT, the pkChng boolean indicates whether or not the rowid
001217  ** was explicitly specified as part of the INSERT statement.  If pkChng
001218  ** is zero, it means that the either rowid is computed automatically or
001219  ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
001220  ** pkChng will only be true if the INSERT statement provides an integer
001221  ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
001222  **
001223  ** The code generated by this routine will store new index entries into
001224  ** registers identified by aRegIdx[].  No index entry is created for
001225  ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
001226  ** the same as the order of indices on the linked list of indices
001227  ** at pTab->pIndex.
001228  **
001229  ** The caller must have already opened writeable cursors on the main
001230  ** table and all applicable indices (that is to say, all indices for which
001231  ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
001232  ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
001233  ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
001234  ** for the first index in the pTab->pIndex list.  Cursors for other indices
001235  ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
001236  **
001237  ** This routine also generates code to check constraints.  NOT NULL,
001238  ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
001239  ** then the appropriate action is performed.  There are five possible
001240  ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
001241  **
001242  **  Constraint type  Action       What Happens
001243  **  ---------------  ----------   ----------------------------------------
001244  **  any              ROLLBACK     The current transaction is rolled back and
001245  **                                sqlite3_step() returns immediately with a
001246  **                                return code of SQLITE_CONSTRAINT.
001247  **
001248  **  any              ABORT        Back out changes from the current command
001249  **                                only (do not do a complete rollback) then
001250  **                                cause sqlite3_step() to return immediately
001251  **                                with SQLITE_CONSTRAINT.
001252  **
001253  **  any              FAIL         Sqlite3_step() returns immediately with a
001254  **                                return code of SQLITE_CONSTRAINT.  The
001255  **                                transaction is not rolled back and any
001256  **                                changes to prior rows are retained.
001257  **
001258  **  any              IGNORE       The attempt in insert or update the current
001259  **                                row is skipped, without throwing an error.
001260  **                                Processing continues with the next row.
001261  **                                (There is an immediate jump to ignoreDest.)
001262  **
001263  **  NOT NULL         REPLACE      The NULL value is replace by the default
001264  **                                value for that column.  If the default value
001265  **                                is NULL, the action is the same as ABORT.
001266  **
001267  **  UNIQUE           REPLACE      The other row that conflicts with the row
001268  **                                being inserted is removed.
001269  **
001270  **  CHECK            REPLACE      Illegal.  The results in an exception.
001271  **
001272  ** Which action to take is determined by the overrideError parameter.
001273  ** Or if overrideError==OE_Default, then the pParse->onError parameter
001274  ** is used.  Or if pParse->onError==OE_Default then the onError value
001275  ** for the constraint is used.
001276  */
001277  void sqlite3GenerateConstraintChecks(
001278    Parse *pParse,       /* The parser context */
001279    Table *pTab,         /* The table being inserted or updated */
001280    int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
001281    int iDataCur,        /* Canonical data cursor (main table or PK index) */
001282    int iIdxCur,         /* First index cursor */
001283    int regNewData,      /* First register in a range holding values to insert */
001284    int regOldData,      /* Previous content.  0 for INSERTs */
001285    u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
001286    u8 overrideError,    /* Override onError to this if not OE_Default */
001287    int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
001288    int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
001289    int *aiChng,         /* column i is unchanged if aiChng[i]<0 */
001290    Upsert *pUpsert      /* ON CONFLICT clauses, if any.  NULL otherwise */
001291  ){
001292    Vdbe *v;             /* VDBE under constrution */
001293    Index *pIdx;         /* Pointer to one of the indices */
001294    Index *pPk = 0;      /* The PRIMARY KEY index */
001295    sqlite3 *db;         /* Database connection */
001296    int i;               /* loop counter */
001297    int ix;              /* Index loop counter */
001298    int nCol;            /* Number of columns */
001299    int onError;         /* Conflict resolution strategy */
001300    int addr1;           /* Address of jump instruction */
001301    int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
001302    int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
001303    Index *pUpIdx = 0;   /* Index to which to apply the upsert */
001304    u8 isUpdate;         /* True if this is an UPDATE operation */
001305    u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
001306    int upsertBypass = 0;  /* Address of Goto to bypass upsert subroutine */
001307    int upsertJump = 0;    /* Address of Goto that jumps into upsert subroutine */
001308    int ipkTop = 0;        /* Top of the IPK uniqueness check */
001309    int ipkBottom = 0;     /* OP_Goto at the end of the IPK uniqueness check */
001310  
001311    isUpdate = regOldData!=0;
001312    db = pParse->db;
001313    v = sqlite3GetVdbe(pParse);
001314    assert( v!=0 );
001315    assert( pTab->pSelect==0 );  /* This table is not a VIEW */
001316    nCol = pTab->nCol;
001317    
001318    /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
001319    ** normal rowid tables.  nPkField is the number of key fields in the 
001320    ** pPk index or 1 for a rowid table.  In other words, nPkField is the
001321    ** number of fields in the true primary key of the table. */
001322    if( HasRowid(pTab) ){
001323      pPk = 0;
001324      nPkField = 1;
001325    }else{
001326      pPk = sqlite3PrimaryKeyIndex(pTab);
001327      nPkField = pPk->nKeyCol;
001328    }
001329  
001330    /* Record that this module has started */
001331    VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
001332                       iDataCur, iIdxCur, regNewData, regOldData, pkChng));
001333  
001334    /* Test all NOT NULL constraints.
001335    */
001336    for(i=0; i<nCol; i++){
001337      if( i==pTab->iPKey ){
001338        continue;        /* ROWID is never NULL */
001339      }
001340      if( aiChng && aiChng[i]<0 ){
001341        /* Don't bother checking for NOT NULL on columns that do not change */
001342        continue;
001343      }
001344      onError = pTab->aCol[i].notNull;
001345      if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
001346      if( overrideError!=OE_Default ){
001347        onError = overrideError;
001348      }else if( onError==OE_Default ){
001349        onError = OE_Abort;
001350      }
001351      if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
001352        onError = OE_Abort;
001353      }
001354      assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
001355          || onError==OE_Ignore || onError==OE_Replace );
001356      addr1 = 0;
001357      switch( onError ){
001358        case OE_Replace: {
001359          assert( onError==OE_Replace );
001360          addr1 = sqlite3VdbeMakeLabel(pParse);
001361          sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1);
001362            VdbeCoverage(v);
001363          sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
001364          sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1);
001365            VdbeCoverage(v);
001366          onError = OE_Abort;
001367          /* Fall through into the OE_Abort case to generate code that runs
001368          ** if both the input and the default value are NULL */
001369        }
001370        case OE_Abort:
001371          sqlite3MayAbort(pParse);
001372          /* Fall through */
001373        case OE_Rollback:
001374        case OE_Fail: {
001375          char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
001376                                      pTab->aCol[i].zName);
001377          sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
001378                            regNewData+1+i);
001379          sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
001380          sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
001381          VdbeCoverage(v);
001382          if( addr1 ) sqlite3VdbeResolveLabel(v, addr1);
001383          break;
001384        }
001385        default: {
001386          assert( onError==OE_Ignore );
001387          sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
001388          VdbeCoverage(v);
001389          break;
001390        }
001391      }
001392    }
001393  
001394    /* Test all CHECK constraints
001395    */
001396  #ifndef SQLITE_OMIT_CHECK
001397    if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
001398      ExprList *pCheck = pTab->pCheck;
001399      pParse->iSelfTab = -(regNewData+1);
001400      onError = overrideError!=OE_Default ? overrideError : OE_Abort;
001401      for(i=0; i<pCheck->nExpr; i++){
001402        int allOk;
001403        Expr *pExpr = pCheck->a[i].pExpr;
001404        if( aiChng
001405         && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
001406        ){
001407          /* The check constraints do not reference any of the columns being
001408          ** updated so there is no point it verifying the check constraint */
001409          continue;
001410        }
001411        allOk = sqlite3VdbeMakeLabel(pParse);
001412        sqlite3VdbeVerifyAbortable(v, onError);
001413        sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
001414        if( onError==OE_Ignore ){
001415          sqlite3VdbeGoto(v, ignoreDest);
001416        }else{
001417          char *zName = pCheck->a[i].zName;
001418          if( zName==0 ) zName = pTab->zName;
001419          if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
001420          sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
001421                                onError, zName, P4_TRANSIENT,
001422                                P5_ConstraintCheck);
001423        }
001424        sqlite3VdbeResolveLabel(v, allOk);
001425      }
001426      pParse->iSelfTab = 0;
001427    }
001428  #endif /* !defined(SQLITE_OMIT_CHECK) */
001429  
001430    /* UNIQUE and PRIMARY KEY constraints should be handled in the following
001431    ** order:
001432    **
001433    **   (1)  OE_Update
001434    **   (2)  OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
001435    **   (3)  OE_Replace
001436    **
001437    ** OE_Fail and OE_Ignore must happen before any changes are made.
001438    ** OE_Update guarantees that only a single row will change, so it
001439    ** must happen before OE_Replace.  Technically, OE_Abort and OE_Rollback
001440    ** could happen in any order, but they are grouped up front for
001441    ** convenience.
001442    **
001443    ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
001444    ** The order of constraints used to have OE_Update as (2) and OE_Abort
001445    ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
001446    ** constraint before any others, so it had to be moved.
001447    **
001448    ** Constraint checking code is generated in this order:
001449    **   (A)  The rowid constraint
001450    **   (B)  Unique index constraints that do not have OE_Replace as their
001451    **        default conflict resolution strategy
001452    **   (C)  Unique index that do use OE_Replace by default.
001453    **
001454    ** The ordering of (2) and (3) is accomplished by making sure the linked
001455    ** list of indexes attached to a table puts all OE_Replace indexes last
001456    ** in the list.  See sqlite3CreateIndex() for where that happens.
001457    */
001458  
001459    if( pUpsert ){
001460      if( pUpsert->pUpsertTarget==0 ){
001461        /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
001462        ** Make all unique constraint resolution be OE_Ignore */
001463        assert( pUpsert->pUpsertSet==0 );
001464        overrideError = OE_Ignore;
001465        pUpsert = 0;
001466      }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
001467        /* If the constraint-target uniqueness check must be run first.
001468        ** Jump to that uniqueness check now */
001469        upsertJump = sqlite3VdbeAddOp0(v, OP_Goto);
001470        VdbeComment((v, "UPSERT constraint goes first"));
001471      }
001472    }
001473  
001474    /* If rowid is changing, make sure the new rowid does not previously
001475    ** exist in the table.
001476    */
001477    if( pkChng && pPk==0 ){
001478      int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
001479  
001480      /* Figure out what action to take in case of a rowid collision */
001481      onError = pTab->keyConf;
001482      if( overrideError!=OE_Default ){
001483        onError = overrideError;
001484      }else if( onError==OE_Default ){
001485        onError = OE_Abort;
001486      }
001487  
001488      /* figure out whether or not upsert applies in this case */
001489      if( pUpsert && pUpsert->pUpsertIdx==0 ){
001490        if( pUpsert->pUpsertSet==0 ){
001491          onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
001492        }else{
001493          onError = OE_Update;  /* DO UPDATE */
001494        }
001495      }
001496  
001497      /* If the response to a rowid conflict is REPLACE but the response
001498      ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
001499      ** to defer the running of the rowid conflict checking until after
001500      ** the UNIQUE constraints have run.
001501      */
001502      if( onError==OE_Replace      /* IPK rule is REPLACE */
001503       && onError!=overrideError   /* Rules for other contraints are different */
001504       && pTab->pIndex             /* There exist other constraints */
001505      ){
001506        ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
001507        VdbeComment((v, "defer IPK REPLACE until last"));
001508      }
001509  
001510      if( isUpdate ){
001511        /* pkChng!=0 does not mean that the rowid has changed, only that
001512        ** it might have changed.  Skip the conflict logic below if the rowid
001513        ** is unchanged. */
001514        sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
001515        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
001516        VdbeCoverage(v);
001517      }
001518  
001519      /* Check to see if the new rowid already exists in the table.  Skip
001520      ** the following conflict logic if it does not. */
001521      VdbeNoopComment((v, "uniqueness check for ROWID"));
001522      sqlite3VdbeVerifyAbortable(v, onError);
001523      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
001524      VdbeCoverage(v);
001525  
001526      switch( onError ){
001527        default: {
001528          onError = OE_Abort;
001529          /* Fall thru into the next case */
001530        }
001531        case OE_Rollback:
001532        case OE_Abort:
001533        case OE_Fail: {
001534          testcase( onError==OE_Rollback );
001535          testcase( onError==OE_Abort );
001536          testcase( onError==OE_Fail );
001537          sqlite3RowidConstraint(pParse, onError, pTab);
001538          break;
001539        }
001540        case OE_Replace: {
001541          /* If there are DELETE triggers on this table and the
001542          ** recursive-triggers flag is set, call GenerateRowDelete() to
001543          ** remove the conflicting row from the table. This will fire
001544          ** the triggers and remove both the table and index b-tree entries.
001545          **
001546          ** Otherwise, if there are no triggers or the recursive-triggers
001547          ** flag is not set, but the table has one or more indexes, call 
001548          ** GenerateRowIndexDelete(). This removes the index b-tree entries 
001549          ** only. The table b-tree entry will be replaced by the new entry 
001550          ** when it is inserted.  
001551          **
001552          ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
001553          ** also invoke MultiWrite() to indicate that this VDBE may require
001554          ** statement rollback (if the statement is aborted after the delete
001555          ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
001556          ** but being more selective here allows statements like:
001557          **
001558          **   REPLACE INTO t(rowid) VALUES($newrowid)
001559          **
001560          ** to run without a statement journal if there are no indexes on the
001561          ** table.
001562          */
001563          Trigger *pTrigger = 0;
001564          if( db->flags&SQLITE_RecTriggers ){
001565            pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
001566          }
001567          if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
001568            sqlite3MultiWrite(pParse);
001569            sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
001570                                     regNewData, 1, 0, OE_Replace, 1, -1);
001571          }else{
001572  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
001573            assert( HasRowid(pTab) );
001574            /* This OP_Delete opcode fires the pre-update-hook only. It does
001575            ** not modify the b-tree. It is more efficient to let the coming
001576            ** OP_Insert replace the existing entry than it is to delete the
001577            ** existing entry and then insert a new one. */
001578            sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
001579            sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
001580  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
001581            if( pTab->pIndex ){
001582              sqlite3MultiWrite(pParse);
001583              sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
001584            }
001585          }
001586          seenReplace = 1;
001587          break;
001588        }
001589  #ifndef SQLITE_OMIT_UPSERT
001590        case OE_Update: {
001591          sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
001592          /* Fall through */
001593        }
001594  #endif
001595        case OE_Ignore: {
001596          testcase( onError==OE_Ignore );
001597          sqlite3VdbeGoto(v, ignoreDest);
001598          break;
001599        }
001600      }
001601      sqlite3VdbeResolveLabel(v, addrRowidOk);
001602      if( ipkTop ){
001603        ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
001604        sqlite3VdbeJumpHere(v, ipkTop-1);
001605      }
001606    }
001607  
001608    /* Test all UNIQUE constraints by creating entries for each UNIQUE
001609    ** index and making sure that duplicate entries do not already exist.
001610    ** Compute the revised record entries for indices as we go.
001611    **
001612    ** This loop also handles the case of the PRIMARY KEY index for a
001613    ** WITHOUT ROWID table.
001614    */
001615    for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
001616      int regIdx;          /* Range of registers hold conent for pIdx */
001617      int regR;            /* Range of registers holding conflicting PK */
001618      int iThisCur;        /* Cursor for this UNIQUE index */
001619      int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
001620  
001621      if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
001622      if( pUpIdx==pIdx ){
001623        addrUniqueOk = upsertJump+1;
001624        upsertBypass = sqlite3VdbeGoto(v, 0);
001625        VdbeComment((v, "Skip upsert subroutine"));
001626        sqlite3VdbeJumpHere(v, upsertJump);
001627      }else{
001628        addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
001629      }
001630      if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){
001631        sqlite3TableAffinity(v, pTab, regNewData+1);
001632        bAffinityDone = 1;
001633      }
001634      VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName));
001635      iThisCur = iIdxCur+ix;
001636  
001637  
001638      /* Skip partial indices for which the WHERE clause is not true */
001639      if( pIdx->pPartIdxWhere ){
001640        sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
001641        pParse->iSelfTab = -(regNewData+1);
001642        sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
001643                              SQLITE_JUMPIFNULL);
001644        pParse->iSelfTab = 0;
001645      }
001646  
001647      /* Create a record for this index entry as it should appear after
001648      ** the insert or update.  Store that record in the aRegIdx[ix] register
001649      */
001650      regIdx = aRegIdx[ix]+1;
001651      for(i=0; i<pIdx->nColumn; i++){
001652        int iField = pIdx->aiColumn[i];
001653        int x;
001654        if( iField==XN_EXPR ){
001655          pParse->iSelfTab = -(regNewData+1);
001656          sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
001657          pParse->iSelfTab = 0;
001658          VdbeComment((v, "%s column %d", pIdx->zName, i));
001659        }else{
001660          if( iField==XN_ROWID || iField==pTab->iPKey ){
001661            x = regNewData;
001662          }else{
001663            x = iField + regNewData + 1;
001664          }
001665          sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
001666          VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
001667        }
001668      }
001669      sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
001670      VdbeComment((v, "for %s", pIdx->zName));
001671  #ifdef SQLITE_ENABLE_NULL_TRIM
001672      if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
001673  #endif
001674  
001675      /* In an UPDATE operation, if this index is the PRIMARY KEY index 
001676      ** of a WITHOUT ROWID table and there has been no change the
001677      ** primary key, then no collision is possible.  The collision detection
001678      ** logic below can all be skipped. */
001679      if( isUpdate && pPk==pIdx && pkChng==0 ){
001680        sqlite3VdbeResolveLabel(v, addrUniqueOk);
001681        continue;
001682      }
001683  
001684      /* Find out what action to take in case there is a uniqueness conflict */
001685      onError = pIdx->onError;
001686      if( onError==OE_None ){ 
001687        sqlite3VdbeResolveLabel(v, addrUniqueOk);
001688        continue;  /* pIdx is not a UNIQUE index */
001689      }
001690      if( overrideError!=OE_Default ){
001691        onError = overrideError;
001692      }else if( onError==OE_Default ){
001693        onError = OE_Abort;
001694      }
001695  
001696      /* Figure out if the upsert clause applies to this index */
001697      if( pUpIdx==pIdx ){
001698        if( pUpsert->pUpsertSet==0 ){
001699          onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
001700        }else{
001701          onError = OE_Update;  /* DO UPDATE */
001702        }
001703      }
001704  
001705      /* Collision detection may be omitted if all of the following are true:
001706      **   (1) The conflict resolution algorithm is REPLACE
001707      **   (2) The table is a WITHOUT ROWID table
001708      **   (3) There are no secondary indexes on the table
001709      **   (4) No delete triggers need to be fired if there is a conflict
001710      **   (5) No FK constraint counters need to be updated if a conflict occurs.
001711      **
001712      ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
001713      ** must be explicitly deleted in order to ensure any pre-update hook
001714      ** is invoked.  */ 
001715  #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
001716      if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
001717       && pPk==pIdx                                   /* Condition 2 */
001718       && onError==OE_Replace                         /* Condition 1 */
001719       && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
001720            0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
001721       && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
001722           (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
001723      ){
001724        sqlite3VdbeResolveLabel(v, addrUniqueOk);
001725        continue;
001726      }
001727  #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
001728  
001729      /* Check to see if the new index entry will be unique */
001730      sqlite3VdbeVerifyAbortable(v, onError);
001731      sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
001732                           regIdx, pIdx->nKeyCol); VdbeCoverage(v);
001733  
001734      /* Generate code to handle collisions */
001735      regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
001736      if( isUpdate || onError==OE_Replace ){
001737        if( HasRowid(pTab) ){
001738          sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
001739          /* Conflict only if the rowid of the existing index entry
001740          ** is different from old-rowid */
001741          if( isUpdate ){
001742            sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
001743            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
001744            VdbeCoverage(v);
001745          }
001746        }else{
001747          int x;
001748          /* Extract the PRIMARY KEY from the end of the index entry and
001749          ** store it in registers regR..regR+nPk-1 */
001750          if( pIdx!=pPk ){
001751            for(i=0; i<pPk->nKeyCol; i++){
001752              assert( pPk->aiColumn[i]>=0 );
001753              x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
001754              sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
001755              VdbeComment((v, "%s.%s", pTab->zName,
001756                           pTab->aCol[pPk->aiColumn[i]].zName));
001757            }
001758          }
001759          if( isUpdate ){
001760            /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 
001761            ** table, only conflict if the new PRIMARY KEY values are actually
001762            ** different from the old.
001763            **
001764            ** For a UNIQUE index, only conflict if the PRIMARY KEY values
001765            ** of the matched index row are different from the original PRIMARY
001766            ** KEY values of this row before the update.  */
001767            int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
001768            int op = OP_Ne;
001769            int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
001770    
001771            for(i=0; i<pPk->nKeyCol; i++){
001772              char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
001773              x = pPk->aiColumn[i];
001774              assert( x>=0 );
001775              if( i==(pPk->nKeyCol-1) ){
001776                addrJump = addrUniqueOk;
001777                op = OP_Eq;
001778              }
001779              sqlite3VdbeAddOp4(v, op, 
001780                  regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
001781              );
001782              sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
001783              VdbeCoverageIf(v, op==OP_Eq);
001784              VdbeCoverageIf(v, op==OP_Ne);
001785            }
001786          }
001787        }
001788      }
001789  
001790      /* Generate code that executes if the new index entry is not unique */
001791      assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
001792          || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
001793      switch( onError ){
001794        case OE_Rollback:
001795        case OE_Abort:
001796        case OE_Fail: {
001797          testcase( onError==OE_Rollback );
001798          testcase( onError==OE_Abort );
001799          testcase( onError==OE_Fail );
001800          sqlite3UniqueConstraint(pParse, onError, pIdx);
001801          break;
001802        }
001803  #ifndef SQLITE_OMIT_UPSERT
001804        case OE_Update: {
001805          sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
001806          /* Fall through */
001807        }
001808  #endif
001809        case OE_Ignore: {
001810          testcase( onError==OE_Ignore );
001811          sqlite3VdbeGoto(v, ignoreDest);
001812          break;
001813        }
001814        default: {
001815          Trigger *pTrigger = 0;
001816          assert( onError==OE_Replace );
001817          if( db->flags&SQLITE_RecTriggers ){
001818            pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
001819          }
001820          if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
001821            sqlite3MultiWrite(pParse);
001822          }
001823          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
001824              regR, nPkField, 0, OE_Replace,
001825              (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
001826          seenReplace = 1;
001827          break;
001828        }
001829      }
001830      if( pUpIdx==pIdx ){
001831        sqlite3VdbeGoto(v, upsertJump+1);
001832        sqlite3VdbeJumpHere(v, upsertBypass);
001833      }else{
001834        sqlite3VdbeResolveLabel(v, addrUniqueOk);
001835      }
001836      if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
001837    }
001838  
001839    /* If the IPK constraint is a REPLACE, run it last */
001840    if( ipkTop ){
001841      sqlite3VdbeGoto(v, ipkTop);
001842      VdbeComment((v, "Do IPK REPLACE"));
001843      sqlite3VdbeJumpHere(v, ipkBottom);
001844    }
001845  
001846    *pbMayReplace = seenReplace;
001847    VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
001848  }
001849  
001850  #ifdef SQLITE_ENABLE_NULL_TRIM
001851  /*
001852  ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
001853  ** to be the number of columns in table pTab that must not be NULL-trimmed.
001854  **
001855  ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
001856  */
001857  void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
001858    u16 i;
001859  
001860    /* Records with omitted columns are only allowed for schema format
001861    ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
001862    if( pTab->pSchema->file_format<2 ) return;
001863  
001864    for(i=pTab->nCol-1; i>0; i--){
001865      if( pTab->aCol[i].pDflt!=0 ) break;
001866      if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
001867    }
001868    sqlite3VdbeChangeP5(v, i+1);
001869  }
001870  #endif
001871  
001872  /*
001873  ** This routine generates code to finish the INSERT or UPDATE operation
001874  ** that was started by a prior call to sqlite3GenerateConstraintChecks.
001875  ** A consecutive range of registers starting at regNewData contains the
001876  ** rowid and the content to be inserted.
001877  **
001878  ** The arguments to this routine should be the same as the first six
001879  ** arguments to sqlite3GenerateConstraintChecks.
001880  */
001881  void sqlite3CompleteInsertion(
001882    Parse *pParse,      /* The parser context */
001883    Table *pTab,        /* the table into which we are inserting */
001884    int iDataCur,       /* Cursor of the canonical data source */
001885    int iIdxCur,        /* First index cursor */
001886    int regNewData,     /* Range of content */
001887    int *aRegIdx,       /* Register used by each index.  0 for unused indices */
001888    int update_flags,   /* True for UPDATE, False for INSERT */
001889    int appendBias,     /* True if this is likely to be an append */
001890    int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
001891  ){
001892    Vdbe *v;            /* Prepared statements under construction */
001893    Index *pIdx;        /* An index being inserted or updated */
001894    u8 pik_flags;       /* flag values passed to the btree insert */
001895    int regData;        /* Content registers (after the rowid) */
001896    int regRec;         /* Register holding assembled record for the table */
001897    int i;              /* Loop counter */
001898    u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
001899  
001900    assert( update_flags==0
001901         || update_flags==OPFLAG_ISUPDATE
001902         || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
001903    );
001904  
001905    v = sqlite3GetVdbe(pParse);
001906    assert( v!=0 );
001907    assert( pTab->pSelect==0 );  /* This table is not a VIEW */
001908    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
001909      if( aRegIdx[i]==0 ) continue;
001910      bAffinityDone = 1;
001911      if( pIdx->pPartIdxWhere ){
001912        sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
001913        VdbeCoverage(v);
001914      }
001915      pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
001916      if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
001917        assert( pParse->nested==0 );
001918        pik_flags |= OPFLAG_NCHANGE;
001919        pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
001920  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
001921        if( update_flags==0 ){
001922          sqlite3VdbeAddOp4(v, OP_InsertInt, 
001923              iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
001924          );
001925          sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
001926        }
001927  #endif
001928      }
001929      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
001930                           aRegIdx[i]+1,
001931                           pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
001932      sqlite3VdbeChangeP5(v, pik_flags);
001933    }
001934    if( !HasRowid(pTab) ) return;
001935    regData = regNewData + 1;
001936    regRec = sqlite3GetTempReg(pParse);
001937    sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
001938    sqlite3SetMakeRecordP5(v, pTab);
001939    if( !bAffinityDone ){
001940      sqlite3TableAffinity(v, pTab, 0);
001941    }
001942    if( pParse->nested ){
001943      pik_flags = 0;
001944    }else{
001945      pik_flags = OPFLAG_NCHANGE;
001946      pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
001947    }
001948    if( appendBias ){
001949      pik_flags |= OPFLAG_APPEND;
001950    }
001951    if( useSeekResult ){
001952      pik_flags |= OPFLAG_USESEEKRESULT;
001953    }
001954    sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
001955    if( !pParse->nested ){
001956      sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
001957    }
001958    sqlite3VdbeChangeP5(v, pik_flags);
001959  }
001960  
001961  /*
001962  ** Allocate cursors for the pTab table and all its indices and generate
001963  ** code to open and initialized those cursors.
001964  **
001965  ** The cursor for the object that contains the complete data (normally
001966  ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
001967  ** ROWID table) is returned in *piDataCur.  The first index cursor is
001968  ** returned in *piIdxCur.  The number of indices is returned.
001969  **
001970  ** Use iBase as the first cursor (either the *piDataCur for rowid tables
001971  ** or the first index for WITHOUT ROWID tables) if it is non-negative.
001972  ** If iBase is negative, then allocate the next available cursor.
001973  **
001974  ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
001975  ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
001976  ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
001977  ** pTab->pIndex list.
001978  **
001979  ** If pTab is a virtual table, then this routine is a no-op and the
001980  ** *piDataCur and *piIdxCur values are left uninitialized.
001981  */
001982  int sqlite3OpenTableAndIndices(
001983    Parse *pParse,   /* Parsing context */
001984    Table *pTab,     /* Table to be opened */
001985    int op,          /* OP_OpenRead or OP_OpenWrite */
001986    u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
001987    int iBase,       /* Use this for the table cursor, if there is one */
001988    u8 *aToOpen,     /* If not NULL: boolean for each table and index */
001989    int *piDataCur,  /* Write the database source cursor number here */
001990    int *piIdxCur    /* Write the first index cursor number here */
001991  ){
001992    int i;
001993    int iDb;
001994    int iDataCur;
001995    Index *pIdx;
001996    Vdbe *v;
001997  
001998    assert( op==OP_OpenRead || op==OP_OpenWrite );
001999    assert( op==OP_OpenWrite || p5==0 );
002000    if( IsVirtual(pTab) ){
002001      /* This routine is a no-op for virtual tables. Leave the output
002002      ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
002003      ** can detect if they are used by mistake in the caller. */
002004      return 0;
002005    }
002006    iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
002007    v = sqlite3GetVdbe(pParse);
002008    assert( v!=0 );
002009    if( iBase<0 ) iBase = pParse->nTab;
002010    iDataCur = iBase++;
002011    if( piDataCur ) *piDataCur = iDataCur;
002012    if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
002013      sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
002014    }else{
002015      sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
002016    }
002017    if( piIdxCur ) *piIdxCur = iBase;
002018    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
002019      int iIdxCur = iBase++;
002020      assert( pIdx->pSchema==pTab->pSchema );
002021      if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
002022        if( piDataCur ) *piDataCur = iIdxCur;
002023        p5 = 0;
002024      }
002025      if( aToOpen==0 || aToOpen[i+1] ){
002026        sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
002027        sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
002028        sqlite3VdbeChangeP5(v, p5);
002029        VdbeComment((v, "%s", pIdx->zName));
002030      }
002031    }
002032    if( iBase>pParse->nTab ) pParse->nTab = iBase;
002033    return i;
002034  }
002035  
002036  
002037  #ifdef SQLITE_TEST
002038  /*
002039  ** The following global variable is incremented whenever the
002040  ** transfer optimization is used.  This is used for testing
002041  ** purposes only - to make sure the transfer optimization really
002042  ** is happening when it is supposed to.
002043  */
002044  int sqlite3_xferopt_count;
002045  #endif /* SQLITE_TEST */
002046  
002047  
002048  #ifndef SQLITE_OMIT_XFER_OPT
002049  /*
002050  ** Check to see if index pSrc is compatible as a source of data
002051  ** for index pDest in an insert transfer optimization.  The rules
002052  ** for a compatible index:
002053  **
002054  **    *   The index is over the same set of columns
002055  **    *   The same DESC and ASC markings occurs on all columns
002056  **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
002057  **    *   The same collating sequence on each column
002058  **    *   The index has the exact same WHERE clause
002059  */
002060  static int xferCompatibleIndex(Index *pDest, Index *pSrc){
002061    int i;
002062    assert( pDest && pSrc );
002063    assert( pDest->pTable!=pSrc->pTable );
002064    if( pDest->nKeyCol!=pSrc->nKeyCol ){
002065      return 0;   /* Different number of columns */
002066    }
002067    if( pDest->onError!=pSrc->onError ){
002068      return 0;   /* Different conflict resolution strategies */
002069    }
002070    for(i=0; i<pSrc->nKeyCol; i++){
002071      if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
002072        return 0;   /* Different columns indexed */
002073      }
002074      if( pSrc->aiColumn[i]==XN_EXPR ){
002075        assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
002076        if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
002077                               pDest->aColExpr->a[i].pExpr, -1)!=0 ){
002078          return 0;   /* Different expressions in the index */
002079        }
002080      }
002081      if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
002082        return 0;   /* Different sort orders */
002083      }
002084      if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
002085        return 0;   /* Different collating sequences */
002086      }
002087    }
002088    if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
002089      return 0;     /* Different WHERE clauses */
002090    }
002091  
002092    /* If no test above fails then the indices must be compatible */
002093    return 1;
002094  }
002095  
002096  /*
002097  ** Attempt the transfer optimization on INSERTs of the form
002098  **
002099  **     INSERT INTO tab1 SELECT * FROM tab2;
002100  **
002101  ** The xfer optimization transfers raw records from tab2 over to tab1.  
002102  ** Columns are not decoded and reassembled, which greatly improves
002103  ** performance.  Raw index records are transferred in the same way.
002104  **
002105  ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
002106  ** There are lots of rules for determining compatibility - see comments
002107  ** embedded in the code for details.
002108  **
002109  ** This routine returns TRUE if the optimization is guaranteed to be used.
002110  ** Sometimes the xfer optimization will only work if the destination table
002111  ** is empty - a factor that can only be determined at run-time.  In that
002112  ** case, this routine generates code for the xfer optimization but also
002113  ** does a test to see if the destination table is empty and jumps over the
002114  ** xfer optimization code if the test fails.  In that case, this routine
002115  ** returns FALSE so that the caller will know to go ahead and generate
002116  ** an unoptimized transfer.  This routine also returns FALSE if there
002117  ** is no chance that the xfer optimization can be applied.
002118  **
002119  ** This optimization is particularly useful at making VACUUM run faster.
002120  */
002121  static int xferOptimization(
002122    Parse *pParse,        /* Parser context */
002123    Table *pDest,         /* The table we are inserting into */
002124    Select *pSelect,      /* A SELECT statement to use as the data source */
002125    int onError,          /* How to handle constraint errors */
002126    int iDbDest           /* The database of pDest */
002127  ){
002128    sqlite3 *db = pParse->db;
002129    ExprList *pEList;                /* The result set of the SELECT */
002130    Table *pSrc;                     /* The table in the FROM clause of SELECT */
002131    Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
002132    struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
002133    int i;                           /* Loop counter */
002134    int iDbSrc;                      /* The database of pSrc */
002135    int iSrc, iDest;                 /* Cursors from source and destination */
002136    int addr1, addr2;                /* Loop addresses */
002137    int emptyDestTest = 0;           /* Address of test for empty pDest */
002138    int emptySrcTest = 0;            /* Address of test for empty pSrc */
002139    Vdbe *v;                         /* The VDBE we are building */
002140    int regAutoinc;                  /* Memory register used by AUTOINC */
002141    int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
002142    int regData, regRowid;           /* Registers holding data and rowid */
002143  
002144    if( pSelect==0 ){
002145      return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
002146    }
002147    if( pParse->pWith || pSelect->pWith ){
002148      /* Do not attempt to process this query if there are an WITH clauses
002149      ** attached to it. Proceeding may generate a false "no such table: xxx"
002150      ** error if pSelect reads from a CTE named "xxx".  */
002151      return 0;
002152    }
002153    if( sqlite3TriggerList(pParse, pDest) ){
002154      return 0;   /* tab1 must not have triggers */
002155    }
002156  #ifndef SQLITE_OMIT_VIRTUALTABLE
002157    if( IsVirtual(pDest) ){
002158      return 0;   /* tab1 must not be a virtual table */
002159    }
002160  #endif
002161    if( onError==OE_Default ){
002162      if( pDest->iPKey>=0 ) onError = pDest->keyConf;
002163      if( onError==OE_Default ) onError = OE_Abort;
002164    }
002165    assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
002166    if( pSelect->pSrc->nSrc!=1 ){
002167      return 0;   /* FROM clause must have exactly one term */
002168    }
002169    if( pSelect->pSrc->a[0].pSelect ){
002170      return 0;   /* FROM clause cannot contain a subquery */
002171    }
002172    if( pSelect->pWhere ){
002173      return 0;   /* SELECT may not have a WHERE clause */
002174    }
002175    if( pSelect->pOrderBy ){
002176      return 0;   /* SELECT may not have an ORDER BY clause */
002177    }
002178    /* Do not need to test for a HAVING clause.  If HAVING is present but
002179    ** there is no ORDER BY, we will get an error. */
002180    if( pSelect->pGroupBy ){
002181      return 0;   /* SELECT may not have a GROUP BY clause */
002182    }
002183    if( pSelect->pLimit ){
002184      return 0;   /* SELECT may not have a LIMIT clause */
002185    }
002186    if( pSelect->pPrior ){
002187      return 0;   /* SELECT may not be a compound query */
002188    }
002189    if( pSelect->selFlags & SF_Distinct ){
002190      return 0;   /* SELECT may not be DISTINCT */
002191    }
002192    pEList = pSelect->pEList;
002193    assert( pEList!=0 );
002194    if( pEList->nExpr!=1 ){
002195      return 0;   /* The result set must have exactly one column */
002196    }
002197    assert( pEList->a[0].pExpr );
002198    if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
002199      return 0;   /* The result set must be the special operator "*" */
002200    }
002201  
002202    /* At this point we have established that the statement is of the
002203    ** correct syntactic form to participate in this optimization.  Now
002204    ** we have to check the semantics.
002205    */
002206    pItem = pSelect->pSrc->a;
002207    pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
002208    if( pSrc==0 ){
002209      return 0;   /* FROM clause does not contain a real table */
002210    }
002211    if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
002212      testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */
002213      return 0;   /* tab1 and tab2 may not be the same table */
002214    }
002215    if( HasRowid(pDest)!=HasRowid(pSrc) ){
002216      return 0;   /* source and destination must both be WITHOUT ROWID or not */
002217    }
002218  #ifndef SQLITE_OMIT_VIRTUALTABLE
002219    if( IsVirtual(pSrc) ){
002220      return 0;   /* tab2 must not be a virtual table */
002221    }
002222  #endif
002223    if( pSrc->pSelect ){
002224      return 0;   /* tab2 may not be a view */
002225    }
002226    if( pDest->nCol!=pSrc->nCol ){
002227      return 0;   /* Number of columns must be the same in tab1 and tab2 */
002228    }
002229    if( pDest->iPKey!=pSrc->iPKey ){
002230      return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
002231    }
002232    for(i=0; i<pDest->nCol; i++){
002233      Column *pDestCol = &pDest->aCol[i];
002234      Column *pSrcCol = &pSrc->aCol[i];
002235  #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
002236      if( (db->mDbFlags & DBFLAG_Vacuum)==0 
002237       && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN 
002238      ){
002239        return 0;    /* Neither table may have __hidden__ columns */
002240      }
002241  #endif
002242      if( pDestCol->affinity!=pSrcCol->affinity ){
002243        return 0;    /* Affinity must be the same on all columns */
002244      }
002245      if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
002246        return 0;    /* Collating sequence must be the same on all columns */
002247      }
002248      if( pDestCol->notNull && !pSrcCol->notNull ){
002249        return 0;    /* tab2 must be NOT NULL if tab1 is */
002250      }
002251      /* Default values for second and subsequent columns need to match. */
002252      if( i>0 ){
002253        assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
002254        assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
002255        if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) 
002256         || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
002257                                         pSrcCol->pDflt->u.zToken)!=0)
002258        ){
002259          return 0;    /* Default values must be the same for all columns */
002260        }
002261      }
002262    }
002263    for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
002264      if( IsUniqueIndex(pDestIdx) ){
002265        destHasUniqueIdx = 1;
002266      }
002267      for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
002268        if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
002269      }
002270      if( pSrcIdx==0 ){
002271        return 0;    /* pDestIdx has no corresponding index in pSrc */
002272      }
002273    }
002274  #ifndef SQLITE_OMIT_CHECK
002275    if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
002276      return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
002277    }
002278  #endif
002279  #ifndef SQLITE_OMIT_FOREIGN_KEY
002280    /* Disallow the transfer optimization if the destination table constains
002281    ** any foreign key constraints.  This is more restrictive than necessary.
002282    ** But the main beneficiary of the transfer optimization is the VACUUM 
002283    ** command, and the VACUUM command disables foreign key constraints.  So
002284    ** the extra complication to make this rule less restrictive is probably
002285    ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
002286    */
002287    if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
002288      return 0;
002289    }
002290  #endif
002291    if( (db->flags & SQLITE_CountRows)!=0 ){
002292      return 0;  /* xfer opt does not play well with PRAGMA count_changes */
002293    }
002294  
002295    /* If we get this far, it means that the xfer optimization is at
002296    ** least a possibility, though it might only work if the destination
002297    ** table (tab1) is initially empty.
002298    */
002299  #ifdef SQLITE_TEST
002300    sqlite3_xferopt_count++;
002301  #endif
002302    iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
002303    v = sqlite3GetVdbe(pParse);
002304    sqlite3CodeVerifySchema(pParse, iDbSrc);
002305    iSrc = pParse->nTab++;
002306    iDest = pParse->nTab++;
002307    regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
002308    regData = sqlite3GetTempReg(pParse);
002309    regRowid = sqlite3GetTempReg(pParse);
002310    sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
002311    assert( HasRowid(pDest) || destHasUniqueIdx );
002312    if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
002313        (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
002314     || destHasUniqueIdx                              /* (2) */
002315     || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
002316    )){
002317      /* In some circumstances, we are able to run the xfer optimization
002318      ** only if the destination table is initially empty. Unless the
002319      ** DBFLAG_Vacuum flag is set, this block generates code to make
002320      ** that determination. If DBFLAG_Vacuum is set, then the destination
002321      ** table is always empty.
002322      **
002323      ** Conditions under which the destination must be empty:
002324      **
002325      ** (1) There is no INTEGER PRIMARY KEY but there are indices.
002326      **     (If the destination is not initially empty, the rowid fields
002327      **     of index entries might need to change.)
002328      **
002329      ** (2) The destination has a unique index.  (The xfer optimization 
002330      **     is unable to test uniqueness.)
002331      **
002332      ** (3) onError is something other than OE_Abort and OE_Rollback.
002333      */
002334      addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
002335      emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
002336      sqlite3VdbeJumpHere(v, addr1);
002337    }
002338    if( HasRowid(pSrc) ){
002339      u8 insFlags;
002340      sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
002341      emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
002342      if( pDest->iPKey>=0 ){
002343        addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
002344        sqlite3VdbeVerifyAbortable(v, onError);
002345        addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
002346        VdbeCoverage(v);
002347        sqlite3RowidConstraint(pParse, onError, pDest);
002348        sqlite3VdbeJumpHere(v, addr2);
002349        autoIncStep(pParse, regAutoinc, regRowid);
002350      }else if( pDest->pIndex==0 ){
002351        addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
002352      }else{
002353        addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
002354        assert( (pDest->tabFlags & TF_Autoincrement)==0 );
002355      }
002356      sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
002357      if( db->mDbFlags & DBFLAG_Vacuum ){
002358        sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
002359        insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
002360                             OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
002361      }else{
002362        insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
002363      }
002364      sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
002365                        (char*)pDest, P4_TABLE);
002366      sqlite3VdbeChangeP5(v, insFlags);
002367      sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
002368      sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
002369      sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
002370    }else{
002371      sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
002372      sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
002373    }
002374    for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
002375      u8 idxInsFlags = 0;
002376      for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
002377        if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
002378      }
002379      assert( pSrcIdx );
002380      sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
002381      sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
002382      VdbeComment((v, "%s", pSrcIdx->zName));
002383      sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
002384      sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
002385      sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
002386      VdbeComment((v, "%s", pDestIdx->zName));
002387      addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
002388      sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
002389      if( db->mDbFlags & DBFLAG_Vacuum ){
002390        /* This INSERT command is part of a VACUUM operation, which guarantees
002391        ** that the destination table is empty. If all indexed columns use
002392        ** collation sequence BINARY, then it can also be assumed that the
002393        ** index will be populated by inserting keys in strictly sorted 
002394        ** order. In this case, instead of seeking within the b-tree as part
002395        ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
002396        ** OP_IdxInsert to seek to the point within the b-tree where each key 
002397        ** should be inserted. This is faster.
002398        **
002399        ** If any of the indexed columns use a collation sequence other than
002400        ** BINARY, this optimization is disabled. This is because the user 
002401        ** might change the definition of a collation sequence and then run
002402        ** a VACUUM command. In that case keys may not be written in strictly
002403        ** sorted order.  */
002404        for(i=0; i<pSrcIdx->nColumn; i++){
002405          const char *zColl = pSrcIdx->azColl[i];
002406          if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
002407        }
002408        if( i==pSrcIdx->nColumn ){
002409          idxInsFlags = OPFLAG_USESEEKRESULT;
002410          sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
002411        }
002412      }
002413      if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
002414        idxInsFlags |= OPFLAG_NCHANGE;
002415      }
002416      sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
002417      sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
002418      sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
002419      sqlite3VdbeJumpHere(v, addr1);
002420      sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
002421      sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
002422    }
002423    if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
002424    sqlite3ReleaseTempReg(pParse, regRowid);
002425    sqlite3ReleaseTempReg(pParse, regData);
002426    if( emptyDestTest ){
002427      sqlite3AutoincrementEnd(pParse);
002428      sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
002429      sqlite3VdbeJumpHere(v, emptyDestTest);
002430      sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
002431      return 0;
002432    }else{
002433      return 1;
002434    }
002435  }
002436  #endif /* SQLITE_OMIT_XFER_OPT */