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