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