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    assert( pParse->pVdbe!=0 );
000036    v = pParse->pVdbe;
000037    assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
000038    if( !pParse->db->noSharedCache ){
000039      sqlite3TableLock(pParse, iDb, pTab->tnum,
000040                       (opcode==OP_OpenWrite)?1:0, pTab->zName);
000041    }
000042    if( HasRowid(pTab) ){
000043      sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
000044      VdbeComment((v, "%s", pTab->zName));
000045    }else{
000046      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
000047      assert( pPk!=0 );
000048      assert( pPk->tnum==pTab->tnum || CORRUPT_DB );
000049      sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
000050      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
000051      VdbeComment((v, "%s", pTab->zName));
000052    }
000053  }
000054  
000055  /*
000056  ** Return a pointer to the column affinity string associated with index
000057  ** pIdx. A column affinity string has one character for each column in
000058  ** the table, according to the affinity of the column:
000059  **
000060  **  Character      Column affinity
000061  **  ------------------------------
000062  **  'A'            BLOB
000063  **  'B'            TEXT
000064  **  'C'            NUMERIC
000065  **  'D'            INTEGER
000066  **  'F'            REAL
000067  **
000068  ** An extra 'D' is appended to the end of the string to cover the
000069  ** rowid that appears as the last column in every index.
000070  **
000071  ** Memory for the buffer containing the column index affinity string
000072  ** is managed along with the rest of the Index structure. It will be
000073  ** released when sqlite3DeleteIndex() is called.
000074  */
000075  static SQLITE_NOINLINE const char *computeIndexAffStr(sqlite3 *db, Index *pIdx){
000076    /* The first time a column affinity string for a particular index is
000077    ** required, it is allocated and populated here. It is then stored as
000078    ** a member of the Index structure for subsequent use.
000079    **
000080    ** The column affinity string will eventually be deleted by
000081    ** sqliteDeleteIndex() when the Index structure itself is cleaned
000082    ** up.
000083    */
000084    int n;
000085    Table *pTab = pIdx->pTable;
000086    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
000087    if( !pIdx->zColAff ){
000088      sqlite3OomFault(db);
000089      return 0;
000090    }
000091    for(n=0; n<pIdx->nColumn; n++){
000092      i16 x = pIdx->aiColumn[n];
000093      char aff;
000094      if( x>=0 ){
000095        aff = pTab->aCol[x].affinity;
000096      }else if( x==XN_ROWID ){
000097        aff = SQLITE_AFF_INTEGER;
000098      }else{
000099        assert( x==XN_EXPR );
000100        assert( pIdx->bHasExpr );
000101        assert( pIdx->aColExpr!=0 );
000102        aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
000103      }
000104      if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
000105      if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
000106      pIdx->zColAff[n] = aff;
000107    }
000108    pIdx->zColAff[n] = 0;
000109    return pIdx->zColAff;
000110  }
000111  const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
000112    if( !pIdx->zColAff ) return computeIndexAffStr(db, pIdx);
000113    return pIdx->zColAff;
000114  }
000115  
000116  
000117  /*
000118  ** Compute an affinity string for a table.   Space is obtained
000119  ** from sqlite3DbMalloc().  The caller is responsible for freeing
000120  ** the space when done.
000121  */
000122  char *sqlite3TableAffinityStr(sqlite3 *db, const Table *pTab){
000123    char *zColAff;
000124    zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1);
000125    if( zColAff ){
000126      int i, j;
000127      for(i=j=0; i<pTab->nCol; i++){
000128        if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
000129          zColAff[j++] = pTab->aCol[i].affinity;
000130        }
000131      }
000132      do{
000133        zColAff[j--] = 0;
000134      }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );
000135    }
000136    return zColAff; 
000137  }
000138  
000139  /*
000140  ** Make changes to the evolving bytecode to do affinity transformations
000141  ** of values that are about to be gathered into a row for table pTab.
000142  **
000143  ** For ordinary (legacy, non-strict) tables:
000144  ** -----------------------------------------
000145  **
000146  ** Compute the affinity string for table pTab, if it has not already been
000147  ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
000148  **
000149  ** If the affinity string is empty (because it was all SQLITE_AFF_BLOB entries
000150  ** which were then optimized out) then this routine becomes a no-op.
000151  **
000152  ** Otherwise if iReg>0 then code an OP_Affinity opcode that will set the
000153  ** affinities for register iReg and following.  Or if iReg==0,
000154  ** then just set the P4 operand of the previous opcode (which should  be
000155  ** an OP_MakeRecord) to the affinity string.
000156  **
000157  ** A column affinity string has one character per column:
000158  **
000159  **    Character      Column affinity
000160  **    ---------      ---------------
000161  **    'A'            BLOB
000162  **    'B'            TEXT
000163  **    'C'            NUMERIC
000164  **    'D'            INTEGER
000165  **    'E'            REAL
000166  **
000167  ** For STRICT tables:
000168  ** ------------------
000169  **
000170  ** Generate an appropriate OP_TypeCheck opcode that will verify the
000171  ** datatypes against the column definitions in pTab.  If iReg==0, that
000172  ** means an OP_MakeRecord opcode has already been generated and should be
000173  ** the last opcode generated.  The new OP_TypeCheck needs to be inserted
000174  ** before the OP_MakeRecord.  The new OP_TypeCheck should use the same
000175  ** register set as the OP_MakeRecord.  If iReg>0 then register iReg is
000176  ** the first of a series of registers that will form the new record.
000177  ** Apply the type checking to that array of registers.
000178  */
000179  void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
000180    int i;
000181    char *zColAff;
000182    if( pTab->tabFlags & TF_Strict ){
000183      if( iReg==0 ){
000184        /* Move the previous opcode (which should be OP_MakeRecord) forward
000185        ** by one slot and insert a new OP_TypeCheck where the current
000186        ** OP_MakeRecord is found */
000187        VdbeOp *pPrev;
000188        sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
000189        pPrev = sqlite3VdbeGetLastOp(v);
000190        assert( pPrev!=0 );
000191        assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );
000192        pPrev->opcode = OP_TypeCheck;
000193        sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, pPrev->p3);
000194      }else{
000195        /* Insert an isolated OP_Typecheck */
000196        sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol);
000197        sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
000198      }
000199      return;
000200    }
000201    zColAff = pTab->zColAff;
000202    if( zColAff==0 ){
000203      zColAff = sqlite3TableAffinityStr(0, pTab);
000204      if( !zColAff ){
000205        sqlite3OomFault(sqlite3VdbeDb(v));
000206        return;
000207      }
000208      pTab->zColAff = zColAff;
000209    }
000210    assert( zColAff!=0 );
000211    i = sqlite3Strlen30NN(zColAff);
000212    if( i ){
000213      if( iReg ){
000214        sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
000215      }else{
000216        assert( sqlite3VdbeGetLastOp(v)->opcode==OP_MakeRecord
000217                || sqlite3VdbeDb(v)->mallocFailed );
000218        sqlite3VdbeChangeP4(v, -1, zColAff, i);
000219      }
000220    }
000221  }
000222  
000223  /*
000224  ** Return non-zero if the table pTab in database iDb or any of its indices
000225  ** have been opened at any point in the VDBE program. This is used to see if
000226  ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
000227  ** run without using a temporary table for the results of the SELECT.
000228  */
000229  static int readsTable(Parse *p, int iDb, Table *pTab){
000230    Vdbe *v = sqlite3GetVdbe(p);
000231    int i;
000232    int iEnd = sqlite3VdbeCurrentAddr(v);
000233  #ifndef SQLITE_OMIT_VIRTUALTABLE
000234    VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
000235  #endif
000236  
000237    for(i=1; i<iEnd; i++){
000238      VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
000239      assert( pOp!=0 );
000240      if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
000241        Index *pIndex;
000242        Pgno tnum = pOp->p2;
000243        if( tnum==pTab->tnum ){
000244          return 1;
000245        }
000246        for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
000247          if( tnum==pIndex->tnum ){
000248            return 1;
000249          }
000250        }
000251      }
000252  #ifndef SQLITE_OMIT_VIRTUALTABLE
000253      if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
000254        assert( pOp->p4.pVtab!=0 );
000255        assert( pOp->p4type==P4_VTAB );
000256        return 1;
000257      }
000258  #endif
000259    }
000260    return 0;
000261  }
000262  
000263  /* This walker callback will compute the union of colFlags flags for all
000264  ** referenced columns in a CHECK constraint or generated column expression.
000265  */
000266  static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
000267    if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
000268      assert( pExpr->iColumn < pWalker->u.pTab->nCol );
000269      pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
000270    }
000271    return WRC_Continue;
000272  }
000273  
000274  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
000275  /*
000276  ** All regular columns for table pTab have been puts into registers
000277  ** starting with iRegStore.  The registers that correspond to STORED
000278  ** or VIRTUAL columns have not yet been initialized.  This routine goes
000279  ** back and computes the values for those columns based on the previously
000280  ** computed normal columns.
000281  */
000282  void sqlite3ComputeGeneratedColumns(
000283    Parse *pParse,    /* Parsing context */
000284    int iRegStore,    /* Register holding the first column */
000285    Table *pTab       /* The table */
000286  ){
000287    int i;
000288    Walker w;
000289    Column *pRedo;
000290    int eProgress;
000291    VdbeOp *pOp;
000292  
000293    assert( pTab->tabFlags & TF_HasGenerated );
000294    testcase( pTab->tabFlags & TF_HasVirtual );
000295    testcase( pTab->tabFlags & TF_HasStored );
000296  
000297    /* Before computing generated columns, first go through and make sure
000298    ** that appropriate affinity has been applied to the regular columns
000299    */
000300    sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
000301    if( (pTab->tabFlags & TF_HasStored)!=0 ){
000302      pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
000303      if( pOp->opcode==OP_Affinity ){
000304        /* Change the OP_Affinity argument to '@' (NONE) for all stored
000305        ** columns.  '@' is the no-op affinity and those columns have not
000306        ** yet been computed. */
000307        int ii, jj;
000308        char *zP4 = pOp->p4.z;
000309        assert( zP4!=0 );
000310        assert( pOp->p4type==P4_DYNAMIC );
000311        for(ii=jj=0; zP4[jj]; ii++){
000312          if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
000313            continue;
000314          }
000315          if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
000316            zP4[jj] = SQLITE_AFF_NONE;
000317          }
000318          jj++;
000319        }
000320      }else if( pOp->opcode==OP_TypeCheck ){
000321        /* If an OP_TypeCheck was generated because the table is STRICT,
000322        ** then set the P3 operand to indicate that generated columns should
000323        ** not be checked */
000324        pOp->p3 = 1;
000325      }
000326    }
000327  
000328    /* Because there can be multiple generated columns that refer to one another,
000329    ** this is a two-pass algorithm.  On the first pass, mark all generated
000330    ** columns as "not available".
000331    */
000332    for(i=0; i<pTab->nCol; i++){
000333      if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
000334        testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
000335        testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
000336        pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
000337      }
000338    }
000339  
000340    w.u.pTab = pTab;
000341    w.xExprCallback = exprColumnFlagUnion;
000342    w.xSelectCallback = 0;
000343    w.xSelectCallback2 = 0;
000344  
000345    /* On the second pass, compute the value of each NOT-AVAILABLE column.
000346    ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will
000347    ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as
000348    ** they are needed.
000349    */
000350    pParse->iSelfTab = -iRegStore;
000351    do{
000352      eProgress = 0;
000353      pRedo = 0;
000354      for(i=0; i<pTab->nCol; i++){
000355        Column *pCol = pTab->aCol + i;
000356        if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
000357          int x;
000358          pCol->colFlags |= COLFLAG_BUSY;
000359          w.eCode = 0;
000360          sqlite3WalkExpr(&w, sqlite3ColumnExpr(pTab, pCol));
000361          pCol->colFlags &= ~COLFLAG_BUSY;
000362          if( w.eCode & COLFLAG_NOTAVAIL ){
000363            pRedo = pCol;
000364            continue;
000365          }
000366          eProgress = 1;
000367          assert( pCol->colFlags & COLFLAG_GENERATED );
000368          x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
000369          sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, x);
000370          pCol->colFlags &= ~COLFLAG_NOTAVAIL;
000371        }
000372      }
000373    }while( pRedo && eProgress );
000374    if( pRedo ){
000375      sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zCnName);
000376    }
000377    pParse->iSelfTab = 0;
000378  }
000379  #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
000380  
000381  
000382  #ifndef SQLITE_OMIT_AUTOINCREMENT
000383  /*
000384  ** Locate or create an AutoincInfo structure associated with table pTab
000385  ** which is in database iDb.  Return the register number for the register
000386  ** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
000387  ** table.  (Also return zero when doing a VACUUM since we do not want to
000388  ** update the AUTOINCREMENT counters during a VACUUM.)
000389  **
000390  ** There is at most one AutoincInfo structure per table even if the
000391  ** same table is autoincremented multiple times due to inserts within
000392  ** triggers.  A new AutoincInfo structure is created if this is the
000393  ** first use of table pTab.  On 2nd and subsequent uses, the original
000394  ** AutoincInfo structure is used.
000395  **
000396  ** Four consecutive registers are allocated:
000397  **
000398  **   (1)  The name of the pTab table.
000399  **   (2)  The maximum ROWID of pTab.
000400  **   (3)  The rowid in sqlite_sequence of pTab
000401  **   (4)  The original value of the max ROWID in pTab, or NULL if none
000402  **
000403  ** The 2nd register is the one that is returned.  That is all the
000404  ** insert routine needs to know about.
000405  */
000406  static int autoIncBegin(
000407    Parse *pParse,      /* Parsing context */
000408    int iDb,            /* Index of the database holding pTab */
000409    Table *pTab         /* The table we are writing to */
000410  ){
000411    int memId = 0;      /* Register holding maximum rowid */
000412    assert( pParse->db->aDb[iDb].pSchema!=0 );
000413    if( (pTab->tabFlags & TF_Autoincrement)!=0
000414     && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
000415    ){
000416      Parse *pToplevel = sqlite3ParseToplevel(pParse);
000417      AutoincInfo *pInfo;
000418      Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
000419  
000420      /* Verify that the sqlite_sequence table exists and is an ordinary
000421      ** rowid table with exactly two columns.
000422      ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
000423      if( pSeqTab==0
000424       || !HasRowid(pSeqTab)
000425       || NEVER(IsVirtual(pSeqTab))
000426       || pSeqTab->nCol!=2
000427      ){
000428        pParse->nErr++;
000429        pParse->rc = SQLITE_CORRUPT_SEQUENCE;
000430        return 0;
000431      }
000432  
000433      pInfo = pToplevel->pAinc;
000434      while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
000435      if( pInfo==0 ){
000436        pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
000437        sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
000438        testcase( pParse->earlyCleanup );
000439        if( pParse->db->mallocFailed ) return 0;
000440        pInfo->pNext = pToplevel->pAinc;
000441        pToplevel->pAinc = pInfo;
000442        pInfo->pTab = pTab;
000443        pInfo->iDb = iDb;
000444        pToplevel->nMem++;                  /* Register to hold name of table */
000445        pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
000446        pToplevel->nMem +=2;       /* Rowid in sqlite_sequence + orig max val */
000447      }
000448      memId = pInfo->regCtr;
000449    }
000450    return memId;
000451  }
000452  
000453  /*
000454  ** This routine generates code that will initialize all of the
000455  ** register used by the autoincrement tracker. 
000456  */
000457  void sqlite3AutoincrementBegin(Parse *pParse){
000458    AutoincInfo *p;            /* Information about an AUTOINCREMENT */
000459    sqlite3 *db = pParse->db;  /* The database connection */
000460    Db *pDb;                   /* Database only autoinc table */
000461    int memId;                 /* Register holding max rowid */
000462    Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
000463  
000464    /* This routine is never called during trigger-generation.  It is
000465    ** only called from the top-level */
000466    assert( pParse->pTriggerTab==0 );
000467    assert( sqlite3IsToplevel(pParse) );
000468  
000469    assert( v );   /* We failed long ago if this is not so */
000470    for(p = pParse->pAinc; p; p = p->pNext){
000471      static const int iLn = VDBE_OFFSET_LINENO(2);
000472      static const VdbeOpList autoInc[] = {
000473        /* 0  */ {OP_Null,    0,  0, 0},
000474        /* 1  */ {OP_Rewind,  0, 10, 0},
000475        /* 2  */ {OP_Column,  0,  0, 0},
000476        /* 3  */ {OP_Ne,      0,  9, 0},
000477        /* 4  */ {OP_Rowid,   0,  0, 0},
000478        /* 5  */ {OP_Column,  0,  1, 0},
000479        /* 6  */ {OP_AddImm,  0,  0, 0},
000480        /* 7  */ {OP_Copy,    0,  0, 0},
000481        /* 8  */ {OP_Goto,    0, 11, 0},
000482        /* 9  */ {OP_Next,    0,  2, 0},
000483        /* 10 */ {OP_Integer, 0,  0, 0},
000484        /* 11 */ {OP_Close,   0,  0, 0}
000485      };
000486      VdbeOp *aOp;
000487      pDb = &db->aDb[p->iDb];
000488      memId = p->regCtr;
000489      assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
000490      sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
000491      sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
000492      aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
000493      if( aOp==0 ) break;
000494      aOp[0].p2 = memId;
000495      aOp[0].p3 = memId+2;
000496      aOp[2].p3 = memId;
000497      aOp[3].p1 = memId-1;
000498      aOp[3].p3 = memId;
000499      aOp[3].p5 = SQLITE_JUMPIFNULL;
000500      aOp[4].p2 = memId+1;
000501      aOp[5].p3 = memId;
000502      aOp[6].p1 = memId;
000503      aOp[7].p2 = memId+2;
000504      aOp[7].p1 = memId;
000505      aOp[10].p2 = memId;
000506      if( pParse->nTab==0 ) pParse->nTab = 1;
000507    }
000508  }
000509  
000510  /*
000511  ** Update the maximum rowid for an autoincrement calculation.
000512  **
000513  ** This routine should be called when the regRowid register holds a
000514  ** new rowid that is about to be inserted.  If that new rowid is
000515  ** larger than the maximum rowid in the memId memory cell, then the
000516  ** memory cell is updated.
000517  */
000518  static void autoIncStep(Parse *pParse, int memId, int regRowid){
000519    if( memId>0 ){
000520      sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
000521    }
000522  }
000523  
000524  /*
000525  ** This routine generates the code needed to write autoincrement
000526  ** maximum rowid values back into the sqlite_sequence register.
000527  ** Every statement that might do an INSERT into an autoincrement
000528  ** table (either directly or through triggers) needs to call this
000529  ** routine just before the "exit" code.
000530  */
000531  static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
000532    AutoincInfo *p;
000533    Vdbe *v = pParse->pVdbe;
000534    sqlite3 *db = pParse->db;
000535  
000536    assert( v );
000537    for(p = pParse->pAinc; p; p = p->pNext){
000538      static const int iLn = VDBE_OFFSET_LINENO(2);
000539      static const VdbeOpList autoIncEnd[] = {
000540        /* 0 */ {OP_NotNull,     0, 2, 0},
000541        /* 1 */ {OP_NewRowid,    0, 0, 0},
000542        /* 2 */ {OP_MakeRecord,  0, 2, 0},
000543        /* 3 */ {OP_Insert,      0, 0, 0},
000544        /* 4 */ {OP_Close,       0, 0, 0}
000545      };
000546      VdbeOp *aOp;
000547      Db *pDb = &db->aDb[p->iDb];
000548      int iRec;
000549      int memId = p->regCtr;
000550  
000551      iRec = sqlite3GetTempReg(pParse);
000552      assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
000553      sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
000554      VdbeCoverage(v);
000555      sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
000556      aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
000557      if( aOp==0 ) break;
000558      aOp[0].p1 = memId+1;
000559      aOp[1].p2 = memId+1;
000560      aOp[2].p1 = memId-1;
000561      aOp[2].p3 = iRec;
000562      aOp[3].p2 = iRec;
000563      aOp[3].p3 = memId+1;
000564      aOp[3].p5 = OPFLAG_APPEND;
000565      sqlite3ReleaseTempReg(pParse, iRec);
000566    }
000567  }
000568  void sqlite3AutoincrementEnd(Parse *pParse){
000569    if( pParse->pAinc ) autoIncrementEnd(pParse);
000570  }
000571  #else
000572  /*
000573  ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
000574  ** above are all no-ops
000575  */
000576  # define autoIncBegin(A,B,C) (0)
000577  # define autoIncStep(A,B,C)
000578  #endif /* SQLITE_OMIT_AUTOINCREMENT */
000579  
000580  /*
000581  ** If argument pVal is a Select object returned by an sqlite3MultiValues()
000582  ** that was able to use the co-routine optimization, finish coding the
000583  ** co-routine.
000584  */
000585  void sqlite3MultiValuesEnd(Parse *pParse, Select *pVal){
000586    if( ALWAYS(pVal) && pVal->pSrc->nSrc>0 ){
000587      SrcItem *pItem = &pVal->pSrc->a[0];
000588      sqlite3VdbeEndCoroutine(pParse->pVdbe, pItem->regReturn);
000589      sqlite3VdbeJumpHere(pParse->pVdbe, pItem->addrFillSub - 1);
000590    }
000591  }
000592  
000593  /*
000594  ** Return true if all expressions in the expression-list passed as the
000595  ** only argument are constant.
000596  */
000597  static int exprListIsConstant(Parse *pParse, ExprList *pRow){
000598    int ii;
000599    for(ii=0; ii<pRow->nExpr; ii++){
000600      if( 0==sqlite3ExprIsConstant(pParse, pRow->a[ii].pExpr) ) return 0;
000601    }
000602    return 1;
000603  }
000604  
000605  /*
000606  ** Return true if all expressions in the expression-list passed as the
000607  ** only argument are both constant and have no affinity.
000608  */
000609  static int exprListIsNoAffinity(Parse *pParse, ExprList *pRow){
000610    int ii;
000611    if( exprListIsConstant(pParse,pRow)==0 ) return 0;
000612    for(ii=0; ii<pRow->nExpr; ii++){
000613      Expr *pExpr = pRow->a[ii].pExpr;
000614      assert( pExpr->op!=TK_RAISE );
000615      assert( pExpr->affExpr==0 );
000616      if( 0!=sqlite3ExprAffinity(pExpr) ) return 0;
000617    }
000618    return 1;
000619  
000620  }
000621  
000622  /*
000623  ** This function is called by the parser for the second and subsequent
000624  ** rows of a multi-row VALUES clause. Argument pLeft is the part of
000625  ** the VALUES clause already parsed, argument pRow is the vector of values
000626  ** for the new row. The Select object returned represents the complete
000627  ** VALUES clause, including the new row.
000628  **
000629  ** There are two ways in which this may be achieved - by incremental 
000630  ** coding of a co-routine (the "co-routine" method) or by returning a
000631  ** Select object equivalent to the following (the "UNION ALL" method):
000632  **
000633  **        "pLeft UNION ALL SELECT pRow"
000634  **
000635  ** If the VALUES clause contains a lot of rows, this compound Select
000636  ** object may consume a lot of memory.
000637  **
000638  ** When the co-routine method is used, each row that will be returned
000639  ** by the VALUES clause is coded into part of a co-routine as it is 
000640  ** passed to this function. The returned Select object is equivalent to:
000641  **
000642  **     SELECT * FROM (
000643  **       Select object to read co-routine
000644  **     )
000645  **
000646  ** The co-routine method is used in most cases. Exceptions are:
000647  **
000648  **    a) If the current statement has a WITH clause. This is to avoid
000649  **       statements like:
000650  **
000651  **            WITH cte AS ( VALUES('x'), ('y') ... )
000652  **            SELECT * FROM cte AS a, cte AS b;
000653  **
000654  **       This will not work, as the co-routine uses a hard-coded register
000655  **       for its OP_Yield instructions, and so it is not possible for two
000656  **       cursors to iterate through it concurrently.
000657  **
000658  **    b) The schema is currently being parsed (i.e. the VALUES clause is part 
000659  **       of a schema item like a VIEW or TRIGGER). In this case there is no VM
000660  **       being generated when parsing is taking place, and so generating 
000661  **       a co-routine is not possible.
000662  **
000663  **    c) There are non-constant expressions in the VALUES clause (e.g.
000664  **       the VALUES clause is part of a correlated sub-query).
000665  **
000666  **    d) One or more of the values in the first row of the VALUES clause
000667  **       has an affinity (i.e. is a CAST expression). This causes problems
000668  **       because the complex rules SQLite uses (see function 
000669  **       sqlite3SubqueryColumnTypes() in select.c) to determine the effective
000670  **       affinity of such a column for all rows require access to all values in
000671  **       the column simultaneously. 
000672  */
000673  Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow){
000674  
000675    if( pParse->bHasWith                   /* condition (a) above */
000676     || pParse->db->init.busy              /* condition (b) above */
000677     || exprListIsConstant(pParse,pRow)==0 /* condition (c) above */
000678     || (pLeft->pSrc->nSrc==0 &&
000679         exprListIsNoAffinity(pParse,pLeft->pEList)==0) /* condition (d) above */
000680     || IN_SPECIAL_PARSE
000681    ){
000682      /* The co-routine method cannot be used. Fall back to UNION ALL. */
000683      Select *pSelect = 0;
000684      int f = SF_Values | SF_MultiValue;
000685      if( pLeft->pSrc->nSrc ){
000686        sqlite3MultiValuesEnd(pParse, pLeft);
000687        f = SF_Values;
000688      }else if( pLeft->pPrior ){
000689        /* In this case set the SF_MultiValue flag only if it was set on pLeft */
000690        f = (f & pLeft->selFlags);
000691      }
000692      pSelect = sqlite3SelectNew(pParse, pRow, 0, 0, 0, 0, 0, f, 0);
000693      pLeft->selFlags &= ~SF_MultiValue;
000694      if( pSelect ){
000695        pSelect->op = TK_ALL;
000696        pSelect->pPrior = pLeft;
000697        pLeft = pSelect;
000698      }
000699    }else{
000700      SrcItem *p = 0;               /* SrcItem that reads from co-routine */
000701  
000702      if( pLeft->pSrc->nSrc==0 ){
000703        /* Co-routine has not yet been started and the special Select object
000704        ** that accesses the co-routine has not yet been created. This block 
000705        ** does both those things. */
000706        Vdbe *v = sqlite3GetVdbe(pParse);
000707        Select *pRet = sqlite3SelectNew(pParse, 0, 0, 0, 0, 0, 0, 0, 0);
000708  
000709        /* Ensure the database schema has been read. This is to ensure we have
000710        ** the correct text encoding.  */
000711        if( (pParse->db->mDbFlags & DBFLAG_SchemaKnownOk)==0 ){
000712          sqlite3ReadSchema(pParse);
000713        }
000714  
000715        if( pRet ){
000716          SelectDest dest;
000717          pRet->pSrc->nSrc = 1;
000718          pRet->pPrior = pLeft->pPrior;
000719          pRet->op = pLeft->op;
000720          if( pRet->pPrior ) pRet->selFlags |= SF_Values;
000721          pLeft->pPrior = 0;
000722          pLeft->op = TK_SELECT;
000723          assert( pLeft->pNext==0 );
000724          assert( pRet->pNext==0 );
000725          p = &pRet->pSrc->a[0];
000726          p->pSelect = pLeft;
000727          p->fg.viaCoroutine = 1;
000728          p->addrFillSub = sqlite3VdbeCurrentAddr(v) + 1;
000729          p->regReturn = ++pParse->nMem;
000730          p->iCursor = -1;
000731          p->u1.nRow = 2;
000732          sqlite3VdbeAddOp3(v,OP_InitCoroutine,p->regReturn,0,p->addrFillSub);
000733          sqlite3SelectDestInit(&dest, SRT_Coroutine, p->regReturn);
000734  
000735          /* Allocate registers for the output of the co-routine. Do so so
000736          ** that there are two unused registers immediately before those
000737          ** used by the co-routine. This allows the code in sqlite3Insert()
000738          ** to use these registers directly, instead of copying the output
000739          ** of the co-routine to a separate array for processing.  */
000740          dest.iSdst = pParse->nMem + 3; 
000741          dest.nSdst = pLeft->pEList->nExpr;
000742          pParse->nMem += 2 + dest.nSdst;
000743  
000744          pLeft->selFlags |= SF_MultiValue;
000745          sqlite3Select(pParse, pLeft, &dest);
000746          p->regResult = dest.iSdst;
000747          assert( pParse->nErr || dest.iSdst>0 );
000748          pLeft = pRet;
000749        }
000750      }else{
000751        p = &pLeft->pSrc->a[0];
000752        assert( !p->fg.isTabFunc && !p->fg.isIndexedBy );
000753        p->u1.nRow++;
000754      }
000755    
000756      if( pParse->nErr==0 ){
000757        assert( p!=0 );
000758        if( p->pSelect->pEList->nExpr!=pRow->nExpr ){
000759          sqlite3SelectWrongNumTermsError(pParse, p->pSelect);
000760        }else{
000761          sqlite3ExprCodeExprList(pParse, pRow, p->regResult, 0, 0);
000762          sqlite3VdbeAddOp1(pParse->pVdbe, OP_Yield, p->regReturn);
000763        }
000764      }
000765      sqlite3ExprListDelete(pParse->db, pRow);
000766    }
000767  
000768    return pLeft;
000769  }
000770  
000771  /* Forward declaration */
000772  static int xferOptimization(
000773    Parse *pParse,        /* Parser context */
000774    Table *pDest,         /* The table we are inserting into */
000775    Select *pSelect,      /* A SELECT statement to use as the data source */
000776    int onError,          /* How to handle constraint errors */
000777    int iDbDest           /* The database of pDest */
000778  );
000779  
000780  /*
000781  ** This routine is called to handle SQL of the following forms:
000782  **
000783  **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
000784  **    insert into TABLE (IDLIST) select
000785  **    insert into TABLE (IDLIST) default values
000786  **
000787  ** The IDLIST following the table name is always optional.  If omitted,
000788  ** then a list of all (non-hidden) columns for the table is substituted.
000789  ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
000790  ** is omitted.
000791  **
000792  ** For the pSelect parameter holds the values to be inserted for the
000793  ** first two forms shown above.  A VALUES clause is really just short-hand
000794  ** for a SELECT statement that omits the FROM clause and everything else
000795  ** that follows.  If the pSelect parameter is NULL, that means that the
000796  ** DEFAULT VALUES form of the INSERT statement is intended.
000797  **
000798  ** The code generated follows one of four templates.  For a simple
000799  ** insert with data coming from a single-row VALUES clause, the code executes
000800  ** once straight down through.  Pseudo-code follows (we call this
000801  ** the "1st template"):
000802  **
000803  **         open write cursor to <table> and its indices
000804  **         put VALUES clause expressions into registers
000805  **         write the resulting record into <table>
000806  **         cleanup
000807  **
000808  ** The three remaining templates assume the statement is of the form
000809  **
000810  **   INSERT INTO <table> SELECT ...
000811  **
000812  ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
000813  ** in other words if the SELECT pulls all columns from a single table
000814  ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
000815  ** if <table2> and <table1> are distinct tables but have identical
000816  ** schemas, including all the same indices, then a special optimization
000817  ** is invoked that copies raw records from <table2> over to <table1>.
000818  ** See the xferOptimization() function for the implementation of this
000819  ** template.  This is the 2nd template.
000820  **
000821  **         open a write cursor to <table>
000822  **         open read cursor on <table2>
000823  **         transfer all records in <table2> over to <table>
000824  **         close cursors
000825  **         foreach index on <table>
000826  **           open a write cursor on the <table> index
000827  **           open a read cursor on the corresponding <table2> index
000828  **           transfer all records from the read to the write cursors
000829  **           close cursors
000830  **         end foreach
000831  **
000832  ** The 3rd template is for when the second template does not apply
000833  ** and the SELECT clause does not read from <table> at any time.
000834  ** The generated code follows this template:
000835  **
000836  **         X <- A
000837  **         goto B
000838  **      A: setup for the SELECT
000839  **         loop over the rows in the SELECT
000840  **           load values into registers R..R+n
000841  **           yield X
000842  **         end loop
000843  **         cleanup after the SELECT
000844  **         end-coroutine X
000845  **      B: open write cursor to <table> and its indices
000846  **      C: yield X, at EOF goto D
000847  **         insert the select result into <table> from R..R+n
000848  **         goto C
000849  **      D: cleanup
000850  **
000851  ** The 4th template is used if the insert statement takes its
000852  ** values from a SELECT but the data is being inserted into a table
000853  ** that is also read as part of the SELECT.  In the third form,
000854  ** we have to use an intermediate table to store the results of
000855  ** the select.  The template is like this:
000856  **
000857  **         X <- A
000858  **         goto B
000859  **      A: setup for the SELECT
000860  **         loop over the tables in the SELECT
000861  **           load value into register R..R+n
000862  **           yield X
000863  **         end loop
000864  **         cleanup after the SELECT
000865  **         end co-routine R
000866  **      B: open temp table
000867  **      L: yield X, at EOF goto M
000868  **         insert row from R..R+n into temp table
000869  **         goto L
000870  **      M: open write cursor to <table> and its indices
000871  **         rewind temp table
000872  **      C: loop over rows of intermediate table
000873  **           transfer values form intermediate table into <table>
000874  **         end loop
000875  **      D: cleanup
000876  */
000877  void sqlite3Insert(
000878    Parse *pParse,        /* Parser context */
000879    SrcList *pTabList,    /* Name of table into which we are inserting */
000880    Select *pSelect,      /* A SELECT statement to use as the data source */
000881    IdList *pColumn,      /* Column names corresponding to IDLIST, or NULL. */
000882    int onError,          /* How to handle constraint errors */
000883    Upsert *pUpsert       /* ON CONFLICT clauses for upsert, or NULL */
000884  ){
000885    sqlite3 *db;          /* The main database structure */
000886    Table *pTab;          /* The table to insert into.  aka TABLE */
000887    int i, j;             /* Loop counters */
000888    Vdbe *v;              /* Generate code into this virtual machine */
000889    Index *pIdx;          /* For looping over indices of the table */
000890    int nColumn;          /* Number of columns in the data */
000891    int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
000892    int iDataCur = 0;     /* VDBE cursor that is the main data repository */
000893    int iIdxCur = 0;      /* First index cursor */
000894    int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
000895    int endOfLoop;        /* Label for the end of the insertion loop */
000896    int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
000897    int addrInsTop = 0;   /* Jump to label "D" */
000898    int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
000899    SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
000900    int iDb;              /* Index of database holding TABLE */
000901    u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
000902    u8 appendFlag = 0;    /* True if the insert is likely to be an append */
000903    u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
000904    u8 bIdListInOrder;    /* True if IDLIST is in table order */
000905    ExprList *pList = 0;  /* List of VALUES() to be inserted  */
000906    int iRegStore;        /* Register in which to store next column */
000907  
000908    /* Register allocations */
000909    int regFromSelect = 0;/* Base register for data coming from SELECT */
000910    int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
000911    int regRowCount = 0;  /* Memory cell used for the row counter */
000912    int regIns;           /* Block of regs holding rowid+data being inserted */
000913    int regRowid;         /* registers holding insert rowid */
000914    int regData;          /* register holding first column to insert */
000915    int *aRegIdx = 0;     /* One register allocated to each index */
000916  
000917  #ifndef SQLITE_OMIT_TRIGGER
000918    int isView;                 /* True if attempting to insert into a view */
000919    Trigger *pTrigger;          /* List of triggers on pTab, if required */
000920    int tmask;                  /* Mask of trigger times */
000921  #endif
000922  
000923    db = pParse->db;
000924    assert( db->pParse==pParse );
000925    if( pParse->nErr ){
000926      goto insert_cleanup;
000927    }
000928    assert( db->mallocFailed==0 );
000929    dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
000930  
000931    /* If the Select object is really just a simple VALUES() list with a
000932    ** single row (the common case) then keep that one row of values
000933    ** and discard the other (unused) parts of the pSelect object
000934    */
000935    if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
000936      pList = pSelect->pEList;
000937      pSelect->pEList = 0;
000938      sqlite3SelectDelete(db, pSelect);
000939      pSelect = 0;
000940    }
000941  
000942    /* Locate the table into which we will be inserting new information.
000943    */
000944    assert( pTabList->nSrc==1 );
000945    pTab = sqlite3SrcListLookup(pParse, pTabList);
000946    if( pTab==0 ){
000947      goto insert_cleanup;
000948    }
000949    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
000950    assert( iDb<db->nDb );
000951    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
000952                         db->aDb[iDb].zDbSName) ){
000953      goto insert_cleanup;
000954    }
000955    withoutRowid = !HasRowid(pTab);
000956  
000957    /* Figure out if we have any triggers and if the table being
000958    ** inserted into is a view
000959    */
000960  #ifndef SQLITE_OMIT_TRIGGER
000961    pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
000962    isView = IsView(pTab);
000963  #else
000964  # define pTrigger 0
000965  # define tmask 0
000966  # define isView 0
000967  #endif
000968  #ifdef SQLITE_OMIT_VIEW
000969  # undef isView
000970  # define isView 0
000971  #endif
000972    assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
000973  
000974  #if TREETRACE_ENABLED
000975    if( sqlite3TreeTrace & 0x10000 ){
000976      sqlite3TreeViewLine(0, "In sqlite3Insert() at %s:%d", __FILE__, __LINE__);
000977      sqlite3TreeViewInsert(pParse->pWith, pTabList, pColumn, pSelect, pList,
000978                            onError, pUpsert, pTrigger);
000979    }
000980  #endif
000981  
000982    /* If pTab is really a view, make sure it has been initialized.
000983    ** ViewGetColumnNames() is a no-op if pTab is not a view.
000984    */
000985    if( sqlite3ViewGetColumnNames(pParse, pTab) ){
000986      goto insert_cleanup;
000987    }
000988  
000989    /* Cannot insert into a read-only table.
000990    */
000991    if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
000992      goto insert_cleanup;
000993    }
000994  
000995    /* Allocate a VDBE
000996    */
000997    v = sqlite3GetVdbe(pParse);
000998    if( v==0 ) goto insert_cleanup;
000999    if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
001000    sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
001001  
001002  #ifndef SQLITE_OMIT_XFER_OPT
001003    /* If the statement is of the form
001004    **
001005    **       INSERT INTO <table1> SELECT * FROM <table2>;
001006    **
001007    ** Then special optimizations can be applied that make the transfer
001008    ** very fast and which reduce fragmentation of indices.
001009    **
001010    ** This is the 2nd template.
001011    */
001012    if( pColumn==0
001013     && pSelect!=0
001014     && pTrigger==0
001015     && xferOptimization(pParse, pTab, pSelect, onError, iDb)
001016    ){
001017      assert( !pTrigger );
001018      assert( pList==0 );
001019      goto insert_end;
001020    }
001021  #endif /* SQLITE_OMIT_XFER_OPT */
001022  
001023    /* If this is an AUTOINCREMENT table, look up the sequence number in the
001024    ** sqlite_sequence table and store it in memory cell regAutoinc.
001025    */
001026    regAutoinc = autoIncBegin(pParse, iDb, pTab);
001027  
001028    /* Allocate a block registers to hold the rowid and the values
001029    ** for all columns of the new row.
001030    */
001031    regRowid = regIns = pParse->nMem+1;
001032    pParse->nMem += pTab->nCol + 1;
001033    if( IsVirtual(pTab) ){
001034      regRowid++;
001035      pParse->nMem++;
001036    }
001037    regData = regRowid+1;
001038  
001039    /* If the INSERT statement included an IDLIST term, then make sure
001040    ** all elements of the IDLIST really are columns of the table and
001041    ** remember the column indices.
001042    **
001043    ** If the table has an INTEGER PRIMARY KEY column and that column
001044    ** is named in the IDLIST, then record in the ipkColumn variable
001045    ** the index into IDLIST of the primary key column.  ipkColumn is
001046    ** the index of the primary key as it appears in IDLIST, not as
001047    ** is appears in the original table.  (The index of the INTEGER
001048    ** PRIMARY KEY in the original table is pTab->iPKey.)  After this
001049    ** loop, if ipkColumn==(-1), that means that integer primary key
001050    ** is unspecified, and hence the table is either WITHOUT ROWID or
001051    ** it will automatically generated an integer primary key.
001052    **
001053    ** bIdListInOrder is true if the columns in IDLIST are in storage
001054    ** order.  This enables an optimization that avoids shuffling the
001055    ** columns into storage order.  False negatives are harmless,
001056    ** but false positives will cause database corruption.
001057    */
001058    bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
001059    if( pColumn ){
001060      assert( pColumn->eU4!=EU4_EXPR );
001061      pColumn->eU4 = EU4_IDX;
001062      for(i=0; i<pColumn->nId; i++){
001063        pColumn->a[i].u4.idx = -1;
001064      }
001065      for(i=0; i<pColumn->nId; i++){
001066        for(j=0; j<pTab->nCol; j++){
001067          if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zCnName)==0 ){
001068            pColumn->a[i].u4.idx = j;
001069            if( i!=j ) bIdListInOrder = 0;
001070            if( j==pTab->iPKey ){
001071              ipkColumn = i;  assert( !withoutRowid );
001072            }
001073  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001074            if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
001075              sqlite3ErrorMsg(pParse,
001076                 "cannot INSERT into generated column \"%s\"",
001077                 pTab->aCol[j].zCnName);
001078              goto insert_cleanup;
001079            }
001080  #endif
001081            break;
001082          }
001083        }
001084        if( j>=pTab->nCol ){
001085          if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
001086            ipkColumn = i;
001087            bIdListInOrder = 0;
001088          }else{
001089            sqlite3ErrorMsg(pParse, "table %S has no column named %s",
001090                pTabList->a, pColumn->a[i].zName);
001091            pParse->checkSchema = 1;
001092            goto insert_cleanup;
001093          }
001094        }
001095      }
001096    }
001097  
001098    /* Figure out how many columns of data are supplied.  If the data
001099    ** is coming from a SELECT statement, then generate a co-routine that
001100    ** produces a single row of the SELECT on each invocation.  The
001101    ** co-routine is the common header to the 3rd and 4th templates.
001102    */
001103    if( pSelect ){
001104      /* Data is coming from a SELECT or from a multi-row VALUES clause.
001105      ** Generate a co-routine to run the SELECT. */
001106      int rc;             /* Result code */
001107  
001108      if( pSelect->pSrc->nSrc==1 
001109       && pSelect->pSrc->a[0].fg.viaCoroutine 
001110       && pSelect->pPrior==0
001111      ){
001112        SrcItem *pItem = &pSelect->pSrc->a[0];
001113        dest.iSDParm = pItem->regReturn;
001114        regFromSelect = pItem->regResult;
001115        nColumn = pItem->pSelect->pEList->nExpr;
001116        ExplainQueryPlan((pParse, 0, "SCAN %S", pItem));
001117        if( bIdListInOrder && nColumn==pTab->nCol ){
001118          regData = regFromSelect;
001119          regRowid = regData - 1;
001120          regIns = regRowid - (IsVirtual(pTab) ? 1 : 0);
001121        }
001122      }else{
001123        int addrTop;        /* Top of the co-routine */
001124        int regYield = ++pParse->nMem;
001125        addrTop = sqlite3VdbeCurrentAddr(v) + 1;
001126        sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
001127        sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
001128        dest.iSdst = bIdListInOrder ? regData : 0;
001129        dest.nSdst = pTab->nCol;
001130        rc = sqlite3Select(pParse, pSelect, &dest);
001131        regFromSelect = dest.iSdst;
001132        assert( db->pParse==pParse );
001133        if( rc || pParse->nErr ) goto insert_cleanup;
001134        assert( db->mallocFailed==0 );
001135        sqlite3VdbeEndCoroutine(v, regYield);
001136        sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
001137        assert( pSelect->pEList );
001138        nColumn = pSelect->pEList->nExpr;
001139      }
001140  
001141      /* Set useTempTable to TRUE if the result of the SELECT statement
001142      ** should be written into a temporary table (template 4).  Set to
001143      ** FALSE if each output row of the SELECT can be written directly into
001144      ** the destination table (template 3).
001145      **
001146      ** A temp table must be used if the table being updated is also one
001147      ** of the tables being read by the SELECT statement.  Also use a
001148      ** temp table in the case of row triggers.
001149      */
001150      if( pTrigger || readsTable(pParse, iDb, pTab) ){
001151        useTempTable = 1;
001152      }
001153  
001154      if( useTempTable ){
001155        /* Invoke the coroutine to extract information from the SELECT
001156        ** and add it to a transient table srcTab.  The code generated
001157        ** here is from the 4th template:
001158        **
001159        **      B: open temp table
001160        **      L: yield X, goto M at EOF
001161        **         insert row from R..R+n into temp table
001162        **         goto L
001163        **      M: ...
001164        */
001165        int regRec;          /* Register to hold packed record */
001166        int regTempRowid;    /* Register to hold temp table ROWID */
001167        int addrL;           /* Label "L" */
001168  
001169        srcTab = pParse->nTab++;
001170        regRec = sqlite3GetTempReg(pParse);
001171        regTempRowid = sqlite3GetTempReg(pParse);
001172        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
001173        addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
001174        sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
001175        sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
001176        sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
001177        sqlite3VdbeGoto(v, addrL);
001178        sqlite3VdbeJumpHere(v, addrL);
001179        sqlite3ReleaseTempReg(pParse, regRec);
001180        sqlite3ReleaseTempReg(pParse, regTempRowid);
001181      }
001182    }else{
001183      /* This is the case if the data for the INSERT is coming from a
001184      ** single-row VALUES clause
001185      */
001186      NameContext sNC;
001187      memset(&sNC, 0, sizeof(sNC));
001188      sNC.pParse = pParse;
001189      srcTab = -1;
001190      assert( useTempTable==0 );
001191      if( pList ){
001192        nColumn = pList->nExpr;
001193        if( sqlite3ResolveExprListNames(&sNC, pList) ){
001194          goto insert_cleanup;
001195        }
001196      }else{
001197        nColumn = 0;
001198      }
001199    }
001200  
001201    /* If there is no IDLIST term but the table has an integer primary
001202    ** key, the set the ipkColumn variable to the integer primary key
001203    ** column index in the original table definition.
001204    */
001205    if( pColumn==0 && nColumn>0 ){
001206      ipkColumn = pTab->iPKey;
001207  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001208      if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
001209        testcase( pTab->tabFlags & TF_HasVirtual );
001210        testcase( pTab->tabFlags & TF_HasStored );
001211        for(i=ipkColumn-1; i>=0; i--){
001212          if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
001213            testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
001214            testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
001215            ipkColumn--;
001216          }
001217        }
001218      }
001219  #endif
001220  
001221      /* Make sure the number of columns in the source data matches the number
001222      ** of columns to be inserted into the table.
001223      */
001224      assert( TF_HasHidden==COLFLAG_HIDDEN );
001225      assert( TF_HasGenerated==COLFLAG_GENERATED );
001226      assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) );
001227      if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
001228        for(i=0; i<pTab->nCol; i++){
001229          if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
001230        }
001231      }
001232      if( nColumn!=(pTab->nCol-nHidden) ){
001233        sqlite3ErrorMsg(pParse,
001234           "table %S has %d columns but %d values were supplied",
001235           pTabList->a, pTab->nCol-nHidden, nColumn);
001236       goto insert_cleanup;
001237      }
001238    }
001239    if( pColumn!=0 && nColumn!=pColumn->nId ){
001240      sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
001241      goto insert_cleanup;
001242    }
001243     
001244    /* Initialize the count of rows to be inserted
001245    */
001246    if( (db->flags & SQLITE_CountRows)!=0
001247     && !pParse->nested
001248     && !pParse->pTriggerTab
001249     && !pParse->bReturning
001250    ){
001251      regRowCount = ++pParse->nMem;
001252      sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
001253    }
001254  
001255    /* If this is not a view, open the table and and all indices */
001256    if( !isView ){
001257      int nIdx;
001258      nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
001259                                        &iDataCur, &iIdxCur);
001260      aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
001261      if( aRegIdx==0 ){
001262        goto insert_cleanup;
001263      }
001264      for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
001265        assert( pIdx );
001266        aRegIdx[i] = ++pParse->nMem;
001267        pParse->nMem += pIdx->nColumn;
001268      }
001269      aRegIdx[i] = ++pParse->nMem;  /* Register to store the table record */
001270    }
001271  #ifndef SQLITE_OMIT_UPSERT
001272    if( pUpsert ){
001273      Upsert *pNx;
001274      if( IsVirtual(pTab) ){
001275        sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
001276                pTab->zName);
001277        goto insert_cleanup;
001278      }
001279      if( IsView(pTab) ){
001280        sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
001281        goto insert_cleanup;
001282      }
001283      if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
001284        goto insert_cleanup;
001285      }
001286      pTabList->a[0].iCursor = iDataCur;
001287      pNx = pUpsert;
001288      do{
001289        pNx->pUpsertSrc = pTabList;
001290        pNx->regData = regData;
001291        pNx->iDataCur = iDataCur;
001292        pNx->iIdxCur = iIdxCur;
001293        if( pNx->pUpsertTarget ){
001294          if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx, pUpsert) ){
001295            goto insert_cleanup;
001296          }
001297        }
001298        pNx = pNx->pNextUpsert;
001299      }while( pNx!=0 );
001300    }
001301  #endif
001302  
001303  
001304    /* This is the top of the main insertion loop */
001305    if( useTempTable ){
001306      /* This block codes the top of loop only.  The complete loop is the
001307      ** following pseudocode (template 4):
001308      **
001309      **         rewind temp table, if empty goto D
001310      **      C: loop over rows of intermediate table
001311      **           transfer values form intermediate table into <table>
001312      **         end loop
001313      **      D: ...
001314      */
001315      addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
001316      addrCont = sqlite3VdbeCurrentAddr(v);
001317    }else if( pSelect ){
001318      /* This block codes the top of loop only.  The complete loop is the
001319      ** following pseudocode (template 3):
001320      **
001321      **      C: yield X, at EOF goto D
001322      **         insert the select result into <table> from R..R+n
001323      **         goto C
001324      **      D: ...
001325      */
001326      sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
001327      addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
001328      VdbeCoverage(v);
001329      if( ipkColumn>=0 ){
001330        /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
001331        ** SELECT, go ahead and copy the value into the rowid slot now, so that
001332        ** the value does not get overwritten by a NULL at tag-20191021-002. */
001333        sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
001334      }
001335    }
001336  
001337    /* Compute data for ordinary columns of the new entry.  Values
001338    ** are written in storage order into registers starting with regData.
001339    ** Only ordinary columns are computed in this loop. The rowid
001340    ** (if there is one) is computed later and generated columns are
001341    ** computed after the rowid since they might depend on the value
001342    ** of the rowid.
001343    */
001344    nHidden = 0;
001345    iRegStore = regData;  assert( regData==regRowid+1 );
001346    for(i=0; i<pTab->nCol; i++, iRegStore++){
001347      int k;
001348      u32 colFlags;
001349      assert( i>=nHidden );
001350      if( i==pTab->iPKey ){
001351        /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
001352        ** using the rowid. So put a NULL in the IPK slot of the record to avoid
001353        ** using excess space.  The file format definition requires this extra
001354        ** NULL - we cannot optimize further by skipping the column completely */
001355        sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
001356        continue;
001357      }
001358      if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
001359        nHidden++;
001360        if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
001361          /* Virtual columns do not participate in OP_MakeRecord.  So back up
001362          ** iRegStore by one slot to compensate for the iRegStore++ in the
001363          ** outer for() loop */
001364          iRegStore--;
001365          continue;
001366        }else if( (colFlags & COLFLAG_STORED)!=0 ){
001367          /* Stored columns are computed later.  But if there are BEFORE
001368          ** triggers, the slots used for stored columns will be OP_Copy-ed
001369          ** to a second block of registers, so the register needs to be
001370          ** initialized to NULL to avoid an uninitialized register read */
001371          if( tmask & TRIGGER_BEFORE ){
001372            sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
001373          }
001374          continue;
001375        }else if( pColumn==0 ){
001376          /* Hidden columns that are not explicitly named in the INSERT
001377          ** get there default value */
001378          sqlite3ExprCodeFactorable(pParse,
001379              sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
001380              iRegStore);
001381          continue;
001382        }
001383      }
001384      if( pColumn ){
001385        assert( pColumn->eU4==EU4_IDX );
001386        for(j=0; j<pColumn->nId && pColumn->a[j].u4.idx!=i; j++){}
001387        if( j>=pColumn->nId ){
001388          /* A column not named in the insert column list gets its
001389          ** default value */
001390          sqlite3ExprCodeFactorable(pParse,
001391              sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
001392              iRegStore);
001393          continue;
001394        }
001395        k = j;
001396      }else if( nColumn==0 ){
001397        /* This is INSERT INTO ... DEFAULT VALUES.  Load the default value. */
001398        sqlite3ExprCodeFactorable(pParse,
001399            sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
001400            iRegStore);
001401        continue;
001402      }else{
001403        k = i - nHidden;
001404      }
001405  
001406      if( useTempTable ){
001407        sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
001408      }else if( pSelect ){
001409        if( regFromSelect!=regData ){
001410          sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
001411        }
001412      }else{
001413        Expr *pX = pList->a[k].pExpr;
001414        int y = sqlite3ExprCodeTarget(pParse, pX, iRegStore);
001415        if( y!=iRegStore ){
001416          sqlite3VdbeAddOp2(v,
001417            ExprHasProperty(pX, EP_Subquery) ? OP_Copy : OP_SCopy, y, iRegStore);
001418        }
001419      }
001420    }
001421  
001422  
001423    /* Run the BEFORE and INSTEAD OF triggers, if there are any
001424    */
001425    endOfLoop = sqlite3VdbeMakeLabel(pParse);
001426    if( tmask & TRIGGER_BEFORE ){
001427      int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
001428  
001429      /* build the NEW.* reference row.  Note that if there is an INTEGER
001430      ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
001431      ** translated into a unique ID for the row.  But on a BEFORE trigger,
001432      ** we do not know what the unique ID will be (because the insert has
001433      ** not happened yet) so we substitute a rowid of -1
001434      */
001435      if( ipkColumn<0 ){
001436        sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
001437      }else{
001438        int addr1;
001439        assert( !withoutRowid );
001440        if( useTempTable ){
001441          sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
001442        }else{
001443          assert( pSelect==0 );  /* Otherwise useTempTable is true */
001444          sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
001445        }
001446        addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
001447        sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
001448        sqlite3VdbeJumpHere(v, addr1);
001449        sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
001450      }
001451  
001452      /* Copy the new data already generated. */
001453      assert( pTab->nNVCol>0 || pParse->nErr>0 );
001454      sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
001455  
001456  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001457      /* Compute the new value for generated columns after all other
001458      ** columns have already been computed.  This must be done after
001459      ** computing the ROWID in case one of the generated columns
001460      ** refers to the ROWID. */
001461      if( pTab->tabFlags & TF_HasGenerated ){
001462        testcase( pTab->tabFlags & TF_HasVirtual );
001463        testcase( pTab->tabFlags & TF_HasStored );
001464        sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
001465      }
001466  #endif
001467  
001468      /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
001469      ** do not attempt any conversions before assembling the record.
001470      ** If this is a real table, attempt conversions as required by the
001471      ** table column affinities.
001472      */
001473      if( !isView ){
001474        sqlite3TableAffinity(v, pTab, regCols+1);
001475      }
001476  
001477      /* Fire BEFORE or INSTEAD OF triggers */
001478      sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
001479          pTab, regCols-pTab->nCol-1, onError, endOfLoop);
001480  
001481      sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
001482    }
001483  
001484    if( !isView ){
001485      if( IsVirtual(pTab) ){
001486        /* The row that the VUpdate opcode will delete: none */
001487        sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
001488      }
001489      if( ipkColumn>=0 ){
001490        /* Compute the new rowid */
001491        if( useTempTable ){
001492          sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
001493        }else if( pSelect ){
001494          /* Rowid already initialized at tag-20191021-001 */
001495        }else{
001496          Expr *pIpk = pList->a[ipkColumn].pExpr;
001497          if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
001498            sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
001499            appendFlag = 1;
001500          }else{
001501            sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
001502          }
001503        }
001504        /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
001505        ** to generate a unique primary key value.
001506        */
001507        if( !appendFlag ){
001508          int addr1;
001509          if( !IsVirtual(pTab) ){
001510            addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
001511            sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
001512            sqlite3VdbeJumpHere(v, addr1);
001513          }else{
001514            addr1 = sqlite3VdbeCurrentAddr(v);
001515            sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
001516          }
001517          sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
001518        }
001519      }else if( IsVirtual(pTab) || withoutRowid ){
001520        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
001521      }else{
001522        sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
001523        appendFlag = 1;
001524      }
001525      autoIncStep(pParse, regAutoinc, regRowid);
001526  
001527  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001528      /* Compute the new value for generated columns after all other
001529      ** columns have already been computed.  This must be done after
001530      ** computing the ROWID in case one of the generated columns
001531      ** is derived from the INTEGER PRIMARY KEY. */
001532      if( pTab->tabFlags & TF_HasGenerated ){
001533        sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
001534      }
001535  #endif
001536  
001537      /* Generate code to check constraints and generate index keys and
001538      ** do the insertion.
001539      */
001540  #ifndef SQLITE_OMIT_VIRTUALTABLE
001541      if( IsVirtual(pTab) ){
001542        const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
001543        sqlite3VtabMakeWritable(pParse, pTab);
001544        sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
001545        sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
001546        sqlite3MayAbort(pParse);
001547      }else
001548  #endif
001549      {
001550        int isReplace = 0;/* Set to true if constraints may cause a replace */
001551        int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
001552        sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
001553            regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
001554        );
001555        if( db->flags & SQLITE_ForeignKeys ){
001556          sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
001557        }
001558  
001559        /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
001560        ** constraints or (b) there are no triggers and this table is not a
001561        ** parent table in a foreign key constraint. It is safe to set the
001562        ** flag in the second case as if any REPLACE constraint is hit, an
001563        ** OP_Delete or OP_IdxDelete instruction will be executed on each
001564        ** cursor that is disturbed. And these instructions both clear the
001565        ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
001566        ** functionality.  */
001567        bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
001568        sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
001569            regIns, aRegIdx, 0, appendFlag, bUseSeek
001570        );
001571      }
001572  #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
001573    }else if( pParse->bReturning ){
001574      /* If there is a RETURNING clause, populate the rowid register with
001575      ** constant value -1, in case one or more of the returned expressions
001576      ** refer to the "rowid" of the view.  */
001577      sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
001578  #endif
001579    }
001580  
001581    /* Update the count of rows that are inserted
001582    */
001583    if( regRowCount ){
001584      sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
001585    }
001586  
001587    if( pTrigger ){
001588      /* Code AFTER triggers */
001589      sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
001590          pTab, regData-2-pTab->nCol, onError, endOfLoop);
001591    }
001592  
001593    /* The bottom of the main insertion loop, if the data source
001594    ** is a SELECT statement.
001595    */
001596    sqlite3VdbeResolveLabel(v, endOfLoop);
001597    if( useTempTable ){
001598      sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
001599      sqlite3VdbeJumpHere(v, addrInsTop);
001600      sqlite3VdbeAddOp1(v, OP_Close, srcTab);
001601    }else if( pSelect ){
001602      sqlite3VdbeGoto(v, addrCont);
001603  #ifdef SQLITE_DEBUG
001604      /* If we are jumping back to an OP_Yield that is preceded by an
001605      ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
001606      ** OP_ReleaseReg will be included in the loop. */
001607      if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
001608        assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
001609        sqlite3VdbeChangeP5(v, 1);
001610      }
001611  #endif
001612      sqlite3VdbeJumpHere(v, addrInsTop);
001613    }
001614  
001615  #ifndef SQLITE_OMIT_XFER_OPT
001616  insert_end:
001617  #endif /* SQLITE_OMIT_XFER_OPT */
001618    /* Update the sqlite_sequence table by storing the content of the
001619    ** maximum rowid counter values recorded while inserting into
001620    ** autoincrement tables.
001621    */
001622    if( pParse->nested==0 && pParse->pTriggerTab==0 ){
001623      sqlite3AutoincrementEnd(pParse);
001624    }
001625  
001626    /*
001627    ** Return the number of rows inserted. If this routine is
001628    ** generating code because of a call to sqlite3NestedParse(), do not
001629    ** invoke the callback function.
001630    */
001631    if( regRowCount ){
001632      sqlite3CodeChangeCount(v, regRowCount, "rows inserted");
001633    }
001634  
001635  insert_cleanup:
001636    sqlite3SrcListDelete(db, pTabList);
001637    sqlite3ExprListDelete(db, pList);
001638    sqlite3UpsertDelete(db, pUpsert);
001639    sqlite3SelectDelete(db, pSelect);
001640    sqlite3IdListDelete(db, pColumn);
001641    if( aRegIdx ) sqlite3DbNNFreeNN(db, aRegIdx);
001642  }
001643  
001644  /* Make sure "isView" and other macros defined above are undefined. Otherwise
001645  ** they may interfere with compilation of other functions in this file
001646  ** (or in another file, if this file becomes part of the amalgamation).  */
001647  #ifdef isView
001648   #undef isView
001649  #endif
001650  #ifdef pTrigger
001651   #undef pTrigger
001652  #endif
001653  #ifdef tmask
001654   #undef tmask
001655  #endif
001656  
001657  /*
001658  ** Meanings of bits in of pWalker->eCode for
001659  ** sqlite3ExprReferencesUpdatedColumn()
001660  */
001661  #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
001662  #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
001663  
001664  /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
001665  *  Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
001666  ** expression node references any of the
001667  ** columns that are being modified by an UPDATE statement.
001668  */
001669  static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
001670    if( pExpr->op==TK_COLUMN ){
001671      assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
001672      if( pExpr->iColumn>=0 ){
001673        if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
001674          pWalker->eCode |= CKCNSTRNT_COLUMN;
001675        }
001676      }else{
001677        pWalker->eCode |= CKCNSTRNT_ROWID;
001678      }
001679    }
001680    return WRC_Continue;
001681  }
001682  
001683  /*
001684  ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
001685  ** only columns that are modified by the UPDATE are those for which
001686  ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
001687  **
001688  ** Return true if CHECK constraint pExpr uses any of the
001689  ** changing columns (or the rowid if it is changing).  In other words,
001690  ** return true if this CHECK constraint must be validated for
001691  ** the new row in the UPDATE statement.
001692  **
001693  ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
001694  ** The operation of this routine is the same - return true if an only if
001695  ** the expression uses one or more of columns identified by the second and
001696  ** third arguments.
001697  */
001698  int sqlite3ExprReferencesUpdatedColumn(
001699    Expr *pExpr,    /* The expression to be checked */
001700    int *aiChng,    /* aiChng[x]>=0 if column x changed by the UPDATE */
001701    int chngRowid   /* True if UPDATE changes the rowid */
001702  ){
001703    Walker w;
001704    memset(&w, 0, sizeof(w));
001705    w.eCode = 0;
001706    w.xExprCallback = checkConstraintExprNode;
001707    w.u.aiCol = aiChng;
001708    sqlite3WalkExpr(&w, pExpr);
001709    if( !chngRowid ){
001710      testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
001711      w.eCode &= ~CKCNSTRNT_ROWID;
001712    }
001713    testcase( w.eCode==0 );
001714    testcase( w.eCode==CKCNSTRNT_COLUMN );
001715    testcase( w.eCode==CKCNSTRNT_ROWID );
001716    testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
001717    return w.eCode!=0;
001718  }
001719  
001720  /*
001721  ** The sqlite3GenerateConstraintChecks() routine usually wants to visit
001722  ** the indexes of a table in the order provided in the Table->pIndex list.
001723  ** However, sometimes (rarely - when there is an upsert) it wants to visit
001724  ** the indexes in a different order.  The following data structures accomplish
001725  ** this.
001726  **
001727  ** The IndexIterator object is used to walk through all of the indexes
001728  ** of a table in either Index.pNext order, or in some other order established
001729  ** by an array of IndexListTerm objects.
001730  */
001731  typedef struct IndexListTerm IndexListTerm;
001732  typedef struct IndexIterator IndexIterator;
001733  struct IndexIterator {
001734    int eType;    /* 0 for Index.pNext list.  1 for an array of IndexListTerm */
001735    int i;        /* Index of the current item from the list */
001736    union {
001737      struct {    /* Use this object for eType==0: A Index.pNext list */
001738        Index *pIdx;   /* The current Index */
001739      } lx;     
001740      struct {    /* Use this object for eType==1; Array of IndexListTerm */
001741        int nIdx;               /* Size of the array */
001742        IndexListTerm *aIdx;    /* Array of IndexListTerms */
001743      } ax;
001744    } u;
001745  };
001746  
001747  /* When IndexIterator.eType==1, then each index is an array of instances
001748  ** of the following object
001749  */
001750  struct IndexListTerm {
001751    Index *p;  /* The index */
001752    int ix;    /* Which entry in the original Table.pIndex list is this index*/
001753  };
001754  
001755  /* Return the first index on the list */
001756  static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){
001757    assert( pIter->i==0 );
001758    if( pIter->eType ){
001759      *pIx = pIter->u.ax.aIdx[0].ix;
001760      return pIter->u.ax.aIdx[0].p;
001761    }else{
001762      *pIx = 0;
001763      return pIter->u.lx.pIdx;
001764    }
001765  }
001766  
001767  /* Return the next index from the list.  Return NULL when out of indexes */
001768  static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){
001769    if( pIter->eType ){
001770      int i = ++pIter->i;
001771      if( i>=pIter->u.ax.nIdx ){
001772        *pIx = i;
001773        return 0;
001774      }
001775      *pIx = pIter->u.ax.aIdx[i].ix;
001776      return pIter->u.ax.aIdx[i].p;
001777    }else{
001778      ++(*pIx);
001779      pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
001780      return pIter->u.lx.pIdx;
001781    }
001782  }
001783   
001784  /*
001785  ** Generate code to do constraint checks prior to an INSERT or an UPDATE
001786  ** on table pTab.
001787  **
001788  ** The regNewData parameter is the first register in a range that contains
001789  ** the data to be inserted or the data after the update.  There will be
001790  ** pTab->nCol+1 registers in this range.  The first register (the one
001791  ** that regNewData points to) will contain the new rowid, or NULL in the
001792  ** case of a WITHOUT ROWID table.  The second register in the range will
001793  ** contain the content of the first table column.  The third register will
001794  ** contain the content of the second table column.  And so forth.
001795  **
001796  ** The regOldData parameter is similar to regNewData except that it contains
001797  ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
001798  ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
001799  ** checking regOldData for zero.
001800  **
001801  ** For an UPDATE, the pkChng boolean is true if the true primary key (the
001802  ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
001803  ** might be modified by the UPDATE.  If pkChng is false, then the key of
001804  ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
001805  **
001806  ** For an INSERT, the pkChng boolean indicates whether or not the rowid
001807  ** was explicitly specified as part of the INSERT statement.  If pkChng
001808  ** is zero, it means that the either rowid is computed automatically or
001809  ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
001810  ** pkChng will only be true if the INSERT statement provides an integer
001811  ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
001812  **
001813  ** The code generated by this routine will store new index entries into
001814  ** registers identified by aRegIdx[].  No index entry is created for
001815  ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
001816  ** the same as the order of indices on the linked list of indices
001817  ** at pTab->pIndex.
001818  **
001819  ** (2019-05-07) The generated code also creates a new record for the
001820  ** main table, if pTab is a rowid table, and stores that record in the
001821  ** register identified by aRegIdx[nIdx] - in other words in the first
001822  ** entry of aRegIdx[] past the last index.  It is important that the
001823  ** record be generated during constraint checks to avoid affinity changes
001824  ** to the register content that occur after constraint checks but before
001825  ** the new record is inserted.
001826  **
001827  ** The caller must have already opened writeable cursors on the main
001828  ** table and all applicable indices (that is to say, all indices for which
001829  ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
001830  ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
001831  ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
001832  ** for the first index in the pTab->pIndex list.  Cursors for other indices
001833  ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
001834  **
001835  ** This routine also generates code to check constraints.  NOT NULL,
001836  ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
001837  ** then the appropriate action is performed.  There are five possible
001838  ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
001839  **
001840  **  Constraint type  Action       What Happens
001841  **  ---------------  ----------   ----------------------------------------
001842  **  any              ROLLBACK     The current transaction is rolled back and
001843  **                                sqlite3_step() returns immediately with a
001844  **                                return code of SQLITE_CONSTRAINT.
001845  **
001846  **  any              ABORT        Back out changes from the current command
001847  **                                only (do not do a complete rollback) then
001848  **                                cause sqlite3_step() to return immediately
001849  **                                with SQLITE_CONSTRAINT.
001850  **
001851  **  any              FAIL         Sqlite3_step() returns immediately with a
001852  **                                return code of SQLITE_CONSTRAINT.  The
001853  **                                transaction is not rolled back and any
001854  **                                changes to prior rows are retained.
001855  **
001856  **  any              IGNORE       The attempt in insert or update the current
001857  **                                row is skipped, without throwing an error.
001858  **                                Processing continues with the next row.
001859  **                                (There is an immediate jump to ignoreDest.)
001860  **
001861  **  NOT NULL         REPLACE      The NULL value is replace by the default
001862  **                                value for that column.  If the default value
001863  **                                is NULL, the action is the same as ABORT.
001864  **
001865  **  UNIQUE           REPLACE      The other row that conflicts with the row
001866  **                                being inserted is removed.
001867  **
001868  **  CHECK            REPLACE      Illegal.  The results in an exception.
001869  **
001870  ** Which action to take is determined by the overrideError parameter.
001871  ** Or if overrideError==OE_Default, then the pParse->onError parameter
001872  ** is used.  Or if pParse->onError==OE_Default then the onError value
001873  ** for the constraint is used.
001874  */
001875  void sqlite3GenerateConstraintChecks(
001876    Parse *pParse,       /* The parser context */
001877    Table *pTab,         /* The table being inserted or updated */
001878    int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
001879    int iDataCur,        /* Canonical data cursor (main table or PK index) */
001880    int iIdxCur,         /* First index cursor */
001881    int regNewData,      /* First register in a range holding values to insert */
001882    int regOldData,      /* Previous content.  0 for INSERTs */
001883    u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
001884    u8 overrideError,    /* Override onError to this if not OE_Default */
001885    int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
001886    int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
001887    int *aiChng,         /* column i is unchanged if aiChng[i]<0 */
001888    Upsert *pUpsert      /* ON CONFLICT clauses, if any.  NULL otherwise */
001889  ){
001890    Vdbe *v;             /* VDBE under construction */
001891    Index *pIdx;         /* Pointer to one of the indices */
001892    Index *pPk = 0;      /* The PRIMARY KEY index for WITHOUT ROWID tables */
001893    sqlite3 *db;         /* Database connection */
001894    int i;               /* loop counter */
001895    int ix;              /* Index loop counter */
001896    int nCol;            /* Number of columns */
001897    int onError;         /* Conflict resolution strategy */
001898    int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
001899    int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
001900    Upsert *pUpsertClause = 0;  /* The specific ON CONFLICT clause for pIdx */
001901    u8 isUpdate;           /* True if this is an UPDATE operation */
001902    u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
001903    int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */
001904    int upsertIpkDelay = 0;  /* Address of Goto to bypass initial IPK check */
001905    int ipkTop = 0;        /* Top of the IPK uniqueness check */
001906    int ipkBottom = 0;     /* OP_Goto at the end of the IPK uniqueness check */
001907    /* Variables associated with retesting uniqueness constraints after
001908    ** replace triggers fire have run */
001909    int regTrigCnt;       /* Register used to count replace trigger invocations */
001910    int addrRecheck = 0;  /* Jump here to recheck all uniqueness constraints */
001911    int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
001912    Trigger *pTrigger;    /* List of DELETE triggers on the table pTab */
001913    int nReplaceTrig = 0; /* Number of replace triggers coded */
001914    IndexIterator sIdxIter;  /* Index iterator */
001915  
001916    isUpdate = regOldData!=0;
001917    db = pParse->db;
001918    v = pParse->pVdbe;
001919    assert( v!=0 );
001920    assert( !IsView(pTab) );  /* This table is not a VIEW */
001921    nCol = pTab->nCol;
001922   
001923    /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
001924    ** normal rowid tables.  nPkField is the number of key fields in the
001925    ** pPk index or 1 for a rowid table.  In other words, nPkField is the
001926    ** number of fields in the true primary key of the table. */
001927    if( HasRowid(pTab) ){
001928      pPk = 0;
001929      nPkField = 1;
001930    }else{
001931      pPk = sqlite3PrimaryKeyIndex(pTab);
001932      nPkField = pPk->nKeyCol;
001933    }
001934  
001935    /* Record that this module has started */
001936    VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
001937                       iDataCur, iIdxCur, regNewData, regOldData, pkChng));
001938  
001939    /* Test all NOT NULL constraints.
001940    */
001941    if( pTab->tabFlags & TF_HasNotNull ){
001942      int b2ndPass = 0;         /* True if currently running 2nd pass */
001943      int nSeenReplace = 0;     /* Number of ON CONFLICT REPLACE operations */
001944      int nGenerated = 0;       /* Number of generated columns with NOT NULL */
001945      while(1){  /* Make 2 passes over columns. Exit loop via "break" */
001946        for(i=0; i<nCol; i++){
001947          int iReg;                        /* Register holding column value */
001948          Column *pCol = &pTab->aCol[i];   /* The column to check for NOT NULL */
001949          int isGenerated;                 /* non-zero if column is generated */
001950          onError = pCol->notNull;
001951          if( onError==OE_None ) continue; /* No NOT NULL on this column */
001952          if( i==pTab->iPKey ){
001953            continue;        /* ROWID is never NULL */
001954          }
001955          isGenerated = pCol->colFlags & COLFLAG_GENERATED;
001956          if( isGenerated && !b2ndPass ){
001957            nGenerated++;
001958            continue;        /* Generated columns processed on 2nd pass */
001959          }
001960          if( aiChng && aiChng[i]<0 && !isGenerated ){
001961            /* Do not check NOT NULL on columns that do not change */
001962            continue;
001963          }
001964          if( overrideError!=OE_Default ){
001965            onError = overrideError;
001966          }else if( onError==OE_Default ){
001967            onError = OE_Abort;
001968          }
001969          if( onError==OE_Replace ){
001970            if( b2ndPass        /* REPLACE becomes ABORT on the 2nd pass */
001971             || pCol->iDflt==0  /* REPLACE is ABORT if no DEFAULT value */
001972            ){
001973              testcase( pCol->colFlags & COLFLAG_VIRTUAL );
001974              testcase( pCol->colFlags & COLFLAG_STORED );
001975              testcase( pCol->colFlags & COLFLAG_GENERATED );
001976              onError = OE_Abort;
001977            }else{
001978              assert( !isGenerated );
001979            }
001980          }else if( b2ndPass && !isGenerated ){
001981            continue;
001982          }
001983          assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
001984              || onError==OE_Ignore || onError==OE_Replace );
001985          testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
001986          iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
001987          switch( onError ){
001988            case OE_Replace: {
001989              int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
001990              VdbeCoverage(v);
001991              assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
001992              nSeenReplace++;
001993              sqlite3ExprCodeCopy(pParse,
001994                 sqlite3ColumnExpr(pTab, pCol), iReg);
001995              sqlite3VdbeJumpHere(v, addr1);
001996              break;
001997            }
001998            case OE_Abort:
001999              sqlite3MayAbort(pParse);
002000              /* no break */ deliberate_fall_through
002001            case OE_Rollback:
002002            case OE_Fail: {
002003              char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
002004                                          pCol->zCnName);
002005              testcase( zMsg==0 && db->mallocFailed==0 );
002006              sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
002007                                onError, iReg);
002008              sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
002009              sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
002010              VdbeCoverage(v);
002011              break;
002012            }
002013            default: {
002014              assert( onError==OE_Ignore );
002015              sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
002016              VdbeCoverage(v);
002017              break;
002018            }
002019          } /* end switch(onError) */
002020        } /* end loop i over columns */
002021        if( nGenerated==0 && nSeenReplace==0 ){
002022          /* If there are no generated columns with NOT NULL constraints
002023          ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
002024          ** pass is sufficient */
002025          break;
002026        }
002027        if( b2ndPass ) break;  /* Never need more than 2 passes */
002028        b2ndPass = 1;
002029  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
002030        if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
002031          /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
002032          ** first pass, recomputed values for all generated columns, as
002033          ** those values might depend on columns affected by the REPLACE.
002034          */
002035          sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
002036        }
002037  #endif
002038      } /* end of 2-pass loop */
002039    } /* end if( has-not-null-constraints ) */
002040  
002041    /* Test all CHECK constraints
002042    */
002043  #ifndef SQLITE_OMIT_CHECK
002044    if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
002045      ExprList *pCheck = pTab->pCheck;
002046      pParse->iSelfTab = -(regNewData+1);
002047      onError = overrideError!=OE_Default ? overrideError : OE_Abort;
002048      for(i=0; i<pCheck->nExpr; i++){
002049        int allOk;
002050        Expr *pCopy;
002051        Expr *pExpr = pCheck->a[i].pExpr;
002052        if( aiChng
002053         && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
002054        ){
002055          /* The check constraints do not reference any of the columns being
002056          ** updated so there is no point it verifying the check constraint */
002057          continue;
002058        }
002059        if( bAffinityDone==0 ){
002060          sqlite3TableAffinity(v, pTab, regNewData+1);
002061          bAffinityDone = 1;
002062        }
002063        allOk = sqlite3VdbeMakeLabel(pParse);
002064        sqlite3VdbeVerifyAbortable(v, onError);
002065        pCopy = sqlite3ExprDup(db, pExpr, 0);
002066        if( !db->mallocFailed ){
002067          sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
002068        }
002069        sqlite3ExprDelete(db, pCopy);
002070        if( onError==OE_Ignore ){
002071          sqlite3VdbeGoto(v, ignoreDest);
002072        }else{
002073          char *zName = pCheck->a[i].zEName;
002074          assert( zName!=0 || pParse->db->mallocFailed );
002075          if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
002076          sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
002077                                onError, zName, P4_TRANSIENT,
002078                                P5_ConstraintCheck);
002079        }
002080        sqlite3VdbeResolveLabel(v, allOk);
002081      }
002082      pParse->iSelfTab = 0;
002083    }
002084  #endif /* !defined(SQLITE_OMIT_CHECK) */
002085  
002086    /* UNIQUE and PRIMARY KEY constraints should be handled in the following
002087    ** order:
002088    **
002089    **   (1)  OE_Update
002090    **   (2)  OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
002091    **   (3)  OE_Replace
002092    **
002093    ** OE_Fail and OE_Ignore must happen before any changes are made.
002094    ** OE_Update guarantees that only a single row will change, so it
002095    ** must happen before OE_Replace.  Technically, OE_Abort and OE_Rollback
002096    ** could happen in any order, but they are grouped up front for
002097    ** convenience.
002098    **
002099    ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
002100    ** The order of constraints used to have OE_Update as (2) and OE_Abort
002101    ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
002102    ** constraint before any others, so it had to be moved.
002103    **
002104    ** Constraint checking code is generated in this order:
002105    **   (A)  The rowid constraint
002106    **   (B)  Unique index constraints that do not have OE_Replace as their
002107    **        default conflict resolution strategy
002108    **   (C)  Unique index that do use OE_Replace by default.
002109    **
002110    ** The ordering of (2) and (3) is accomplished by making sure the linked
002111    ** list of indexes attached to a table puts all OE_Replace indexes last
002112    ** in the list.  See sqlite3CreateIndex() for where that happens.
002113    */
002114    sIdxIter.eType = 0;
002115    sIdxIter.i = 0;
002116    sIdxIter.u.ax.aIdx = 0;  /* Silence harmless compiler warning */
002117    sIdxIter.u.lx.pIdx = pTab->pIndex;
002118    if( pUpsert ){
002119      if( pUpsert->pUpsertTarget==0 ){
002120        /* There is just on ON CONFLICT clause and it has no constraint-target */
002121        assert( pUpsert->pNextUpsert==0 );
002122        if( pUpsert->isDoUpdate==0 ){
002123          /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
002124          ** Make all unique constraint resolution be OE_Ignore */
002125          overrideError = OE_Ignore;
002126          pUpsert = 0;
002127        }else{
002128          /* A single ON CONFLICT DO UPDATE.  Make all resolutions OE_Update */
002129          overrideError = OE_Update;
002130        }
002131      }else if( pTab->pIndex!=0 ){
002132        /* Otherwise, we'll need to run the IndexListTerm array version of the
002133        ** iterator to ensure that all of the ON CONFLICT conditions are
002134        ** checked first and in order. */
002135        int nIdx, jj;
002136        u64 nByte;
002137        Upsert *pTerm;
002138        u8 *bUsed;
002139        for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
002140           assert( aRegIdx[nIdx]>0 );
002141        }
002142        sIdxIter.eType = 1;
002143        sIdxIter.u.ax.nIdx = nIdx;
002144        nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx;
002145        sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte);
002146        if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */
002147        bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx];
002148        pUpsert->pToFree = sIdxIter.u.ax.aIdx;
002149        for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
002150          if( pTerm->pUpsertTarget==0 ) break;
002151          if( pTerm->pUpsertIdx==0 ) continue;  /* Skip ON CONFLICT for the IPK */
002152          jj = 0;
002153          pIdx = pTab->pIndex;
002154          while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
002155             pIdx = pIdx->pNext;
002156             jj++;
002157          }
002158          if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */
002159          bUsed[jj] = 1;
002160          sIdxIter.u.ax.aIdx[i].p = pIdx;
002161          sIdxIter.u.ax.aIdx[i].ix = jj;
002162          i++;
002163        }
002164        for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
002165          if( bUsed[jj] ) continue;
002166          sIdxIter.u.ax.aIdx[i].p = pIdx;
002167          sIdxIter.u.ax.aIdx[i].ix = jj;
002168          i++;
002169        }
002170        assert( i==nIdx );
002171      }
002172    }
002173  
002174    /* Determine if it is possible that triggers (either explicitly coded
002175    ** triggers or FK resolution actions) might run as a result of deletes
002176    ** that happen when OE_Replace conflict resolution occurs. (Call these
002177    ** "replace triggers".)  If any replace triggers run, we will need to
002178    ** recheck all of the uniqueness constraints after they have all run.
002179    ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
002180    **
002181    ** If replace triggers are a possibility, then
002182    **
002183    **   (1) Allocate register regTrigCnt and initialize it to zero.
002184    **       That register will count the number of replace triggers that
002185    **       fire.  Constraint recheck only occurs if the number is positive.
002186    **   (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
002187    **   (3) Initialize addrRecheck and lblRecheckOk
002188    **
002189    ** The uniqueness rechecking code will create a series of tests to run
002190    ** in a second pass.  The addrRecheck and lblRecheckOk variables are
002191    ** used to link together these tests which are separated from each other
002192    ** in the generate bytecode.
002193    */
002194    if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
002195      /* There are not DELETE triggers nor FK constraints.  No constraint
002196      ** rechecks are needed. */
002197      pTrigger = 0;
002198      regTrigCnt = 0;
002199    }else{
002200      if( db->flags&SQLITE_RecTriggers ){
002201        pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
002202        regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
002203      }else{
002204        pTrigger = 0;
002205        regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
002206      }
002207      if( regTrigCnt ){
002208        /* Replace triggers might exist.  Allocate the counter and
002209        ** initialize it to zero. */
002210        regTrigCnt = ++pParse->nMem;
002211        sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
002212        VdbeComment((v, "trigger count"));
002213        lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
002214        addrRecheck = lblRecheckOk;
002215      }
002216    }
002217  
002218    /* If rowid is changing, make sure the new rowid does not previously
002219    ** exist in the table.
002220    */
002221    if( pkChng && pPk==0 ){
002222      int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
002223  
002224      /* Figure out what action to take in case of a rowid collision */
002225      onError = pTab->keyConf;
002226      if( overrideError!=OE_Default ){
002227        onError = overrideError;
002228      }else if( onError==OE_Default ){
002229        onError = OE_Abort;
002230      }
002231  
002232      /* figure out whether or not upsert applies in this case */
002233      if( pUpsert ){
002234        pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0);
002235        if( pUpsertClause!=0 ){
002236          if( pUpsertClause->isDoUpdate==0 ){
002237            onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
002238          }else{
002239            onError = OE_Update;  /* DO UPDATE */
002240          }
002241        }
002242        if( pUpsertClause!=pUpsert ){
002243          /* The first ON CONFLICT clause has a conflict target other than
002244          ** the IPK.  We have to jump ahead to that first ON CONFLICT clause
002245          ** and then come back here and deal with the IPK afterwards */
002246          upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto);
002247        }
002248      }
002249  
002250      /* If the response to a rowid conflict is REPLACE but the response
002251      ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
002252      ** to defer the running of the rowid conflict checking until after
002253      ** the UNIQUE constraints have run.
002254      */
002255      if( onError==OE_Replace      /* IPK rule is REPLACE */
002256       && onError!=overrideError   /* Rules for other constraints are different */
002257       && pTab->pIndex             /* There exist other constraints */
002258       && !upsertIpkDelay          /* IPK check already deferred by UPSERT */
002259      ){
002260        ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
002261        VdbeComment((v, "defer IPK REPLACE until last"));
002262      }
002263  
002264      if( isUpdate ){
002265        /* pkChng!=0 does not mean that the rowid has changed, only that
002266        ** it might have changed.  Skip the conflict logic below if the rowid
002267        ** is unchanged. */
002268        sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
002269        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
002270        VdbeCoverage(v);
002271      }
002272  
002273      /* Check to see if the new rowid already exists in the table.  Skip
002274      ** the following conflict logic if it does not. */
002275      VdbeNoopComment((v, "uniqueness check for ROWID"));
002276      sqlite3VdbeVerifyAbortable(v, onError);
002277      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
002278      VdbeCoverage(v);
002279  
002280      switch( onError ){
002281        default: {
002282          onError = OE_Abort;
002283          /* no break */ deliberate_fall_through
002284        }
002285        case OE_Rollback:
002286        case OE_Abort:
002287        case OE_Fail: {
002288          testcase( onError==OE_Rollback );
002289          testcase( onError==OE_Abort );
002290          testcase( onError==OE_Fail );
002291          sqlite3RowidConstraint(pParse, onError, pTab);
002292          break;
002293        }
002294        case OE_Replace: {
002295          /* If there are DELETE triggers on this table and the
002296          ** recursive-triggers flag is set, call GenerateRowDelete() to
002297          ** remove the conflicting row from the table. This will fire
002298          ** the triggers and remove both the table and index b-tree entries.
002299          **
002300          ** Otherwise, if there are no triggers or the recursive-triggers
002301          ** flag is not set, but the table has one or more indexes, call
002302          ** GenerateRowIndexDelete(). This removes the index b-tree entries
002303          ** only. The table b-tree entry will be replaced by the new entry
002304          ** when it is inserted. 
002305          **
002306          ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
002307          ** also invoke MultiWrite() to indicate that this VDBE may require
002308          ** statement rollback (if the statement is aborted after the delete
002309          ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
002310          ** but being more selective here allows statements like:
002311          **
002312          **   REPLACE INTO t(rowid) VALUES($newrowid)
002313          **
002314          ** to run without a statement journal if there are no indexes on the
002315          ** table.
002316          */
002317          if( regTrigCnt ){
002318            sqlite3MultiWrite(pParse);
002319            sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
002320                                     regNewData, 1, 0, OE_Replace, 1, -1);
002321            sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
002322            nReplaceTrig++;
002323          }else{
002324  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002325            assert( HasRowid(pTab) );
002326            /* This OP_Delete opcode fires the pre-update-hook only. It does
002327            ** not modify the b-tree. It is more efficient to let the coming
002328            ** OP_Insert replace the existing entry than it is to delete the
002329            ** existing entry and then insert a new one. */
002330            sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
002331            sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
002332  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
002333            if( pTab->pIndex ){
002334              sqlite3MultiWrite(pParse);
002335              sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
002336            }
002337          }
002338          seenReplace = 1;
002339          break;
002340        }
002341  #ifndef SQLITE_OMIT_UPSERT
002342        case OE_Update: {
002343          sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
002344          /* no break */ deliberate_fall_through
002345        }
002346  #endif
002347        case OE_Ignore: {
002348          testcase( onError==OE_Ignore );
002349          sqlite3VdbeGoto(v, ignoreDest);
002350          break;
002351        }
002352      }
002353      sqlite3VdbeResolveLabel(v, addrRowidOk);
002354      if( pUpsert && pUpsertClause!=pUpsert ){
002355        upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
002356      }else if( ipkTop ){
002357        ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
002358        sqlite3VdbeJumpHere(v, ipkTop-1);
002359      }
002360    }
002361  
002362    /* Test all UNIQUE constraints by creating entries for each UNIQUE
002363    ** index and making sure that duplicate entries do not already exist.
002364    ** Compute the revised record entries for indices as we go.
002365    **
002366    ** This loop also handles the case of the PRIMARY KEY index for a
002367    ** WITHOUT ROWID table.
002368    */
002369    for(pIdx = indexIteratorFirst(&sIdxIter, &ix);
002370        pIdx;
002371        pIdx = indexIteratorNext(&sIdxIter, &ix)
002372    ){
002373      int regIdx;          /* Range of registers holding content for pIdx */
002374      int regR;            /* Range of registers holding conflicting PK */
002375      int iThisCur;        /* Cursor for this UNIQUE index */
002376      int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
002377      int addrConflictCk;  /* First opcode in the conflict check logic */
002378  
002379      if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
002380      if( pUpsert ){
002381        pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
002382        if( upsertIpkDelay && pUpsertClause==pUpsert ){
002383          sqlite3VdbeJumpHere(v, upsertIpkDelay);
002384        }
002385      }
002386      addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
002387      if( bAffinityDone==0 ){
002388        sqlite3TableAffinity(v, pTab, regNewData+1);
002389        bAffinityDone = 1;
002390      }
002391      VdbeNoopComment((v, "prep index %s", pIdx->zName));
002392      iThisCur = iIdxCur+ix;
002393  
002394  
002395      /* Skip partial indices for which the WHERE clause is not true */
002396      if( pIdx->pPartIdxWhere ){
002397        sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
002398        pParse->iSelfTab = -(regNewData+1);
002399        sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
002400                              SQLITE_JUMPIFNULL);
002401        pParse->iSelfTab = 0;
002402      }
002403  
002404      /* Create a record for this index entry as it should appear after
002405      ** the insert or update.  Store that record in the aRegIdx[ix] register
002406      */
002407      regIdx = aRegIdx[ix]+1;
002408      for(i=0; i<pIdx->nColumn; i++){
002409        int iField = pIdx->aiColumn[i];
002410        int x;
002411        if( iField==XN_EXPR ){
002412          pParse->iSelfTab = -(regNewData+1);
002413          sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
002414          pParse->iSelfTab = 0;
002415          VdbeComment((v, "%s column %d", pIdx->zName, i));
002416        }else if( iField==XN_ROWID || iField==pTab->iPKey ){
002417          x = regNewData;
002418          sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
002419          VdbeComment((v, "rowid"));
002420        }else{
002421          testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
002422          x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
002423          sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
002424          VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
002425        }
002426      }
002427      sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
002428      VdbeComment((v, "for %s", pIdx->zName));
002429  #ifdef SQLITE_ENABLE_NULL_TRIM
002430      if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
002431        sqlite3SetMakeRecordP5(v, pIdx->pTable);
002432      }
002433  #endif
002434      sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
002435  
002436      /* In an UPDATE operation, if this index is the PRIMARY KEY index
002437      ** of a WITHOUT ROWID table and there has been no change the
002438      ** primary key, then no collision is possible.  The collision detection
002439      ** logic below can all be skipped. */
002440      if( isUpdate && pPk==pIdx && pkChng==0 ){
002441        sqlite3VdbeResolveLabel(v, addrUniqueOk);
002442        continue;
002443      }
002444  
002445      /* Find out what action to take in case there is a uniqueness conflict */
002446      onError = pIdx->onError;
002447      if( onError==OE_None ){
002448        sqlite3VdbeResolveLabel(v, addrUniqueOk);
002449        continue;  /* pIdx is not a UNIQUE index */
002450      }
002451      if( overrideError!=OE_Default ){
002452        onError = overrideError;
002453      }else if( onError==OE_Default ){
002454        onError = OE_Abort;
002455      }
002456  
002457      /* Figure out if the upsert clause applies to this index */
002458      if( pUpsertClause ){
002459        if( pUpsertClause->isDoUpdate==0 ){
002460          onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
002461        }else{
002462          onError = OE_Update;  /* DO UPDATE */
002463        }
002464      }
002465  
002466      /* Collision detection may be omitted if all of the following are true:
002467      **   (1) The conflict resolution algorithm is REPLACE
002468      **   (2) The table is a WITHOUT ROWID table
002469      **   (3) There are no secondary indexes on the table
002470      **   (4) No delete triggers need to be fired if there is a conflict
002471      **   (5) No FK constraint counters need to be updated if a conflict occurs.
002472      **
002473      ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
002474      ** must be explicitly deleted in order to ensure any pre-update hook
002475      ** is invoked.  */
002476      assert( IsOrdinaryTable(pTab) );
002477  #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
002478      if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
002479       && pPk==pIdx                                   /* Condition 2 */
002480       && onError==OE_Replace                         /* Condition 1 */
002481       && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
002482            0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
002483       && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
002484           (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
002485      ){
002486        sqlite3VdbeResolveLabel(v, addrUniqueOk);
002487        continue;
002488      }
002489  #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
002490  
002491      /* Check to see if the new index entry will be unique */
002492      sqlite3VdbeVerifyAbortable(v, onError);
002493      addrConflictCk =
002494        sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
002495                             regIdx, pIdx->nKeyCol); VdbeCoverage(v);
002496  
002497      /* Generate code to handle collisions */
002498      regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField);
002499      if( isUpdate || onError==OE_Replace ){
002500        if( HasRowid(pTab) ){
002501          sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
002502          /* Conflict only if the rowid of the existing index entry
002503          ** is different from old-rowid */
002504          if( isUpdate ){
002505            sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
002506            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
002507            VdbeCoverage(v);
002508          }
002509        }else{
002510          int x;
002511          /* Extract the PRIMARY KEY from the end of the index entry and
002512          ** store it in registers regR..regR+nPk-1 */
002513          if( pIdx!=pPk ){
002514            for(i=0; i<pPk->nKeyCol; i++){
002515              assert( pPk->aiColumn[i]>=0 );
002516              x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
002517              sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
002518              VdbeComment((v, "%s.%s", pTab->zName,
002519                           pTab->aCol[pPk->aiColumn[i]].zCnName));
002520            }
002521          }
002522          if( isUpdate ){
002523            /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
002524            ** table, only conflict if the new PRIMARY KEY values are actually
002525            ** different from the old.  See TH3 withoutrowid04.test.
002526            **
002527            ** For a UNIQUE index, only conflict if the PRIMARY KEY values
002528            ** of the matched index row are different from the original PRIMARY
002529            ** KEY values of this row before the update.  */
002530            int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
002531            int op = OP_Ne;
002532            int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
002533   
002534            for(i=0; i<pPk->nKeyCol; i++){
002535              char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
002536              x = pPk->aiColumn[i];
002537              assert( x>=0 );
002538              if( i==(pPk->nKeyCol-1) ){
002539                addrJump = addrUniqueOk;
002540                op = OP_Eq;
002541              }
002542              x = sqlite3TableColumnToStorage(pTab, x);
002543              sqlite3VdbeAddOp4(v, op,
002544                  regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
002545              );
002546              sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
002547              VdbeCoverageIf(v, op==OP_Eq);
002548              VdbeCoverageIf(v, op==OP_Ne);
002549            }
002550          }
002551        }
002552      }
002553  
002554      /* Generate code that executes if the new index entry is not unique */
002555      assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
002556          || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
002557      switch( onError ){
002558        case OE_Rollback:
002559        case OE_Abort:
002560        case OE_Fail: {
002561          testcase( onError==OE_Rollback );
002562          testcase( onError==OE_Abort );
002563          testcase( onError==OE_Fail );
002564          sqlite3UniqueConstraint(pParse, onError, pIdx);
002565          break;
002566        }
002567  #ifndef SQLITE_OMIT_UPSERT
002568        case OE_Update: {
002569          sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
002570          /* no break */ deliberate_fall_through
002571        }
002572  #endif
002573        case OE_Ignore: {
002574          testcase( onError==OE_Ignore );
002575          sqlite3VdbeGoto(v, ignoreDest);
002576          break;
002577        }
002578        default: {
002579          int nConflictCk;   /* Number of opcodes in conflict check logic */
002580  
002581          assert( onError==OE_Replace );
002582          nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
002583          assert( nConflictCk>0 || db->mallocFailed );
002584          testcase( nConflictCk<=0 );
002585          testcase( nConflictCk>1 );
002586          if( regTrigCnt ){
002587            sqlite3MultiWrite(pParse);
002588            nReplaceTrig++;
002589          }
002590          if( pTrigger && isUpdate ){
002591            sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
002592          }
002593          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
002594              regR, nPkField, 0, OE_Replace,
002595              (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
002596          if( pTrigger && isUpdate ){
002597            sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
002598          }
002599          if( regTrigCnt ){
002600            int addrBypass;  /* Jump destination to bypass recheck logic */
002601  
002602            sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
002603            addrBypass = sqlite3VdbeAddOp0(v, OP_Goto);  /* Bypass recheck */
002604            VdbeComment((v, "bypass recheck"));
002605  
002606            /* Here we insert code that will be invoked after all constraint
002607            ** checks have run, if and only if one or more replace triggers
002608            ** fired. */
002609            sqlite3VdbeResolveLabel(v, lblRecheckOk);
002610            lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
002611            if( pIdx->pPartIdxWhere ){
002612              /* Bypass the recheck if this partial index is not defined
002613              ** for the current row */
002614              sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
002615              VdbeCoverage(v);
002616            }
002617            /* Copy the constraint check code from above, except change
002618            ** the constraint-ok jump destination to be the address of
002619            ** the next retest block */
002620            while( nConflictCk>0 ){
002621              VdbeOp x;    /* Conflict check opcode to copy */
002622              /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
002623              ** Hence, make a complete copy of the opcode, rather than using
002624              ** a pointer to the opcode. */
002625              x = *sqlite3VdbeGetOp(v, addrConflictCk);
002626              if( x.opcode!=OP_IdxRowid ){
002627                int p2;      /* New P2 value for copied conflict check opcode */
002628                const char *zP4;
002629                if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
002630                  p2 = lblRecheckOk;
002631                }else{
002632                  p2 = x.p2;
002633                }
002634                zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
002635                sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
002636                sqlite3VdbeChangeP5(v, x.p5);
002637                VdbeCoverageIf(v, p2!=x.p2);
002638              }
002639              nConflictCk--;
002640              addrConflictCk++;
002641            }
002642            /* If the retest fails, issue an abort */
002643            sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
002644  
002645            sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
002646          }
002647          seenReplace = 1;
002648          break;
002649        }
002650      }
002651      sqlite3VdbeResolveLabel(v, addrUniqueOk);
002652      if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
002653      if( pUpsertClause
002654       && upsertIpkReturn
002655       && sqlite3UpsertNextIsIPK(pUpsertClause)
002656      ){
002657        sqlite3VdbeGoto(v, upsertIpkDelay+1);
002658        sqlite3VdbeJumpHere(v, upsertIpkReturn);
002659        upsertIpkReturn = 0;
002660      }
002661    }
002662  
002663    /* If the IPK constraint is a REPLACE, run it last */
002664    if( ipkTop ){
002665      sqlite3VdbeGoto(v, ipkTop);
002666      VdbeComment((v, "Do IPK REPLACE"));
002667      assert( ipkBottom>0 );
002668      sqlite3VdbeJumpHere(v, ipkBottom);
002669    }
002670  
002671    /* Recheck all uniqueness constraints after replace triggers have run */
002672    testcase( regTrigCnt!=0 && nReplaceTrig==0 );
002673    assert( regTrigCnt!=0 || nReplaceTrig==0 );
002674    if( nReplaceTrig ){
002675      sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
002676      if( !pPk ){
002677        if( isUpdate ){
002678          sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
002679          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
002680          VdbeCoverage(v);
002681        }
002682        sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
002683        VdbeCoverage(v);
002684        sqlite3RowidConstraint(pParse, OE_Abort, pTab);
002685      }else{
002686        sqlite3VdbeGoto(v, addrRecheck);
002687      }
002688      sqlite3VdbeResolveLabel(v, lblRecheckOk);
002689    }
002690  
002691    /* Generate the table record */
002692    if( HasRowid(pTab) ){
002693      int regRec = aRegIdx[ix];
002694      sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
002695      sqlite3SetMakeRecordP5(v, pTab);
002696      if( !bAffinityDone ){
002697        sqlite3TableAffinity(v, pTab, 0);
002698      }
002699    }
002700  
002701    *pbMayReplace = seenReplace;
002702    VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
002703  }
002704  
002705  #ifdef SQLITE_ENABLE_NULL_TRIM
002706  /*
002707  ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
002708  ** to be the number of columns in table pTab that must not be NULL-trimmed.
002709  **
002710  ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
002711  */
002712  void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
002713    u16 i;
002714  
002715    /* Records with omitted columns are only allowed for schema format
002716    ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
002717    if( pTab->pSchema->file_format<2 ) return;
002718  
002719    for(i=pTab->nCol-1; i>0; i--){
002720      if( pTab->aCol[i].iDflt!=0 ) break;
002721      if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
002722    }
002723    sqlite3VdbeChangeP5(v, i+1);
002724  }
002725  #endif
002726  
002727  /*
002728  ** Table pTab is a WITHOUT ROWID table that is being written to. The cursor
002729  ** number is iCur, and register regData contains the new record for the
002730  ** PK index. This function adds code to invoke the pre-update hook,
002731  ** if one is registered.
002732  */
002733  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002734  static void codeWithoutRowidPreupdate(
002735    Parse *pParse,                  /* Parse context */
002736    Table *pTab,                    /* Table being updated */
002737    int iCur,                       /* Cursor number for table */
002738    int regData                     /* Data containing new record */
002739  ){
002740    Vdbe *v = pParse->pVdbe;
002741    int r = sqlite3GetTempReg(pParse);
002742    assert( !HasRowid(pTab) );
002743    assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
002744    sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
002745    sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE);
002746    sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
002747    sqlite3ReleaseTempReg(pParse, r);
002748  }
002749  #else
002750  # define codeWithoutRowidPreupdate(a,b,c,d)
002751  #endif
002752  
002753  /*
002754  ** This routine generates code to finish the INSERT or UPDATE operation
002755  ** that was started by a prior call to sqlite3GenerateConstraintChecks.
002756  ** A consecutive range of registers starting at regNewData contains the
002757  ** rowid and the content to be inserted.
002758  **
002759  ** The arguments to this routine should be the same as the first six
002760  ** arguments to sqlite3GenerateConstraintChecks.
002761  */
002762  void sqlite3CompleteInsertion(
002763    Parse *pParse,      /* The parser context */
002764    Table *pTab,        /* the table into which we are inserting */
002765    int iDataCur,       /* Cursor of the canonical data source */
002766    int iIdxCur,        /* First index cursor */
002767    int regNewData,     /* Range of content */
002768    int *aRegIdx,       /* Register used by each index.  0 for unused indices */
002769    int update_flags,   /* True for UPDATE, False for INSERT */
002770    int appendBias,     /* True if this is likely to be an append */
002771    int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
002772  ){
002773    Vdbe *v;            /* Prepared statements under construction */
002774    Index *pIdx;        /* An index being inserted or updated */
002775    u8 pik_flags;       /* flag values passed to the btree insert */
002776    int i;              /* Loop counter */
002777  
002778    assert( update_flags==0
002779         || update_flags==OPFLAG_ISUPDATE
002780         || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
002781    );
002782  
002783    v = pParse->pVdbe;
002784    assert( v!=0 );
002785    assert( !IsView(pTab) );  /* This table is not a VIEW */
002786    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
002787      /* All REPLACE indexes are at the end of the list */
002788      assert( pIdx->onError!=OE_Replace
002789           || pIdx->pNext==0
002790           || pIdx->pNext->onError==OE_Replace );
002791      if( aRegIdx[i]==0 ) continue;
002792      if( pIdx->pPartIdxWhere ){
002793        sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
002794        VdbeCoverage(v);
002795      }
002796      pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
002797      if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
002798        pik_flags |= OPFLAG_NCHANGE;
002799        pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
002800        if( update_flags==0 ){
002801          codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]);
002802        }
002803      }
002804      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
002805                           aRegIdx[i]+1,
002806                           pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
002807      sqlite3VdbeChangeP5(v, pik_flags);
002808    }
002809    if( !HasRowid(pTab) ) return;
002810    if( pParse->nested ){
002811      pik_flags = 0;
002812    }else{
002813      pik_flags = OPFLAG_NCHANGE;
002814      pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
002815    }
002816    if( appendBias ){
002817      pik_flags |= OPFLAG_APPEND;
002818    }
002819    if( useSeekResult ){
002820      pik_flags |= OPFLAG_USESEEKRESULT;
002821    }
002822    sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
002823    if( !pParse->nested ){
002824      sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
002825    }
002826    sqlite3VdbeChangeP5(v, pik_flags);
002827  }
002828  
002829  /*
002830  ** Allocate cursors for the pTab table and all its indices and generate
002831  ** code to open and initialized those cursors.
002832  **
002833  ** The cursor for the object that contains the complete data (normally
002834  ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
002835  ** ROWID table) is returned in *piDataCur.  The first index cursor is
002836  ** returned in *piIdxCur.  The number of indices is returned.
002837  **
002838  ** Use iBase as the first cursor (either the *piDataCur for rowid tables
002839  ** or the first index for WITHOUT ROWID tables) if it is non-negative.
002840  ** If iBase is negative, then allocate the next available cursor.
002841  **
002842  ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
002843  ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
002844  ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
002845  ** pTab->pIndex list.
002846  **
002847  ** If pTab is a virtual table, then this routine is a no-op and the
002848  ** *piDataCur and *piIdxCur values are left uninitialized.
002849  */
002850  int sqlite3OpenTableAndIndices(
002851    Parse *pParse,   /* Parsing context */
002852    Table *pTab,     /* Table to be opened */
002853    int op,          /* OP_OpenRead or OP_OpenWrite */
002854    u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
002855    int iBase,       /* Use this for the table cursor, if there is one */
002856    u8 *aToOpen,     /* If not NULL: boolean for each table and index */
002857    int *piDataCur,  /* Write the database source cursor number here */
002858    int *piIdxCur    /* Write the first index cursor number here */
002859  ){
002860    int i;
002861    int iDb;
002862    int iDataCur;
002863    Index *pIdx;
002864    Vdbe *v;
002865  
002866    assert( op==OP_OpenRead || op==OP_OpenWrite );
002867    assert( op==OP_OpenWrite || p5==0 );
002868    assert( piDataCur!=0 );
002869    assert( piIdxCur!=0 );
002870    if( IsVirtual(pTab) ){
002871      /* This routine is a no-op for virtual tables. Leave the output
002872      ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
002873      ** for improved error detection. */
002874      *piDataCur = *piIdxCur = -999;
002875      return 0;
002876    }
002877    iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
002878    v = pParse->pVdbe;
002879    assert( v!=0 );
002880    if( iBase<0 ) iBase = pParse->nTab;
002881    iDataCur = iBase++;
002882    *piDataCur = iDataCur;
002883    if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
002884      sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
002885    }else if( pParse->db->noSharedCache==0 ){
002886      sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
002887    }
002888    *piIdxCur = iBase;
002889    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
002890      int iIdxCur = iBase++;
002891      assert( pIdx->pSchema==pTab->pSchema );
002892      if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
002893        *piDataCur = iIdxCur;
002894        p5 = 0;
002895      }
002896      if( aToOpen==0 || aToOpen[i+1] ){
002897        sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
002898        sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
002899        sqlite3VdbeChangeP5(v, p5);
002900        VdbeComment((v, "%s", pIdx->zName));
002901      }
002902    }
002903    if( iBase>pParse->nTab ) pParse->nTab = iBase;
002904    return i;
002905  }
002906  
002907  
002908  #ifdef SQLITE_TEST
002909  /*
002910  ** The following global variable is incremented whenever the
002911  ** transfer optimization is used.  This is used for testing
002912  ** purposes only - to make sure the transfer optimization really
002913  ** is happening when it is supposed to.
002914  */
002915  int sqlite3_xferopt_count;
002916  #endif /* SQLITE_TEST */
002917  
002918  
002919  #ifndef SQLITE_OMIT_XFER_OPT
002920  /*
002921  ** Check to see if index pSrc is compatible as a source of data
002922  ** for index pDest in an insert transfer optimization.  The rules
002923  ** for a compatible index:
002924  **
002925  **    *   The index is over the same set of columns
002926  **    *   The same DESC and ASC markings occurs on all columns
002927  **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
002928  **    *   The same collating sequence on each column
002929  **    *   The index has the exact same WHERE clause
002930  */
002931  static int xferCompatibleIndex(Index *pDest, Index *pSrc){
002932    int i;
002933    assert( pDest && pSrc );
002934    assert( pDest->pTable!=pSrc->pTable );
002935    if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
002936      return 0;   /* Different number of columns */
002937    }
002938    if( pDest->onError!=pSrc->onError ){
002939      return 0;   /* Different conflict resolution strategies */
002940    }
002941    for(i=0; i<pSrc->nKeyCol; i++){
002942      if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
002943        return 0;   /* Different columns indexed */
002944      }
002945      if( pSrc->aiColumn[i]==XN_EXPR ){
002946        assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
002947        if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
002948                               pDest->aColExpr->a[i].pExpr, -1)!=0 ){
002949          return 0;   /* Different expressions in the index */
002950        }
002951      }
002952      if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
002953        return 0;   /* Different sort orders */
002954      }
002955      if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
002956        return 0;   /* Different collating sequences */
002957      }
002958    }
002959    if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
002960      return 0;     /* Different WHERE clauses */
002961    }
002962  
002963    /* If no test above fails then the indices must be compatible */
002964    return 1;
002965  }
002966  
002967  /*
002968  ** Attempt the transfer optimization on INSERTs of the form
002969  **
002970  **     INSERT INTO tab1 SELECT * FROM tab2;
002971  **
002972  ** The xfer optimization transfers raw records from tab2 over to tab1. 
002973  ** Columns are not decoded and reassembled, which greatly improves
002974  ** performance.  Raw index records are transferred in the same way.
002975  **
002976  ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
002977  ** There are lots of rules for determining compatibility - see comments
002978  ** embedded in the code for details.
002979  **
002980  ** This routine returns TRUE if the optimization is guaranteed to be used.
002981  ** Sometimes the xfer optimization will only work if the destination table
002982  ** is empty - a factor that can only be determined at run-time.  In that
002983  ** case, this routine generates code for the xfer optimization but also
002984  ** does a test to see if the destination table is empty and jumps over the
002985  ** xfer optimization code if the test fails.  In that case, this routine
002986  ** returns FALSE so that the caller will know to go ahead and generate
002987  ** an unoptimized transfer.  This routine also returns FALSE if there
002988  ** is no chance that the xfer optimization can be applied.
002989  **
002990  ** This optimization is particularly useful at making VACUUM run faster.
002991  */
002992  static int xferOptimization(
002993    Parse *pParse,        /* Parser context */
002994    Table *pDest,         /* The table we are inserting into */
002995    Select *pSelect,      /* A SELECT statement to use as the data source */
002996    int onError,          /* How to handle constraint errors */
002997    int iDbDest           /* The database of pDest */
002998  ){
002999    sqlite3 *db = pParse->db;
003000    ExprList *pEList;                /* The result set of the SELECT */
003001    Table *pSrc;                     /* The table in the FROM clause of SELECT */
003002    Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
003003    SrcItem *pItem;                  /* An element of pSelect->pSrc */
003004    int i;                           /* Loop counter */
003005    int iDbSrc;                      /* The database of pSrc */
003006    int iSrc, iDest;                 /* Cursors from source and destination */
003007    int addr1, addr2;                /* Loop addresses */
003008    int emptyDestTest = 0;           /* Address of test for empty pDest */
003009    int emptySrcTest = 0;            /* Address of test for empty pSrc */
003010    Vdbe *v;                         /* The VDBE we are building */
003011    int regAutoinc;                  /* Memory register used by AUTOINC */
003012    int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
003013    int regData, regRowid;           /* Registers holding data and rowid */
003014  
003015    assert( pSelect!=0 );
003016    if( pParse->pWith || pSelect->pWith ){
003017      /* Do not attempt to process this query if there are an WITH clauses
003018      ** attached to it. Proceeding may generate a false "no such table: xxx"
003019      ** error if pSelect reads from a CTE named "xxx".  */
003020      return 0;
003021    }
003022  #ifndef SQLITE_OMIT_VIRTUALTABLE
003023    if( IsVirtual(pDest) ){
003024      return 0;   /* tab1 must not be a virtual table */
003025    }
003026  #endif
003027    if( onError==OE_Default ){
003028      if( pDest->iPKey>=0 ) onError = pDest->keyConf;
003029      if( onError==OE_Default ) onError = OE_Abort;
003030    }
003031    assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
003032    if( pSelect->pSrc->nSrc!=1 ){
003033      return 0;   /* FROM clause must have exactly one term */
003034    }
003035    if( pSelect->pSrc->a[0].pSelect ){
003036      return 0;   /* FROM clause cannot contain a subquery */
003037    }
003038    if( pSelect->pWhere ){
003039      return 0;   /* SELECT may not have a WHERE clause */
003040    }
003041    if( pSelect->pOrderBy ){
003042      return 0;   /* SELECT may not have an ORDER BY clause */
003043    }
003044    /* Do not need to test for a HAVING clause.  If HAVING is present but
003045    ** there is no ORDER BY, we will get an error. */
003046    if( pSelect->pGroupBy ){
003047      return 0;   /* SELECT may not have a GROUP BY clause */
003048    }
003049    if( pSelect->pLimit ){
003050      return 0;   /* SELECT may not have a LIMIT clause */
003051    }
003052    if( pSelect->pPrior ){
003053      return 0;   /* SELECT may not be a compound query */
003054    }
003055    if( pSelect->selFlags & SF_Distinct ){
003056      return 0;   /* SELECT may not be DISTINCT */
003057    }
003058    pEList = pSelect->pEList;
003059    assert( pEList!=0 );
003060    if( pEList->nExpr!=1 ){
003061      return 0;   /* The result set must have exactly one column */
003062    }
003063    assert( pEList->a[0].pExpr );
003064    if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
003065      return 0;   /* The result set must be the special operator "*" */
003066    }
003067  
003068    /* At this point we have established that the statement is of the
003069    ** correct syntactic form to participate in this optimization.  Now
003070    ** we have to check the semantics.
003071    */
003072    pItem = pSelect->pSrc->a;
003073    pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
003074    if( pSrc==0 ){
003075      return 0;   /* FROM clause does not contain a real table */
003076    }
003077    if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
003078      testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
003079      return 0;   /* tab1 and tab2 may not be the same table */
003080    }
003081    if( HasRowid(pDest)!=HasRowid(pSrc) ){
003082      return 0;   /* source and destination must both be WITHOUT ROWID or not */
003083    }
003084    if( !IsOrdinaryTable(pSrc) ){
003085      return 0;   /* tab2 may not be a view or virtual table */
003086    }
003087    if( pDest->nCol!=pSrc->nCol ){
003088      return 0;   /* Number of columns must be the same in tab1 and tab2 */
003089    }
003090    if( pDest->iPKey!=pSrc->iPKey ){
003091      return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
003092    }
003093    if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
003094      return 0;   /* Cannot feed from a non-strict into a strict table */
003095    }
003096    for(i=0; i<pDest->nCol; i++){
003097      Column *pDestCol = &pDest->aCol[i];
003098      Column *pSrcCol = &pSrc->aCol[i];
003099  #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
003100      if( (db->mDbFlags & DBFLAG_Vacuum)==0
003101       && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
003102      ){
003103        return 0;    /* Neither table may have __hidden__ columns */
003104      }
003105  #endif
003106  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
003107      /* Even if tables t1 and t2 have identical schemas, if they contain
003108      ** generated columns, then this statement is semantically incorrect:
003109      **
003110      **     INSERT INTO t2 SELECT * FROM t1;
003111      **
003112      ** The reason is that generated column values are returned by the
003113      ** the SELECT statement on the right but the INSERT statement on the
003114      ** left wants them to be omitted.
003115      **
003116      ** Nevertheless, this is a useful notational shorthand to tell SQLite
003117      ** to do a bulk transfer all of the content from t1 over to t2.
003118      **
003119      ** We could, in theory, disable this (except for internal use by the
003120      ** VACUUM command where it is actually needed).  But why do that?  It
003121      ** seems harmless enough, and provides a useful service.
003122      */
003123      if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
003124          (pSrcCol->colFlags & COLFLAG_GENERATED) ){
003125        return 0;    /* Both columns have the same generated-column type */
003126      }
003127      /* But the transfer is only allowed if both the source and destination
003128      ** tables have the exact same expressions for generated columns.
003129      ** This requirement could be relaxed for VIRTUAL columns, I suppose.
003130      */
003131      if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
003132        if( sqlite3ExprCompare(0,
003133               sqlite3ColumnExpr(pSrc, pSrcCol),
003134               sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
003135          testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
003136          testcase( pDestCol->colFlags & COLFLAG_STORED );
003137          return 0;  /* Different generator expressions */
003138        }
003139      }
003140  #endif
003141      if( pDestCol->affinity!=pSrcCol->affinity ){
003142        return 0;    /* Affinity must be the same on all columns */
003143      }
003144      if( sqlite3_stricmp(sqlite3ColumnColl(pDestCol),
003145                          sqlite3ColumnColl(pSrcCol))!=0 ){
003146        return 0;    /* Collating sequence must be the same on all columns */
003147      }
003148      if( pDestCol->notNull && !pSrcCol->notNull ){
003149        return 0;    /* tab2 must be NOT NULL if tab1 is */
003150      }
003151      /* Default values for second and subsequent columns need to match. */
003152      if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
003153        Expr *pDestExpr = sqlite3ColumnExpr(pDest, pDestCol);
003154        Expr *pSrcExpr = sqlite3ColumnExpr(pSrc, pSrcCol);
003155        assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
003156        assert( pDestExpr==0 || !ExprHasProperty(pDestExpr, EP_IntValue) );
003157        assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
003158        assert( pSrcExpr==0 || !ExprHasProperty(pSrcExpr, EP_IntValue) );
003159        if( (pDestExpr==0)!=(pSrcExpr==0)
003160         || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
003161                                         pSrcExpr->u.zToken)!=0)
003162        ){
003163          return 0;    /* Default values must be the same for all columns */
003164        }
003165      }
003166    }
003167    for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
003168      if( IsUniqueIndex(pDestIdx) ){
003169        destHasUniqueIdx = 1;
003170      }
003171      for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
003172        if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
003173      }
003174      if( pSrcIdx==0 ){
003175        return 0;    /* pDestIdx has no corresponding index in pSrc */
003176      }
003177      if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
003178           && sqlite3FaultSim(411)==SQLITE_OK ){
003179        /* The sqlite3FaultSim() call allows this corruption test to be
003180        ** bypassed during testing, in order to exercise other corruption tests
003181        ** further downstream. */
003182        return 0;   /* Corrupt schema - two indexes on the same btree */
003183      }
003184    }
003185  #ifndef SQLITE_OMIT_CHECK
003186    if( pDest->pCheck
003187     && (db->mDbFlags & DBFLAG_Vacuum)==0
003188     && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1)
003189    ){
003190      return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
003191    }
003192  #endif
003193  #ifndef SQLITE_OMIT_FOREIGN_KEY
003194    /* Disallow the transfer optimization if the destination table contains
003195    ** any foreign key constraints.  This is more restrictive than necessary.
003196    ** But the main beneficiary of the transfer optimization is the VACUUM
003197    ** command, and the VACUUM command disables foreign key constraints.  So
003198    ** the extra complication to make this rule less restrictive is probably
003199    ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
003200    */
003201    assert( IsOrdinaryTable(pDest) );
003202    if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
003203      return 0;
003204    }
003205  #endif
003206    if( (db->flags & SQLITE_CountRows)!=0 ){
003207      return 0;  /* xfer opt does not play well with PRAGMA count_changes */
003208    }
003209  
003210    /* If we get this far, it means that the xfer optimization is at
003211    ** least a possibility, though it might only work if the destination
003212    ** table (tab1) is initially empty.
003213    */
003214  #ifdef SQLITE_TEST
003215    sqlite3_xferopt_count++;
003216  #endif
003217    iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
003218    v = sqlite3GetVdbe(pParse);
003219    sqlite3CodeVerifySchema(pParse, iDbSrc);
003220    iSrc = pParse->nTab++;
003221    iDest = pParse->nTab++;
003222    regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
003223    regData = sqlite3GetTempReg(pParse);
003224    sqlite3VdbeAddOp2(v, OP_Null, 0, regData);
003225    regRowid = sqlite3GetTempReg(pParse);
003226    sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
003227    assert( HasRowid(pDest) || destHasUniqueIdx );
003228    if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
003229        (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
003230     || destHasUniqueIdx                              /* (2) */
003231     || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
003232    )){
003233      /* In some circumstances, we are able to run the xfer optimization
003234      ** only if the destination table is initially empty. Unless the
003235      ** DBFLAG_Vacuum flag is set, this block generates code to make
003236      ** that determination. If DBFLAG_Vacuum is set, then the destination
003237      ** table is always empty.
003238      **
003239      ** Conditions under which the destination must be empty:
003240      **
003241      ** (1) There is no INTEGER PRIMARY KEY but there are indices.
003242      **     (If the destination is not initially empty, the rowid fields
003243      **     of index entries might need to change.)
003244      **
003245      ** (2) The destination has a unique index.  (The xfer optimization
003246      **     is unable to test uniqueness.)
003247      **
003248      ** (3) onError is something other than OE_Abort and OE_Rollback.
003249      */
003250      addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
003251      emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
003252      sqlite3VdbeJumpHere(v, addr1);
003253    }
003254    if( HasRowid(pSrc) ){
003255      u8 insFlags;
003256      sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
003257      emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
003258      if( pDest->iPKey>=0 ){
003259        addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
003260        if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
003261          sqlite3VdbeVerifyAbortable(v, onError);
003262          addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
003263          VdbeCoverage(v);
003264          sqlite3RowidConstraint(pParse, onError, pDest);
003265          sqlite3VdbeJumpHere(v, addr2);
003266        }
003267        autoIncStep(pParse, regAutoinc, regRowid);
003268      }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
003269        addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
003270      }else{
003271        addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
003272        assert( (pDest->tabFlags & TF_Autoincrement)==0 );
003273      }
003274  
003275      if( db->mDbFlags & DBFLAG_Vacuum ){
003276        sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
003277        insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
003278      }else{
003279        insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT;
003280      }
003281  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
003282      if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
003283        sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
003284        insFlags &= ~OPFLAG_PREFORMAT;
003285      }else
003286  #endif
003287      {
003288        sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid);
003289      }
003290      sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
003291      if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
003292        sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
003293      }
003294      sqlite3VdbeChangeP5(v, insFlags);
003295  
003296      sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
003297      sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
003298      sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
003299    }else{
003300      sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
003301      sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
003302    }
003303    for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
003304      u8 idxInsFlags = 0;
003305      for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
003306        if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
003307      }
003308      assert( pSrcIdx );
003309      sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
003310      sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
003311      VdbeComment((v, "%s", pSrcIdx->zName));
003312      sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
003313      sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
003314      sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
003315      VdbeComment((v, "%s", pDestIdx->zName));
003316      addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
003317      if( db->mDbFlags & DBFLAG_Vacuum ){
003318        /* This INSERT command is part of a VACUUM operation, which guarantees
003319        ** that the destination table is empty. If all indexed columns use
003320        ** collation sequence BINARY, then it can also be assumed that the
003321        ** index will be populated by inserting keys in strictly sorted
003322        ** order. In this case, instead of seeking within the b-tree as part
003323        ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
003324        ** OP_IdxInsert to seek to the point within the b-tree where each key
003325        ** should be inserted. This is faster.
003326        **
003327        ** If any of the indexed columns use a collation sequence other than
003328        ** BINARY, this optimization is disabled. This is because the user
003329        ** might change the definition of a collation sequence and then run
003330        ** a VACUUM command. In that case keys may not be written in strictly
003331        ** sorted order.  */
003332        for(i=0; i<pSrcIdx->nColumn; i++){
003333          const char *zColl = pSrcIdx->azColl[i];
003334          if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
003335        }
003336        if( i==pSrcIdx->nColumn ){
003337          idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
003338          sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
003339          sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc);
003340        }
003341      }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
003342        idxInsFlags |= OPFLAG_NCHANGE;
003343      }
003344      if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){
003345        sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
003346        if( (db->mDbFlags & DBFLAG_Vacuum)==0
003347         && !HasRowid(pDest)
003348         && IsPrimaryKeyIndex(pDestIdx)
003349        ){
003350          codeWithoutRowidPreupdate(pParse, pDest, iDest, regData);
003351        }
003352      }
003353      sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
003354      sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
003355      sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
003356      sqlite3VdbeJumpHere(v, addr1);
003357      sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
003358      sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
003359    }
003360    if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
003361    sqlite3ReleaseTempReg(pParse, regRowid);
003362    sqlite3ReleaseTempReg(pParse, regData);
003363    if( emptyDestTest ){
003364      sqlite3AutoincrementEnd(pParse);
003365      sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
003366      sqlite3VdbeJumpHere(v, emptyDestTest);
003367      sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
003368      return 0;
003369    }else{
003370      return 1;
003371    }
003372  }
003373  #endif /* SQLITE_OMIT_XFER_OPT */