Annotation of embedaddon/sqlite3/src/insert.c, revision 1.1

1.1     ! misho       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 open a table for reading.
        !            19: */
        !            20: void sqlite3OpenTable(
        !            21:   Parse *p,       /* Generate code into this VDBE */
        !            22:   int iCur,       /* The cursor number of the table */
        !            23:   int iDb,        /* The database index in sqlite3.aDb[] */
        !            24:   Table *pTab,    /* The table to be opened */
        !            25:   int opcode      /* OP_OpenRead or OP_OpenWrite */
        !            26: ){
        !            27:   Vdbe *v;
        !            28:   if( IsVirtual(pTab) ) return;
        !            29:   v = sqlite3GetVdbe(p);
        !            30:   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
        !            31:   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
        !            32:   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
        !            33:   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
        !            34:   VdbeComment((v, "%s", pTab->zName));
        !            35: }
        !            36: 
        !            37: /*
        !            38: ** Return a pointer to the column affinity string associated with index
        !            39: ** pIdx. A column affinity string has one character for each column in 
        !            40: ** the table, according to the affinity of the column:
        !            41: **
        !            42: **  Character      Column affinity
        !            43: **  ------------------------------
        !            44: **  'a'            TEXT
        !            45: **  'b'            NONE
        !            46: **  'c'            NUMERIC
        !            47: **  'd'            INTEGER
        !            48: **  'e'            REAL
        !            49: **
        !            50: ** An extra 'd' is appended to the end of the string to cover the
        !            51: ** rowid that appears as the last column in every index.
        !            52: **
        !            53: ** Memory for the buffer containing the column index affinity string
        !            54: ** is managed along with the rest of the Index structure. It will be
        !            55: ** released when sqlite3DeleteIndex() is called.
        !            56: */
        !            57: const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
        !            58:   if( !pIdx->zColAff ){
        !            59:     /* The first time a column affinity string for a particular index is
        !            60:     ** required, it is allocated and populated here. It is then stored as
        !            61:     ** a member of the Index structure for subsequent use.
        !            62:     **
        !            63:     ** The column affinity string will eventually be deleted by
        !            64:     ** sqliteDeleteIndex() when the Index structure itself is cleaned
        !            65:     ** up.
        !            66:     */
        !            67:     int n;
        !            68:     Table *pTab = pIdx->pTable;
        !            69:     sqlite3 *db = sqlite3VdbeDb(v);
        !            70:     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
        !            71:     if( !pIdx->zColAff ){
        !            72:       db->mallocFailed = 1;
        !            73:       return 0;
        !            74:     }
        !            75:     for(n=0; n<pIdx->nColumn; n++){
        !            76:       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
        !            77:     }
        !            78:     pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
        !            79:     pIdx->zColAff[n] = 0;
        !            80:   }
        !            81:  
        !            82:   return pIdx->zColAff;
        !            83: }
        !            84: 
        !            85: /*
        !            86: ** Set P4 of the most recently inserted opcode to a column affinity
        !            87: ** string for table pTab. A column affinity string has one character
        !            88: ** for each column indexed by the index, according to the affinity of the
        !            89: ** column:
        !            90: **
        !            91: **  Character      Column affinity
        !            92: **  ------------------------------
        !            93: **  'a'            TEXT
        !            94: **  'b'            NONE
        !            95: **  'c'            NUMERIC
        !            96: **  'd'            INTEGER
        !            97: **  'e'            REAL
        !            98: */
        !            99: void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
        !           100:   /* The first time a column affinity string for a particular table
        !           101:   ** is required, it is allocated and populated here. It is then 
        !           102:   ** stored as a member of the Table structure for subsequent use.
        !           103:   **
        !           104:   ** The column affinity string will eventually be deleted by
        !           105:   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
        !           106:   */
        !           107:   if( !pTab->zColAff ){
        !           108:     char *zColAff;
        !           109:     int i;
        !           110:     sqlite3 *db = sqlite3VdbeDb(v);
        !           111: 
        !           112:     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
        !           113:     if( !zColAff ){
        !           114:       db->mallocFailed = 1;
        !           115:       return;
        !           116:     }
        !           117: 
        !           118:     for(i=0; i<pTab->nCol; i++){
        !           119:       zColAff[i] = pTab->aCol[i].affinity;
        !           120:     }
        !           121:     zColAff[pTab->nCol] = '\0';
        !           122: 
        !           123:     pTab->zColAff = zColAff;
        !           124:   }
        !           125: 
        !           126:   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
        !           127: }
        !           128: 
        !           129: /*
        !           130: ** Return non-zero if the table pTab in database iDb or any of its indices
        !           131: ** have been opened at any point in the VDBE program beginning at location
        !           132: ** iStartAddr throught the end of the program.  This is used to see if 
        !           133: ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
        !           134: ** run without using temporary table for the results of the SELECT. 
        !           135: */
        !           136: static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
        !           137:   Vdbe *v = sqlite3GetVdbe(p);
        !           138:   int i;
        !           139:   int iEnd = sqlite3VdbeCurrentAddr(v);
        !           140: #ifndef SQLITE_OMIT_VIRTUALTABLE
        !           141:   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
        !           142: #endif
        !           143: 
        !           144:   for(i=iStartAddr; i<iEnd; i++){
        !           145:     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
        !           146:     assert( pOp!=0 );
        !           147:     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
        !           148:       Index *pIndex;
        !           149:       int tnum = pOp->p2;
        !           150:       if( tnum==pTab->tnum ){
        !           151:         return 1;
        !           152:       }
        !           153:       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
        !           154:         if( tnum==pIndex->tnum ){
        !           155:           return 1;
        !           156:         }
        !           157:       }
        !           158:     }
        !           159: #ifndef SQLITE_OMIT_VIRTUALTABLE
        !           160:     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
        !           161:       assert( pOp->p4.pVtab!=0 );
        !           162:       assert( pOp->p4type==P4_VTAB );
        !           163:       return 1;
        !           164:     }
        !           165: #endif
        !           166:   }
        !           167:   return 0;
        !           168: }
        !           169: 
        !           170: #ifndef SQLITE_OMIT_AUTOINCREMENT
        !           171: /*
        !           172: ** Locate or create an AutoincInfo structure associated with table pTab
        !           173: ** which is in database iDb.  Return the register number for the register
        !           174: ** that holds the maximum rowid.
        !           175: **
        !           176: ** There is at most one AutoincInfo structure per table even if the
        !           177: ** same table is autoincremented multiple times due to inserts within
        !           178: ** triggers.  A new AutoincInfo structure is created if this is the
        !           179: ** first use of table pTab.  On 2nd and subsequent uses, the original
        !           180: ** AutoincInfo structure is used.
        !           181: **
        !           182: ** Three memory locations are allocated:
        !           183: **
        !           184: **   (1)  Register to hold the name of the pTab table.
        !           185: **   (2)  Register to hold the maximum ROWID of pTab.
        !           186: **   (3)  Register to hold the rowid in sqlite_sequence of pTab
        !           187: **
        !           188: ** The 2nd register is the one that is returned.  That is all the
        !           189: ** insert routine needs to know about.
        !           190: */
        !           191: static int autoIncBegin(
        !           192:   Parse *pParse,      /* Parsing context */
        !           193:   int iDb,            /* Index of the database holding pTab */
        !           194:   Table *pTab         /* The table we are writing to */
        !           195: ){
        !           196:   int memId = 0;      /* Register holding maximum rowid */
        !           197:   if( pTab->tabFlags & TF_Autoincrement ){
        !           198:     Parse *pToplevel = sqlite3ParseToplevel(pParse);
        !           199:     AutoincInfo *pInfo;
        !           200: 
        !           201:     pInfo = pToplevel->pAinc;
        !           202:     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
        !           203:     if( pInfo==0 ){
        !           204:       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
        !           205:       if( pInfo==0 ) return 0;
        !           206:       pInfo->pNext = pToplevel->pAinc;
        !           207:       pToplevel->pAinc = pInfo;
        !           208:       pInfo->pTab = pTab;
        !           209:       pInfo->iDb = iDb;
        !           210:       pToplevel->nMem++;                  /* Register to hold name of table */
        !           211:       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
        !           212:       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
        !           213:     }
        !           214:     memId = pInfo->regCtr;
        !           215:   }
        !           216:   return memId;
        !           217: }
        !           218: 
        !           219: /*
        !           220: ** This routine generates code that will initialize all of the
        !           221: ** register used by the autoincrement tracker.  
        !           222: */
        !           223: void sqlite3AutoincrementBegin(Parse *pParse){
        !           224:   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
        !           225:   sqlite3 *db = pParse->db;  /* The database connection */
        !           226:   Db *pDb;                   /* Database only autoinc table */
        !           227:   int memId;                 /* Register holding max rowid */
        !           228:   int addr;                  /* A VDBE address */
        !           229:   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
        !           230: 
        !           231:   /* This routine is never called during trigger-generation.  It is
        !           232:   ** only called from the top-level */
        !           233:   assert( pParse->pTriggerTab==0 );
        !           234:   assert( pParse==sqlite3ParseToplevel(pParse) );
        !           235: 
        !           236:   assert( v );   /* We failed long ago if this is not so */
        !           237:   for(p = pParse->pAinc; p; p = p->pNext){
        !           238:     pDb = &db->aDb[p->iDb];
        !           239:     memId = p->regCtr;
        !           240:     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
        !           241:     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
        !           242:     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
        !           243:     addr = sqlite3VdbeCurrentAddr(v);
        !           244:     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
        !           245:     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
        !           246:     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
        !           247:     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
        !           248:     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
        !           249:     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
        !           250:     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
        !           251:     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
        !           252:     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
        !           253:     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
        !           254:     sqlite3VdbeAddOp0(v, OP_Close);
        !           255:   }
        !           256: }
        !           257: 
        !           258: /*
        !           259: ** Update the maximum rowid for an autoincrement calculation.
        !           260: **
        !           261: ** This routine should be called when the top of the stack holds a
        !           262: ** new rowid that is about to be inserted.  If that new rowid is
        !           263: ** larger than the maximum rowid in the memId memory cell, then the
        !           264: ** memory cell is updated.  The stack is unchanged.
        !           265: */
        !           266: static void autoIncStep(Parse *pParse, int memId, int regRowid){
        !           267:   if( memId>0 ){
        !           268:     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
        !           269:   }
        !           270: }
        !           271: 
        !           272: /*
        !           273: ** This routine generates the code needed to write autoincrement
        !           274: ** maximum rowid values back into the sqlite_sequence register.
        !           275: ** Every statement that might do an INSERT into an autoincrement
        !           276: ** table (either directly or through triggers) needs to call this
        !           277: ** routine just before the "exit" code.
        !           278: */
        !           279: void sqlite3AutoincrementEnd(Parse *pParse){
        !           280:   AutoincInfo *p;
        !           281:   Vdbe *v = pParse->pVdbe;
        !           282:   sqlite3 *db = pParse->db;
        !           283: 
        !           284:   assert( v );
        !           285:   for(p = pParse->pAinc; p; p = p->pNext){
        !           286:     Db *pDb = &db->aDb[p->iDb];
        !           287:     int j1, j2, j3, j4, j5;
        !           288:     int iRec;
        !           289:     int memId = p->regCtr;
        !           290: 
        !           291:     iRec = sqlite3GetTempReg(pParse);
        !           292:     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
        !           293:     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
        !           294:     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
        !           295:     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
        !           296:     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
        !           297:     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
        !           298:     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
        !           299:     sqlite3VdbeJumpHere(v, j2);
        !           300:     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
        !           301:     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
        !           302:     sqlite3VdbeJumpHere(v, j4);
        !           303:     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
        !           304:     sqlite3VdbeJumpHere(v, j1);
        !           305:     sqlite3VdbeJumpHere(v, j5);
        !           306:     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
        !           307:     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
        !           308:     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
        !           309:     sqlite3VdbeAddOp0(v, OP_Close);
        !           310:     sqlite3ReleaseTempReg(pParse, iRec);
        !           311:   }
        !           312: }
        !           313: #else
        !           314: /*
        !           315: ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
        !           316: ** above are all no-ops
        !           317: */
        !           318: # define autoIncBegin(A,B,C) (0)
        !           319: # define autoIncStep(A,B,C)
        !           320: #endif /* SQLITE_OMIT_AUTOINCREMENT */
        !           321: 
        !           322: 
        !           323: /* Forward declaration */
        !           324: static int xferOptimization(
        !           325:   Parse *pParse,        /* Parser context */
        !           326:   Table *pDest,         /* The table we are inserting into */
        !           327:   Select *pSelect,      /* A SELECT statement to use as the data source */
        !           328:   int onError,          /* How to handle constraint errors */
        !           329:   int iDbDest           /* The database of pDest */
        !           330: );
        !           331: 
        !           332: /*
        !           333: ** This routine is call to handle SQL of the following forms:
        !           334: **
        !           335: **    insert into TABLE (IDLIST) values(EXPRLIST)
        !           336: **    insert into TABLE (IDLIST) select
        !           337: **
        !           338: ** The IDLIST following the table name is always optional.  If omitted,
        !           339: ** then a list of all columns for the table is substituted.  The IDLIST
        !           340: ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
        !           341: **
        !           342: ** The pList parameter holds EXPRLIST in the first form of the INSERT
        !           343: ** statement above, and pSelect is NULL.  For the second form, pList is
        !           344: ** NULL and pSelect is a pointer to the select statement used to generate
        !           345: ** data for the insert.
        !           346: **
        !           347: ** The code generated follows one of four templates.  For a simple
        !           348: ** select with data coming from a VALUES clause, the code executes
        !           349: ** once straight down through.  Pseudo-code follows (we call this
        !           350: ** the "1st template"):
        !           351: **
        !           352: **         open write cursor to <table> and its indices
        !           353: **         puts VALUES clause expressions onto the stack
        !           354: **         write the resulting record into <table>
        !           355: **         cleanup
        !           356: **
        !           357: ** The three remaining templates assume the statement is of the form
        !           358: **
        !           359: **   INSERT INTO <table> SELECT ...
        !           360: **
        !           361: ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
        !           362: ** in other words if the SELECT pulls all columns from a single table
        !           363: ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
        !           364: ** if <table2> and <table1> are distinct tables but have identical
        !           365: ** schemas, including all the same indices, then a special optimization
        !           366: ** is invoked that copies raw records from <table2> over to <table1>.
        !           367: ** See the xferOptimization() function for the implementation of this
        !           368: ** template.  This is the 2nd template.
        !           369: **
        !           370: **         open a write cursor to <table>
        !           371: **         open read cursor on <table2>
        !           372: **         transfer all records in <table2> over to <table>
        !           373: **         close cursors
        !           374: **         foreach index on <table>
        !           375: **           open a write cursor on the <table> index
        !           376: **           open a read cursor on the corresponding <table2> index
        !           377: **           transfer all records from the read to the write cursors
        !           378: **           close cursors
        !           379: **         end foreach
        !           380: **
        !           381: ** The 3rd template is for when the second template does not apply
        !           382: ** and the SELECT clause does not read from <table> at any time.
        !           383: ** The generated code follows this template:
        !           384: **
        !           385: **         EOF <- 0
        !           386: **         X <- A
        !           387: **         goto B
        !           388: **      A: setup for the SELECT
        !           389: **         loop over the rows in the SELECT
        !           390: **           load values into registers R..R+n
        !           391: **           yield X
        !           392: **         end loop
        !           393: **         cleanup after the SELECT
        !           394: **         EOF <- 1
        !           395: **         yield X
        !           396: **         goto A
        !           397: **      B: open write cursor to <table> and its indices
        !           398: **      C: yield X
        !           399: **         if EOF goto D
        !           400: **         insert the select result into <table> from R..R+n
        !           401: **         goto C
        !           402: **      D: cleanup
        !           403: **
        !           404: ** The 4th template is used if the insert statement takes its
        !           405: ** values from a SELECT but the data is being inserted into a table
        !           406: ** that is also read as part of the SELECT.  In the third form,
        !           407: ** we have to use a intermediate table to store the results of
        !           408: ** the select.  The template is like this:
        !           409: **
        !           410: **         EOF <- 0
        !           411: **         X <- A
        !           412: **         goto B
        !           413: **      A: setup for the SELECT
        !           414: **         loop over the tables in the SELECT
        !           415: **           load value into register R..R+n
        !           416: **           yield X
        !           417: **         end loop
        !           418: **         cleanup after the SELECT
        !           419: **         EOF <- 1
        !           420: **         yield X
        !           421: **         halt-error
        !           422: **      B: open temp table
        !           423: **      L: yield X
        !           424: **         if EOF goto M
        !           425: **         insert row from R..R+n into temp table
        !           426: **         goto L
        !           427: **      M: open write cursor to <table> and its indices
        !           428: **         rewind temp table
        !           429: **      C: loop over rows of intermediate table
        !           430: **           transfer values form intermediate table into <table>
        !           431: **         end loop
        !           432: **      D: cleanup
        !           433: */
        !           434: void sqlite3Insert(
        !           435:   Parse *pParse,        /* Parser context */
        !           436:   SrcList *pTabList,    /* Name of table into which we are inserting */
        !           437:   ExprList *pList,      /* List of values to be inserted */
        !           438:   Select *pSelect,      /* A SELECT statement to use as the data source */
        !           439:   IdList *pColumn,      /* Column names corresponding to IDLIST. */
        !           440:   int onError           /* How to handle constraint errors */
        !           441: ){
        !           442:   sqlite3 *db;          /* The main database structure */
        !           443:   Table *pTab;          /* The table to insert into.  aka TABLE */
        !           444:   char *zTab;           /* Name of the table into which we are inserting */
        !           445:   const char *zDb;      /* Name of the database holding this table */
        !           446:   int i, j, idx;        /* Loop counters */
        !           447:   Vdbe *v;              /* Generate code into this virtual machine */
        !           448:   Index *pIdx;          /* For looping over indices of the table */
        !           449:   int nColumn;          /* Number of columns in the data */
        !           450:   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
        !           451:   int baseCur = 0;      /* VDBE Cursor number for pTab */
        !           452:   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
        !           453:   int endOfLoop;        /* Label for the end of the insertion loop */
        !           454:   int useTempTable = 0; /* Store SELECT results in intermediate table */
        !           455:   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
        !           456:   int addrInsTop = 0;   /* Jump to label "D" */
        !           457:   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
        !           458:   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
        !           459:   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
        !           460:   int iDb;              /* Index of database holding TABLE */
        !           461:   Db *pDb;              /* The database containing table being inserted into */
        !           462:   int appendFlag = 0;   /* True if the insert is likely to be an append */
        !           463: 
        !           464:   /* Register allocations */
        !           465:   int regFromSelect = 0;/* Base register for data coming from SELECT */
        !           466:   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
        !           467:   int regRowCount = 0;  /* Memory cell used for the row counter */
        !           468:   int regIns;           /* Block of regs holding rowid+data being inserted */
        !           469:   int regRowid;         /* registers holding insert rowid */
        !           470:   int regData;          /* register holding first column to insert */
        !           471:   int regEof = 0;       /* Register recording end of SELECT data */
        !           472:   int *aRegIdx = 0;     /* One register allocated to each index */
        !           473: 
        !           474: #ifndef SQLITE_OMIT_TRIGGER
        !           475:   int isView;                 /* True if attempting to insert into a view */
        !           476:   Trigger *pTrigger;          /* List of triggers on pTab, if required */
        !           477:   int tmask;                  /* Mask of trigger times */
        !           478: #endif
        !           479: 
        !           480:   db = pParse->db;
        !           481:   memset(&dest, 0, sizeof(dest));
        !           482:   if( pParse->nErr || db->mallocFailed ){
        !           483:     goto insert_cleanup;
        !           484:   }
        !           485: 
        !           486:   /* Locate the table into which we will be inserting new information.
        !           487:   */
        !           488:   assert( pTabList->nSrc==1 );
        !           489:   zTab = pTabList->a[0].zName;
        !           490:   if( NEVER(zTab==0) ) goto insert_cleanup;
        !           491:   pTab = sqlite3SrcListLookup(pParse, pTabList);
        !           492:   if( pTab==0 ){
        !           493:     goto insert_cleanup;
        !           494:   }
        !           495:   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
        !           496:   assert( iDb<db->nDb );
        !           497:   pDb = &db->aDb[iDb];
        !           498:   zDb = pDb->zName;
        !           499:   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
        !           500:     goto insert_cleanup;
        !           501:   }
        !           502: 
        !           503:   /* Figure out if we have any triggers and if the table being
        !           504:   ** inserted into is a view
        !           505:   */
        !           506: #ifndef SQLITE_OMIT_TRIGGER
        !           507:   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
        !           508:   isView = pTab->pSelect!=0;
        !           509: #else
        !           510: # define pTrigger 0
        !           511: # define tmask 0
        !           512: # define isView 0
        !           513: #endif
        !           514: #ifdef SQLITE_OMIT_VIEW
        !           515: # undef isView
        !           516: # define isView 0
        !           517: #endif
        !           518:   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
        !           519: 
        !           520:   /* If pTab is really a view, make sure it has been initialized.
        !           521:   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
        !           522:   ** module table).
        !           523:   */
        !           524:   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
        !           525:     goto insert_cleanup;
        !           526:   }
        !           527: 
        !           528:   /* Ensure that:
        !           529:   *  (a) the table is not read-only, 
        !           530:   *  (b) that if it is a view then ON INSERT triggers exist
        !           531:   */
        !           532:   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
        !           533:     goto insert_cleanup;
        !           534:   }
        !           535: 
        !           536:   /* Allocate a VDBE
        !           537:   */
        !           538:   v = sqlite3GetVdbe(pParse);
        !           539:   if( v==0 ) goto insert_cleanup;
        !           540:   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
        !           541:   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
        !           542: 
        !           543: #ifndef SQLITE_OMIT_XFER_OPT
        !           544:   /* If the statement is of the form
        !           545:   **
        !           546:   **       INSERT INTO <table1> SELECT * FROM <table2>;
        !           547:   **
        !           548:   ** Then special optimizations can be applied that make the transfer
        !           549:   ** very fast and which reduce fragmentation of indices.
        !           550:   **
        !           551:   ** This is the 2nd template.
        !           552:   */
        !           553:   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
        !           554:     assert( !pTrigger );
        !           555:     assert( pList==0 );
        !           556:     goto insert_end;
        !           557:   }
        !           558: #endif /* SQLITE_OMIT_XFER_OPT */
        !           559: 
        !           560:   /* If this is an AUTOINCREMENT table, look up the sequence number in the
        !           561:   ** sqlite_sequence table and store it in memory cell regAutoinc.
        !           562:   */
        !           563:   regAutoinc = autoIncBegin(pParse, iDb, pTab);
        !           564: 
        !           565:   /* Figure out how many columns of data are supplied.  If the data
        !           566:   ** is coming from a SELECT statement, then generate a co-routine that
        !           567:   ** produces a single row of the SELECT on each invocation.  The
        !           568:   ** co-routine is the common header to the 3rd and 4th templates.
        !           569:   */
        !           570:   if( pSelect ){
        !           571:     /* Data is coming from a SELECT.  Generate code to implement that SELECT
        !           572:     ** as a co-routine.  The code is common to both the 3rd and 4th
        !           573:     ** templates:
        !           574:     **
        !           575:     **         EOF <- 0
        !           576:     **         X <- A
        !           577:     **         goto B
        !           578:     **      A: setup for the SELECT
        !           579:     **         loop over the tables in the SELECT
        !           580:     **           load value into register R..R+n
        !           581:     **           yield X
        !           582:     **         end loop
        !           583:     **         cleanup after the SELECT
        !           584:     **         EOF <- 1
        !           585:     **         yield X
        !           586:     **         halt-error
        !           587:     **
        !           588:     ** On each invocation of the co-routine, it puts a single row of the
        !           589:     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
        !           590:     ** (These output registers are allocated by sqlite3Select().)  When
        !           591:     ** the SELECT completes, it sets the EOF flag stored in regEof.
        !           592:     */
        !           593:     int rc, j1;
        !           594: 
        !           595:     regEof = ++pParse->nMem;
        !           596:     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
        !           597:     VdbeComment((v, "SELECT eof flag"));
        !           598:     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
        !           599:     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
        !           600:     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
        !           601:     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
        !           602:     VdbeComment((v, "Jump over SELECT coroutine"));
        !           603: 
        !           604:     /* Resolve the expressions in the SELECT statement and execute it. */
        !           605:     rc = sqlite3Select(pParse, pSelect, &dest);
        !           606:     assert( pParse->nErr==0 || rc );
        !           607:     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
        !           608:       goto insert_cleanup;
        !           609:     }
        !           610:     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
        !           611:     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
        !           612:     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
        !           613:     VdbeComment((v, "End of SELECT coroutine"));
        !           614:     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
        !           615: 
        !           616:     regFromSelect = dest.iMem;
        !           617:     assert( pSelect->pEList );
        !           618:     nColumn = pSelect->pEList->nExpr;
        !           619:     assert( dest.nMem==nColumn );
        !           620: 
        !           621:     /* Set useTempTable to TRUE if the result of the SELECT statement
        !           622:     ** should be written into a temporary table (template 4).  Set to
        !           623:     ** FALSE if each* row of the SELECT can be written directly into
        !           624:     ** the destination table (template 3).
        !           625:     **
        !           626:     ** A temp table must be used if the table being updated is also one
        !           627:     ** of the tables being read by the SELECT statement.  Also use a 
        !           628:     ** temp table in the case of row triggers.
        !           629:     */
        !           630:     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
        !           631:       useTempTable = 1;
        !           632:     }
        !           633: 
        !           634:     if( useTempTable ){
        !           635:       /* Invoke the coroutine to extract information from the SELECT
        !           636:       ** and add it to a transient table srcTab.  The code generated
        !           637:       ** here is from the 4th template:
        !           638:       **
        !           639:       **      B: open temp table
        !           640:       **      L: yield X
        !           641:       **         if EOF goto M
        !           642:       **         insert row from R..R+n into temp table
        !           643:       **         goto L
        !           644:       **      M: ...
        !           645:       */
        !           646:       int regRec;          /* Register to hold packed record */
        !           647:       int regTempRowid;    /* Register to hold temp table ROWID */
        !           648:       int addrTop;         /* Label "L" */
        !           649:       int addrIf;          /* Address of jump to M */
        !           650: 
        !           651:       srcTab = pParse->nTab++;
        !           652:       regRec = sqlite3GetTempReg(pParse);
        !           653:       regTempRowid = sqlite3GetTempReg(pParse);
        !           654:       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
        !           655:       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
        !           656:       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
        !           657:       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
        !           658:       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
        !           659:       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
        !           660:       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
        !           661:       sqlite3VdbeJumpHere(v, addrIf);
        !           662:       sqlite3ReleaseTempReg(pParse, regRec);
        !           663:       sqlite3ReleaseTempReg(pParse, regTempRowid);
        !           664:     }
        !           665:   }else{
        !           666:     /* This is the case if the data for the INSERT is coming from a VALUES
        !           667:     ** clause
        !           668:     */
        !           669:     NameContext sNC;
        !           670:     memset(&sNC, 0, sizeof(sNC));
        !           671:     sNC.pParse = pParse;
        !           672:     srcTab = -1;
        !           673:     assert( useTempTable==0 );
        !           674:     nColumn = pList ? pList->nExpr : 0;
        !           675:     for(i=0; i<nColumn; i++){
        !           676:       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
        !           677:         goto insert_cleanup;
        !           678:       }
        !           679:     }
        !           680:   }
        !           681: 
        !           682:   /* Make sure the number of columns in the source data matches the number
        !           683:   ** of columns to be inserted into the table.
        !           684:   */
        !           685:   if( IsVirtual(pTab) ){
        !           686:     for(i=0; i<pTab->nCol; i++){
        !           687:       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
        !           688:     }
        !           689:   }
        !           690:   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
        !           691:     sqlite3ErrorMsg(pParse, 
        !           692:        "table %S has %d columns but %d values were supplied",
        !           693:        pTabList, 0, pTab->nCol-nHidden, nColumn);
        !           694:     goto insert_cleanup;
        !           695:   }
        !           696:   if( pColumn!=0 && nColumn!=pColumn->nId ){
        !           697:     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
        !           698:     goto insert_cleanup;
        !           699:   }
        !           700: 
        !           701:   /* If the INSERT statement included an IDLIST term, then make sure
        !           702:   ** all elements of the IDLIST really are columns of the table and 
        !           703:   ** remember the column indices.
        !           704:   **
        !           705:   ** If the table has an INTEGER PRIMARY KEY column and that column
        !           706:   ** is named in the IDLIST, then record in the keyColumn variable
        !           707:   ** the index into IDLIST of the primary key column.  keyColumn is
        !           708:   ** the index of the primary key as it appears in IDLIST, not as
        !           709:   ** is appears in the original table.  (The index of the primary
        !           710:   ** key in the original table is pTab->iPKey.)
        !           711:   */
        !           712:   if( pColumn ){
        !           713:     for(i=0; i<pColumn->nId; i++){
        !           714:       pColumn->a[i].idx = -1;
        !           715:     }
        !           716:     for(i=0; i<pColumn->nId; i++){
        !           717:       for(j=0; j<pTab->nCol; j++){
        !           718:         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
        !           719:           pColumn->a[i].idx = j;
        !           720:           if( j==pTab->iPKey ){
        !           721:             keyColumn = i;
        !           722:           }
        !           723:           break;
        !           724:         }
        !           725:       }
        !           726:       if( j>=pTab->nCol ){
        !           727:         if( sqlite3IsRowid(pColumn->a[i].zName) ){
        !           728:           keyColumn = i;
        !           729:         }else{
        !           730:           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
        !           731:               pTabList, 0, pColumn->a[i].zName);
        !           732:           pParse->checkSchema = 1;
        !           733:           goto insert_cleanup;
        !           734:         }
        !           735:       }
        !           736:     }
        !           737:   }
        !           738: 
        !           739:   /* If there is no IDLIST term but the table has an integer primary
        !           740:   ** key, the set the keyColumn variable to the primary key column index
        !           741:   ** in the original table definition.
        !           742:   */
        !           743:   if( pColumn==0 && nColumn>0 ){
        !           744:     keyColumn = pTab->iPKey;
        !           745:   }
        !           746:     
        !           747:   /* Initialize the count of rows to be inserted
        !           748:   */
        !           749:   if( db->flags & SQLITE_CountRows ){
        !           750:     regRowCount = ++pParse->nMem;
        !           751:     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
        !           752:   }
        !           753: 
        !           754:   /* If this is not a view, open the table and and all indices */
        !           755:   if( !isView ){
        !           756:     int nIdx;
        !           757: 
        !           758:     baseCur = pParse->nTab;
        !           759:     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
        !           760:     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
        !           761:     if( aRegIdx==0 ){
        !           762:       goto insert_cleanup;
        !           763:     }
        !           764:     for(i=0; i<nIdx; i++){
        !           765:       aRegIdx[i] = ++pParse->nMem;
        !           766:     }
        !           767:   }
        !           768: 
        !           769:   /* This is the top of the main insertion loop */
        !           770:   if( useTempTable ){
        !           771:     /* This block codes the top of loop only.  The complete loop is the
        !           772:     ** following pseudocode (template 4):
        !           773:     **
        !           774:     **         rewind temp table
        !           775:     **      C: loop over rows of intermediate table
        !           776:     **           transfer values form intermediate table into <table>
        !           777:     **         end loop
        !           778:     **      D: ...
        !           779:     */
        !           780:     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
        !           781:     addrCont = sqlite3VdbeCurrentAddr(v);
        !           782:   }else if( pSelect ){
        !           783:     /* This block codes the top of loop only.  The complete loop is the
        !           784:     ** following pseudocode (template 3):
        !           785:     **
        !           786:     **      C: yield X
        !           787:     **         if EOF goto D
        !           788:     **         insert the select result into <table> from R..R+n
        !           789:     **         goto C
        !           790:     **      D: ...
        !           791:     */
        !           792:     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
        !           793:     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
        !           794:   }
        !           795: 
        !           796:   /* Allocate registers for holding the rowid of the new row,
        !           797:   ** the content of the new row, and the assemblied row record.
        !           798:   */
        !           799:   regRowid = regIns = pParse->nMem+1;
        !           800:   pParse->nMem += pTab->nCol + 1;
        !           801:   if( IsVirtual(pTab) ){
        !           802:     regRowid++;
        !           803:     pParse->nMem++;
        !           804:   }
        !           805:   regData = regRowid+1;
        !           806: 
        !           807:   /* Run the BEFORE and INSTEAD OF triggers, if there are any
        !           808:   */
        !           809:   endOfLoop = sqlite3VdbeMakeLabel(v);
        !           810:   if( tmask & TRIGGER_BEFORE ){
        !           811:     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
        !           812: 
        !           813:     /* build the NEW.* reference row.  Note that if there is an INTEGER
        !           814:     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
        !           815:     ** translated into a unique ID for the row.  But on a BEFORE trigger,
        !           816:     ** we do not know what the unique ID will be (because the insert has
        !           817:     ** not happened yet) so we substitute a rowid of -1
        !           818:     */
        !           819:     if( keyColumn<0 ){
        !           820:       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
        !           821:     }else{
        !           822:       int j1;
        !           823:       if( useTempTable ){
        !           824:         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
        !           825:       }else{
        !           826:         assert( pSelect==0 );  /* Otherwise useTempTable is true */
        !           827:         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
        !           828:       }
        !           829:       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
        !           830:       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
        !           831:       sqlite3VdbeJumpHere(v, j1);
        !           832:       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
        !           833:     }
        !           834: 
        !           835:     /* Cannot have triggers on a virtual table. If it were possible,
        !           836:     ** this block would have to account for hidden column.
        !           837:     */
        !           838:     assert( !IsVirtual(pTab) );
        !           839: 
        !           840:     /* Create the new column data
        !           841:     */
        !           842:     for(i=0; i<pTab->nCol; i++){
        !           843:       if( pColumn==0 ){
        !           844:         j = i;
        !           845:       }else{
        !           846:         for(j=0; j<pColumn->nId; j++){
        !           847:           if( pColumn->a[j].idx==i ) break;
        !           848:         }
        !           849:       }
        !           850:       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
        !           851:         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
        !           852:       }else if( useTempTable ){
        !           853:         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
        !           854:       }else{
        !           855:         assert( pSelect==0 ); /* Otherwise useTempTable is true */
        !           856:         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
        !           857:       }
        !           858:     }
        !           859: 
        !           860:     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
        !           861:     ** do not attempt any conversions before assembling the record.
        !           862:     ** If this is a real table, attempt conversions as required by the
        !           863:     ** table column affinities.
        !           864:     */
        !           865:     if( !isView ){
        !           866:       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
        !           867:       sqlite3TableAffinityStr(v, pTab);
        !           868:     }
        !           869: 
        !           870:     /* Fire BEFORE or INSTEAD OF triggers */
        !           871:     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
        !           872:         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
        !           873: 
        !           874:     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
        !           875:   }
        !           876: 
        !           877:   /* Push the record number for the new entry onto the stack.  The
        !           878:   ** record number is a randomly generate integer created by NewRowid
        !           879:   ** except when the table has an INTEGER PRIMARY KEY column, in which
        !           880:   ** case the record number is the same as that column. 
        !           881:   */
        !           882:   if( !isView ){
        !           883:     if( IsVirtual(pTab) ){
        !           884:       /* The row that the VUpdate opcode will delete: none */
        !           885:       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
        !           886:     }
        !           887:     if( keyColumn>=0 ){
        !           888:       if( useTempTable ){
        !           889:         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
        !           890:       }else if( pSelect ){
        !           891:         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
        !           892:       }else{
        !           893:         VdbeOp *pOp;
        !           894:         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
        !           895:         pOp = sqlite3VdbeGetOp(v, -1);
        !           896:         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
        !           897:           appendFlag = 1;
        !           898:           pOp->opcode = OP_NewRowid;
        !           899:           pOp->p1 = baseCur;
        !           900:           pOp->p2 = regRowid;
        !           901:           pOp->p3 = regAutoinc;
        !           902:         }
        !           903:       }
        !           904:       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
        !           905:       ** to generate a unique primary key value.
        !           906:       */
        !           907:       if( !appendFlag ){
        !           908:         int j1;
        !           909:         if( !IsVirtual(pTab) ){
        !           910:           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
        !           911:           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
        !           912:           sqlite3VdbeJumpHere(v, j1);
        !           913:         }else{
        !           914:           j1 = sqlite3VdbeCurrentAddr(v);
        !           915:           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
        !           916:         }
        !           917:         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
        !           918:       }
        !           919:     }else if( IsVirtual(pTab) ){
        !           920:       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
        !           921:     }else{
        !           922:       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
        !           923:       appendFlag = 1;
        !           924:     }
        !           925:     autoIncStep(pParse, regAutoinc, regRowid);
        !           926: 
        !           927:     /* Push onto the stack, data for all columns of the new entry, beginning
        !           928:     ** with the first column.
        !           929:     */
        !           930:     nHidden = 0;
        !           931:     for(i=0; i<pTab->nCol; i++){
        !           932:       int iRegStore = regRowid+1+i;
        !           933:       if( i==pTab->iPKey ){
        !           934:         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
        !           935:         ** Whenever this column is read, the record number will be substituted
        !           936:         ** in its place.  So will fill this column with a NULL to avoid
        !           937:         ** taking up data space with information that will never be used. */
        !           938:         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
        !           939:         continue;
        !           940:       }
        !           941:       if( pColumn==0 ){
        !           942:         if( IsHiddenColumn(&pTab->aCol[i]) ){
        !           943:           assert( IsVirtual(pTab) );
        !           944:           j = -1;
        !           945:           nHidden++;
        !           946:         }else{
        !           947:           j = i - nHidden;
        !           948:         }
        !           949:       }else{
        !           950:         for(j=0; j<pColumn->nId; j++){
        !           951:           if( pColumn->a[j].idx==i ) break;
        !           952:         }
        !           953:       }
        !           954:       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
        !           955:         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
        !           956:       }else if( useTempTable ){
        !           957:         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
        !           958:       }else if( pSelect ){
        !           959:         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
        !           960:       }else{
        !           961:         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
        !           962:       }
        !           963:     }
        !           964: 
        !           965:     /* Generate code to check constraints and generate index keys and
        !           966:     ** do the insertion.
        !           967:     */
        !           968: #ifndef SQLITE_OMIT_VIRTUALTABLE
        !           969:     if( IsVirtual(pTab) ){
        !           970:       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
        !           971:       sqlite3VtabMakeWritable(pParse, pTab);
        !           972:       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
        !           973:       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
        !           974:       sqlite3MayAbort(pParse);
        !           975:     }else
        !           976: #endif
        !           977:     {
        !           978:       int isReplace;    /* Set to true if constraints may cause a replace */
        !           979:       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
        !           980:           keyColumn>=0, 0, onError, endOfLoop, &isReplace
        !           981:       );
        !           982:       sqlite3FkCheck(pParse, pTab, 0, regIns);
        !           983:       sqlite3CompleteInsertion(
        !           984:           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
        !           985:       );
        !           986:     }
        !           987:   }
        !           988: 
        !           989:   /* Update the count of rows that are inserted
        !           990:   */
        !           991:   if( (db->flags & SQLITE_CountRows)!=0 ){
        !           992:     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
        !           993:   }
        !           994: 
        !           995:   if( pTrigger ){
        !           996:     /* Code AFTER triggers */
        !           997:     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
        !           998:         pTab, regData-2-pTab->nCol, onError, endOfLoop);
        !           999:   }
        !          1000: 
        !          1001:   /* The bottom of the main insertion loop, if the data source
        !          1002:   ** is a SELECT statement.
        !          1003:   */
        !          1004:   sqlite3VdbeResolveLabel(v, endOfLoop);
        !          1005:   if( useTempTable ){
        !          1006:     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
        !          1007:     sqlite3VdbeJumpHere(v, addrInsTop);
        !          1008:     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
        !          1009:   }else if( pSelect ){
        !          1010:     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
        !          1011:     sqlite3VdbeJumpHere(v, addrInsTop);
        !          1012:   }
        !          1013: 
        !          1014:   if( !IsVirtual(pTab) && !isView ){
        !          1015:     /* Close all tables opened */
        !          1016:     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
        !          1017:     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
        !          1018:       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
        !          1019:     }
        !          1020:   }
        !          1021: 
        !          1022: insert_end:
        !          1023:   /* Update the sqlite_sequence table by storing the content of the
        !          1024:   ** maximum rowid counter values recorded while inserting into
        !          1025:   ** autoincrement tables.
        !          1026:   */
        !          1027:   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
        !          1028:     sqlite3AutoincrementEnd(pParse);
        !          1029:   }
        !          1030: 
        !          1031:   /*
        !          1032:   ** Return the number of rows inserted. If this routine is 
        !          1033:   ** generating code because of a call to sqlite3NestedParse(), do not
        !          1034:   ** invoke the callback function.
        !          1035:   */
        !          1036:   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
        !          1037:     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
        !          1038:     sqlite3VdbeSetNumCols(v, 1);
        !          1039:     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
        !          1040:   }
        !          1041: 
        !          1042: insert_cleanup:
        !          1043:   sqlite3SrcListDelete(db, pTabList);
        !          1044:   sqlite3ExprListDelete(db, pList);
        !          1045:   sqlite3SelectDelete(db, pSelect);
        !          1046:   sqlite3IdListDelete(db, pColumn);
        !          1047:   sqlite3DbFree(db, aRegIdx);
        !          1048: }
        !          1049: 
        !          1050: /* Make sure "isView" and other macros defined above are undefined. Otherwise
        !          1051: ** thely may interfere with compilation of other functions in this file
        !          1052: ** (or in another file, if this file becomes part of the amalgamation).  */
        !          1053: #ifdef isView
        !          1054:  #undef isView
        !          1055: #endif
        !          1056: #ifdef pTrigger
        !          1057:  #undef pTrigger
        !          1058: #endif
        !          1059: #ifdef tmask
        !          1060:  #undef tmask
        !          1061: #endif
        !          1062: 
        !          1063: 
        !          1064: /*
        !          1065: ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
        !          1066: **
        !          1067: ** The input is a range of consecutive registers as follows:
        !          1068: **
        !          1069: **    1.  The rowid of the row after the update.
        !          1070: **
        !          1071: **    2.  The data in the first column of the entry after the update.
        !          1072: **
        !          1073: **    i.  Data from middle columns...
        !          1074: **
        !          1075: **    N.  The data in the last column of the entry after the update.
        !          1076: **
        !          1077: ** The regRowid parameter is the index of the register containing (1).
        !          1078: **
        !          1079: ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
        !          1080: ** the address of a register containing the rowid before the update takes
        !          1081: ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
        !          1082: ** is false, indicating an INSERT statement, then a non-zero rowidChng 
        !          1083: ** indicates that the rowid was explicitly specified as part of the
        !          1084: ** INSERT statement. If rowidChng is false, it means that  the rowid is
        !          1085: ** computed automatically in an insert or that the rowid value is not 
        !          1086: ** modified by an update.
        !          1087: **
        !          1088: ** The code generated by this routine store new index entries into
        !          1089: ** registers identified by aRegIdx[].  No index entry is created for
        !          1090: ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
        !          1091: ** the same as the order of indices on the linked list of indices
        !          1092: ** attached to the table.
        !          1093: **
        !          1094: ** This routine also generates code to check constraints.  NOT NULL,
        !          1095: ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
        !          1096: ** then the appropriate action is performed.  There are five possible
        !          1097: ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
        !          1098: **
        !          1099: **  Constraint type  Action       What Happens
        !          1100: **  ---------------  ----------   ----------------------------------------
        !          1101: **  any              ROLLBACK     The current transaction is rolled back and
        !          1102: **                                sqlite3_exec() returns immediately with a
        !          1103: **                                return code of SQLITE_CONSTRAINT.
        !          1104: **
        !          1105: **  any              ABORT        Back out changes from the current command
        !          1106: **                                only (do not do a complete rollback) then
        !          1107: **                                cause sqlite3_exec() to return immediately
        !          1108: **                                with SQLITE_CONSTRAINT.
        !          1109: **
        !          1110: **  any              FAIL         Sqlite3_exec() returns immediately with a
        !          1111: **                                return code of SQLITE_CONSTRAINT.  The
        !          1112: **                                transaction is not rolled back and any
        !          1113: **                                prior changes are retained.
        !          1114: **
        !          1115: **  any              IGNORE       The record number and data is popped from
        !          1116: **                                the stack and there is an immediate jump
        !          1117: **                                to label ignoreDest.
        !          1118: **
        !          1119: **  NOT NULL         REPLACE      The NULL value is replace by the default
        !          1120: **                                value for that column.  If the default value
        !          1121: **                                is NULL, the action is the same as ABORT.
        !          1122: **
        !          1123: **  UNIQUE           REPLACE      The other row that conflicts with the row
        !          1124: **                                being inserted is removed.
        !          1125: **
        !          1126: **  CHECK            REPLACE      Illegal.  The results in an exception.
        !          1127: **
        !          1128: ** Which action to take is determined by the overrideError parameter.
        !          1129: ** Or if overrideError==OE_Default, then the pParse->onError parameter
        !          1130: ** is used.  Or if pParse->onError==OE_Default then the onError value
        !          1131: ** for the constraint is used.
        !          1132: **
        !          1133: ** The calling routine must open a read/write cursor for pTab with
        !          1134: ** cursor number "baseCur".  All indices of pTab must also have open
        !          1135: ** read/write cursors with cursor number baseCur+i for the i-th cursor.
        !          1136: ** Except, if there is no possibility of a REPLACE action then
        !          1137: ** cursors do not need to be open for indices where aRegIdx[i]==0.
        !          1138: */
        !          1139: void sqlite3GenerateConstraintChecks(
        !          1140:   Parse *pParse,      /* The parser context */
        !          1141:   Table *pTab,        /* the table into which we are inserting */
        !          1142:   int baseCur,        /* Index of a read/write cursor pointing at pTab */
        !          1143:   int regRowid,       /* Index of the range of input registers */
        !          1144:   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
        !          1145:   int rowidChng,      /* True if the rowid might collide with existing entry */
        !          1146:   int isUpdate,       /* True for UPDATE, False for INSERT */
        !          1147:   int overrideError,  /* Override onError to this if not OE_Default */
        !          1148:   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
        !          1149:   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
        !          1150: ){
        !          1151:   int i;              /* loop counter */
        !          1152:   Vdbe *v;            /* VDBE under constrution */
        !          1153:   int nCol;           /* Number of columns */
        !          1154:   int onError;        /* Conflict resolution strategy */
        !          1155:   int j1;             /* Addresss of jump instruction */
        !          1156:   int j2 = 0, j3;     /* Addresses of jump instructions */
        !          1157:   int regData;        /* Register containing first data column */
        !          1158:   int iCur;           /* Table cursor number */
        !          1159:   Index *pIdx;         /* Pointer to one of the indices */
        !          1160:   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
        !          1161:   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
        !          1162: 
        !          1163:   v = sqlite3GetVdbe(pParse);
        !          1164:   assert( v!=0 );
        !          1165:   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
        !          1166:   nCol = pTab->nCol;
        !          1167:   regData = regRowid + 1;
        !          1168: 
        !          1169:   /* Test all NOT NULL constraints.
        !          1170:   */
        !          1171:   for(i=0; i<nCol; i++){
        !          1172:     if( i==pTab->iPKey ){
        !          1173:       continue;
        !          1174:     }
        !          1175:     onError = pTab->aCol[i].notNull;
        !          1176:     if( onError==OE_None ) continue;
        !          1177:     if( overrideError!=OE_Default ){
        !          1178:       onError = overrideError;
        !          1179:     }else if( onError==OE_Default ){
        !          1180:       onError = OE_Abort;
        !          1181:     }
        !          1182:     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
        !          1183:       onError = OE_Abort;
        !          1184:     }
        !          1185:     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
        !          1186:         || onError==OE_Ignore || onError==OE_Replace );
        !          1187:     switch( onError ){
        !          1188:       case OE_Abort:
        !          1189:         sqlite3MayAbort(pParse);
        !          1190:       case OE_Rollback:
        !          1191:       case OE_Fail: {
        !          1192:         char *zMsg;
        !          1193:         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
        !          1194:                                   SQLITE_CONSTRAINT, onError, regData+i);
        !          1195:         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
        !          1196:                               pTab->zName, pTab->aCol[i].zName);
        !          1197:         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
        !          1198:         break;
        !          1199:       }
        !          1200:       case OE_Ignore: {
        !          1201:         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
        !          1202:         break;
        !          1203:       }
        !          1204:       default: {
        !          1205:         assert( onError==OE_Replace );
        !          1206:         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
        !          1207:         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
        !          1208:         sqlite3VdbeJumpHere(v, j1);
        !          1209:         break;
        !          1210:       }
        !          1211:     }
        !          1212:   }
        !          1213: 
        !          1214:   /* Test all CHECK constraints
        !          1215:   */
        !          1216: #ifndef SQLITE_OMIT_CHECK
        !          1217:   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
        !          1218:     int allOk = sqlite3VdbeMakeLabel(v);
        !          1219:     pParse->ckBase = regData;
        !          1220:     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
        !          1221:     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
        !          1222:     if( onError==OE_Ignore ){
        !          1223:       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
        !          1224:     }else{
        !          1225:       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
        !          1226:       sqlite3HaltConstraint(pParse, onError, 0, 0);
        !          1227:     }
        !          1228:     sqlite3VdbeResolveLabel(v, allOk);
        !          1229:   }
        !          1230: #endif /* !defined(SQLITE_OMIT_CHECK) */
        !          1231: 
        !          1232:   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
        !          1233:   ** of the new record does not previously exist.  Except, if this
        !          1234:   ** is an UPDATE and the primary key is not changing, that is OK.
        !          1235:   */
        !          1236:   if( rowidChng ){
        !          1237:     onError = pTab->keyConf;
        !          1238:     if( overrideError!=OE_Default ){
        !          1239:       onError = overrideError;
        !          1240:     }else if( onError==OE_Default ){
        !          1241:       onError = OE_Abort;
        !          1242:     }
        !          1243:     
        !          1244:     if( isUpdate ){
        !          1245:       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
        !          1246:     }
        !          1247:     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
        !          1248:     switch( onError ){
        !          1249:       default: {
        !          1250:         onError = OE_Abort;
        !          1251:         /* Fall thru into the next case */
        !          1252:       }
        !          1253:       case OE_Rollback:
        !          1254:       case OE_Abort:
        !          1255:       case OE_Fail: {
        !          1256:         sqlite3HaltConstraint(
        !          1257:           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
        !          1258:         break;
        !          1259:       }
        !          1260:       case OE_Replace: {
        !          1261:         /* If there are DELETE triggers on this table and the
        !          1262:         ** recursive-triggers flag is set, call GenerateRowDelete() to
        !          1263:         ** remove the conflicting row from the the table. This will fire
        !          1264:         ** the triggers and remove both the table and index b-tree entries.
        !          1265:         **
        !          1266:         ** Otherwise, if there are no triggers or the recursive-triggers
        !          1267:         ** flag is not set, but the table has one or more indexes, call 
        !          1268:         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
        !          1269:         ** only. The table b-tree entry will be replaced by the new entry 
        !          1270:         ** when it is inserted.  
        !          1271:         **
        !          1272:         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
        !          1273:         ** also invoke MultiWrite() to indicate that this VDBE may require
        !          1274:         ** statement rollback (if the statement is aborted after the delete
        !          1275:         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
        !          1276:         ** but being more selective here allows statements like:
        !          1277:         **
        !          1278:         **   REPLACE INTO t(rowid) VALUES($newrowid)
        !          1279:         **
        !          1280:         ** to run without a statement journal if there are no indexes on the
        !          1281:         ** table.
        !          1282:         */
        !          1283:         Trigger *pTrigger = 0;
        !          1284:         if( pParse->db->flags&SQLITE_RecTriggers ){
        !          1285:           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
        !          1286:         }
        !          1287:         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
        !          1288:           sqlite3MultiWrite(pParse);
        !          1289:           sqlite3GenerateRowDelete(
        !          1290:               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
        !          1291:           );
        !          1292:         }else if( pTab->pIndex ){
        !          1293:           sqlite3MultiWrite(pParse);
        !          1294:           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
        !          1295:         }
        !          1296:         seenReplace = 1;
        !          1297:         break;
        !          1298:       }
        !          1299:       case OE_Ignore: {
        !          1300:         assert( seenReplace==0 );
        !          1301:         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
        !          1302:         break;
        !          1303:       }
        !          1304:     }
        !          1305:     sqlite3VdbeJumpHere(v, j3);
        !          1306:     if( isUpdate ){
        !          1307:       sqlite3VdbeJumpHere(v, j2);
        !          1308:     }
        !          1309:   }
        !          1310: 
        !          1311:   /* Test all UNIQUE constraints by creating entries for each UNIQUE
        !          1312:   ** index and making sure that duplicate entries do not already exist.
        !          1313:   ** Add the new records to the indices as we go.
        !          1314:   */
        !          1315:   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
        !          1316:     int regIdx;
        !          1317:     int regR;
        !          1318: 
        !          1319:     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
        !          1320: 
        !          1321:     /* Create a key for accessing the index entry */
        !          1322:     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
        !          1323:     for(i=0; i<pIdx->nColumn; i++){
        !          1324:       int idx = pIdx->aiColumn[i];
        !          1325:       if( idx==pTab->iPKey ){
        !          1326:         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
        !          1327:       }else{
        !          1328:         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
        !          1329:       }
        !          1330:     }
        !          1331:     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
        !          1332:     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
        !          1333:     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
        !          1334:     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
        !          1335: 
        !          1336:     /* Find out what action to take in case there is an indexing conflict */
        !          1337:     onError = pIdx->onError;
        !          1338:     if( onError==OE_None ){ 
        !          1339:       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
        !          1340:       continue;  /* pIdx is not a UNIQUE index */
        !          1341:     }
        !          1342:     if( overrideError!=OE_Default ){
        !          1343:       onError = overrideError;
        !          1344:     }else if( onError==OE_Default ){
        !          1345:       onError = OE_Abort;
        !          1346:     }
        !          1347:     if( seenReplace ){
        !          1348:       if( onError==OE_Ignore ) onError = OE_Replace;
        !          1349:       else if( onError==OE_Fail ) onError = OE_Abort;
        !          1350:     }
        !          1351:     
        !          1352:     /* Check to see if the new index entry will be unique */
        !          1353:     regR = sqlite3GetTempReg(pParse);
        !          1354:     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
        !          1355:     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
        !          1356:                            regR, SQLITE_INT_TO_PTR(regIdx),
        !          1357:                            P4_INT32);
        !          1358:     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
        !          1359: 
        !          1360:     /* Generate code that executes if the new index entry is not unique */
        !          1361:     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
        !          1362:         || onError==OE_Ignore || onError==OE_Replace );
        !          1363:     switch( onError ){
        !          1364:       case OE_Rollback:
        !          1365:       case OE_Abort:
        !          1366:       case OE_Fail: {
        !          1367:         int j;
        !          1368:         StrAccum errMsg;
        !          1369:         const char *zSep;
        !          1370:         char *zErr;
        !          1371: 
        !          1372:         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
        !          1373:         errMsg.db = pParse->db;
        !          1374:         zSep = pIdx->nColumn>1 ? "columns " : "column ";
        !          1375:         for(j=0; j<pIdx->nColumn; j++){
        !          1376:           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
        !          1377:           sqlite3StrAccumAppend(&errMsg, zSep, -1);
        !          1378:           zSep = ", ";
        !          1379:           sqlite3StrAccumAppend(&errMsg, zCol, -1);
        !          1380:         }
        !          1381:         sqlite3StrAccumAppend(&errMsg,
        !          1382:             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
        !          1383:         zErr = sqlite3StrAccumFinish(&errMsg);
        !          1384:         sqlite3HaltConstraint(pParse, onError, zErr, 0);
        !          1385:         sqlite3DbFree(errMsg.db, zErr);
        !          1386:         break;
        !          1387:       }
        !          1388:       case OE_Ignore: {
        !          1389:         assert( seenReplace==0 );
        !          1390:         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
        !          1391:         break;
        !          1392:       }
        !          1393:       default: {
        !          1394:         Trigger *pTrigger = 0;
        !          1395:         assert( onError==OE_Replace );
        !          1396:         sqlite3MultiWrite(pParse);
        !          1397:         if( pParse->db->flags&SQLITE_RecTriggers ){
        !          1398:           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
        !          1399:         }
        !          1400:         sqlite3GenerateRowDelete(
        !          1401:             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
        !          1402:         );
        !          1403:         seenReplace = 1;
        !          1404:         break;
        !          1405:       }
        !          1406:     }
        !          1407:     sqlite3VdbeJumpHere(v, j3);
        !          1408:     sqlite3ReleaseTempReg(pParse, regR);
        !          1409:   }
        !          1410:   
        !          1411:   if( pbMayReplace ){
        !          1412:     *pbMayReplace = seenReplace;
        !          1413:   }
        !          1414: }
        !          1415: 
        !          1416: /*
        !          1417: ** This routine generates code to finish the INSERT or UPDATE operation
        !          1418: ** that was started by a prior call to sqlite3GenerateConstraintChecks.
        !          1419: ** A consecutive range of registers starting at regRowid contains the
        !          1420: ** rowid and the content to be inserted.
        !          1421: **
        !          1422: ** The arguments to this routine should be the same as the first six
        !          1423: ** arguments to sqlite3GenerateConstraintChecks.
        !          1424: */
        !          1425: void sqlite3CompleteInsertion(
        !          1426:   Parse *pParse,      /* The parser context */
        !          1427:   Table *pTab,        /* the table into which we are inserting */
        !          1428:   int baseCur,        /* Index of a read/write cursor pointing at pTab */
        !          1429:   int regRowid,       /* Range of content */
        !          1430:   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
        !          1431:   int isUpdate,       /* True for UPDATE, False for INSERT */
        !          1432:   int appendBias,     /* True if this is likely to be an append */
        !          1433:   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
        !          1434: ){
        !          1435:   int i;
        !          1436:   Vdbe *v;
        !          1437:   int nIdx;
        !          1438:   Index *pIdx;
        !          1439:   u8 pik_flags;
        !          1440:   int regData;
        !          1441:   int regRec;
        !          1442: 
        !          1443:   v = sqlite3GetVdbe(pParse);
        !          1444:   assert( v!=0 );
        !          1445:   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
        !          1446:   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
        !          1447:   for(i=nIdx-1; i>=0; i--){
        !          1448:     if( aRegIdx[i]==0 ) continue;
        !          1449:     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
        !          1450:     if( useSeekResult ){
        !          1451:       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
        !          1452:     }
        !          1453:   }
        !          1454:   regData = regRowid + 1;
        !          1455:   regRec = sqlite3GetTempReg(pParse);
        !          1456:   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
        !          1457:   sqlite3TableAffinityStr(v, pTab);
        !          1458:   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
        !          1459:   if( pParse->nested ){
        !          1460:     pik_flags = 0;
        !          1461:   }else{
        !          1462:     pik_flags = OPFLAG_NCHANGE;
        !          1463:     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
        !          1464:   }
        !          1465:   if( appendBias ){
        !          1466:     pik_flags |= OPFLAG_APPEND;
        !          1467:   }
        !          1468:   if( useSeekResult ){
        !          1469:     pik_flags |= OPFLAG_USESEEKRESULT;
        !          1470:   }
        !          1471:   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
        !          1472:   if( !pParse->nested ){
        !          1473:     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
        !          1474:   }
        !          1475:   sqlite3VdbeChangeP5(v, pik_flags);
        !          1476: }
        !          1477: 
        !          1478: /*
        !          1479: ** Generate code that will open cursors for a table and for all
        !          1480: ** indices of that table.  The "baseCur" parameter is the cursor number used
        !          1481: ** for the table.  Indices are opened on subsequent cursors.
        !          1482: **
        !          1483: ** Return the number of indices on the table.
        !          1484: */
        !          1485: int sqlite3OpenTableAndIndices(
        !          1486:   Parse *pParse,   /* Parsing context */
        !          1487:   Table *pTab,     /* Table to be opened */
        !          1488:   int baseCur,     /* Cursor number assigned to the table */
        !          1489:   int op           /* OP_OpenRead or OP_OpenWrite */
        !          1490: ){
        !          1491:   int i;
        !          1492:   int iDb;
        !          1493:   Index *pIdx;
        !          1494:   Vdbe *v;
        !          1495: 
        !          1496:   if( IsVirtual(pTab) ) return 0;
        !          1497:   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
        !          1498:   v = sqlite3GetVdbe(pParse);
        !          1499:   assert( v!=0 );
        !          1500:   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
        !          1501:   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
        !          1502:     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
        !          1503:     assert( pIdx->pSchema==pTab->pSchema );
        !          1504:     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
        !          1505:                       (char*)pKey, P4_KEYINFO_HANDOFF);
        !          1506:     VdbeComment((v, "%s", pIdx->zName));
        !          1507:   }
        !          1508:   if( pParse->nTab<baseCur+i ){
        !          1509:     pParse->nTab = baseCur+i;
        !          1510:   }
        !          1511:   return i-1;
        !          1512: }
        !          1513: 
        !          1514: 
        !          1515: #ifdef SQLITE_TEST
        !          1516: /*
        !          1517: ** The following global variable is incremented whenever the
        !          1518: ** transfer optimization is used.  This is used for testing
        !          1519: ** purposes only - to make sure the transfer optimization really
        !          1520: ** is happening when it is suppose to.
        !          1521: */
        !          1522: int sqlite3_xferopt_count;
        !          1523: #endif /* SQLITE_TEST */
        !          1524: 
        !          1525: 
        !          1526: #ifndef SQLITE_OMIT_XFER_OPT
        !          1527: /*
        !          1528: ** Check to collation names to see if they are compatible.
        !          1529: */
        !          1530: static int xferCompatibleCollation(const char *z1, const char *z2){
        !          1531:   if( z1==0 ){
        !          1532:     return z2==0;
        !          1533:   }
        !          1534:   if( z2==0 ){
        !          1535:     return 0;
        !          1536:   }
        !          1537:   return sqlite3StrICmp(z1, z2)==0;
        !          1538: }
        !          1539: 
        !          1540: 
        !          1541: /*
        !          1542: ** Check to see if index pSrc is compatible as a source of data
        !          1543: ** for index pDest in an insert transfer optimization.  The rules
        !          1544: ** for a compatible index:
        !          1545: **
        !          1546: **    *   The index is over the same set of columns
        !          1547: **    *   The same DESC and ASC markings occurs on all columns
        !          1548: **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
        !          1549: **    *   The same collating sequence on each column
        !          1550: */
        !          1551: static int xferCompatibleIndex(Index *pDest, Index *pSrc){
        !          1552:   int i;
        !          1553:   assert( pDest && pSrc );
        !          1554:   assert( pDest->pTable!=pSrc->pTable );
        !          1555:   if( pDest->nColumn!=pSrc->nColumn ){
        !          1556:     return 0;   /* Different number of columns */
        !          1557:   }
        !          1558:   if( pDest->onError!=pSrc->onError ){
        !          1559:     return 0;   /* Different conflict resolution strategies */
        !          1560:   }
        !          1561:   for(i=0; i<pSrc->nColumn; i++){
        !          1562:     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
        !          1563:       return 0;   /* Different columns indexed */
        !          1564:     }
        !          1565:     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
        !          1566:       return 0;   /* Different sort orders */
        !          1567:     }
        !          1568:     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
        !          1569:       return 0;   /* Different collating sequences */
        !          1570:     }
        !          1571:   }
        !          1572: 
        !          1573:   /* If no test above fails then the indices must be compatible */
        !          1574:   return 1;
        !          1575: }
        !          1576: 
        !          1577: /*
        !          1578: ** Attempt the transfer optimization on INSERTs of the form
        !          1579: **
        !          1580: **     INSERT INTO tab1 SELECT * FROM tab2;
        !          1581: **
        !          1582: ** The xfer optimization transfers raw records from tab2 over to tab1.  
        !          1583: ** Columns are not decoded and reassemblied, which greatly improves
        !          1584: ** performance.  Raw index records are transferred in the same way.
        !          1585: **
        !          1586: ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
        !          1587: ** There are lots of rules for determining compatibility - see comments
        !          1588: ** embedded in the code for details.
        !          1589: **
        !          1590: ** This routine returns TRUE if the optimization is guaranteed to be used.
        !          1591: ** Sometimes the xfer optimization will only work if the destination table
        !          1592: ** is empty - a factor that can only be determined at run-time.  In that
        !          1593: ** case, this routine generates code for the xfer optimization but also
        !          1594: ** does a test to see if the destination table is empty and jumps over the
        !          1595: ** xfer optimization code if the test fails.  In that case, this routine
        !          1596: ** returns FALSE so that the caller will know to go ahead and generate
        !          1597: ** an unoptimized transfer.  This routine also returns FALSE if there
        !          1598: ** is no chance that the xfer optimization can be applied.
        !          1599: **
        !          1600: ** This optimization is particularly useful at making VACUUM run faster.
        !          1601: */
        !          1602: static int xferOptimization(
        !          1603:   Parse *pParse,        /* Parser context */
        !          1604:   Table *pDest,         /* The table we are inserting into */
        !          1605:   Select *pSelect,      /* A SELECT statement to use as the data source */
        !          1606:   int onError,          /* How to handle constraint errors */
        !          1607:   int iDbDest           /* The database of pDest */
        !          1608: ){
        !          1609:   ExprList *pEList;                /* The result set of the SELECT */
        !          1610:   Table *pSrc;                     /* The table in the FROM clause of SELECT */
        !          1611:   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
        !          1612:   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
        !          1613:   int i;                           /* Loop counter */
        !          1614:   int iDbSrc;                      /* The database of pSrc */
        !          1615:   int iSrc, iDest;                 /* Cursors from source and destination */
        !          1616:   int addr1, addr2;                /* Loop addresses */
        !          1617:   int emptyDestTest;               /* Address of test for empty pDest */
        !          1618:   int emptySrcTest;                /* Address of test for empty pSrc */
        !          1619:   Vdbe *v;                         /* The VDBE we are building */
        !          1620:   KeyInfo *pKey;                   /* Key information for an index */
        !          1621:   int regAutoinc;                  /* Memory register used by AUTOINC */
        !          1622:   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
        !          1623:   int regData, regRowid;           /* Registers holding data and rowid */
        !          1624: 
        !          1625:   if( pSelect==0 ){
        !          1626:     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
        !          1627:   }
        !          1628:   if( sqlite3TriggerList(pParse, pDest) ){
        !          1629:     return 0;   /* tab1 must not have triggers */
        !          1630:   }
        !          1631: #ifndef SQLITE_OMIT_VIRTUALTABLE
        !          1632:   if( pDest->tabFlags & TF_Virtual ){
        !          1633:     return 0;   /* tab1 must not be a virtual table */
        !          1634:   }
        !          1635: #endif
        !          1636:   if( onError==OE_Default ){
        !          1637:     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
        !          1638:     if( onError==OE_Default ) onError = OE_Abort;
        !          1639:   }
        !          1640:   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
        !          1641:   if( pSelect->pSrc->nSrc!=1 ){
        !          1642:     return 0;   /* FROM clause must have exactly one term */
        !          1643:   }
        !          1644:   if( pSelect->pSrc->a[0].pSelect ){
        !          1645:     return 0;   /* FROM clause cannot contain a subquery */
        !          1646:   }
        !          1647:   if( pSelect->pWhere ){
        !          1648:     return 0;   /* SELECT may not have a WHERE clause */
        !          1649:   }
        !          1650:   if( pSelect->pOrderBy ){
        !          1651:     return 0;   /* SELECT may not have an ORDER BY clause */
        !          1652:   }
        !          1653:   /* Do not need to test for a HAVING clause.  If HAVING is present but
        !          1654:   ** there is no ORDER BY, we will get an error. */
        !          1655:   if( pSelect->pGroupBy ){
        !          1656:     return 0;   /* SELECT may not have a GROUP BY clause */
        !          1657:   }
        !          1658:   if( pSelect->pLimit ){
        !          1659:     return 0;   /* SELECT may not have a LIMIT clause */
        !          1660:   }
        !          1661:   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
        !          1662:   if( pSelect->pPrior ){
        !          1663:     return 0;   /* SELECT may not be a compound query */
        !          1664:   }
        !          1665:   if( pSelect->selFlags & SF_Distinct ){
        !          1666:     return 0;   /* SELECT may not be DISTINCT */
        !          1667:   }
        !          1668:   pEList = pSelect->pEList;
        !          1669:   assert( pEList!=0 );
        !          1670:   if( pEList->nExpr!=1 ){
        !          1671:     return 0;   /* The result set must have exactly one column */
        !          1672:   }
        !          1673:   assert( pEList->a[0].pExpr );
        !          1674:   if( pEList->a[0].pExpr->op!=TK_ALL ){
        !          1675:     return 0;   /* The result set must be the special operator "*" */
        !          1676:   }
        !          1677: 
        !          1678:   /* At this point we have established that the statement is of the
        !          1679:   ** correct syntactic form to participate in this optimization.  Now
        !          1680:   ** we have to check the semantics.
        !          1681:   */
        !          1682:   pItem = pSelect->pSrc->a;
        !          1683:   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
        !          1684:   if( pSrc==0 ){
        !          1685:     return 0;   /* FROM clause does not contain a real table */
        !          1686:   }
        !          1687:   if( pSrc==pDest ){
        !          1688:     return 0;   /* tab1 and tab2 may not be the same table */
        !          1689:   }
        !          1690: #ifndef SQLITE_OMIT_VIRTUALTABLE
        !          1691:   if( pSrc->tabFlags & TF_Virtual ){
        !          1692:     return 0;   /* tab2 must not be a virtual table */
        !          1693:   }
        !          1694: #endif
        !          1695:   if( pSrc->pSelect ){
        !          1696:     return 0;   /* tab2 may not be a view */
        !          1697:   }
        !          1698:   if( pDest->nCol!=pSrc->nCol ){
        !          1699:     return 0;   /* Number of columns must be the same in tab1 and tab2 */
        !          1700:   }
        !          1701:   if( pDest->iPKey!=pSrc->iPKey ){
        !          1702:     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
        !          1703:   }
        !          1704:   for(i=0; i<pDest->nCol; i++){
        !          1705:     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
        !          1706:       return 0;    /* Affinity must be the same on all columns */
        !          1707:     }
        !          1708:     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
        !          1709:       return 0;    /* Collating sequence must be the same on all columns */
        !          1710:     }
        !          1711:     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
        !          1712:       return 0;    /* tab2 must be NOT NULL if tab1 is */
        !          1713:     }
        !          1714:   }
        !          1715:   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
        !          1716:     if( pDestIdx->onError!=OE_None ){
        !          1717:       destHasUniqueIdx = 1;
        !          1718:     }
        !          1719:     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
        !          1720:       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
        !          1721:     }
        !          1722:     if( pSrcIdx==0 ){
        !          1723:       return 0;    /* pDestIdx has no corresponding index in pSrc */
        !          1724:     }
        !          1725:   }
        !          1726: #ifndef SQLITE_OMIT_CHECK
        !          1727:   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
        !          1728:     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
        !          1729:   }
        !          1730: #endif
        !          1731: #ifndef SQLITE_OMIT_FOREIGN_KEY
        !          1732:   /* Disallow the transfer optimization if the destination table constains
        !          1733:   ** any foreign key constraints.  This is more restrictive than necessary.
        !          1734:   ** But the main beneficiary of the transfer optimization is the VACUUM 
        !          1735:   ** command, and the VACUUM command disables foreign key constraints.  So
        !          1736:   ** the extra complication to make this rule less restrictive is probably
        !          1737:   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
        !          1738:   */
        !          1739:   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
        !          1740:     return 0;
        !          1741:   }
        !          1742: #endif
        !          1743:   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
        !          1744:     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
        !          1745:   }
        !          1746: 
        !          1747:   /* If we get this far, it means that the xfer optimization is at
        !          1748:   ** least a possibility, though it might only work if the destination
        !          1749:   ** table (tab1) is initially empty.
        !          1750:   */
        !          1751: #ifdef SQLITE_TEST
        !          1752:   sqlite3_xferopt_count++;
        !          1753: #endif
        !          1754:   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
        !          1755:   v = sqlite3GetVdbe(pParse);
        !          1756:   sqlite3CodeVerifySchema(pParse, iDbSrc);
        !          1757:   iSrc = pParse->nTab++;
        !          1758:   iDest = pParse->nTab++;
        !          1759:   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
        !          1760:   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
        !          1761:   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
        !          1762:    || destHasUniqueIdx                              /* (2) */
        !          1763:    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
        !          1764:   ){
        !          1765:     /* In some circumstances, we are able to run the xfer optimization
        !          1766:     ** only if the destination table is initially empty.  This code makes
        !          1767:     ** that determination.  Conditions under which the destination must
        !          1768:     ** be empty:
        !          1769:     **
        !          1770:     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
        !          1771:     **     (If the destination is not initially empty, the rowid fields
        !          1772:     **     of index entries might need to change.)
        !          1773:     **
        !          1774:     ** (2) The destination has a unique index.  (The xfer optimization 
        !          1775:     **     is unable to test uniqueness.)
        !          1776:     **
        !          1777:     ** (3) onError is something other than OE_Abort and OE_Rollback.
        !          1778:     */
        !          1779:     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
        !          1780:     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
        !          1781:     sqlite3VdbeJumpHere(v, addr1);
        !          1782:   }else{
        !          1783:     emptyDestTest = 0;
        !          1784:   }
        !          1785:   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
        !          1786:   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
        !          1787:   regData = sqlite3GetTempReg(pParse);
        !          1788:   regRowid = sqlite3GetTempReg(pParse);
        !          1789:   if( pDest->iPKey>=0 ){
        !          1790:     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
        !          1791:     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
        !          1792:     sqlite3HaltConstraint(
        !          1793:         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
        !          1794:     sqlite3VdbeJumpHere(v, addr2);
        !          1795:     autoIncStep(pParse, regAutoinc, regRowid);
        !          1796:   }else if( pDest->pIndex==0 ){
        !          1797:     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
        !          1798:   }else{
        !          1799:     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
        !          1800:     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
        !          1801:   }
        !          1802:   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
        !          1803:   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
        !          1804:   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
        !          1805:   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
        !          1806:   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
        !          1807:   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
        !          1808:     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
        !          1809:       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
        !          1810:     }
        !          1811:     assert( pSrcIdx );
        !          1812:     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
        !          1813:     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
        !          1814:     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
        !          1815:     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
        !          1816:                       (char*)pKey, P4_KEYINFO_HANDOFF);
        !          1817:     VdbeComment((v, "%s", pSrcIdx->zName));
        !          1818:     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
        !          1819:     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
        !          1820:                       (char*)pKey, P4_KEYINFO_HANDOFF);
        !          1821:     VdbeComment((v, "%s", pDestIdx->zName));
        !          1822:     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
        !          1823:     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
        !          1824:     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
        !          1825:     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
        !          1826:     sqlite3VdbeJumpHere(v, addr1);
        !          1827:   }
        !          1828:   sqlite3VdbeJumpHere(v, emptySrcTest);
        !          1829:   sqlite3ReleaseTempReg(pParse, regRowid);
        !          1830:   sqlite3ReleaseTempReg(pParse, regData);
        !          1831:   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
        !          1832:   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
        !          1833:   if( emptyDestTest ){
        !          1834:     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
        !          1835:     sqlite3VdbeJumpHere(v, emptyDestTest);
        !          1836:     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
        !          1837:     return 0;
        !          1838:   }else{
        !          1839:     return 1;
        !          1840:   }
        !          1841: }
        !          1842: #endif /* SQLITE_OMIT_XFER_OPT */

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>