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