extensions/sqlite/sqlite-source/insert.c
changeset 1203 633c25ce6405
child 1645 27307df4d711
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/extensions/sqlite/sqlite-source/insert.c	Sun Jul 29 01:15:31 2007 +0000
     1.3 @@ -0,0 +1,1604 @@
     1.4 +/*
     1.5 +** 2001 September 15
     1.6 +**
     1.7 +** The author disclaims copyright to this source code.  In place of
     1.8 +** a legal notice, here is a blessing:
     1.9 +**
    1.10 +**    May you do good and not evil.
    1.11 +**    May you find forgiveness for yourself and forgive others.
    1.12 +**    May you share freely, never taking more than you give.
    1.13 +**
    1.14 +*************************************************************************
    1.15 +** This file contains C code routines that are called by the parser
    1.16 +** to handle INSERT statements in SQLite.
    1.17 +**
    1.18 +** $Id$
    1.19 +*/
    1.20 +#include "sqliteInt.h"
    1.21 +
    1.22 +/*
    1.23 +** Set P3 of the most recently inserted opcode to a column affinity
    1.24 +** string for index pIdx. A column affinity string has one character
    1.25 +** for each column in the table, according to the affinity of the column:
    1.26 +**
    1.27 +**  Character      Column affinity
    1.28 +**  ------------------------------
    1.29 +**  'a'            TEXT
    1.30 +**  'b'            NONE
    1.31 +**  'c'            NUMERIC
    1.32 +**  'd'            INTEGER
    1.33 +**  'e'            REAL
    1.34 +*/
    1.35 +void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
    1.36 +  if( !pIdx->zColAff ){
    1.37 +    /* The first time a column affinity string for a particular index is
    1.38 +    ** required, it is allocated and populated here. It is then stored as
    1.39 +    ** a member of the Index structure for subsequent use.
    1.40 +    **
    1.41 +    ** The column affinity string will eventually be deleted by
    1.42 +    ** sqliteDeleteIndex() when the Index structure itself is cleaned
    1.43 +    ** up.
    1.44 +    */
    1.45 +    int n;
    1.46 +    Table *pTab = pIdx->pTable;
    1.47 +    pIdx->zColAff = (char *)sqliteMalloc(pIdx->nColumn+1);
    1.48 +    if( !pIdx->zColAff ){
    1.49 +      return;
    1.50 +    }
    1.51 +    for(n=0; n<pIdx->nColumn; n++){
    1.52 +      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
    1.53 +    }
    1.54 +    pIdx->zColAff[pIdx->nColumn] = '\0';
    1.55 +  }
    1.56 + 
    1.57 +  sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
    1.58 +}
    1.59 +
    1.60 +/*
    1.61 +** Set P3 of the most recently inserted opcode to a column affinity
    1.62 +** string for table pTab. A column affinity string has one character
    1.63 +** for each column indexed by the index, according to the affinity of the
    1.64 +** column:
    1.65 +**
    1.66 +**  Character      Column affinity
    1.67 +**  ------------------------------
    1.68 +**  'a'            TEXT
    1.69 +**  'b'            NONE
    1.70 +**  'c'            NUMERIC
    1.71 +**  'd'            INTEGER
    1.72 +**  'e'            REAL
    1.73 +*/
    1.74 +void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
    1.75 +  /* The first time a column affinity string for a particular table
    1.76 +  ** is required, it is allocated and populated here. It is then 
    1.77 +  ** stored as a member of the Table structure for subsequent use.
    1.78 +  **
    1.79 +  ** The column affinity string will eventually be deleted by
    1.80 +  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
    1.81 +  */
    1.82 +  if( !pTab->zColAff ){
    1.83 +    char *zColAff;
    1.84 +    int i;
    1.85 +
    1.86 +    zColAff = (char *)sqliteMalloc(pTab->nCol+1);
    1.87 +    if( !zColAff ){
    1.88 +      return;
    1.89 +    }
    1.90 +
    1.91 +    for(i=0; i<pTab->nCol; i++){
    1.92 +      zColAff[i] = pTab->aCol[i].affinity;
    1.93 +    }
    1.94 +    zColAff[pTab->nCol] = '\0';
    1.95 +
    1.96 +    pTab->zColAff = zColAff;
    1.97 +  }
    1.98 +
    1.99 +  sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
   1.100 +}
   1.101 +
   1.102 +/*
   1.103 +** Return non-zero if SELECT statement p opens the table with rootpage
   1.104 +** iTab in database iDb.  This is used to see if a statement of the form 
   1.105 +** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
   1.106 +** table for the results of the SELECT. 
   1.107 +**
   1.108 +** No checking is done for sub-selects that are part of expressions.
   1.109 +*/
   1.110 +static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
   1.111 +  int i;
   1.112 +  struct SrcList_item *pItem;
   1.113 +  if( p->pSrc==0 ) return 0;
   1.114 +  for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
   1.115 +    if( pItem->pSelect ){
   1.116 +      if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
   1.117 +    }else{
   1.118 +      if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
   1.119 +    }
   1.120 +  }
   1.121 +  return 0;
   1.122 +}
   1.123 +
   1.124 +#ifndef SQLITE_OMIT_AUTOINCREMENT
   1.125 +/*
   1.126 +** Write out code to initialize the autoincrement logic.  This code
   1.127 +** looks up the current autoincrement value in the sqlite_sequence
   1.128 +** table and stores that value in a memory cell.  Code generated by
   1.129 +** autoIncStep() will keep that memory cell holding the largest
   1.130 +** rowid value.  Code generated by autoIncEnd() will write the new
   1.131 +** largest value of the counter back into the sqlite_sequence table.
   1.132 +**
   1.133 +** This routine returns the index of the mem[] cell that contains
   1.134 +** the maximum rowid counter.
   1.135 +**
   1.136 +** Two memory cells are allocated.  The next memory cell after the
   1.137 +** one returned holds the rowid in sqlite_sequence where we will
   1.138 +** write back the revised maximum rowid.
   1.139 +*/
   1.140 +static int autoIncBegin(
   1.141 +  Parse *pParse,      /* Parsing context */
   1.142 +  int iDb,            /* Index of the database holding pTab */
   1.143 +  Table *pTab         /* The table we are writing to */
   1.144 +){
   1.145 +  int memId = 0;
   1.146 +  if( pTab->autoInc ){
   1.147 +    Vdbe *v = pParse->pVdbe;
   1.148 +    Db *pDb = &pParse->db->aDb[iDb];
   1.149 +    int iCur = pParse->nTab;
   1.150 +    int addr;
   1.151 +    assert( v );
   1.152 +    addr = sqlite3VdbeCurrentAddr(v);
   1.153 +    memId = pParse->nMem+1;
   1.154 +    pParse->nMem += 2;
   1.155 +    sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
   1.156 +    sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
   1.157 +    sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
   1.158 +    sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
   1.159 +    sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
   1.160 +    sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
   1.161 +    sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
   1.162 +    sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
   1.163 +    sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
   1.164 +    sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
   1.165 +    sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
   1.166 +    sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
   1.167 +  }
   1.168 +  return memId;
   1.169 +}
   1.170 +
   1.171 +/*
   1.172 +** Update the maximum rowid for an autoincrement calculation.
   1.173 +**
   1.174 +** This routine should be called when the top of the stack holds a
   1.175 +** new rowid that is about to be inserted.  If that new rowid is
   1.176 +** larger than the maximum rowid in the memId memory cell, then the
   1.177 +** memory cell is updated.  The stack is unchanged.
   1.178 +*/
   1.179 +static void autoIncStep(Parse *pParse, int memId){
   1.180 +  if( memId>0 ){
   1.181 +    sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
   1.182 +  }
   1.183 +}
   1.184 +
   1.185 +/*
   1.186 +** After doing one or more inserts, the maximum rowid is stored
   1.187 +** in mem[memId].  Generate code to write this value back into the
   1.188 +** the sqlite_sequence table.
   1.189 +*/
   1.190 +static void autoIncEnd(
   1.191 +  Parse *pParse,     /* The parsing context */
   1.192 +  int iDb,           /* Index of the database holding pTab */
   1.193 +  Table *pTab,       /* Table we are inserting into */
   1.194 +  int memId          /* Memory cell holding the maximum rowid */
   1.195 +){
   1.196 +  if( pTab->autoInc ){
   1.197 +    int iCur = pParse->nTab;
   1.198 +    Vdbe *v = pParse->pVdbe;
   1.199 +    Db *pDb = &pParse->db->aDb[iDb];
   1.200 +    int addr;
   1.201 +    assert( v );
   1.202 +    addr = sqlite3VdbeCurrentAddr(v);
   1.203 +    sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
   1.204 +    sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
   1.205 +    sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
   1.206 +    sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
   1.207 +    sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
   1.208 +    sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
   1.209 +    sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
   1.210 +    sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
   1.211 +    sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
   1.212 +    sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
   1.213 +  }
   1.214 +}
   1.215 +#else
   1.216 +/*
   1.217 +** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
   1.218 +** above are all no-ops
   1.219 +*/
   1.220 +# define autoIncBegin(A,B,C) (0)
   1.221 +# define autoIncStep(A,B)
   1.222 +# define autoIncEnd(A,B,C,D)
   1.223 +#endif /* SQLITE_OMIT_AUTOINCREMENT */
   1.224 +
   1.225 +
   1.226 +/* Forward declaration */
   1.227 +static int xferOptimization(
   1.228 +  Parse *pParse,        /* Parser context */
   1.229 +  Table *pDest,         /* The table we are inserting into */
   1.230 +  Select *pSelect,      /* A SELECT statement to use as the data source */
   1.231 +  int onError,          /* How to handle constraint errors */
   1.232 +  int iDbDest           /* The database of pDest */
   1.233 +);
   1.234 +
   1.235 +/*
   1.236 +** This routine is call to handle SQL of the following forms:
   1.237 +**
   1.238 +**    insert into TABLE (IDLIST) values(EXPRLIST)
   1.239 +**    insert into TABLE (IDLIST) select
   1.240 +**
   1.241 +** The IDLIST following the table name is always optional.  If omitted,
   1.242 +** then a list of all columns for the table is substituted.  The IDLIST
   1.243 +** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
   1.244 +**
   1.245 +** The pList parameter holds EXPRLIST in the first form of the INSERT
   1.246 +** statement above, and pSelect is NULL.  For the second form, pList is
   1.247 +** NULL and pSelect is a pointer to the select statement used to generate
   1.248 +** data for the insert.
   1.249 +**
   1.250 +** The code generated follows one of four templates.  For a simple
   1.251 +** select with data coming from a VALUES clause, the code executes
   1.252 +** once straight down through.  The template looks like this:
   1.253 +**
   1.254 +**         open write cursor to <table> and its indices
   1.255 +**         puts VALUES clause expressions onto the stack
   1.256 +**         write the resulting record into <table>
   1.257 +**         cleanup
   1.258 +**
   1.259 +** The three remaining templates assume the statement is of the form
   1.260 +**
   1.261 +**   INSERT INTO <table> SELECT ...
   1.262 +**
   1.263 +** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
   1.264 +** in other words if the SELECT pulls all columns from a single table
   1.265 +** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
   1.266 +** if <table2> and <table1> are distinct tables but have identical
   1.267 +** schemas, including all the same indices, then a special optimization
   1.268 +** is invoked that copies raw records from <table2> over to <table1>.
   1.269 +** See the xferOptimization() function for the implementation of this
   1.270 +** template.  This is the second template.
   1.271 +**
   1.272 +**         open a write cursor to <table>
   1.273 +**         open read cursor on <table2>
   1.274 +**         transfer all records in <table2> over to <table>
   1.275 +**         close cursors
   1.276 +**         foreach index on <table>
   1.277 +**           open a write cursor on the <table> index
   1.278 +**           open a read cursor on the corresponding <table2> index
   1.279 +**           transfer all records from the read to the write cursors
   1.280 +**           close cursors
   1.281 +**         end foreach
   1.282 +**
   1.283 +** The third template is for when the second template does not apply
   1.284 +** and the SELECT clause does not read from <table> at any time.
   1.285 +** The generated code follows this template:
   1.286 +**
   1.287 +**         goto B
   1.288 +**      A: setup for the SELECT
   1.289 +**         loop over the rows in the SELECT
   1.290 +**           gosub C
   1.291 +**         end loop
   1.292 +**         cleanup after the SELECT
   1.293 +**         goto D
   1.294 +**      B: open write cursor to <table> and its indices
   1.295 +**         goto A
   1.296 +**      C: insert the select result into <table>
   1.297 +**         return
   1.298 +**      D: cleanup
   1.299 +**
   1.300 +** The fourth template is used if the insert statement takes its
   1.301 +** values from a SELECT but the data is being inserted into a table
   1.302 +** that is also read as part of the SELECT.  In the third form,
   1.303 +** we have to use a intermediate table to store the results of
   1.304 +** the select.  The template is like this:
   1.305 +**
   1.306 +**         goto B
   1.307 +**      A: setup for the SELECT
   1.308 +**         loop over the tables in the SELECT
   1.309 +**           gosub C
   1.310 +**         end loop
   1.311 +**         cleanup after the SELECT
   1.312 +**         goto D
   1.313 +**      C: insert the select result into the intermediate table
   1.314 +**         return
   1.315 +**      B: open a cursor to an intermediate table
   1.316 +**         goto A
   1.317 +**      D: open write cursor to <table> and its indices
   1.318 +**         loop over the intermediate table
   1.319 +**           transfer values form intermediate table into <table>
   1.320 +**         end the loop
   1.321 +**         cleanup
   1.322 +*/
   1.323 +void sqlite3Insert(
   1.324 +  Parse *pParse,        /* Parser context */
   1.325 +  SrcList *pTabList,    /* Name of table into which we are inserting */
   1.326 +  ExprList *pList,      /* List of values to be inserted */
   1.327 +  Select *pSelect,      /* A SELECT statement to use as the data source */
   1.328 +  IdList *pColumn,      /* Column names corresponding to IDLIST. */
   1.329 +  int onError           /* How to handle constraint errors */
   1.330 +){
   1.331 +  Table *pTab;          /* The table to insert into */
   1.332 +  char *zTab;           /* Name of the table into which we are inserting */
   1.333 +  const char *zDb;      /* Name of the database holding this table */
   1.334 +  int i, j, idx;        /* Loop counters */
   1.335 +  Vdbe *v;              /* Generate code into this virtual machine */
   1.336 +  Index *pIdx;          /* For looping over indices of the table */
   1.337 +  int nColumn;          /* Number of columns in the data */
   1.338 +  int base = 0;         /* VDBE Cursor number for pTab */
   1.339 +  int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
   1.340 +  sqlite3 *db;          /* The main database structure */
   1.341 +  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
   1.342 +  int endOfLoop;        /* Label for the end of the insertion loop */
   1.343 +  int useTempTable = 0; /* Store SELECT results in intermediate table */
   1.344 +  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
   1.345 +  int iSelectLoop = 0;  /* Address of code that implements the SELECT */
   1.346 +  int iCleanup = 0;     /* Address of the cleanup code */
   1.347 +  int iInsertBlock = 0; /* Address of the subroutine used to insert data */
   1.348 +  int iCntMem = 0;      /* Memory cell used for the row counter */
   1.349 +  int newIdx = -1;      /* Cursor for the NEW table */
   1.350 +  Db *pDb;              /* The database containing table being inserted into */
   1.351 +  int counterMem = 0;   /* Memory cell holding AUTOINCREMENT counter */
   1.352 +  int appendFlag = 0;   /* True if the insert is likely to be an append */
   1.353 +  int iDb;
   1.354 +
   1.355 +  int nHidden = 0;
   1.356 +
   1.357 +#ifndef SQLITE_OMIT_TRIGGER
   1.358 +  int isView;                 /* True if attempting to insert into a view */
   1.359 +  int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
   1.360 +#endif
   1.361 +
   1.362 +  if( pParse->nErr || sqlite3MallocFailed() ){
   1.363 +    goto insert_cleanup;
   1.364 +  }
   1.365 +  db = pParse->db;
   1.366 +
   1.367 +  /* Locate the table into which we will be inserting new information.
   1.368 +  */
   1.369 +  assert( pTabList->nSrc==1 );
   1.370 +  zTab = pTabList->a[0].zName;
   1.371 +  if( zTab==0 ) goto insert_cleanup;
   1.372 +  pTab = sqlite3SrcListLookup(pParse, pTabList);
   1.373 +  if( pTab==0 ){
   1.374 +    goto insert_cleanup;
   1.375 +  }
   1.376 +  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   1.377 +  assert( iDb<db->nDb );
   1.378 +  pDb = &db->aDb[iDb];
   1.379 +  zDb = pDb->zName;
   1.380 +  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
   1.381 +    goto insert_cleanup;
   1.382 +  }
   1.383 +
   1.384 +  /* Figure out if we have any triggers and if the table being
   1.385 +  ** inserted into is a view
   1.386 +  */
   1.387 +#ifndef SQLITE_OMIT_TRIGGER
   1.388 +  triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
   1.389 +  isView = pTab->pSelect!=0;
   1.390 +#else
   1.391 +# define triggers_exist 0
   1.392 +# define isView 0
   1.393 +#endif
   1.394 +#ifdef SQLITE_OMIT_VIEW
   1.395 +# undef isView
   1.396 +# define isView 0
   1.397 +#endif
   1.398 +
   1.399 +  /* Ensure that:
   1.400 +  *  (a) the table is not read-only, 
   1.401 +  *  (b) that if it is a view then ON INSERT triggers exist
   1.402 +  */
   1.403 +  if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
   1.404 +    goto insert_cleanup;
   1.405 +  }
   1.406 +  assert( pTab!=0 );
   1.407 +
   1.408 +  /* If pTab is really a view, make sure it has been initialized.
   1.409 +  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
   1.410 +  ** module table).
   1.411 +  */
   1.412 +  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   1.413 +    goto insert_cleanup;
   1.414 +  }
   1.415 +
   1.416 +  /* Allocate a VDBE
   1.417 +  */
   1.418 +  v = sqlite3GetVdbe(pParse);
   1.419 +  if( v==0 ) goto insert_cleanup;
   1.420 +  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   1.421 +  sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
   1.422 +
   1.423 +  /* if there are row triggers, allocate a temp table for new.* references. */
   1.424 +  if( triggers_exist ){
   1.425 +    newIdx = pParse->nTab++;
   1.426 +  }
   1.427 +
   1.428 +#ifndef SQLITE_OMIT_XFER_OPT
   1.429 +  /* If the statement is of the form
   1.430 +  **
   1.431 +  **       INSERT INTO <table1> SELECT * FROM <table2>;
   1.432 +  **
   1.433 +  ** Then special optimizations can be applied that make the transfer
   1.434 +  ** very fast and which reduce fragmentation of indices.
   1.435 +  */
   1.436 +  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
   1.437 +    assert( !triggers_exist );
   1.438 +    assert( pList==0 );
   1.439 +    goto insert_cleanup;
   1.440 +  }
   1.441 +#endif /* SQLITE_OMIT_XFER_OPT */
   1.442 +
   1.443 +  /* If this is an AUTOINCREMENT table, look up the sequence number in the
   1.444 +  ** sqlite_sequence table and store it in memory cell counterMem.  Also
   1.445 +  ** remember the rowid of the sqlite_sequence table entry in memory cell
   1.446 +  ** counterRowid.
   1.447 +  */
   1.448 +  counterMem = autoIncBegin(pParse, iDb, pTab);
   1.449 +
   1.450 +  /* Figure out how many columns of data are supplied.  If the data
   1.451 +  ** is coming from a SELECT statement, then this step also generates
   1.452 +  ** all the code to implement the SELECT statement and invoke a subroutine
   1.453 +  ** to process each row of the result. (Template 2.) If the SELECT
   1.454 +  ** statement uses the the table that is being inserted into, then the
   1.455 +  ** subroutine is also coded here.  That subroutine stores the SELECT
   1.456 +  ** results in a temporary table. (Template 3.)
   1.457 +  */
   1.458 +  if( pSelect ){
   1.459 +    /* Data is coming from a SELECT.  Generate code to implement that SELECT
   1.460 +    */
   1.461 +    int rc, iInitCode;
   1.462 +    iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
   1.463 +    iSelectLoop = sqlite3VdbeCurrentAddr(v);
   1.464 +    iInsertBlock = sqlite3VdbeMakeLabel(v);
   1.465 +
   1.466 +    /* Resolve the expressions in the SELECT statement and execute it. */
   1.467 +    rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
   1.468 +    if( rc || pParse->nErr || sqlite3MallocFailed() ){
   1.469 +      goto insert_cleanup;
   1.470 +    }
   1.471 +
   1.472 +    iCleanup = sqlite3VdbeMakeLabel(v);
   1.473 +    sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
   1.474 +    assert( pSelect->pEList );
   1.475 +    nColumn = pSelect->pEList->nExpr;
   1.476 +
   1.477 +    /* Set useTempTable to TRUE if the result of the SELECT statement
   1.478 +    ** should be written into a temporary table.  Set to FALSE if each
   1.479 +    ** row of the SELECT can be written directly into the result table.
   1.480 +    **
   1.481 +    ** A temp table must be used if the table being updated is also one
   1.482 +    ** of the tables being read by the SELECT statement.  Also use a 
   1.483 +    ** temp table in the case of row triggers.
   1.484 +    */
   1.485 +    if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
   1.486 +      useTempTable = 1;
   1.487 +    }
   1.488 +
   1.489 +    if( useTempTable ){
   1.490 +      /* Generate the subroutine that SELECT calls to process each row of
   1.491 +      ** the result.  Store the result in a temporary table
   1.492 +      */
   1.493 +      srcTab = pParse->nTab++;
   1.494 +      sqlite3VdbeResolveLabel(v, iInsertBlock);
   1.495 +      sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
   1.496 +      sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
   1.497 +      sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
   1.498 +      sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
   1.499 +      sqlite3VdbeAddOp(v, OP_Return, 0, 0);
   1.500 +
   1.501 +      /* The following code runs first because the GOTO at the very top
   1.502 +      ** of the program jumps to it.  Create the temporary table, then jump
   1.503 +      ** back up and execute the SELECT code above.
   1.504 +      */
   1.505 +      sqlite3VdbeJumpHere(v, iInitCode);
   1.506 +      sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
   1.507 +      sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
   1.508 +      sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
   1.509 +      sqlite3VdbeResolveLabel(v, iCleanup);
   1.510 +    }else{
   1.511 +      sqlite3VdbeJumpHere(v, iInitCode);
   1.512 +    }
   1.513 +  }else{
   1.514 +    /* This is the case if the data for the INSERT is coming from a VALUES
   1.515 +    ** clause
   1.516 +    */
   1.517 +    NameContext sNC;
   1.518 +    memset(&sNC, 0, sizeof(sNC));
   1.519 +    sNC.pParse = pParse;
   1.520 +    srcTab = -1;
   1.521 +    useTempTable = 0;
   1.522 +    nColumn = pList ? pList->nExpr : 0;
   1.523 +    for(i=0; i<nColumn; i++){
   1.524 +      if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
   1.525 +        goto insert_cleanup;
   1.526 +      }
   1.527 +    }
   1.528 +  }
   1.529 +
   1.530 +  /* Make sure the number of columns in the source data matches the number
   1.531 +  ** of columns to be inserted into the table.
   1.532 +  */
   1.533 +  if( IsVirtual(pTab) ){
   1.534 +    for(i=0; i<pTab->nCol; i++){
   1.535 +      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
   1.536 +    }
   1.537 +  }
   1.538 +  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
   1.539 +    sqlite3ErrorMsg(pParse, 
   1.540 +       "table %S has %d columns but %d values were supplied",
   1.541 +       pTabList, 0, pTab->nCol, nColumn);
   1.542 +    goto insert_cleanup;
   1.543 +  }
   1.544 +  if( pColumn!=0 && nColumn!=pColumn->nId ){
   1.545 +    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
   1.546 +    goto insert_cleanup;
   1.547 +  }
   1.548 +
   1.549 +  /* If the INSERT statement included an IDLIST term, then make sure
   1.550 +  ** all elements of the IDLIST really are columns of the table and 
   1.551 +  ** remember the column indices.
   1.552 +  **
   1.553 +  ** If the table has an INTEGER PRIMARY KEY column and that column
   1.554 +  ** is named in the IDLIST, then record in the keyColumn variable
   1.555 +  ** the index into IDLIST of the primary key column.  keyColumn is
   1.556 +  ** the index of the primary key as it appears in IDLIST, not as
   1.557 +  ** is appears in the original table.  (The index of the primary
   1.558 +  ** key in the original table is pTab->iPKey.)
   1.559 +  */
   1.560 +  if( pColumn ){
   1.561 +    for(i=0; i<pColumn->nId; i++){
   1.562 +      pColumn->a[i].idx = -1;
   1.563 +    }
   1.564 +    for(i=0; i<pColumn->nId; i++){
   1.565 +      for(j=0; j<pTab->nCol; j++){
   1.566 +        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
   1.567 +          pColumn->a[i].idx = j;
   1.568 +          if( j==pTab->iPKey ){
   1.569 +            keyColumn = i;
   1.570 +          }
   1.571 +          break;
   1.572 +        }
   1.573 +      }
   1.574 +      if( j>=pTab->nCol ){
   1.575 +        if( sqlite3IsRowid(pColumn->a[i].zName) ){
   1.576 +          keyColumn = i;
   1.577 +        }else{
   1.578 +          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
   1.579 +              pTabList, 0, pColumn->a[i].zName);
   1.580 +          pParse->nErr++;
   1.581 +          goto insert_cleanup;
   1.582 +        }
   1.583 +      }
   1.584 +    }
   1.585 +  }
   1.586 +
   1.587 +  /* If there is no IDLIST term but the table has an integer primary
   1.588 +  ** key, the set the keyColumn variable to the primary key column index
   1.589 +  ** in the original table definition.
   1.590 +  */
   1.591 +  if( pColumn==0 && nColumn>0 ){
   1.592 +    keyColumn = pTab->iPKey;
   1.593 +  }
   1.594 +
   1.595 +  /* Open the temp table for FOR EACH ROW triggers
   1.596 +  */
   1.597 +  if( triggers_exist ){
   1.598 +    sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
   1.599 +    sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
   1.600 +  }
   1.601 +    
   1.602 +  /* Initialize the count of rows to be inserted
   1.603 +  */
   1.604 +  if( db->flags & SQLITE_CountRows ){
   1.605 +    iCntMem = pParse->nMem++;
   1.606 +    sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
   1.607 +  }
   1.608 +
   1.609 +  /* Open tables and indices if there are no row triggers */
   1.610 +  if( !triggers_exist ){
   1.611 +    base = pParse->nTab;
   1.612 +    sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
   1.613 +  }
   1.614 +
   1.615 +  /* If the data source is a temporary table, then we have to create
   1.616 +  ** a loop because there might be multiple rows of data.  If the data
   1.617 +  ** source is a subroutine call from the SELECT statement, then we need
   1.618 +  ** to launch the SELECT statement processing.
   1.619 +  */
   1.620 +  if( useTempTable ){
   1.621 +    iBreak = sqlite3VdbeMakeLabel(v);
   1.622 +    sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
   1.623 +    iCont = sqlite3VdbeCurrentAddr(v);
   1.624 +  }else if( pSelect ){
   1.625 +    sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
   1.626 +    sqlite3VdbeResolveLabel(v, iInsertBlock);
   1.627 +  }
   1.628 +
   1.629 +  /* Run the BEFORE and INSTEAD OF triggers, if there are any
   1.630 +  */
   1.631 +  endOfLoop = sqlite3VdbeMakeLabel(v);
   1.632 +  if( triggers_exist & TRIGGER_BEFORE ){
   1.633 +
   1.634 +    /* build the NEW.* reference row.  Note that if there is an INTEGER
   1.635 +    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
   1.636 +    ** translated into a unique ID for the row.  But on a BEFORE trigger,
   1.637 +    ** we do not know what the unique ID will be (because the insert has
   1.638 +    ** not happened yet) so we substitute a rowid of -1
   1.639 +    */
   1.640 +    if( keyColumn<0 ){
   1.641 +      sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
   1.642 +    }else if( useTempTable ){
   1.643 +      sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
   1.644 +    }else{
   1.645 +      assert( pSelect==0 );  /* Otherwise useTempTable is true */
   1.646 +      sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
   1.647 +      sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
   1.648 +      sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
   1.649 +      sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
   1.650 +      sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
   1.651 +    }
   1.652 +
   1.653 +    /* Cannot have triggers on a virtual table. If it were possible,
   1.654 +    ** this block would have to account for hidden column.
   1.655 +    */
   1.656 +    assert(!IsVirtual(pTab));
   1.657 +
   1.658 +    /* Create the new column data
   1.659 +    */
   1.660 +    for(i=0; i<pTab->nCol; i++){
   1.661 +      if( pColumn==0 ){
   1.662 +        j = i;
   1.663 +      }else{
   1.664 +        for(j=0; j<pColumn->nId; j++){
   1.665 +          if( pColumn->a[j].idx==i ) break;
   1.666 +        }
   1.667 +      }
   1.668 +      if( pColumn && j>=pColumn->nId ){
   1.669 +        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
   1.670 +      }else if( useTempTable ){
   1.671 +        sqlite3VdbeAddOp(v, OP_Column, srcTab, j); 
   1.672 +      }else{
   1.673 +        assert( pSelect==0 ); /* Otherwise useTempTable is true */
   1.674 +        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
   1.675 +      }
   1.676 +    }
   1.677 +    sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
   1.678 +
   1.679 +    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
   1.680 +    ** do not attempt any conversions before assembling the record.
   1.681 +    ** If this is a real table, attempt conversions as required by the
   1.682 +    ** table column affinities.
   1.683 +    */
   1.684 +    if( !isView ){
   1.685 +      sqlite3TableAffinityStr(v, pTab);
   1.686 +    }
   1.687 +    sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
   1.688 +
   1.689 +    /* Fire BEFORE or INSTEAD OF triggers */
   1.690 +    if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 
   1.691 +        newIdx, -1, onError, endOfLoop) ){
   1.692 +      goto insert_cleanup;
   1.693 +    }
   1.694 +  }
   1.695 +
   1.696 +  /* If any triggers exists, the opening of tables and indices is deferred
   1.697 +  ** until now.
   1.698 +  */
   1.699 +  if( triggers_exist && !isView ){
   1.700 +    base = pParse->nTab;
   1.701 +    sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
   1.702 +  }
   1.703 +
   1.704 +  /* Push the record number for the new entry onto the stack.  The
   1.705 +  ** record number is a randomly generate integer created by NewRowid
   1.706 +  ** except when the table has an INTEGER PRIMARY KEY column, in which
   1.707 +  ** case the record number is the same as that column. 
   1.708 +  */
   1.709 +  if( !isView ){
   1.710 +    if( IsVirtual(pTab) ){
   1.711 +      /* The row that the VUpdate opcode will delete:  none */
   1.712 +      sqlite3VdbeAddOp(v, OP_Null, 0, 0);
   1.713 +    }
   1.714 +    if( keyColumn>=0 ){
   1.715 +      if( useTempTable ){
   1.716 +        sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
   1.717 +      }else if( pSelect ){
   1.718 +        sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
   1.719 +      }else{
   1.720 +        VdbeOp *pOp;
   1.721 +        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
   1.722 +        pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
   1.723 +        if( pOp && pOp->opcode==OP_Null ){
   1.724 +          appendFlag = 1;
   1.725 +          pOp->opcode = OP_NewRowid;
   1.726 +          pOp->p1 = base;
   1.727 +          pOp->p2 = counterMem;
   1.728 +        }
   1.729 +      }
   1.730 +      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
   1.731 +      ** to generate a unique primary key value.
   1.732 +      */
   1.733 +      if( !appendFlag ){
   1.734 +        sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
   1.735 +        sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
   1.736 +        sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
   1.737 +        sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
   1.738 +      }
   1.739 +    }else if( IsVirtual(pTab) ){
   1.740 +      sqlite3VdbeAddOp(v, OP_Null, 0, 0);
   1.741 +    }else{
   1.742 +      sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
   1.743 +      appendFlag = 1;
   1.744 +    }
   1.745 +    autoIncStep(pParse, counterMem);
   1.746 +
   1.747 +    /* Push onto the stack, data for all columns of the new entry, beginning
   1.748 +    ** with the first column.
   1.749 +    */
   1.750 +    nHidden = 0;
   1.751 +    for(i=0; i<pTab->nCol; i++){
   1.752 +      if( i==pTab->iPKey ){
   1.753 +        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
   1.754 +        ** Whenever this column is read, the record number will be substituted
   1.755 +        ** in its place.  So will fill this column with a NULL to avoid
   1.756 +        ** taking up data space with information that will never be used. */
   1.757 +        sqlite3VdbeAddOp(v, OP_Null, 0, 0);
   1.758 +        continue;
   1.759 +      }
   1.760 +      if( pColumn==0 ){
   1.761 +        if( IsHiddenColumn(&pTab->aCol[i]) ){
   1.762 +          assert( IsVirtual(pTab) );
   1.763 +          j = -1;
   1.764 +          nHidden++;
   1.765 +        }else{
   1.766 +          j = i - nHidden;
   1.767 +        }
   1.768 +      }else{
   1.769 +        for(j=0; j<pColumn->nId; j++){
   1.770 +          if( pColumn->a[j].idx==i ) break;
   1.771 +        }
   1.772 +      }
   1.773 +      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
   1.774 +        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
   1.775 +      }else if( useTempTable ){
   1.776 +        sqlite3VdbeAddOp(v, OP_Column, srcTab, j); 
   1.777 +      }else if( pSelect ){
   1.778 +        sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
   1.779 +      }else{
   1.780 +        sqlite3ExprCode(pParse, pList->a[j].pExpr);
   1.781 +      }
   1.782 +    }
   1.783 +
   1.784 +    /* Generate code to check constraints and generate index keys and
   1.785 +    ** do the insertion.
   1.786 +    */
   1.787 +#ifndef SQLITE_OMIT_VIRTUALTABLE
   1.788 +    if( IsVirtual(pTab) ){
   1.789 +      pParse->pVirtualLock = pTab;
   1.790 +      sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
   1.791 +                     (const char*)pTab->pVtab, P3_VTAB);
   1.792 +    }else
   1.793 +#endif
   1.794 +    {
   1.795 +      sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
   1.796 +                                     0, onError, endOfLoop);
   1.797 +      sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
   1.798 +                            (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
   1.799 +                            appendFlag);
   1.800 +    }
   1.801 +  }
   1.802 +
   1.803 +  /* Update the count of rows that are inserted
   1.804 +  */
   1.805 +  if( (db->flags & SQLITE_CountRows)!=0 ){
   1.806 +    sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
   1.807 +  }
   1.808 +
   1.809 +  if( triggers_exist ){
   1.810 +    /* Close all tables opened */
   1.811 +    if( !isView ){
   1.812 +      sqlite3VdbeAddOp(v, OP_Close, base, 0);
   1.813 +      for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
   1.814 +        sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
   1.815 +      }
   1.816 +    }
   1.817 +
   1.818 +    /* Code AFTER triggers */
   1.819 +    if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
   1.820 +          newIdx, -1, onError, endOfLoop) ){
   1.821 +      goto insert_cleanup;
   1.822 +    }
   1.823 +  }
   1.824 +
   1.825 +  /* The bottom of the loop, if the data source is a SELECT statement
   1.826 +  */
   1.827 +  sqlite3VdbeResolveLabel(v, endOfLoop);
   1.828 +  if( useTempTable ){
   1.829 +    sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
   1.830 +    sqlite3VdbeResolveLabel(v, iBreak);
   1.831 +    sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
   1.832 +  }else if( pSelect ){
   1.833 +    sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
   1.834 +    sqlite3VdbeAddOp(v, OP_Return, 0, 0);
   1.835 +    sqlite3VdbeResolveLabel(v, iCleanup);
   1.836 +  }
   1.837 +
   1.838 +  if( !triggers_exist && !IsVirtual(pTab) ){
   1.839 +    /* Close all tables opened */
   1.840 +    sqlite3VdbeAddOp(v, OP_Close, base, 0);
   1.841 +    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
   1.842 +      sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
   1.843 +    }
   1.844 +  }
   1.845 +
   1.846 +  /* Update the sqlite_sequence table by storing the content of the
   1.847 +  ** counter value in memory counterMem back into the sqlite_sequence
   1.848 +  ** table.
   1.849 +  */
   1.850 +  autoIncEnd(pParse, iDb, pTab, counterMem);
   1.851 +
   1.852 +  /*
   1.853 +  ** Return the number of rows inserted. If this routine is 
   1.854 +  ** generating code because of a call to sqlite3NestedParse(), do not
   1.855 +  ** invoke the callback function.
   1.856 +  */
   1.857 +  if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
   1.858 +    sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
   1.859 +    sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
   1.860 +    sqlite3VdbeSetNumCols(v, 1);
   1.861 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
   1.862 +  }
   1.863 +
   1.864 +insert_cleanup:
   1.865 +  sqlite3SrcListDelete(pTabList);
   1.866 +  sqlite3ExprListDelete(pList);
   1.867 +  sqlite3SelectDelete(pSelect);
   1.868 +  sqlite3IdListDelete(pColumn);
   1.869 +}
   1.870 +
   1.871 +/*
   1.872 +** Generate code to do a constraint check prior to an INSERT or an UPDATE.
   1.873 +**
   1.874 +** When this routine is called, the stack contains (from bottom to top)
   1.875 +** the following values:
   1.876 +**
   1.877 +**    1.  The rowid of the row to be updated before the update.  This
   1.878 +**        value is omitted unless we are doing an UPDATE that involves a
   1.879 +**        change to the record number.
   1.880 +**
   1.881 +**    2.  The rowid of the row after the update.
   1.882 +**
   1.883 +**    3.  The data in the first column of the entry after the update.
   1.884 +**
   1.885 +**    i.  Data from middle columns...
   1.886 +**
   1.887 +**    N.  The data in the last column of the entry after the update.
   1.888 +**
   1.889 +** The old rowid shown as entry (1) above is omitted unless both isUpdate
   1.890 +** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
   1.891 +** INSERTs and rowidChng is true if the record number is being changed.
   1.892 +**
   1.893 +** The code generated by this routine pushes additional entries onto
   1.894 +** the stack which are the keys for new index entries for the new record.
   1.895 +** The order of index keys is the same as the order of the indices on
   1.896 +** the pTable->pIndex list.  A key is only created for index i if 
   1.897 +** aIdxUsed!=0 and aIdxUsed[i]!=0.
   1.898 +**
   1.899 +** This routine also generates code to check constraints.  NOT NULL,
   1.900 +** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
   1.901 +** then the appropriate action is performed.  There are five possible
   1.902 +** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
   1.903 +**
   1.904 +**  Constraint type  Action       What Happens
   1.905 +**  ---------------  ----------   ----------------------------------------
   1.906 +**  any              ROLLBACK     The current transaction is rolled back and
   1.907 +**                                sqlite3_exec() returns immediately with a
   1.908 +**                                return code of SQLITE_CONSTRAINT.
   1.909 +**
   1.910 +**  any              ABORT        Back out changes from the current command
   1.911 +**                                only (do not do a complete rollback) then
   1.912 +**                                cause sqlite3_exec() to return immediately
   1.913 +**                                with SQLITE_CONSTRAINT.
   1.914 +**
   1.915 +**  any              FAIL         Sqlite_exec() returns immediately with a
   1.916 +**                                return code of SQLITE_CONSTRAINT.  The
   1.917 +**                                transaction is not rolled back and any
   1.918 +**                                prior changes are retained.
   1.919 +**
   1.920 +**  any              IGNORE       The record number and data is popped from
   1.921 +**                                the stack and there is an immediate jump
   1.922 +**                                to label ignoreDest.
   1.923 +**
   1.924 +**  NOT NULL         REPLACE      The NULL value is replace by the default
   1.925 +**                                value for that column.  If the default value
   1.926 +**                                is NULL, the action is the same as ABORT.
   1.927 +**
   1.928 +**  UNIQUE           REPLACE      The other row that conflicts with the row
   1.929 +**                                being inserted is removed.
   1.930 +**
   1.931 +**  CHECK            REPLACE      Illegal.  The results in an exception.
   1.932 +**
   1.933 +** Which action to take is determined by the overrideError parameter.
   1.934 +** Or if overrideError==OE_Default, then the pParse->onError parameter
   1.935 +** is used.  Or if pParse->onError==OE_Default then the onError value
   1.936 +** for the constraint is used.
   1.937 +**
   1.938 +** The calling routine must open a read/write cursor for pTab with
   1.939 +** cursor number "base".  All indices of pTab must also have open
   1.940 +** read/write cursors with cursor number base+i for the i-th cursor.
   1.941 +** Except, if there is no possibility of a REPLACE action then
   1.942 +** cursors do not need to be open for indices where aIdxUsed[i]==0.
   1.943 +**
   1.944 +** If the isUpdate flag is true, it means that the "base" cursor is
   1.945 +** initially pointing to an entry that is being updated.  The isUpdate
   1.946 +** flag causes extra code to be generated so that the "base" cursor
   1.947 +** is still pointing at the same entry after the routine returns.
   1.948 +** Without the isUpdate flag, the "base" cursor might be moved.
   1.949 +*/
   1.950 +void sqlite3GenerateConstraintChecks(
   1.951 +  Parse *pParse,      /* The parser context */
   1.952 +  Table *pTab,        /* the table into which we are inserting */
   1.953 +  int base,           /* Index of a read/write cursor pointing at pTab */
   1.954 +  char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
   1.955 +  int rowidChng,      /* True if the record number will change */
   1.956 +  int isUpdate,       /* True for UPDATE, False for INSERT */
   1.957 +  int overrideError,  /* Override onError to this if not OE_Default */
   1.958 +  int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
   1.959 +){
   1.960 +  int i;
   1.961 +  Vdbe *v;
   1.962 +  int nCol;
   1.963 +  int onError;
   1.964 +  int addr;
   1.965 +  int extra;
   1.966 +  int iCur;
   1.967 +  Index *pIdx;
   1.968 +  int seenReplace = 0;
   1.969 +  int jumpInst1=0, jumpInst2;
   1.970 +  int hasTwoRowids = (isUpdate && rowidChng);
   1.971 +
   1.972 +  v = sqlite3GetVdbe(pParse);
   1.973 +  assert( v!=0 );
   1.974 +  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   1.975 +  nCol = pTab->nCol;
   1.976 +
   1.977 +  /* Test all NOT NULL constraints.
   1.978 +  */
   1.979 +  for(i=0; i<nCol; i++){
   1.980 +    if( i==pTab->iPKey ){
   1.981 +      continue;
   1.982 +    }
   1.983 +    onError = pTab->aCol[i].notNull;
   1.984 +    if( onError==OE_None ) continue;
   1.985 +    if( overrideError!=OE_Default ){
   1.986 +      onError = overrideError;
   1.987 +    }else if( onError==OE_Default ){
   1.988 +      onError = OE_Abort;
   1.989 +    }
   1.990 +    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
   1.991 +      onError = OE_Abort;
   1.992 +    }
   1.993 +    sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
   1.994 +    addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
   1.995 +    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   1.996 +        || onError==OE_Ignore || onError==OE_Replace );
   1.997 +    switch( onError ){
   1.998 +      case OE_Rollback:
   1.999 +      case OE_Abort:
  1.1000 +      case OE_Fail: {
  1.1001 +        char *zMsg = 0;
  1.1002 +        sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
  1.1003 +        sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
  1.1004 +                        " may not be NULL", (char*)0);
  1.1005 +        sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
  1.1006 +        break;
  1.1007 +      }
  1.1008 +      case OE_Ignore: {
  1.1009 +        sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
  1.1010 +        sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
  1.1011 +        break;
  1.1012 +      }
  1.1013 +      case OE_Replace: {
  1.1014 +        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
  1.1015 +        sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
  1.1016 +        break;
  1.1017 +      }
  1.1018 +    }
  1.1019 +    sqlite3VdbeJumpHere(v, addr);
  1.1020 +  }
  1.1021 +
  1.1022 +  /* Test all CHECK constraints
  1.1023 +  */
  1.1024 +#ifndef SQLITE_OMIT_CHECK
  1.1025 +  if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
  1.1026 +    int allOk = sqlite3VdbeMakeLabel(v);
  1.1027 +    assert( pParse->ckOffset==0 );
  1.1028 +    pParse->ckOffset = nCol;
  1.1029 +    sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
  1.1030 +    assert( pParse->ckOffset==nCol );
  1.1031 +    pParse->ckOffset = 0;
  1.1032 +    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  1.1033 +    if( onError==OE_Ignore || onError==OE_Replace ){
  1.1034 +      sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
  1.1035 +      sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
  1.1036 +    }else{
  1.1037 +      sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
  1.1038 +    }
  1.1039 +    sqlite3VdbeResolveLabel(v, allOk);
  1.1040 +  }
  1.1041 +#endif /* !defined(SQLITE_OMIT_CHECK) */
  1.1042 +
  1.1043 +  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  1.1044 +  ** of the new record does not previously exist.  Except, if this
  1.1045 +  ** is an UPDATE and the primary key is not changing, that is OK.
  1.1046 +  */
  1.1047 +  if( rowidChng ){
  1.1048 +    onError = pTab->keyConf;
  1.1049 +    if( overrideError!=OE_Default ){
  1.1050 +      onError = overrideError;
  1.1051 +    }else if( onError==OE_Default ){
  1.1052 +      onError = OE_Abort;
  1.1053 +    }
  1.1054 +    
  1.1055 +    if( isUpdate ){
  1.1056 +      sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
  1.1057 +      sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
  1.1058 +      jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
  1.1059 +    }
  1.1060 +    sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
  1.1061 +    jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
  1.1062 +    switch( onError ){
  1.1063 +      default: {
  1.1064 +        onError = OE_Abort;
  1.1065 +        /* Fall thru into the next case */
  1.1066 +      }
  1.1067 +      case OE_Rollback:
  1.1068 +      case OE_Abort:
  1.1069 +      case OE_Fail: {
  1.1070 +        sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
  1.1071 +                         "PRIMARY KEY must be unique", P3_STATIC);
  1.1072 +        break;
  1.1073 +      }
  1.1074 +      case OE_Replace: {
  1.1075 +        sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
  1.1076 +        if( isUpdate ){
  1.1077 +          sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
  1.1078 +          sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
  1.1079 +        }
  1.1080 +        seenReplace = 1;
  1.1081 +        break;
  1.1082 +      }
  1.1083 +      case OE_Ignore: {
  1.1084 +        assert( seenReplace==0 );
  1.1085 +        sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
  1.1086 +        sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
  1.1087 +        break;
  1.1088 +      }
  1.1089 +    }
  1.1090 +    sqlite3VdbeJumpHere(v, jumpInst2);
  1.1091 +    if( isUpdate ){
  1.1092 +      sqlite3VdbeJumpHere(v, jumpInst1);
  1.1093 +      sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
  1.1094 +      sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
  1.1095 +    }
  1.1096 +  }
  1.1097 +
  1.1098 +  /* Test all UNIQUE constraints by creating entries for each UNIQUE
  1.1099 +  ** index and making sure that duplicate entries do not already exist.
  1.1100 +  ** Add the new records to the indices as we go.
  1.1101 +  */
  1.1102 +  extra = -1;
  1.1103 +  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  1.1104 +    if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;  /* Skip unused indices */
  1.1105 +    extra++;
  1.1106 +
  1.1107 +    /* Create a key for accessing the index entry */
  1.1108 +    sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
  1.1109 +    for(i=0; i<pIdx->nColumn; i++){
  1.1110 +      int idx = pIdx->aiColumn[i];
  1.1111 +      if( idx==pTab->iPKey ){
  1.1112 +        sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
  1.1113 +      }else{
  1.1114 +        sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
  1.1115 +      }
  1.1116 +    }
  1.1117 +    jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
  1.1118 +    sqlite3IndexAffinityStr(v, pIdx);
  1.1119 +
  1.1120 +    /* Find out what action to take in case there is an indexing conflict */
  1.1121 +    onError = pIdx->onError;
  1.1122 +    if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
  1.1123 +    if( overrideError!=OE_Default ){
  1.1124 +      onError = overrideError;
  1.1125 +    }else if( onError==OE_Default ){
  1.1126 +      onError = OE_Abort;
  1.1127 +    }
  1.1128 +    if( seenReplace ){
  1.1129 +      if( onError==OE_Ignore ) onError = OE_Replace;
  1.1130 +      else if( onError==OE_Fail ) onError = OE_Abort;
  1.1131 +    }
  1.1132 +    
  1.1133 +
  1.1134 +    /* Check to see if the new index entry will be unique */
  1.1135 +    sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
  1.1136 +    jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
  1.1137 +
  1.1138 +    /* Generate code that executes if the new index entry is not unique */
  1.1139 +    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  1.1140 +        || onError==OE_Ignore || onError==OE_Replace );
  1.1141 +    switch( onError ){
  1.1142 +      case OE_Rollback:
  1.1143 +      case OE_Abort:
  1.1144 +      case OE_Fail: {
  1.1145 +        int j, n1, n2;
  1.1146 +        char zErrMsg[200];
  1.1147 +        sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
  1.1148 +                         pIdx->nColumn>1 ? "columns " : "column ");
  1.1149 +        n1 = strlen(zErrMsg);
  1.1150 +        for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
  1.1151 +          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  1.1152 +          n2 = strlen(zCol);
  1.1153 +          if( j>0 ){
  1.1154 +            sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
  1.1155 +            n1 += 2;
  1.1156 +          }
  1.1157 +          if( n1+n2>sizeof(zErrMsg)-30 ){
  1.1158 +            sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
  1.1159 +            n1 += 3;
  1.1160 +            break;
  1.1161 +          }else{
  1.1162 +            sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
  1.1163 +            n1 += n2;
  1.1164 +          }
  1.1165 +        }
  1.1166 +        sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], 
  1.1167 +            pIdx->nColumn>1 ? " are not unique" : " is not unique");
  1.1168 +        sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
  1.1169 +        break;
  1.1170 +      }
  1.1171 +      case OE_Ignore: {
  1.1172 +        assert( seenReplace==0 );
  1.1173 +        sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
  1.1174 +        sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
  1.1175 +        break;
  1.1176 +      }
  1.1177 +      case OE_Replace: {
  1.1178 +        sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
  1.1179 +        if( isUpdate ){
  1.1180 +          sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
  1.1181 +          sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
  1.1182 +        }
  1.1183 +        seenReplace = 1;
  1.1184 +        break;
  1.1185 +      }
  1.1186 +    }
  1.1187 +#if NULL_DISTINCT_FOR_UNIQUE
  1.1188 +    sqlite3VdbeJumpHere(v, jumpInst1);
  1.1189 +#endif
  1.1190 +    sqlite3VdbeJumpHere(v, jumpInst2);
  1.1191 +  }
  1.1192 +}
  1.1193 +
  1.1194 +/*
  1.1195 +** This routine generates code to finish the INSERT or UPDATE operation
  1.1196 +** that was started by a prior call to sqlite3GenerateConstraintChecks.
  1.1197 +** The stack must contain keys for all active indices followed by data
  1.1198 +** and the rowid for the new entry.  This routine creates the new
  1.1199 +** entries in all indices and in the main table.
  1.1200 +**
  1.1201 +** The arguments to this routine should be the same as the first six
  1.1202 +** arguments to sqlite3GenerateConstraintChecks.
  1.1203 +*/
  1.1204 +void sqlite3CompleteInsertion(
  1.1205 +  Parse *pParse,      /* The parser context */
  1.1206 +  Table *pTab,        /* the table into which we are inserting */
  1.1207 +  int base,           /* Index of a read/write cursor pointing at pTab */
  1.1208 +  char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
  1.1209 +  int rowidChng,      /* True if the record number will change */
  1.1210 +  int isUpdate,       /* True for UPDATE, False for INSERT */
  1.1211 +  int newIdx,         /* Index of NEW table for triggers.  -1 if none */
  1.1212 +  int appendBias      /* True if this is likely to be an append */
  1.1213 +){
  1.1214 +  int i;
  1.1215 +  Vdbe *v;
  1.1216 +  int nIdx;
  1.1217 +  Index *pIdx;
  1.1218 +  int pik_flags;
  1.1219 +
  1.1220 +  v = sqlite3GetVdbe(pParse);
  1.1221 +  assert( v!=0 );
  1.1222 +  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
  1.1223 +  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  1.1224 +  for(i=nIdx-1; i>=0; i--){
  1.1225 +    if( aIdxUsed && aIdxUsed[i]==0 ) continue;
  1.1226 +    sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
  1.1227 +  }
  1.1228 +  sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
  1.1229 +  sqlite3TableAffinityStr(v, pTab);
  1.1230 +#ifndef SQLITE_OMIT_TRIGGER
  1.1231 +  if( newIdx>=0 ){
  1.1232 +    sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
  1.1233 +    sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
  1.1234 +    sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
  1.1235 +  }
  1.1236 +#endif
  1.1237 +  if( pParse->nested ){
  1.1238 +    pik_flags = 0;
  1.1239 +  }else{
  1.1240 +    pik_flags = OPFLAG_NCHANGE;
  1.1241 +    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  1.1242 +  }
  1.1243 +  if( appendBias ){
  1.1244 +    pik_flags |= OPFLAG_APPEND;
  1.1245 +  }
  1.1246 +  sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
  1.1247 +  if( !pParse->nested ){
  1.1248 +    sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
  1.1249 +  }
  1.1250 +  
  1.1251 +  if( isUpdate && rowidChng ){
  1.1252 +    sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
  1.1253 +  }
  1.1254 +}
  1.1255 +
  1.1256 +/*
  1.1257 +** Generate code that will open cursors for a table and for all
  1.1258 +** indices of that table.  The "base" parameter is the cursor number used
  1.1259 +** for the table.  Indices are opened on subsequent cursors.
  1.1260 +*/
  1.1261 +void sqlite3OpenTableAndIndices(
  1.1262 +  Parse *pParse,   /* Parsing context */
  1.1263 +  Table *pTab,     /* Table to be opened */
  1.1264 +  int base,        /* Cursor number assigned to the table */
  1.1265 +  int op           /* OP_OpenRead or OP_OpenWrite */
  1.1266 +){
  1.1267 +  int i;
  1.1268 +  int iDb;
  1.1269 +  Index *pIdx;
  1.1270 +  Vdbe *v;
  1.1271 +
  1.1272 +  if( IsVirtual(pTab) ) return;
  1.1273 +  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  1.1274 +  v = sqlite3GetVdbe(pParse);
  1.1275 +  assert( v!=0 );
  1.1276 +  sqlite3OpenTable(pParse, base, iDb, pTab, op);
  1.1277 +  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  1.1278 +    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  1.1279 +    assert( pIdx->pSchema==pTab->pSchema );
  1.1280 +    sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
  1.1281 +    VdbeComment((v, "# %s", pIdx->zName));
  1.1282 +    sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
  1.1283 +  }
  1.1284 +  if( pParse->nTab<=base+i ){
  1.1285 +    pParse->nTab = base+i;
  1.1286 +  }
  1.1287 +}
  1.1288 +
  1.1289 +
  1.1290 +#ifdef SQLITE_TEST
  1.1291 +/*
  1.1292 +** The following global variable is incremented whenever the
  1.1293 +** transfer optimization is used.  This is used for testing
  1.1294 +** purposes only - to make sure the transfer optimization really
  1.1295 +** is happening when it is suppose to.
  1.1296 +*/
  1.1297 +int sqlite3_xferopt_count;
  1.1298 +#endif /* SQLITE_TEST */
  1.1299 +
  1.1300 +
  1.1301 +#ifndef SQLITE_OMIT_XFER_OPT
  1.1302 +/*
  1.1303 +** Check to collation names to see if they are compatible.
  1.1304 +*/
  1.1305 +static int xferCompatibleCollation(const char *z1, const char *z2){
  1.1306 +  if( z1==0 ){
  1.1307 +    return z2==0;
  1.1308 +  }
  1.1309 +  if( z2==0 ){
  1.1310 +    return 0;
  1.1311 +  }
  1.1312 +  return sqlite3StrICmp(z1, z2)==0;
  1.1313 +}
  1.1314 +
  1.1315 +
  1.1316 +/*
  1.1317 +** Check to see if index pSrc is compatible as a source of data
  1.1318 +** for index pDest in an insert transfer optimization.  The rules
  1.1319 +** for a compatible index:
  1.1320 +**
  1.1321 +**    *   The index is over the same set of columns
  1.1322 +**    *   The same DESC and ASC markings occurs on all columns
  1.1323 +**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
  1.1324 +**    *   The same collating sequence on each column
  1.1325 +*/
  1.1326 +static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  1.1327 +  int i;
  1.1328 +  assert( pDest && pSrc );
  1.1329 +  assert( pDest->pTable!=pSrc->pTable );
  1.1330 +  if( pDest->nColumn!=pSrc->nColumn ){
  1.1331 +    return 0;   /* Different number of columns */
  1.1332 +  }
  1.1333 +  if( pDest->onError!=pSrc->onError ){
  1.1334 +    return 0;   /* Different conflict resolution strategies */
  1.1335 +  }
  1.1336 +  for(i=0; i<pSrc->nColumn; i++){
  1.1337 +    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  1.1338 +      return 0;   /* Different columns indexed */
  1.1339 +    }
  1.1340 +    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  1.1341 +      return 0;   /* Different sort orders */
  1.1342 +    }
  1.1343 +    if( pSrc->azColl[i]!=pDest->azColl[i] ){
  1.1344 +      return 0;   /* Different sort orders */
  1.1345 +    }
  1.1346 +  }
  1.1347 +
  1.1348 +  /* If no test above fails then the indices must be compatible */
  1.1349 +  return 1;
  1.1350 +}
  1.1351 +
  1.1352 +/*
  1.1353 +** Attempt the transfer optimization on INSERTs of the form
  1.1354 +**
  1.1355 +**     INSERT INTO tab1 SELECT * FROM tab2;
  1.1356 +**
  1.1357 +** This optimization is only attempted if
  1.1358 +**
  1.1359 +**    (1)  tab1 and tab2 have identical schemas including all the
  1.1360 +**         same indices and constraints
  1.1361 +**
  1.1362 +**    (2)  tab1 and tab2 are different tables
  1.1363 +**
  1.1364 +**    (3)  There must be no triggers on tab1
  1.1365 +**
  1.1366 +**    (4)  The result set of the SELECT statement is "*"
  1.1367 +**
  1.1368 +**    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
  1.1369 +**         or LIMIT clause.
  1.1370 +**
  1.1371 +**    (6)  The SELECT statement is a simple (not a compound) select that
  1.1372 +**         contains only tab2 in its FROM clause
  1.1373 +**
  1.1374 +** This method for implementing the INSERT transfers raw records from
  1.1375 +** tab2 over to tab1.  The columns are not decoded.  Raw records from
  1.1376 +** the indices of tab2 are transfered to tab1 as well.  In so doing,
  1.1377 +** the resulting tab1 has much less fragmentation.
  1.1378 +**
  1.1379 +** This routine returns TRUE if the optimization is attempted.  If any
  1.1380 +** of the conditions above fail so that the optimization should not
  1.1381 +** be attempted, then this routine returns FALSE.
  1.1382 +*/
  1.1383 +static int xferOptimization(
  1.1384 +  Parse *pParse,        /* Parser context */
  1.1385 +  Table *pDest,         /* The table we are inserting into */
  1.1386 +  Select *pSelect,      /* A SELECT statement to use as the data source */
  1.1387 +  int onError,          /* How to handle constraint errors */
  1.1388 +  int iDbDest           /* The database of pDest */
  1.1389 +){
  1.1390 +  ExprList *pEList;                /* The result set of the SELECT */
  1.1391 +  Table *pSrc;                     /* The table in the FROM clause of SELECT */
  1.1392 +  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
  1.1393 +  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
  1.1394 +  int i;                           /* Loop counter */
  1.1395 +  int iDbSrc;                      /* The database of pSrc */
  1.1396 +  int iSrc, iDest;                 /* Cursors from source and destination */
  1.1397 +  int addr1, addr2;                /* Loop addresses */
  1.1398 +  int emptyDestTest;               /* Address of test for empty pDest */
  1.1399 +  int emptySrcTest;                /* Address of test for empty pSrc */
  1.1400 +  Vdbe *v;                         /* The VDBE we are building */
  1.1401 +  KeyInfo *pKey;                   /* Key information for an index */
  1.1402 +  int counterMem;                  /* Memory register used by AUTOINC */
  1.1403 +  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
  1.1404 +
  1.1405 +  if( pSelect==0 ){
  1.1406 +    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
  1.1407 +  }
  1.1408 +  if( pDest->pTrigger ){
  1.1409 +    return 0;   /* tab1 must not have triggers */
  1.1410 +  }
  1.1411 +#ifndef SQLITE_OMIT_VIRTUALTABLE
  1.1412 +  if( pDest->isVirtual ){
  1.1413 +    return 0;   /* tab1 must not be a virtual table */
  1.1414 +  }
  1.1415 +#endif
  1.1416 +  if( onError==OE_Default ){
  1.1417 +    onError = OE_Abort;
  1.1418 +  }
  1.1419 +  if( onError!=OE_Abort && onError!=OE_Rollback ){
  1.1420 +    return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
  1.1421 +  }
  1.1422 +  if( pSelect->pSrc==0 ){
  1.1423 +    return 0;   /* SELECT must have a FROM clause */
  1.1424 +  }
  1.1425 +  if( pSelect->pSrc->nSrc!=1 ){
  1.1426 +    return 0;   /* FROM clause must have exactly one term */
  1.1427 +  }
  1.1428 +  if( pSelect->pSrc->a[0].pSelect ){
  1.1429 +    return 0;   /* FROM clause cannot contain a subquery */
  1.1430 +  }
  1.1431 +  if( pSelect->pWhere ){
  1.1432 +    return 0;   /* SELECT may not have a WHERE clause */
  1.1433 +  }
  1.1434 +  if( pSelect->pOrderBy ){
  1.1435 +    return 0;   /* SELECT may not have an ORDER BY clause */
  1.1436 +  }
  1.1437 +  /* Do not need to test for a HAVING clause.  If HAVING is present but
  1.1438 +  ** there is no ORDER BY, we will get an error. */
  1.1439 +  if( pSelect->pGroupBy ){
  1.1440 +    return 0;   /* SELECT may not have a GROUP BY clause */
  1.1441 +  }
  1.1442 +  if( pSelect->pLimit ){
  1.1443 +    return 0;   /* SELECT may not have a LIMIT clause */
  1.1444 +  }
  1.1445 +  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
  1.1446 +  if( pSelect->pPrior ){
  1.1447 +    return 0;   /* SELECT may not be a compound query */
  1.1448 +  }
  1.1449 +  if( pSelect->isDistinct ){
  1.1450 +    return 0;   /* SELECT may not be DISTINCT */
  1.1451 +  }
  1.1452 +  pEList = pSelect->pEList;
  1.1453 +  assert( pEList!=0 );
  1.1454 +  if( pEList->nExpr!=1 ){
  1.1455 +    return 0;   /* The result set must have exactly one column */
  1.1456 +  }
  1.1457 +  assert( pEList->a[0].pExpr );
  1.1458 +  if( pEList->a[0].pExpr->op!=TK_ALL ){
  1.1459 +    return 0;   /* The result set must be the special operator "*" */
  1.1460 +  }
  1.1461 +
  1.1462 +  /* At this point we have established that the statement is of the
  1.1463 +  ** correct syntactic form to participate in this optimization.  Now
  1.1464 +  ** we have to check the semantics.
  1.1465 +  */
  1.1466 +  pItem = pSelect->pSrc->a;
  1.1467 +  pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
  1.1468 +  if( pSrc==0 ){
  1.1469 +    return 0;   /* FROM clause does not contain a real table */
  1.1470 +  }
  1.1471 +  if( pSrc==pDest ){
  1.1472 +    return 0;   /* tab1 and tab2 may not be the same table */
  1.1473 +  }
  1.1474 +#ifndef SQLITE_OMIT_VIRTUALTABLE
  1.1475 +  if( pSrc->isVirtual ){
  1.1476 +    return 0;   /* tab2 must not be a virtual table */
  1.1477 +  }
  1.1478 +#endif
  1.1479 +  if( pSrc->pSelect ){
  1.1480 +    return 0;   /* tab2 may not be a view */
  1.1481 +  }
  1.1482 +  if( pDest->nCol!=pSrc->nCol ){
  1.1483 +    return 0;   /* Number of columns must be the same in tab1 and tab2 */
  1.1484 +  }
  1.1485 +  if( pDest->iPKey!=pSrc->iPKey ){
  1.1486 +    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
  1.1487 +  }
  1.1488 +  for(i=0; i<pDest->nCol; i++){
  1.1489 +    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
  1.1490 +      return 0;    /* Affinity must be the same on all columns */
  1.1491 +    }
  1.1492 +    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
  1.1493 +      return 0;    /* Collating sequence must be the same on all columns */
  1.1494 +    }
  1.1495 +    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
  1.1496 +      return 0;    /* tab2 must be NOT NULL if tab1 is */
  1.1497 +    }
  1.1498 +  }
  1.1499 +  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  1.1500 +    if( pDestIdx->onError!=OE_None ){
  1.1501 +      destHasUniqueIdx = 1;
  1.1502 +    }
  1.1503 +    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  1.1504 +      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  1.1505 +    }
  1.1506 +    if( pSrcIdx==0 ){
  1.1507 +      return 0;    /* pDestIdx has no corresponding index in pSrc */
  1.1508 +    }
  1.1509 +  }
  1.1510 +#ifndef SQLITE_OMIT_CHECK
  1.1511 +  if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
  1.1512 +    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
  1.1513 +  }
  1.1514 +#endif
  1.1515 +
  1.1516 +  /* If we get this far, it means either:
  1.1517 +  **
  1.1518 +  **    *   We can always do the transfer if the table contains an
  1.1519 +  **        an integer primary key
  1.1520 +  **
  1.1521 +  **    *   We can conditionally do the transfer if the destination
  1.1522 +  **        table is empty.
  1.1523 +  */
  1.1524 +#ifdef SQLITE_TEST
  1.1525 +  sqlite3_xferopt_count++;
  1.1526 +#endif
  1.1527 +  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  1.1528 +  v = sqlite3GetVdbe(pParse);
  1.1529 +  iSrc = pParse->nTab++;
  1.1530 +  iDest = pParse->nTab++;
  1.1531 +  counterMem = autoIncBegin(pParse, iDbDest, pDest);
  1.1532 +  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  1.1533 +  if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
  1.1534 +    /* If tables do not have an INTEGER PRIMARY KEY and there
  1.1535 +    ** are indices to be copied and the destination is not empty,
  1.1536 +    ** we have to disallow the transfer optimization because the
  1.1537 +    ** the rowids might change which will mess up indexing.
  1.1538 +    **
  1.1539 +    ** Or if the destination has a UNIQUE index and is not empty,
  1.1540 +    ** we also disallow the transfer optimization because we cannot
  1.1541 +    ** insure that all entries in the union of DEST and SRC will be
  1.1542 +    ** unique.
  1.1543 +    */
  1.1544 +    addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
  1.1545 +    emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
  1.1546 +    sqlite3VdbeJumpHere(v, addr1);
  1.1547 +  }else{
  1.1548 +    emptyDestTest = 0;
  1.1549 +  }
  1.1550 +  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  1.1551 +  emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
  1.1552 +  if( pDest->iPKey>=0 ){
  1.1553 +    addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
  1.1554 +    sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
  1.1555 +    addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
  1.1556 +    sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, 
  1.1557 +                      "PRIMARY KEY must be unique", P3_STATIC);
  1.1558 +    sqlite3VdbeJumpHere(v, addr2);
  1.1559 +    autoIncStep(pParse, counterMem);
  1.1560 +  }else if( pDest->pIndex==0 ){
  1.1561 +    addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
  1.1562 +  }else{
  1.1563 +    addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
  1.1564 +    assert( pDest->autoInc==0 );
  1.1565 +  }
  1.1566 +  sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
  1.1567 +  sqlite3VdbeOp3(v, OP_Insert, iDest,
  1.1568 +                    OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
  1.1569 +                    pDest->zName, 0);
  1.1570 +  sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
  1.1571 +  autoIncEnd(pParse, iDbDest, pDest, counterMem);
  1.1572 +  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  1.1573 +    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  1.1574 +      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  1.1575 +    }
  1.1576 +    assert( pSrcIdx );
  1.1577 +    sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
  1.1578 +    sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
  1.1579 +    sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
  1.1580 +    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
  1.1581 +    VdbeComment((v, "# %s", pSrcIdx->zName));
  1.1582 +    sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, 
  1.1583 +                   (char*)pKey, P3_KEYINFO_HANDOFF);
  1.1584 +    sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
  1.1585 +    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
  1.1586 +    VdbeComment((v, "# %s", pDestIdx->zName));
  1.1587 +    sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, 
  1.1588 +                   (char*)pKey, P3_KEYINFO_HANDOFF);
  1.1589 +    addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
  1.1590 +    sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
  1.1591 +    sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
  1.1592 +    sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
  1.1593 +    sqlite3VdbeJumpHere(v, addr1);
  1.1594 +  }
  1.1595 +  sqlite3VdbeJumpHere(v, emptySrcTest);
  1.1596 +  sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
  1.1597 +  sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
  1.1598 +  if( emptyDestTest ){
  1.1599 +    sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
  1.1600 +    sqlite3VdbeJumpHere(v, emptyDestTest);
  1.1601 +    sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
  1.1602 +    return 0;
  1.1603 +  }else{
  1.1604 +    return 1;
  1.1605 +  }
  1.1606 +}
  1.1607 +#endif /* SQLITE_OMIT_XFER_OPT */