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