SQLite
Artifact Content
Not logged in

Artifact 7af46a3be2656f5e13791464625d93d6b07b8612:


     1  /*
     2  ** 2001 September 15
     3  **
     4  ** The author disclaims copyright to this source code.  In place of
     5  ** a legal notice, here is a blessing:
     6  **
     7  **    May you do good and not evil.
     8  **    May you find forgiveness for yourself and forgive others.
     9  **    May you share freely, never taking more than you give.
    10  **
    11  *************************************************************************
    12  ** This file contains C code routines that are called by the parser
    13  ** to handle INSERT statements in SQLite.
    14  */
    15  #include "sqliteInt.h"
    16  
    17  /*
    18  ** Generate code that will 
    19  **
    20  **   (1) acquire a lock for table pTab then
    21  **   (2) open pTab as cursor iCur.
    22  **
    23  ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
    24  ** for that table that is actually opened.
    25  */
    26  void sqlite3OpenTable(
    27    Parse *pParse,  /* Generate code into this VDBE */
    28    int iCur,       /* The cursor number of the table */
    29    int iDb,        /* The database index in sqlite3.aDb[] */
    30    Table *pTab,    /* The table to be opened */
    31    int opcode      /* OP_OpenRead or OP_OpenWrite */
    32  ){
    33    Vdbe *v;
    34    assert( !IsVirtual(pTab) );
    35    v = sqlite3GetVdbe(pParse);
    36    assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
    37    sqlite3TableLock(pParse, iDb, pTab->tnum, 
    38                     (opcode==OP_OpenWrite)?1:0, pTab->zName);
    39    if( HasRowid(pTab) ){
    40      sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
    41      VdbeComment((v, "%s", pTab->zName));
    42    }else{
    43      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
    44      assert( pPk!=0 );
    45      assert( pPk->tnum==pTab->tnum );
    46      sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
    47      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
    48      VdbeComment((v, "%s", pTab->zName));
    49    }
    50  }
    51  
    52  /*
    53  ** Return a pointer to the column affinity string associated with index
    54  ** pIdx. A column affinity string has one character for each column in 
    55  ** the table, according to the affinity of the column:
    56  **
    57  **  Character      Column affinity
    58  **  ------------------------------
    59  **  'A'            BLOB
    60  **  'B'            TEXT
    61  **  'C'            NUMERIC
    62  **  'D'            INTEGER
    63  **  'F'            REAL
    64  **
    65  ** An extra 'D' is appended to the end of the string to cover the
    66  ** rowid that appears as the last column in every index.
    67  **
    68  ** Memory for the buffer containing the column index affinity string
    69  ** is managed along with the rest of the Index structure. It will be
    70  ** released when sqlite3DeleteIndex() is called.
    71  */
    72  const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
    73    if( !pIdx->zColAff ){
    74      /* The first time a column affinity string for a particular index is
    75      ** required, it is allocated and populated here. It is then stored as
    76      ** a member of the Index structure for subsequent use.
    77      **
    78      ** The column affinity string will eventually be deleted by
    79      ** sqliteDeleteIndex() when the Index structure itself is cleaned
    80      ** up.
    81      */
    82      int n;
    83      Table *pTab = pIdx->pTable;
    84      pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
    85      if( !pIdx->zColAff ){
    86        sqlite3OomFault(db);
    87        return 0;
    88      }
    89      for(n=0; n<pIdx->nColumn; n++){
    90        i16 x = pIdx->aiColumn[n];
    91        if( x>=0 ){
    92          pIdx->zColAff[n] = pTab->aCol[x].affinity;
    93        }else if( x==XN_ROWID ){
    94          pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
    95        }else{
    96          char aff;
    97          assert( x==XN_EXPR );
    98          assert( pIdx->aColExpr!=0 );
    99          aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
   100          if( aff==0 ) aff = SQLITE_AFF_BLOB;
   101          pIdx->zColAff[n] = aff;
   102        }
   103      }
   104      pIdx->zColAff[n] = 0;
   105    }
   106   
   107    return pIdx->zColAff;
   108  }
   109  
   110  /*
   111  ** Compute the affinity string for table pTab, if it has not already been
   112  ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
   113  **
   114  ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
   115  ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
   116  ** for register iReg and following.  Or if affinities exists and iReg==0,
   117  ** then just set the P4 operand of the previous opcode (which should  be
   118  ** an OP_MakeRecord) to the affinity string.
   119  **
   120  ** A column affinity string has one character per column:
   121  **
   122  **  Character      Column affinity
   123  **  ------------------------------
   124  **  'A'            BLOB
   125  **  'B'            TEXT
   126  **  'C'            NUMERIC
   127  **  'D'            INTEGER
   128  **  'E'            REAL
   129  */
   130  void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
   131    int i;
   132    char *zColAff = pTab->zColAff;
   133    if( zColAff==0 ){
   134      sqlite3 *db = sqlite3VdbeDb(v);
   135      zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
   136      if( !zColAff ){
   137        sqlite3OomFault(db);
   138        return;
   139      }
   140  
   141      for(i=0; i<pTab->nCol; i++){
   142        zColAff[i] = pTab->aCol[i].affinity;
   143      }
   144      do{
   145        zColAff[i--] = 0;
   146      }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
   147      pTab->zColAff = zColAff;
   148    }
   149    i = sqlite3Strlen30(zColAff);
   150    if( i ){
   151      if( iReg ){
   152        sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
   153      }else{
   154        sqlite3VdbeChangeP4(v, -1, zColAff, i);
   155      }
   156    }
   157  }
   158  
   159  /*
   160  ** Return non-zero if the table pTab in database iDb or any of its indices
   161  ** have been opened at any point in the VDBE program. This is used to see if 
   162  ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
   163  ** run without using a temporary table for the results of the SELECT. 
   164  */
   165  static int readsTable(Parse *p, int iDb, Table *pTab){
   166    Vdbe *v = sqlite3GetVdbe(p);
   167    int i;
   168    int iEnd = sqlite3VdbeCurrentAddr(v);
   169  #ifndef SQLITE_OMIT_VIRTUALTABLE
   170    VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
   171  #endif
   172  
   173    for(i=1; i<iEnd; i++){
   174      VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
   175      assert( pOp!=0 );
   176      if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
   177        Index *pIndex;
   178        int tnum = pOp->p2;
   179        if( tnum==pTab->tnum ){
   180          return 1;
   181        }
   182        for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   183          if( tnum==pIndex->tnum ){
   184            return 1;
   185          }
   186        }
   187      }
   188  #ifndef SQLITE_OMIT_VIRTUALTABLE
   189      if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
   190        assert( pOp->p4.pVtab!=0 );
   191        assert( pOp->p4type==P4_VTAB );
   192        return 1;
   193      }
   194  #endif
   195    }
   196    return 0;
   197  }
   198  
   199  #ifndef SQLITE_OMIT_AUTOINCREMENT
   200  /*
   201  ** Locate or create an AutoincInfo structure associated with table pTab
   202  ** which is in database iDb.  Return the register number for the register
   203  ** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
   204  ** table.  (Also return zero when doing a VACUUM since we do not want to
   205  ** update the AUTOINCREMENT counters during a VACUUM.)
   206  **
   207  ** There is at most one AutoincInfo structure per table even if the
   208  ** same table is autoincremented multiple times due to inserts within
   209  ** triggers.  A new AutoincInfo structure is created if this is the
   210  ** first use of table pTab.  On 2nd and subsequent uses, the original
   211  ** AutoincInfo structure is used.
   212  **
   213  ** Three memory locations are allocated:
   214  **
   215  **   (1)  Register to hold the name of the pTab table.
   216  **   (2)  Register to hold the maximum ROWID of pTab.
   217  **   (3)  Register to hold the rowid in sqlite_sequence of pTab
   218  **
   219  ** The 2nd register is the one that is returned.  That is all the
   220  ** insert routine needs to know about.
   221  */
   222  static int autoIncBegin(
   223    Parse *pParse,      /* Parsing context */
   224    int iDb,            /* Index of the database holding pTab */
   225    Table *pTab         /* The table we are writing to */
   226  ){
   227    int memId = 0;      /* Register holding maximum rowid */
   228    if( (pTab->tabFlags & TF_Autoincrement)!=0
   229     && (pParse->db->flags & SQLITE_Vacuum)==0
   230    ){
   231      Parse *pToplevel = sqlite3ParseToplevel(pParse);
   232      AutoincInfo *pInfo;
   233  
   234      pInfo = pToplevel->pAinc;
   235      while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
   236      if( pInfo==0 ){
   237        pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
   238        if( pInfo==0 ) return 0;
   239        pInfo->pNext = pToplevel->pAinc;
   240        pToplevel->pAinc = pInfo;
   241        pInfo->pTab = pTab;
   242        pInfo->iDb = iDb;
   243        pToplevel->nMem++;                  /* Register to hold name of table */
   244        pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
   245        pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
   246      }
   247      memId = pInfo->regCtr;
   248    }
   249    return memId;
   250  }
   251  
   252  /*
   253  ** This routine generates code that will initialize all of the
   254  ** register used by the autoincrement tracker.  
   255  */
   256  void sqlite3AutoincrementBegin(Parse *pParse){
   257    AutoincInfo *p;            /* Information about an AUTOINCREMENT */
   258    sqlite3 *db = pParse->db;  /* The database connection */
   259    Db *pDb;                   /* Database only autoinc table */
   260    int memId;                 /* Register holding max rowid */
   261    Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
   262  
   263    /* This routine is never called during trigger-generation.  It is
   264    ** only called from the top-level */
   265    assert( pParse->pTriggerTab==0 );
   266    assert( sqlite3IsToplevel(pParse) );
   267  
   268    assert( v );   /* We failed long ago if this is not so */
   269    for(p = pParse->pAinc; p; p = p->pNext){
   270      static const int iLn = VDBE_OFFSET_LINENO(2);
   271      static const VdbeOpList autoInc[] = {
   272        /* 0  */ {OP_Null,    0,  0, 0},
   273        /* 1  */ {OP_Rewind,  0,  9, 0},
   274        /* 2  */ {OP_Column,  0,  0, 0},
   275        /* 3  */ {OP_Ne,      0,  7, 0},
   276        /* 4  */ {OP_Rowid,   0,  0, 0},
   277        /* 5  */ {OP_Column,  0,  1, 0},
   278        /* 6  */ {OP_Goto,    0,  9, 0},
   279        /* 7  */ {OP_Next,    0,  2, 0},
   280        /* 8  */ {OP_Integer, 0,  0, 0},
   281        /* 9  */ {OP_Close,   0,  0, 0} 
   282      };
   283      VdbeOp *aOp;
   284      pDb = &db->aDb[p->iDb];
   285      memId = p->regCtr;
   286      assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   287      sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
   288      sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
   289      aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
   290      if( aOp==0 ) break;
   291      aOp[0].p2 = memId;
   292      aOp[0].p3 = memId+1;
   293      aOp[2].p3 = memId;
   294      aOp[3].p1 = memId-1;
   295      aOp[3].p3 = memId;
   296      aOp[3].p5 = SQLITE_JUMPIFNULL;
   297      aOp[4].p2 = memId+1;
   298      aOp[5].p3 = memId;
   299      aOp[8].p2 = memId;
   300    }
   301  }
   302  
   303  /*
   304  ** Update the maximum rowid for an autoincrement calculation.
   305  **
   306  ** This routine should be called when the regRowid register holds a
   307  ** new rowid that is about to be inserted.  If that new rowid is
   308  ** larger than the maximum rowid in the memId memory cell, then the
   309  ** memory cell is updated.
   310  */
   311  static void autoIncStep(Parse *pParse, int memId, int regRowid){
   312    if( memId>0 ){
   313      sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
   314    }
   315  }
   316  
   317  /*
   318  ** This routine generates the code needed to write autoincrement
   319  ** maximum rowid values back into the sqlite_sequence register.
   320  ** Every statement that might do an INSERT into an autoincrement
   321  ** table (either directly or through triggers) needs to call this
   322  ** routine just before the "exit" code.
   323  */
   324  static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
   325    AutoincInfo *p;
   326    Vdbe *v = pParse->pVdbe;
   327    sqlite3 *db = pParse->db;
   328  
   329    assert( v );
   330    for(p = pParse->pAinc; p; p = p->pNext){
   331      static const int iLn = VDBE_OFFSET_LINENO(2);
   332      static const VdbeOpList autoIncEnd[] = {
   333        /* 0 */ {OP_NotNull,     0, 2, 0},
   334        /* 1 */ {OP_NewRowid,    0, 0, 0},
   335        /* 2 */ {OP_MakeRecord,  0, 2, 0},
   336        /* 3 */ {OP_Insert,      0, 0, 0},
   337        /* 4 */ {OP_Close,       0, 0, 0}
   338      };
   339      VdbeOp *aOp;
   340      Db *pDb = &db->aDb[p->iDb];
   341      int iRec;
   342      int memId = p->regCtr;
   343  
   344      iRec = sqlite3GetTempReg(pParse);
   345      assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   346      sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
   347      aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
   348      if( aOp==0 ) break;
   349      aOp[0].p1 = memId+1;
   350      aOp[1].p2 = memId+1;
   351      aOp[2].p1 = memId-1;
   352      aOp[2].p3 = iRec;
   353      aOp[3].p2 = iRec;
   354      aOp[3].p3 = memId+1;
   355      aOp[3].p5 = OPFLAG_APPEND;
   356      sqlite3ReleaseTempReg(pParse, iRec);
   357    }
   358  }
   359  void sqlite3AutoincrementEnd(Parse *pParse){
   360    if( pParse->pAinc ) autoIncrementEnd(pParse);
   361  }
   362  #else
   363  /*
   364  ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
   365  ** above are all no-ops
   366  */
   367  # define autoIncBegin(A,B,C) (0)
   368  # define autoIncStep(A,B,C)
   369  #endif /* SQLITE_OMIT_AUTOINCREMENT */
   370  
   371  
   372  /* Forward declaration */
   373  static int xferOptimization(
   374    Parse *pParse,        /* Parser context */
   375    Table *pDest,         /* The table we are inserting into */
   376    Select *pSelect,      /* A SELECT statement to use as the data source */
   377    int onError,          /* How to handle constraint errors */
   378    int iDbDest           /* The database of pDest */
   379  );
   380  
   381  /*
   382  ** This routine is called to handle SQL of the following forms:
   383  **
   384  **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
   385  **    insert into TABLE (IDLIST) select
   386  **    insert into TABLE (IDLIST) default values
   387  **
   388  ** The IDLIST following the table name is always optional.  If omitted,
   389  ** then a list of all (non-hidden) columns for the table is substituted.
   390  ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
   391  ** is omitted.
   392  **
   393  ** For the pSelect parameter holds the values to be inserted for the
   394  ** first two forms shown above.  A VALUES clause is really just short-hand
   395  ** for a SELECT statement that omits the FROM clause and everything else
   396  ** that follows.  If the pSelect parameter is NULL, that means that the
   397  ** DEFAULT VALUES form of the INSERT statement is intended.
   398  **
   399  ** The code generated follows one of four templates.  For a simple
   400  ** insert with data coming from a single-row VALUES clause, the code executes
   401  ** once straight down through.  Pseudo-code follows (we call this
   402  ** the "1st template"):
   403  **
   404  **         open write cursor to <table> and its indices
   405  **         put VALUES clause expressions into registers
   406  **         write the resulting record into <table>
   407  **         cleanup
   408  **
   409  ** The three remaining templates assume the statement is of the form
   410  **
   411  **   INSERT INTO <table> SELECT ...
   412  **
   413  ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
   414  ** in other words if the SELECT pulls all columns from a single table
   415  ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
   416  ** if <table2> and <table1> are distinct tables but have identical
   417  ** schemas, including all the same indices, then a special optimization
   418  ** is invoked that copies raw records from <table2> over to <table1>.
   419  ** See the xferOptimization() function for the implementation of this
   420  ** template.  This is the 2nd template.
   421  **
   422  **         open a write cursor to <table>
   423  **         open read cursor on <table2>
   424  **         transfer all records in <table2> over to <table>
   425  **         close cursors
   426  **         foreach index on <table>
   427  **           open a write cursor on the <table> index
   428  **           open a read cursor on the corresponding <table2> index
   429  **           transfer all records from the read to the write cursors
   430  **           close cursors
   431  **         end foreach
   432  **
   433  ** The 3rd template is for when the second template does not apply
   434  ** and the SELECT clause does not read from <table> at any time.
   435  ** The generated code follows this template:
   436  **
   437  **         X <- A
   438  **         goto B
   439  **      A: setup for the SELECT
   440  **         loop over the rows in the SELECT
   441  **           load values into registers R..R+n
   442  **           yield X
   443  **         end loop
   444  **         cleanup after the SELECT
   445  **         end-coroutine X
   446  **      B: open write cursor to <table> and its indices
   447  **      C: yield X, at EOF goto D
   448  **         insert the select result into <table> from R..R+n
   449  **         goto C
   450  **      D: cleanup
   451  **
   452  ** The 4th template is used if the insert statement takes its
   453  ** values from a SELECT but the data is being inserted into a table
   454  ** that is also read as part of the SELECT.  In the third form,
   455  ** we have to use an intermediate table to store the results of
   456  ** the select.  The template is like this:
   457  **
   458  **         X <- A
   459  **         goto B
   460  **      A: setup for the SELECT
   461  **         loop over the tables in the SELECT
   462  **           load value into register R..R+n
   463  **           yield X
   464  **         end loop
   465  **         cleanup after the SELECT
   466  **         end co-routine R
   467  **      B: open temp table
   468  **      L: yield X, at EOF goto M
   469  **         insert row from R..R+n into temp table
   470  **         goto L
   471  **      M: open write cursor to <table> and its indices
   472  **         rewind temp table
   473  **      C: loop over rows of intermediate table
   474  **           transfer values form intermediate table into <table>
   475  **         end loop
   476  **      D: cleanup
   477  */
   478  void sqlite3Insert(
   479    Parse *pParse,        /* Parser context */
   480    SrcList *pTabList,    /* Name of table into which we are inserting */
   481    Select *pSelect,      /* A SELECT statement to use as the data source */
   482    IdList *pColumn,      /* Column names corresponding to IDLIST. */
   483    int onError           /* How to handle constraint errors */
   484  ){
   485    sqlite3 *db;          /* The main database structure */
   486    Table *pTab;          /* The table to insert into.  aka TABLE */
   487    char *zTab;           /* Name of the table into which we are inserting */
   488    int i, j;             /* Loop counters */
   489    Vdbe *v;              /* Generate code into this virtual machine */
   490    Index *pIdx;          /* For looping over indices of the table */
   491    int nColumn;          /* Number of columns in the data */
   492    int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
   493    int iDataCur = 0;     /* VDBE cursor that is the main data repository */
   494    int iIdxCur = 0;      /* First index cursor */
   495    int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
   496    int endOfLoop;        /* Label for the end of the insertion loop */
   497    int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
   498    int addrInsTop = 0;   /* Jump to label "D" */
   499    int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
   500    SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
   501    int iDb;              /* Index of database holding TABLE */
   502    u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
   503    u8 appendFlag = 0;    /* True if the insert is likely to be an append */
   504    u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
   505    u8 bIdListInOrder;    /* True if IDLIST is in table order */
   506    ExprList *pList = 0;  /* List of VALUES() to be inserted  */
   507  
   508    /* Register allocations */
   509    int regFromSelect = 0;/* Base register for data coming from SELECT */
   510    int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
   511    int regRowCount = 0;  /* Memory cell used for the row counter */
   512    int regIns;           /* Block of regs holding rowid+data being inserted */
   513    int regRowid;         /* registers holding insert rowid */
   514    int regData;          /* register holding first column to insert */
   515    int *aRegIdx = 0;     /* One register allocated to each index */
   516  
   517  #ifndef SQLITE_OMIT_TRIGGER
   518    int isView;                 /* True if attempting to insert into a view */
   519    Trigger *pTrigger;          /* List of triggers on pTab, if required */
   520    int tmask;                  /* Mask of trigger times */
   521  #endif
   522  
   523    db = pParse->db;
   524    memset(&dest, 0, sizeof(dest));
   525    if( pParse->nErr || db->mallocFailed ){
   526      goto insert_cleanup;
   527    }
   528  
   529    /* If the Select object is really just a simple VALUES() list with a
   530    ** single row (the common case) then keep that one row of values
   531    ** and discard the other (unused) parts of the pSelect object
   532    */
   533    if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
   534      pList = pSelect->pEList;
   535      pSelect->pEList = 0;
   536      sqlite3SelectDelete(db, pSelect);
   537      pSelect = 0;
   538    }
   539  
   540    /* Locate the table into which we will be inserting new information.
   541    */
   542    assert( pTabList->nSrc==1 );
   543    zTab = pTabList->a[0].zName;
   544    if( NEVER(zTab==0) ) goto insert_cleanup;
   545    pTab = sqlite3SrcListLookup(pParse, pTabList);
   546    if( pTab==0 ){
   547      goto insert_cleanup;
   548    }
   549    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   550    assert( iDb<db->nDb );
   551    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
   552                         db->aDb[iDb].zDbSName) ){
   553      goto insert_cleanup;
   554    }
   555    withoutRowid = !HasRowid(pTab);
   556  
   557    /* Figure out if we have any triggers and if the table being
   558    ** inserted into is a view
   559    */
   560  #ifndef SQLITE_OMIT_TRIGGER
   561    pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
   562    isView = pTab->pSelect!=0;
   563  #else
   564  # define pTrigger 0
   565  # define tmask 0
   566  # define isView 0
   567  #endif
   568  #ifdef SQLITE_OMIT_VIEW
   569  # undef isView
   570  # define isView 0
   571  #endif
   572    assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
   573  
   574    /* If pTab is really a view, make sure it has been initialized.
   575    ** ViewGetColumnNames() is a no-op if pTab is not a view.
   576    */
   577    if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   578      goto insert_cleanup;
   579    }
   580  
   581    /* Cannot insert into a read-only table.
   582    */
   583    if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   584      goto insert_cleanup;
   585    }
   586  
   587    /* Allocate a VDBE
   588    */
   589    v = sqlite3GetVdbe(pParse);
   590    if( v==0 ) goto insert_cleanup;
   591    if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   592    sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
   593  
   594  #ifndef SQLITE_OMIT_XFER_OPT
   595    /* If the statement is of the form
   596    **
   597    **       INSERT INTO <table1> SELECT * FROM <table2>;
   598    **
   599    ** Then special optimizations can be applied that make the transfer
   600    ** very fast and which reduce fragmentation of indices.
   601    **
   602    ** This is the 2nd template.
   603    */
   604    if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
   605      assert( !pTrigger );
   606      assert( pList==0 );
   607      goto insert_end;
   608    }
   609  #endif /* SQLITE_OMIT_XFER_OPT */
   610  
   611    /* If this is an AUTOINCREMENT table, look up the sequence number in the
   612    ** sqlite_sequence table and store it in memory cell regAutoinc.
   613    */
   614    regAutoinc = autoIncBegin(pParse, iDb, pTab);
   615  
   616    /* Allocate registers for holding the rowid of the new row,
   617    ** the content of the new row, and the assembled row record.
   618    */
   619    regRowid = regIns = pParse->nMem+1;
   620    pParse->nMem += pTab->nCol + 1;
   621    if( IsVirtual(pTab) ){
   622      regRowid++;
   623      pParse->nMem++;
   624    }
   625    regData = regRowid+1;
   626  
   627    /* If the INSERT statement included an IDLIST term, then make sure
   628    ** all elements of the IDLIST really are columns of the table and 
   629    ** remember the column indices.
   630    **
   631    ** If the table has an INTEGER PRIMARY KEY column and that column
   632    ** is named in the IDLIST, then record in the ipkColumn variable
   633    ** the index into IDLIST of the primary key column.  ipkColumn is
   634    ** the index of the primary key as it appears in IDLIST, not as
   635    ** is appears in the original table.  (The index of the INTEGER
   636    ** PRIMARY KEY in the original table is pTab->iPKey.)
   637    */
   638    bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
   639    if( pColumn ){
   640      for(i=0; i<pColumn->nId; i++){
   641        pColumn->a[i].idx = -1;
   642      }
   643      for(i=0; i<pColumn->nId; i++){
   644        for(j=0; j<pTab->nCol; j++){
   645          if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
   646            pColumn->a[i].idx = j;
   647            if( i!=j ) bIdListInOrder = 0;
   648            if( j==pTab->iPKey ){
   649              ipkColumn = i;  assert( !withoutRowid );
   650            }
   651            break;
   652          }
   653        }
   654        if( j>=pTab->nCol ){
   655          if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
   656            ipkColumn = i;
   657            bIdListInOrder = 0;
   658          }else{
   659            sqlite3ErrorMsg(pParse, "table %S has no column named %s",
   660                pTabList, 0, pColumn->a[i].zName);
   661            pParse->checkSchema = 1;
   662            goto insert_cleanup;
   663          }
   664        }
   665      }
   666    }
   667  
   668    /* Figure out how many columns of data are supplied.  If the data
   669    ** is coming from a SELECT statement, then generate a co-routine that
   670    ** produces a single row of the SELECT on each invocation.  The
   671    ** co-routine is the common header to the 3rd and 4th templates.
   672    */
   673    if( pSelect ){
   674      /* Data is coming from a SELECT or from a multi-row VALUES clause.
   675      ** Generate a co-routine to run the SELECT. */
   676      int regYield;       /* Register holding co-routine entry-point */
   677      int addrTop;        /* Top of the co-routine */
   678      int rc;             /* Result code */
   679  
   680      regYield = ++pParse->nMem;
   681      addrTop = sqlite3VdbeCurrentAddr(v) + 1;
   682      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
   683      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
   684      dest.iSdst = bIdListInOrder ? regData : 0;
   685      dest.nSdst = pTab->nCol;
   686      rc = sqlite3Select(pParse, pSelect, &dest);
   687      regFromSelect = dest.iSdst;
   688      if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
   689      sqlite3VdbeEndCoroutine(v, regYield);
   690      sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
   691      assert( pSelect->pEList );
   692      nColumn = pSelect->pEList->nExpr;
   693  
   694      /* Set useTempTable to TRUE if the result of the SELECT statement
   695      ** should be written into a temporary table (template 4).  Set to
   696      ** FALSE if each output row of the SELECT can be written directly into
   697      ** the destination table (template 3).
   698      **
   699      ** A temp table must be used if the table being updated is also one
   700      ** of the tables being read by the SELECT statement.  Also use a 
   701      ** temp table in the case of row triggers.
   702      */
   703      if( pTrigger || readsTable(pParse, iDb, pTab) ){
   704        useTempTable = 1;
   705      }
   706  
   707      if( useTempTable ){
   708        /* Invoke the coroutine to extract information from the SELECT
   709        ** and add it to a transient table srcTab.  The code generated
   710        ** here is from the 4th template:
   711        **
   712        **      B: open temp table
   713        **      L: yield X, goto M at EOF
   714        **         insert row from R..R+n into temp table
   715        **         goto L
   716        **      M: ...
   717        */
   718        int regRec;          /* Register to hold packed record */
   719        int regTempRowid;    /* Register to hold temp table ROWID */
   720        int addrL;           /* Label "L" */
   721  
   722        srcTab = pParse->nTab++;
   723        regRec = sqlite3GetTempReg(pParse);
   724        regTempRowid = sqlite3GetTempReg(pParse);
   725        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
   726        addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
   727        sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
   728        sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
   729        sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
   730        sqlite3VdbeGoto(v, addrL);
   731        sqlite3VdbeJumpHere(v, addrL);
   732        sqlite3ReleaseTempReg(pParse, regRec);
   733        sqlite3ReleaseTempReg(pParse, regTempRowid);
   734      }
   735    }else{
   736      /* This is the case if the data for the INSERT is coming from a 
   737      ** single-row VALUES clause
   738      */
   739      NameContext sNC;
   740      memset(&sNC, 0, sizeof(sNC));
   741      sNC.pParse = pParse;
   742      srcTab = -1;
   743      assert( useTempTable==0 );
   744      if( pList ){
   745        nColumn = pList->nExpr;
   746        if( sqlite3ResolveExprListNames(&sNC, pList) ){
   747          goto insert_cleanup;
   748        }
   749      }else{
   750        nColumn = 0;
   751      }
   752    }
   753  
   754    /* If there is no IDLIST term but the table has an integer primary
   755    ** key, the set the ipkColumn variable to the integer primary key 
   756    ** column index in the original table definition.
   757    */
   758    if( pColumn==0 && nColumn>0 ){
   759      ipkColumn = pTab->iPKey;
   760    }
   761  
   762    /* Make sure the number of columns in the source data matches the number
   763    ** of columns to be inserted into the table.
   764    */
   765    for(i=0; i<pTab->nCol; i++){
   766      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
   767    }
   768    if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
   769      sqlite3ErrorMsg(pParse, 
   770         "table %S has %d columns but %d values were supplied",
   771         pTabList, 0, pTab->nCol-nHidden, nColumn);
   772      goto insert_cleanup;
   773    }
   774    if( pColumn!=0 && nColumn!=pColumn->nId ){
   775      sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
   776      goto insert_cleanup;
   777    }
   778      
   779    /* Initialize the count of rows to be inserted
   780    */
   781    if( db->flags & SQLITE_CountRows ){
   782      regRowCount = ++pParse->nMem;
   783      sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   784    }
   785  
   786    /* If this is not a view, open the table and and all indices */
   787    if( !isView ){
   788      int nIdx;
   789      nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
   790                                        &iDataCur, &iIdxCur);
   791      aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
   792      if( aRegIdx==0 ){
   793        goto insert_cleanup;
   794      }
   795      for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
   796        assert( pIdx );
   797        aRegIdx[i] = ++pParse->nMem;
   798        pParse->nMem += pIdx->nColumn;
   799      }
   800    }
   801  
   802    /* This is the top of the main insertion loop */
   803    if( useTempTable ){
   804      /* This block codes the top of loop only.  The complete loop is the
   805      ** following pseudocode (template 4):
   806      **
   807      **         rewind temp table, if empty goto D
   808      **      C: loop over rows of intermediate table
   809      **           transfer values form intermediate table into <table>
   810      **         end loop
   811      **      D: ...
   812      */
   813      addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
   814      addrCont = sqlite3VdbeCurrentAddr(v);
   815    }else if( pSelect ){
   816      /* This block codes the top of loop only.  The complete loop is the
   817      ** following pseudocode (template 3):
   818      **
   819      **      C: yield X, at EOF goto D
   820      **         insert the select result into <table> from R..R+n
   821      **         goto C
   822      **      D: ...
   823      */
   824      addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
   825      VdbeCoverage(v);
   826    }
   827  
   828    /* Run the BEFORE and INSTEAD OF triggers, if there are any
   829    */
   830    endOfLoop = sqlite3VdbeMakeLabel(v);
   831    if( tmask & TRIGGER_BEFORE ){
   832      int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
   833  
   834      /* build the NEW.* reference row.  Note that if there is an INTEGER
   835      ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
   836      ** translated into a unique ID for the row.  But on a BEFORE trigger,
   837      ** we do not know what the unique ID will be (because the insert has
   838      ** not happened yet) so we substitute a rowid of -1
   839      */
   840      if( ipkColumn<0 ){
   841        sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   842      }else{
   843        int addr1;
   844        assert( !withoutRowid );
   845        if( useTempTable ){
   846          sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
   847        }else{
   848          assert( pSelect==0 );  /* Otherwise useTempTable is true */
   849          sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
   850        }
   851        addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
   852        sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   853        sqlite3VdbeJumpHere(v, addr1);
   854        sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
   855      }
   856  
   857      /* Cannot have triggers on a virtual table. If it were possible,
   858      ** this block would have to account for hidden column.
   859      */
   860      assert( !IsVirtual(pTab) );
   861  
   862      /* Create the new column data
   863      */
   864      for(i=j=0; i<pTab->nCol; i++){
   865        if( pColumn ){
   866          for(j=0; j<pColumn->nId; j++){
   867            if( pColumn->a[j].idx==i ) break;
   868          }
   869        }
   870        if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
   871              || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
   872          sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
   873        }else if( useTempTable ){
   874          sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
   875        }else{
   876          assert( pSelect==0 ); /* Otherwise useTempTable is true */
   877          sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
   878        }
   879        if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
   880      }
   881  
   882      /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
   883      ** do not attempt any conversions before assembling the record.
   884      ** If this is a real table, attempt conversions as required by the
   885      ** table column affinities.
   886      */
   887      if( !isView ){
   888        sqlite3TableAffinity(v, pTab, regCols+1);
   889      }
   890  
   891      /* Fire BEFORE or INSTEAD OF triggers */
   892      sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
   893          pTab, regCols-pTab->nCol-1, onError, endOfLoop);
   894  
   895      sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
   896    }
   897  
   898    /* Compute the content of the next row to insert into a range of
   899    ** registers beginning at regIns.
   900    */
   901    if( !isView ){
   902      if( IsVirtual(pTab) ){
   903        /* The row that the VUpdate opcode will delete: none */
   904        sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
   905      }
   906      if( ipkColumn>=0 ){
   907        if( useTempTable ){
   908          sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
   909        }else if( pSelect ){
   910          sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
   911        }else{
   912          VdbeOp *pOp;
   913          sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
   914          pOp = sqlite3VdbeGetOp(v, -1);
   915          if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
   916            appendFlag = 1;
   917            pOp->opcode = OP_NewRowid;
   918            pOp->p1 = iDataCur;
   919            pOp->p2 = regRowid;
   920            pOp->p3 = regAutoinc;
   921          }
   922        }
   923        /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
   924        ** to generate a unique primary key value.
   925        */
   926        if( !appendFlag ){
   927          int addr1;
   928          if( !IsVirtual(pTab) ){
   929            addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
   930            sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
   931            sqlite3VdbeJumpHere(v, addr1);
   932          }else{
   933            addr1 = sqlite3VdbeCurrentAddr(v);
   934            sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
   935          }
   936          sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
   937        }
   938      }else if( IsVirtual(pTab) || withoutRowid ){
   939        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
   940      }else{
   941        sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
   942        appendFlag = 1;
   943      }
   944      autoIncStep(pParse, regAutoinc, regRowid);
   945  
   946      /* Compute data for all columns of the new entry, beginning
   947      ** with the first column.
   948      */
   949      nHidden = 0;
   950      for(i=0; i<pTab->nCol; i++){
   951        int iRegStore = regRowid+1+i;
   952        if( i==pTab->iPKey ){
   953          /* The value of the INTEGER PRIMARY KEY column is always a NULL.
   954          ** Whenever this column is read, the rowid will be substituted
   955          ** in its place.  Hence, fill this column with a NULL to avoid
   956          ** taking up data space with information that will never be used.
   957          ** As there may be shallow copies of this value, make it a soft-NULL */
   958          sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
   959          continue;
   960        }
   961        if( pColumn==0 ){
   962          if( IsHiddenColumn(&pTab->aCol[i]) ){
   963            j = -1;
   964            nHidden++;
   965          }else{
   966            j = i - nHidden;
   967          }
   968        }else{
   969          for(j=0; j<pColumn->nId; j++){
   970            if( pColumn->a[j].idx==i ) break;
   971          }
   972        }
   973        if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
   974          sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
   975        }else if( useTempTable ){
   976          sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
   977        }else if( pSelect ){
   978          if( regFromSelect!=regData ){
   979            sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
   980          }
   981        }else{
   982          sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
   983        }
   984      }
   985  
   986      /* Generate code to check constraints and generate index keys and
   987      ** do the insertion.
   988      */
   989  #ifndef SQLITE_OMIT_VIRTUALTABLE
   990      if( IsVirtual(pTab) ){
   991        const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   992        sqlite3VtabMakeWritable(pParse, pTab);
   993        sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
   994        sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
   995        sqlite3MayAbort(pParse);
   996      }else
   997  #endif
   998      {
   999        int isReplace;    /* Set to true if constraints may cause a replace */
  1000        int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
  1001        sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  1002            regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
  1003        );
  1004        sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  1005  
  1006        /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
  1007        ** constraints or (b) there are no triggers and this table is not a
  1008        ** parent table in a foreign key constraint. It is safe to set the
  1009        ** flag in the second case as if any REPLACE constraint is hit, an
  1010        ** OP_Delete or OP_IdxDelete instruction will be executed on each 
  1011        ** cursor that is disturbed. And these instructions both clear the
  1012        ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
  1013        ** functionality.  */
  1014        bUseSeek = (isReplace==0 || (pTrigger==0 &&
  1015            ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
  1016        ));
  1017        sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  1018            regIns, aRegIdx, 0, appendFlag, bUseSeek
  1019        );
  1020      }
  1021    }
  1022  
  1023    /* Update the count of rows that are inserted
  1024    */
  1025    if( (db->flags & SQLITE_CountRows)!=0 ){
  1026      sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  1027    }
  1028  
  1029    if( pTrigger ){
  1030      /* Code AFTER triggers */
  1031      sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
  1032          pTab, regData-2-pTab->nCol, onError, endOfLoop);
  1033    }
  1034  
  1035    /* The bottom of the main insertion loop, if the data source
  1036    ** is a SELECT statement.
  1037    */
  1038    sqlite3VdbeResolveLabel(v, endOfLoop);
  1039    if( useTempTable ){
  1040      sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  1041      sqlite3VdbeJumpHere(v, addrInsTop);
  1042      sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  1043    }else if( pSelect ){
  1044      sqlite3VdbeGoto(v, addrCont);
  1045      sqlite3VdbeJumpHere(v, addrInsTop);
  1046    }
  1047  
  1048  insert_end:
  1049    /* Update the sqlite_sequence table by storing the content of the
  1050    ** maximum rowid counter values recorded while inserting into
  1051    ** autoincrement tables.
  1052    */
  1053    if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  1054      sqlite3AutoincrementEnd(pParse);
  1055    }
  1056  
  1057    /*
  1058    ** Return the number of rows inserted. If this routine is 
  1059    ** generating code because of a call to sqlite3NestedParse(), do not
  1060    ** invoke the callback function.
  1061    */
  1062    if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  1063      sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  1064      sqlite3VdbeSetNumCols(v, 1);
  1065      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  1066    }
  1067  
  1068  insert_cleanup:
  1069    sqlite3SrcListDelete(db, pTabList);
  1070    sqlite3ExprListDelete(db, pList);
  1071    sqlite3SelectDelete(db, pSelect);
  1072    sqlite3IdListDelete(db, pColumn);
  1073    sqlite3DbFree(db, aRegIdx);
  1074  }
  1075  
  1076  /* Make sure "isView" and other macros defined above are undefined. Otherwise
  1077  ** they may interfere with compilation of other functions in this file
  1078  ** (or in another file, if this file becomes part of the amalgamation).  */
  1079  #ifdef isView
  1080   #undef isView
  1081  #endif
  1082  #ifdef pTrigger
  1083   #undef pTrigger
  1084  #endif
  1085  #ifdef tmask
  1086   #undef tmask
  1087  #endif
  1088  
  1089  /*
  1090  ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
  1091  */
  1092  #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
  1093  #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
  1094  
  1095  /* This is the Walker callback from checkConstraintUnchanged().  Set
  1096  ** bit 0x01 of pWalker->eCode if
  1097  ** pWalker->eCode to 0 if this expression node references any of the
  1098  ** columns that are being modifed by an UPDATE statement.
  1099  */
  1100  static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
  1101    if( pExpr->op==TK_COLUMN ){
  1102      assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
  1103      if( pExpr->iColumn>=0 ){
  1104        if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
  1105          pWalker->eCode |= CKCNSTRNT_COLUMN;
  1106        }
  1107      }else{
  1108        pWalker->eCode |= CKCNSTRNT_ROWID;
  1109      }
  1110    }
  1111    return WRC_Continue;
  1112  }
  1113  
  1114  /*
  1115  ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
  1116  ** only columns that are modified by the UPDATE are those for which
  1117  ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
  1118  **
  1119  ** Return true if CHECK constraint pExpr does not use any of the
  1120  ** changing columns (or the rowid if it is changing).  In other words,
  1121  ** return true if this CHECK constraint can be skipped when validating
  1122  ** the new row in the UPDATE statement.
  1123  */
  1124  static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
  1125    Walker w;
  1126    memset(&w, 0, sizeof(w));
  1127    w.eCode = 0;
  1128    w.xExprCallback = checkConstraintExprNode;
  1129    w.u.aiCol = aiChng;
  1130    sqlite3WalkExpr(&w, pExpr);
  1131    if( !chngRowid ){
  1132      testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
  1133      w.eCode &= ~CKCNSTRNT_ROWID;
  1134    }
  1135    testcase( w.eCode==0 );
  1136    testcase( w.eCode==CKCNSTRNT_COLUMN );
  1137    testcase( w.eCode==CKCNSTRNT_ROWID );
  1138    testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
  1139    return !w.eCode;
  1140  }
  1141  
  1142  /*
  1143  ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  1144  ** on table pTab.
  1145  **
  1146  ** The regNewData parameter is the first register in a range that contains
  1147  ** the data to be inserted or the data after the update.  There will be
  1148  ** pTab->nCol+1 registers in this range.  The first register (the one
  1149  ** that regNewData points to) will contain the new rowid, or NULL in the
  1150  ** case of a WITHOUT ROWID table.  The second register in the range will
  1151  ** contain the content of the first table column.  The third register will
  1152  ** contain the content of the second table column.  And so forth.
  1153  **
  1154  ** The regOldData parameter is similar to regNewData except that it contains
  1155  ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
  1156  ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
  1157  ** checking regOldData for zero.
  1158  **
  1159  ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  1160  ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  1161  ** might be modified by the UPDATE.  If pkChng is false, then the key of
  1162  ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  1163  **
  1164  ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  1165  ** was explicitly specified as part of the INSERT statement.  If pkChng
  1166  ** is zero, it means that the either rowid is computed automatically or
  1167  ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
  1168  ** pkChng will only be true if the INSERT statement provides an integer
  1169  ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  1170  **
  1171  ** The code generated by this routine will store new index entries into
  1172  ** registers identified by aRegIdx[].  No index entry is created for
  1173  ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
  1174  ** the same as the order of indices on the linked list of indices
  1175  ** at pTab->pIndex.
  1176  **
  1177  ** The caller must have already opened writeable cursors on the main
  1178  ** table and all applicable indices (that is to say, all indices for which
  1179  ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
  1180  ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  1181  ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
  1182  ** for the first index in the pTab->pIndex list.  Cursors for other indices
  1183  ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  1184  **
  1185  ** This routine also generates code to check constraints.  NOT NULL,
  1186  ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
  1187  ** then the appropriate action is performed.  There are five possible
  1188  ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  1189  **
  1190  **  Constraint type  Action       What Happens
  1191  **  ---------------  ----------   ----------------------------------------
  1192  **  any              ROLLBACK     The current transaction is rolled back and
  1193  **                                sqlite3_step() returns immediately with a
  1194  **                                return code of SQLITE_CONSTRAINT.
  1195  **
  1196  **  any              ABORT        Back out changes from the current command
  1197  **                                only (do not do a complete rollback) then
  1198  **                                cause sqlite3_step() to return immediately
  1199  **                                with SQLITE_CONSTRAINT.
  1200  **
  1201  **  any              FAIL         Sqlite3_step() returns immediately with a
  1202  **                                return code of SQLITE_CONSTRAINT.  The
  1203  **                                transaction is not rolled back and any
  1204  **                                changes to prior rows are retained.
  1205  **
  1206  **  any              IGNORE       The attempt in insert or update the current
  1207  **                                row is skipped, without throwing an error.
  1208  **                                Processing continues with the next row.
  1209  **                                (There is an immediate jump to ignoreDest.)
  1210  **
  1211  **  NOT NULL         REPLACE      The NULL value is replace by the default
  1212  **                                value for that column.  If the default value
  1213  **                                is NULL, the action is the same as ABORT.
  1214  **
  1215  **  UNIQUE           REPLACE      The other row that conflicts with the row
  1216  **                                being inserted is removed.
  1217  **
  1218  **  CHECK            REPLACE      Illegal.  The results in an exception.
  1219  **
  1220  ** Which action to take is determined by the overrideError parameter.
  1221  ** Or if overrideError==OE_Default, then the pParse->onError parameter
  1222  ** is used.  Or if pParse->onError==OE_Default then the onError value
  1223  ** for the constraint is used.
  1224  */
  1225  void sqlite3GenerateConstraintChecks(
  1226    Parse *pParse,       /* The parser context */
  1227    Table *pTab,         /* The table being inserted or updated */
  1228    int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
  1229    int iDataCur,        /* Canonical data cursor (main table or PK index) */
  1230    int iIdxCur,         /* First index cursor */
  1231    int regNewData,      /* First register in a range holding values to insert */
  1232    int regOldData,      /* Previous content.  0 for INSERTs */
  1233    u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
  1234    u8 overrideError,    /* Override onError to this if not OE_Default */
  1235    int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
  1236    int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
  1237    int *aiChng          /* column i is unchanged if aiChng[i]<0 */
  1238  ){
  1239    Vdbe *v;             /* VDBE under constrution */
  1240    Index *pIdx;         /* Pointer to one of the indices */
  1241    Index *pPk = 0;      /* The PRIMARY KEY index */
  1242    sqlite3 *db;         /* Database connection */
  1243    int i;               /* loop counter */
  1244    int ix;              /* Index loop counter */
  1245    int nCol;            /* Number of columns */
  1246    int onError;         /* Conflict resolution strategy */
  1247    int addr1;           /* Address of jump instruction */
  1248    int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  1249    int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  1250    int ipkTop = 0;      /* Top of the rowid change constraint check */
  1251    int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
  1252    u8 isUpdate;         /* True if this is an UPDATE operation */
  1253    u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
  1254  
  1255    isUpdate = regOldData!=0;
  1256    db = pParse->db;
  1257    v = sqlite3GetVdbe(pParse);
  1258    assert( v!=0 );
  1259    assert( pTab->pSelect==0 );  /* This table is not a VIEW */
  1260    nCol = pTab->nCol;
  1261    
  1262    /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  1263    ** normal rowid tables.  nPkField is the number of key fields in the 
  1264    ** pPk index or 1 for a rowid table.  In other words, nPkField is the
  1265    ** number of fields in the true primary key of the table. */
  1266    if( HasRowid(pTab) ){
  1267      pPk = 0;
  1268      nPkField = 1;
  1269    }else{
  1270      pPk = sqlite3PrimaryKeyIndex(pTab);
  1271      nPkField = pPk->nKeyCol;
  1272    }
  1273  
  1274    /* Record that this module has started */
  1275    VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  1276                       iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  1277  
  1278    /* Test all NOT NULL constraints.
  1279    */
  1280    for(i=0; i<nCol; i++){
  1281      if( i==pTab->iPKey ){
  1282        continue;        /* ROWID is never NULL */
  1283      }
  1284      if( aiChng && aiChng[i]<0 ){
  1285        /* Don't bother checking for NOT NULL on columns that do not change */
  1286        continue;
  1287      }
  1288      onError = pTab->aCol[i].notNull;
  1289      if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
  1290      if( overrideError!=OE_Default ){
  1291        onError = overrideError;
  1292      }else if( onError==OE_Default ){
  1293        onError = OE_Abort;
  1294      }
  1295      if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  1296        onError = OE_Abort;
  1297      }
  1298      assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  1299          || onError==OE_Ignore || onError==OE_Replace );
  1300      switch( onError ){
  1301        case OE_Abort:
  1302          sqlite3MayAbort(pParse);
  1303          /* Fall through */
  1304        case OE_Rollback:
  1305        case OE_Fail: {
  1306          char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  1307                                      pTab->aCol[i].zName);
  1308          sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  1309                            regNewData+1+i);
  1310          sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
  1311          sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  1312          VdbeCoverage(v);
  1313          break;
  1314        }
  1315        case OE_Ignore: {
  1316          sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  1317          VdbeCoverage(v);
  1318          break;
  1319        }
  1320        default: {
  1321          assert( onError==OE_Replace );
  1322          addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
  1323             VdbeCoverage(v);
  1324          sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  1325          sqlite3VdbeJumpHere(v, addr1);
  1326          break;
  1327        }
  1328      }
  1329    }
  1330  
  1331    /* Test all CHECK constraints
  1332    */
  1333  #ifndef SQLITE_OMIT_CHECK
  1334    if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  1335      ExprList *pCheck = pTab->pCheck;
  1336      pParse->ckBase = regNewData+1;
  1337      onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  1338      for(i=0; i<pCheck->nExpr; i++){
  1339        int allOk;
  1340        Expr *pExpr = pCheck->a[i].pExpr;
  1341        if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
  1342        allOk = sqlite3VdbeMakeLabel(v);
  1343        sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
  1344        if( onError==OE_Ignore ){
  1345          sqlite3VdbeGoto(v, ignoreDest);
  1346        }else{
  1347          char *zName = pCheck->a[i].zName;
  1348          if( zName==0 ) zName = pTab->zName;
  1349          if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  1350          sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  1351                                onError, zName, P4_TRANSIENT,
  1352                                P5_ConstraintCheck);
  1353        }
  1354        sqlite3VdbeResolveLabel(v, allOk);
  1355      }
  1356    }
  1357  #endif /* !defined(SQLITE_OMIT_CHECK) */
  1358  
  1359    /* If rowid is changing, make sure the new rowid does not previously
  1360    ** exist in the table.
  1361    */
  1362    if( pkChng && pPk==0 ){
  1363      int addrRowidOk = sqlite3VdbeMakeLabel(v);
  1364  
  1365      /* Figure out what action to take in case of a rowid collision */
  1366      onError = pTab->keyConf;
  1367      if( overrideError!=OE_Default ){
  1368        onError = overrideError;
  1369      }else if( onError==OE_Default ){
  1370        onError = OE_Abort;
  1371      }
  1372  
  1373      if( isUpdate ){
  1374        /* pkChng!=0 does not mean that the rowid has changed, only that
  1375        ** it might have changed.  Skip the conflict logic below if the rowid
  1376        ** is unchanged. */
  1377        sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  1378        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  1379        VdbeCoverage(v);
  1380      }
  1381  
  1382      /* If the response to a rowid conflict is REPLACE but the response
  1383      ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  1384      ** to defer the running of the rowid conflict checking until after
  1385      ** the UNIQUE constraints have run.
  1386      */
  1387      if( onError==OE_Replace && overrideError!=OE_Replace ){
  1388        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  1389          if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
  1390            ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
  1391            break;
  1392          }
  1393        }
  1394      }
  1395  
  1396      /* Check to see if the new rowid already exists in the table.  Skip
  1397      ** the following conflict logic if it does not. */
  1398      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  1399      VdbeCoverage(v);
  1400  
  1401      /* Generate code that deals with a rowid collision */
  1402      switch( onError ){
  1403        default: {
  1404          onError = OE_Abort;
  1405          /* Fall thru into the next case */
  1406        }
  1407        case OE_Rollback:
  1408        case OE_Abort:
  1409        case OE_Fail: {
  1410          sqlite3RowidConstraint(pParse, onError, pTab);
  1411          break;
  1412        }
  1413        case OE_Replace: {
  1414          /* If there are DELETE triggers on this table and the
  1415          ** recursive-triggers flag is set, call GenerateRowDelete() to
  1416          ** remove the conflicting row from the table. This will fire
  1417          ** the triggers and remove both the table and index b-tree entries.
  1418          **
  1419          ** Otherwise, if there are no triggers or the recursive-triggers
  1420          ** flag is not set, but the table has one or more indexes, call 
  1421          ** GenerateRowIndexDelete(). This removes the index b-tree entries 
  1422          ** only. The table b-tree entry will be replaced by the new entry 
  1423          ** when it is inserted.  
  1424          **
  1425          ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  1426          ** also invoke MultiWrite() to indicate that this VDBE may require
  1427          ** statement rollback (if the statement is aborted after the delete
  1428          ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  1429          ** but being more selective here allows statements like:
  1430          **
  1431          **   REPLACE INTO t(rowid) VALUES($newrowid)
  1432          **
  1433          ** to run without a statement journal if there are no indexes on the
  1434          ** table.
  1435          */
  1436          Trigger *pTrigger = 0;
  1437          if( db->flags&SQLITE_RecTriggers ){
  1438            pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  1439          }
  1440          if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  1441            sqlite3MultiWrite(pParse);
  1442            sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  1443                                     regNewData, 1, 0, OE_Replace, 1, -1);
  1444          }else{
  1445  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  1446            if( HasRowid(pTab) ){
  1447              /* This OP_Delete opcode fires the pre-update-hook only. It does
  1448              ** not modify the b-tree. It is more efficient to let the coming
  1449              ** OP_Insert replace the existing entry than it is to delete the
  1450              ** existing entry and then insert a new one. */
  1451              sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
  1452              sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  1453            }
  1454  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  1455            if( pTab->pIndex ){
  1456              sqlite3MultiWrite(pParse);
  1457              sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  1458            }
  1459          }
  1460          seenReplace = 1;
  1461          break;
  1462        }
  1463        case OE_Ignore: {
  1464          /*assert( seenReplace==0 );*/
  1465          sqlite3VdbeGoto(v, ignoreDest);
  1466          break;
  1467        }
  1468      }
  1469      sqlite3VdbeResolveLabel(v, addrRowidOk);
  1470      if( ipkTop ){
  1471        ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  1472        sqlite3VdbeJumpHere(v, ipkTop);
  1473      }
  1474    }
  1475  
  1476    /* Test all UNIQUE constraints by creating entries for each UNIQUE
  1477    ** index and making sure that duplicate entries do not already exist.
  1478    ** Compute the revised record entries for indices as we go.
  1479    **
  1480    ** This loop also handles the case of the PRIMARY KEY index for a
  1481    ** WITHOUT ROWID table.
  1482    */
  1483    for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  1484      int regIdx;          /* Range of registers hold conent for pIdx */
  1485      int regR;            /* Range of registers holding conflicting PK */
  1486      int iThisCur;        /* Cursor for this UNIQUE index */
  1487      int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
  1488  
  1489      if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
  1490      if( bAffinityDone==0 ){
  1491        sqlite3TableAffinity(v, pTab, regNewData+1);
  1492        bAffinityDone = 1;
  1493      }
  1494      iThisCur = iIdxCur+ix;
  1495      addrUniqueOk = sqlite3VdbeMakeLabel(v);
  1496  
  1497      /* Skip partial indices for which the WHERE clause is not true */
  1498      if( pIdx->pPartIdxWhere ){
  1499        sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  1500        pParse->ckBase = regNewData+1;
  1501        sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  1502                              SQLITE_JUMPIFNULL);
  1503        pParse->ckBase = 0;
  1504      }
  1505  
  1506      /* Create a record for this index entry as it should appear after
  1507      ** the insert or update.  Store that record in the aRegIdx[ix] register
  1508      */
  1509      regIdx = aRegIdx[ix]+1;
  1510      for(i=0; i<pIdx->nColumn; i++){
  1511        int iField = pIdx->aiColumn[i];
  1512        int x;
  1513        if( iField==XN_EXPR ){
  1514          pParse->ckBase = regNewData+1;
  1515          sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  1516          pParse->ckBase = 0;
  1517          VdbeComment((v, "%s column %d", pIdx->zName, i));
  1518        }else{
  1519          if( iField==XN_ROWID || iField==pTab->iPKey ){
  1520            x = regNewData;
  1521          }else{
  1522            x = iField + regNewData + 1;
  1523          }
  1524          sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
  1525          VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  1526        }
  1527      }
  1528      sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  1529      VdbeComment((v, "for %s", pIdx->zName));
  1530  
  1531      /* In an UPDATE operation, if this index is the PRIMARY KEY index 
  1532      ** of a WITHOUT ROWID table and there has been no change the
  1533      ** primary key, then no collision is possible.  The collision detection
  1534      ** logic below can all be skipped. */
  1535      if( isUpdate && pPk==pIdx && pkChng==0 ){
  1536        sqlite3VdbeResolveLabel(v, addrUniqueOk);
  1537        continue;
  1538      }
  1539  
  1540      /* Find out what action to take in case there is a uniqueness conflict */
  1541      onError = pIdx->onError;
  1542      if( onError==OE_None ){ 
  1543        sqlite3VdbeResolveLabel(v, addrUniqueOk);
  1544        continue;  /* pIdx is not a UNIQUE index */
  1545      }
  1546      if( overrideError!=OE_Default ){
  1547        onError = overrideError;
  1548      }else if( onError==OE_Default ){
  1549        onError = OE_Abort;
  1550      }
  1551  
1552 /* Collision detection may be omitted if all of the following are true: 1553 ** (1) The conflict resolution algorithm is REPLACE 1554 ** (2) The table is a WITHOUT ROWID table 1555 ** (3) There are no secondary indexes on the table 1556 ** (4) No delete triggers need to be fired if there is a conflict 1557 ** (5) No FK constraint counters need to be updated if a conflict occurs. 1558 */ 1559 if( (ix==0 && pIdx->pNext==0) /* Condition 3 */ 1560 && pPk==pIdx /* Condition 2 */ 1561 && onError==OE_Replace /* Condition 1 */ 1562 && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */ 1563 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0)) 1564 && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */ 1565 (0==pTab->pFKey && 0==sqlite3FkReferences(pTab))) 1566 ){ 1567 sqlite3VdbeResolveLabel(v, addrUniqueOk); 1568 continue; 1569 }
1570 1571 /* Check to see if the new index entry will be unique */ 1572 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, 1573 regIdx, pIdx->nKeyCol); VdbeCoverage(v); 1574 1575 /* Generate code to handle collisions */ 1576 regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); 1577 if( isUpdate || onError==OE_Replace ){ 1578 if( HasRowid(pTab) ){ 1579 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); 1580 /* Conflict only if the rowid of the existing index entry 1581 ** is different from old-rowid */ 1582 if( isUpdate ){ 1583 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); 1584 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1585 VdbeCoverage(v); 1586 } 1587 }else{ 1588 int x; 1589 /* Extract the PRIMARY KEY from the end of the index entry and 1590 ** store it in registers regR..regR+nPk-1 */ 1591 if( pIdx!=pPk ){ 1592 for(i=0; i<pPk->nKeyCol; i++){ 1593 assert( pPk->aiColumn[i]>=0 ); 1594 x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]); 1595 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); 1596 VdbeComment((v, "%s.%s", pTab->zName, 1597 pTab->aCol[pPk->aiColumn[i]].zName)); 1598 } 1599 } 1600 if( isUpdate ){ 1601 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 1602 ** table, only conflict if the new PRIMARY KEY values are actually 1603 ** different from the old. 1604 ** 1605 ** For a UNIQUE index, only conflict if the PRIMARY KEY values 1606 ** of the matched index row are different from the original PRIMARY 1607 ** KEY values of this row before the update. */ 1608 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; 1609 int op = OP_Ne; 1610 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); 1611 1612 for(i=0; i<pPk->nKeyCol; i++){ 1613 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); 1614 x = pPk->aiColumn[i]; 1615 assert( x>=0 ); 1616 if( i==(pPk->nKeyCol-1) ){ 1617 addrJump = addrUniqueOk; 1618 op = OP_Eq; 1619 } 1620 sqlite3VdbeAddOp4(v, op, 1621 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ 1622 ); 1623 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1624 VdbeCoverageIf(v, op==OP_Eq); 1625 VdbeCoverageIf(v, op==OP_Ne); 1626 } 1627 } 1628 } 1629 } 1630 1631 /* Generate code that executes if the new index entry is not unique */ 1632 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1633 || onError==OE_Ignore || onError==OE_Replace ); 1634 switch( onError ){ 1635 case OE_Rollback: 1636 case OE_Abort: 1637 case OE_Fail: { 1638 sqlite3UniqueConstraint(pParse, onError, pIdx); 1639 break; 1640 } 1641 case OE_Ignore: { 1642 sqlite3VdbeGoto(v, ignoreDest); 1643 break; 1644 } 1645 default: { 1646 Trigger *pTrigger = 0; 1647 assert( onError==OE_Replace ); 1648 sqlite3MultiWrite(pParse); 1649 if( db->flags&SQLITE_RecTriggers ){ 1650 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 1651 } 1652 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1653 regR, nPkField, 0, OE_Replace, 1654 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1); 1655 seenReplace = 1; 1656 break; 1657 } 1658 } 1659 sqlite3VdbeResolveLabel(v, addrUniqueOk); 1660 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); 1661 } 1662 if( ipkTop ){ 1663 sqlite3VdbeGoto(v, ipkTop+1); 1664 sqlite3VdbeJumpHere(v, ipkBottom); 1665 } 1666 1667 *pbMayReplace = seenReplace; 1668 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); 1669 } 1670 1671 /* 1672 ** This routine generates code to finish the INSERT or UPDATE operation 1673 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 1674 ** A consecutive range of registers starting at regNewData contains the 1675 ** rowid and the content to be inserted. 1676 ** 1677 ** The arguments to this routine should be the same as the first six 1678 ** arguments to sqlite3GenerateConstraintChecks. 1679 */ 1680 void sqlite3CompleteInsertion( 1681 Parse *pParse, /* The parser context */ 1682 Table *pTab, /* the table into which we are inserting */ 1683 int iDataCur, /* Cursor of the canonical data source */ 1684 int iIdxCur, /* First index cursor */ 1685 int regNewData, /* Range of content */ 1686 int *aRegIdx, /* Register used by each index. 0 for unused indices */ 1687 int isUpdate, /* True for UPDATE, False for INSERT */ 1688 int appendBias, /* True if this is likely to be an append */ 1689 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ 1690 ){ 1691 Vdbe *v; /* Prepared statements under construction */ 1692 Index *pIdx; /* An index being inserted or updated */ 1693 u8 pik_flags; /* flag values passed to the btree insert */ 1694 int regData; /* Content registers (after the rowid) */ 1695 int regRec; /* Register holding assembled record for the table */ 1696 int i; /* Loop counter */ 1697 u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */ 1698 1699 v = sqlite3GetVdbe(pParse); 1700 assert( v!=0 ); 1701 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 1702 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1703 if( aRegIdx[i]==0 ) continue; 1704 bAffinityDone = 1; 1705 if( pIdx->pPartIdxWhere ){ 1706 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); 1707 VdbeCoverage(v); 1708 } 1709 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i], 1710 aRegIdx[i]+1, 1711 pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn); 1712 pik_flags = 0; 1713 if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT; 1714 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 1715 assert( pParse->nested==0 ); 1716 pik_flags |= OPFLAG_NCHANGE; 1717 } 1718 sqlite3VdbeChangeP5(v, pik_flags); 1719 } 1720 if( !HasRowid(pTab) ) return; 1721 regData = regNewData + 1; 1722 regRec = sqlite3GetTempReg(pParse); 1723 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); 1724 if( !bAffinityDone ){ 1725 sqlite3TableAffinity(v, pTab, 0); 1726 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); 1727 } 1728 if( pParse->nested ){ 1729 pik_flags = 0; 1730 }else{ 1731 pik_flags = OPFLAG_NCHANGE; 1732 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); 1733 } 1734 if( appendBias ){ 1735 pik_flags |= OPFLAG_APPEND; 1736 } 1737 if( useSeekResult ){ 1738 pik_flags |= OPFLAG_USESEEKRESULT; 1739 } 1740 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData); 1741 if( !pParse->nested ){ 1742 sqlite3VdbeAppendP4(v, pTab, P4_TABLE); 1743 } 1744 sqlite3VdbeChangeP5(v, pik_flags); 1745 } 1746 1747 /* 1748 ** Allocate cursors for the pTab table and all its indices and generate 1749 ** code to open and initialized those cursors. 1750 ** 1751 ** The cursor for the object that contains the complete data (normally 1752 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT 1753 ** ROWID table) is returned in *piDataCur. The first index cursor is 1754 ** returned in *piIdxCur. The number of indices is returned. 1755 ** 1756 ** Use iBase as the first cursor (either the *piDataCur for rowid tables 1757 ** or the first index for WITHOUT ROWID tables) if it is non-negative. 1758 ** If iBase is negative, then allocate the next available cursor. 1759 ** 1760 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. 1761 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range 1762 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the 1763 ** pTab->pIndex list. 1764 ** 1765 ** If pTab is a virtual table, then this routine is a no-op and the 1766 ** *piDataCur and *piIdxCur values are left uninitialized. 1767 */ 1768 int sqlite3OpenTableAndIndices( 1769 Parse *pParse, /* Parsing context */ 1770 Table *pTab, /* Table to be opened */ 1771 int op, /* OP_OpenRead or OP_OpenWrite */ 1772 u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */ 1773 int iBase, /* Use this for the table cursor, if there is one */ 1774 u8 *aToOpen, /* If not NULL: boolean for each table and index */ 1775 int *piDataCur, /* Write the database source cursor number here */ 1776 int *piIdxCur /* Write the first index cursor number here */ 1777 ){ 1778 int i; 1779 int iDb; 1780 int iDataCur; 1781 Index *pIdx; 1782 Vdbe *v; 1783 1784 assert( op==OP_OpenRead || op==OP_OpenWrite ); 1785 assert( op==OP_OpenWrite || p5==0 ); 1786 if( IsVirtual(pTab) ){ 1787 /* This routine is a no-op for virtual tables. Leave the output 1788 ** variables *piDataCur and *piIdxCur uninitialized so that valgrind 1789 ** can detect if they are used by mistake in the caller. */ 1790 return 0; 1791 } 1792 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 1793 v = sqlite3GetVdbe(pParse); 1794 assert( v!=0 ); 1795 if( iBase<0 ) iBase = pParse->nTab; 1796 iDataCur = iBase++; 1797 if( piDataCur ) *piDataCur = iDataCur; 1798 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ 1799 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); 1800 }else{ 1801 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); 1802 } 1803 if( piIdxCur ) *piIdxCur = iBase; 1804 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1805 int iIdxCur = iBase++; 1806 assert( pIdx->pSchema==pTab->pSchema ); 1807 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 1808 if( piDataCur ) *piDataCur = iIdxCur; 1809 p5 = 0; 1810 } 1811 if( aToOpen==0 || aToOpen[i+1] ){ 1812 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); 1813 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 1814 sqlite3VdbeChangeP5(v, p5); 1815 VdbeComment((v, "%s", pIdx->zName)); 1816 } 1817 } 1818 if( iBase>pParse->nTab ) pParse->nTab = iBase; 1819 return i; 1820 } 1821 1822 1823 #ifdef SQLITE_TEST 1824 /* 1825 ** The following global variable is incremented whenever the 1826 ** transfer optimization is used. This is used for testing 1827 ** purposes only - to make sure the transfer optimization really 1828 ** is happening when it is supposed to. 1829 */ 1830 int sqlite3_xferopt_count; 1831 #endif /* SQLITE_TEST */ 1832 1833 1834 #ifndef SQLITE_OMIT_XFER_OPT 1835 /* 1836 ** Check to see if index pSrc is compatible as a source of data 1837 ** for index pDest in an insert transfer optimization. The rules 1838 ** for a compatible index: 1839 ** 1840 ** * The index is over the same set of columns 1841 ** * The same DESC and ASC markings occurs on all columns 1842 ** * The same onError processing (OE_Abort, OE_Ignore, etc) 1843 ** * The same collating sequence on each column 1844 ** * The index has the exact same WHERE clause 1845 */ 1846 static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 1847 int i; 1848 assert( pDest && pSrc ); 1849 assert( pDest->pTable!=pSrc->pTable ); 1850 if( pDest->nKeyCol!=pSrc->nKeyCol ){ 1851 return 0; /* Different number of columns */ 1852 } 1853 if( pDest->onError!=pSrc->onError ){ 1854 return 0; /* Different conflict resolution strategies */ 1855 } 1856 for(i=0; i<pSrc->nKeyCol; i++){ 1857 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 1858 return 0; /* Different columns indexed */ 1859 } 1860 if( pSrc->aiColumn[i]==XN_EXPR ){ 1861 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); 1862 if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr, 1863 pDest->aColExpr->a[i].pExpr, -1)!=0 ){ 1864 return 0; /* Different expressions in the index */ 1865 } 1866 } 1867 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 1868 return 0; /* Different sort orders */ 1869 } 1870 if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){ 1871 return 0; /* Different collating sequences */ 1872 } 1873 } 1874 if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ 1875 return 0; /* Different WHERE clauses */ 1876 } 1877 1878 /* If no test above fails then the indices must be compatible */ 1879 return 1; 1880 } 1881 1882 /* 1883 ** Attempt the transfer optimization on INSERTs of the form 1884 ** 1885 ** INSERT INTO tab1 SELECT * FROM tab2; 1886 ** 1887 ** The xfer optimization transfers raw records from tab2 over to tab1. 1888 ** Columns are not decoded and reassembled, which greatly improves 1889 ** performance. Raw index records are transferred in the same way. 1890 ** 1891 ** The xfer optimization is only attempted if tab1 and tab2 are compatible. 1892 ** There are lots of rules for determining compatibility - see comments 1893 ** embedded in the code for details. 1894 ** 1895 ** This routine returns TRUE if the optimization is guaranteed to be used. 1896 ** Sometimes the xfer optimization will only work if the destination table 1897 ** is empty - a factor that can only be determined at run-time. In that 1898 ** case, this routine generates code for the xfer optimization but also 1899 ** does a test to see if the destination table is empty and jumps over the 1900 ** xfer optimization code if the test fails. In that case, this routine 1901 ** returns FALSE so that the caller will know to go ahead and generate 1902 ** an unoptimized transfer. This routine also returns FALSE if there 1903 ** is no chance that the xfer optimization can be applied. 1904 ** 1905 ** This optimization is particularly useful at making VACUUM run faster. 1906 */ 1907 static int xferOptimization( 1908 Parse *pParse, /* Parser context */ 1909 Table *pDest, /* The table we are inserting into */ 1910 Select *pSelect, /* A SELECT statement to use as the data source */ 1911 int onError, /* How to handle constraint errors */ 1912 int iDbDest /* The database of pDest */ 1913 ){ 1914 sqlite3 *db = pParse->db; 1915 ExprList *pEList; /* The result set of the SELECT */ 1916 Table *pSrc; /* The table in the FROM clause of SELECT */ 1917 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 1918 struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 1919 int i; /* Loop counter */ 1920 int iDbSrc; /* The database of pSrc */ 1921 int iSrc, iDest; /* Cursors from source and destination */ 1922 int addr1, addr2; /* Loop addresses */ 1923 int emptyDestTest = 0; /* Address of test for empty pDest */ 1924 int emptySrcTest = 0; /* Address of test for empty pSrc */ 1925 Vdbe *v; /* The VDBE we are building */ 1926 int regAutoinc; /* Memory register used by AUTOINC */ 1927 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 1928 int regData, regRowid; /* Registers holding data and rowid */ 1929 1930 if( pSelect==0 ){ 1931 return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 1932 } 1933 if( pParse->pWith || pSelect->pWith ){ 1934 /* Do not attempt to process this query if there are an WITH clauses 1935 ** attached to it. Proceeding may generate a false "no such table: xxx" 1936 ** error if pSelect reads from a CTE named "xxx". */ 1937 return 0; 1938 } 1939 if( sqlite3TriggerList(pParse, pDest) ){ 1940 return 0; /* tab1 must not have triggers */ 1941 } 1942 #ifndef SQLITE_OMIT_VIRTUALTABLE 1943 if( pDest->tabFlags & TF_Virtual ){ 1944 return 0; /* tab1 must not be a virtual table */ 1945 } 1946 #endif 1947 if( onError==OE_Default ){ 1948 if( pDest->iPKey>=0 ) onError = pDest->keyConf; 1949 if( onError==OE_Default ) onError = OE_Abort; 1950 } 1951 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 1952 if( pSelect->pSrc->nSrc!=1 ){ 1953 return 0; /* FROM clause must have exactly one term */ 1954 } 1955 if( pSelect->pSrc->a[0].pSelect ){ 1956 return 0; /* FROM clause cannot contain a subquery */ 1957 } 1958 if( pSelect->pWhere ){ 1959 return 0; /* SELECT may not have a WHERE clause */ 1960 } 1961 if( pSelect->pOrderBy ){ 1962 return 0; /* SELECT may not have an ORDER BY clause */ 1963 } 1964 /* Do not need to test for a HAVING clause. If HAVING is present but 1965 ** there is no ORDER BY, we will get an error. */ 1966 if( pSelect->pGroupBy ){ 1967 return 0; /* SELECT may not have a GROUP BY clause */ 1968 } 1969 if( pSelect->pLimit ){ 1970 return 0; /* SELECT may not have a LIMIT clause */ 1971 } 1972 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ 1973 if( pSelect->pPrior ){ 1974 return 0; /* SELECT may not be a compound query */ 1975 } 1976 if( pSelect->selFlags & SF_Distinct ){ 1977 return 0; /* SELECT may not be DISTINCT */ 1978 } 1979 pEList = pSelect->pEList; 1980 assert( pEList!=0 ); 1981 if( pEList->nExpr!=1 ){ 1982 return 0; /* The result set must have exactly one column */ 1983 } 1984 assert( pEList->a[0].pExpr ); 1985 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){ 1986 return 0; /* The result set must be the special operator "*" */ 1987 } 1988 1989 /* At this point we have established that the statement is of the 1990 ** correct syntactic form to participate in this optimization. Now 1991 ** we have to check the semantics. 1992 */ 1993 pItem = pSelect->pSrc->a; 1994 pSrc = sqlite3LocateTableItem(pParse, 0, pItem); 1995 if( pSrc==0 ){ 1996 return 0; /* FROM clause does not contain a real table */ 1997 } 1998 if( pSrc==pDest ){ 1999 return 0; /* tab1 and tab2 may not be the same table */ 2000 } 2001 if( HasRowid(pDest)!=HasRowid(pSrc) ){ 2002 return 0; /* source and destination must both be WITHOUT ROWID or not */ 2003 } 2004 #ifndef SQLITE_OMIT_VIRTUALTABLE 2005 if( pSrc->tabFlags & TF_Virtual ){ 2006 return 0; /* tab2 must not be a virtual table */ 2007 } 2008 #endif 2009 if( pSrc->pSelect ){ 2010 return 0; /* tab2 may not be a view */ 2011 } 2012 if( pDest->nCol!=pSrc->nCol ){ 2013 return 0; /* Number of columns must be the same in tab1 and tab2 */ 2014 } 2015 if( pDest->iPKey!=pSrc->iPKey ){ 2016 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 2017 } 2018 for(i=0; i<pDest->nCol; i++){ 2019 Column *pDestCol = &pDest->aCol[i]; 2020 Column *pSrcCol = &pSrc->aCol[i]; 2021 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS 2022 if( (db->flags & SQLITE_Vacuum)==0 2023 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN 2024 ){ 2025 return 0; /* Neither table may have __hidden__ columns */ 2026 } 2027 #endif 2028 if( pDestCol->affinity!=pSrcCol->affinity ){ 2029 return 0; /* Affinity must be the same on all columns */ 2030 } 2031 if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){ 2032 return 0; /* Collating sequence must be the same on all columns */ 2033 } 2034 if( pDestCol->notNull && !pSrcCol->notNull ){ 2035 return 0; /* tab2 must be NOT NULL if tab1 is */ 2036 } 2037 /* Default values for second and subsequent columns need to match. */ 2038 if( i>0 ){ 2039 assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN ); 2040 assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN ); 2041 if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) 2042 || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken, 2043 pSrcCol->pDflt->u.zToken)!=0) 2044 ){ 2045 return 0; /* Default values must be the same for all columns */ 2046 } 2047 } 2048 } 2049 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 2050 if( IsUniqueIndex(pDestIdx) ){ 2051 destHasUniqueIdx = 1; 2052 } 2053 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 2054 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 2055 } 2056 if( pSrcIdx==0 ){ 2057 return 0; /* pDestIdx has no corresponding index in pSrc */ 2058 } 2059 } 2060 #ifndef SQLITE_OMIT_CHECK 2061 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ 2062 return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 2063 } 2064 #endif 2065 #ifndef SQLITE_OMIT_FOREIGN_KEY 2066 /* Disallow the transfer optimization if the destination table constains 2067 ** any foreign key constraints. This is more restrictive than necessary. 2068 ** But the main beneficiary of the transfer optimization is the VACUUM 2069 ** command, and the VACUUM command disables foreign key constraints. So 2070 ** the extra complication to make this rule less restrictive is probably 2071 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] 2072 */ 2073 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ 2074 return 0; 2075 } 2076 #endif 2077 if( (db->flags & SQLITE_CountRows)!=0 ){ 2078 return 0; /* xfer opt does not play well with PRAGMA count_changes */ 2079 } 2080 2081 /* If we get this far, it means that the xfer optimization is at 2082 ** least a possibility, though it might only work if the destination 2083 ** table (tab1) is initially empty. 2084 */ 2085 #ifdef SQLITE_TEST 2086 sqlite3_xferopt_count++; 2087 #endif 2088 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); 2089 v = sqlite3GetVdbe(pParse); 2090 sqlite3CodeVerifySchema(pParse, iDbSrc); 2091 iSrc = pParse->nTab++; 2092 iDest = pParse->nTab++; 2093 regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 2094 regData = sqlite3GetTempReg(pParse); 2095 regRowid = sqlite3GetTempReg(pParse); 2096 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 2097 assert( HasRowid(pDest) || destHasUniqueIdx ); 2098 if( (db->flags & SQLITE_Vacuum)==0 && ( 2099 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ 2100 || destHasUniqueIdx /* (2) */ 2101 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ 2102 )){ 2103 /* In some circumstances, we are able to run the xfer optimization 2104 ** only if the destination table is initially empty. Unless the 2105 ** SQLITE_Vacuum flag is set, this block generates code to make 2106 ** that determination. If SQLITE_Vacuum is set, then the destination 2107 ** table is always empty. 2108 ** 2109 ** Conditions under which the destination must be empty: 2110 ** 2111 ** (1) There is no INTEGER PRIMARY KEY but there are indices. 2112 ** (If the destination is not initially empty, the rowid fields 2113 ** of index entries might need to change.) 2114 ** 2115 ** (2) The destination has a unique index. (The xfer optimization 2116 ** is unable to test uniqueness.) 2117 ** 2118 ** (3) onError is something other than OE_Abort and OE_Rollback. 2119 */ 2120 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); 2121 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); 2122 sqlite3VdbeJumpHere(v, addr1); 2123 } 2124 if( HasRowid(pSrc) ){ 2125 u8 insFlags; 2126 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 2127 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2128 if( pDest->iPKey>=0 ){ 2129 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 2130 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 2131 VdbeCoverage(v); 2132 sqlite3RowidConstraint(pParse, onError, pDest); 2133 sqlite3VdbeJumpHere(v, addr2); 2134 autoIncStep(pParse, regAutoinc, regRowid); 2135 }else if( pDest->pIndex==0 ){ 2136 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 2137 }else{ 2138 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 2139 assert( (pDest->tabFlags & TF_Autoincrement)==0 ); 2140 } 2141 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); 2142 if( db->flags & SQLITE_Vacuum ){ 2143 sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1); 2144 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID| 2145 OPFLAG_APPEND|OPFLAG_USESEEKRESULT; 2146 }else{ 2147 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND; 2148 } 2149 sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid, 2150 (char*)pDest, P4_TABLE); 2151 sqlite3VdbeChangeP5(v, insFlags); 2152 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); 2153 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 2154 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2155 }else{ 2156 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); 2157 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); 2158 } 2159 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 2160 u8 idxInsFlags = 0; 2161 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ 2162 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 2163 } 2164 assert( pSrcIdx ); 2165 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); 2166 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); 2167 VdbeComment((v, "%s", pSrcIdx->zName)); 2168 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); 2169 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); 2170 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); 2171 VdbeComment((v, "%s", pDestIdx->zName)); 2172 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2173 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); 2174 if( db->flags & SQLITE_Vacuum ){ 2175 /* This INSERT command is part of a VACUUM operation, which guarantees 2176 ** that the destination table is empty. If all indexed columns use 2177 ** collation sequence BINARY, then it can also be assumed that the 2178 ** index will be populated by inserting keys in strictly sorted 2179 ** order. In this case, instead of seeking within the b-tree as part 2180 ** of every OP_IdxInsert opcode, an OP_Last is added before the 2181 ** OP_IdxInsert to seek to the point within the b-tree where each key 2182 ** should be inserted. This is faster. 2183 ** 2184 ** If any of the indexed columns use a collation sequence other than 2185 ** BINARY, this optimization is disabled. This is because the user 2186 ** might change the definition of a collation sequence and then run 2187 ** a VACUUM command. In that case keys may not be written in strictly 2188 ** sorted order. */ 2189 for(i=0; i<pSrcIdx->nColumn; i++){ 2190 const char *zColl = pSrcIdx->azColl[i]; 2191 assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0 2192 || sqlite3StrBINARY==zColl ); 2193 if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break; 2194 } 2195 if( i==pSrcIdx->nColumn ){ 2196 idxInsFlags = OPFLAG_USESEEKRESULT; 2197 sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1); 2198 } 2199 } 2200 if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){ 2201 idxInsFlags |= OPFLAG_NCHANGE; 2202 } 2203 sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData); 2204 sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND); 2205 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); 2206 sqlite3VdbeJumpHere(v, addr1); 2207 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 2208 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2209 } 2210 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); 2211 sqlite3ReleaseTempReg(pParse, regRowid); 2212 sqlite3ReleaseTempReg(pParse, regData); 2213 if( emptyDestTest ){ 2214 sqlite3AutoincrementEnd(pParse); 2215 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 2216 sqlite3VdbeJumpHere(v, emptyDestTest); 2217 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2218 return 0; 2219 }else{ 2220 return 1; 2221 } 2222 } 2223 #endif /* SQLITE_OMIT_XFER_OPT */