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