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