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