xref: /sqlite-3.40.0/src/insert.c (revision fd3b2226)
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     Parse *pToplevel = sqlite3ParseToplevel(pParse);
201     AutoincInfo *pInfo;
202 
203     pInfo = pToplevel->pAinc;
204     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
205     if( pInfo==0 ){
206       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
207       if( pInfo==0 ) return 0;
208       pInfo->pNext = pToplevel->pAinc;
209       pToplevel->pAinc = pInfo;
210       pInfo->pTab = pTab;
211       pInfo->iDb = iDb;
212       pToplevel->nMem++;                  /* Register to hold name of table */
213       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
214       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
215     }
216     memId = pInfo->regCtr;
217   }
218   return memId;
219 }
220 
221 /*
222 ** This routine generates code that will initialize all of the
223 ** register used by the autoincrement tracker.
224 */
225 void sqlite3AutoincrementBegin(Parse *pParse){
226   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
227   sqlite3 *db = pParse->db;  /* The database connection */
228   Db *pDb;                   /* Database only autoinc table */
229   int memId;                 /* Register holding max rowid */
230   int addr;                  /* A VDBE address */
231   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
232 
233   /* This routine is never called during trigger-generation.  It is
234   ** only called from the top-level */
235   assert( pParse->pTriggerTab==0 );
236   assert( pParse==sqlite3ParseToplevel(pParse) );
237 
238   assert( v );   /* We failed long ago if this is not so */
239   for(p = pParse->pAinc; p; p = p->pNext){
240     pDb = &db->aDb[p->iDb];
241     memId = p->regCtr;
242     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
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     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
293     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
294     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
295     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
296     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
297     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
298     sqlite3VdbeJumpHere(v, j2);
299     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
300     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
301     sqlite3VdbeJumpHere(v, j4);
302     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
303     sqlite3VdbeJumpHere(v, j1);
304     sqlite3VdbeJumpHere(v, j5);
305     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
306     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
307     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
308     sqlite3VdbeAddOp0(v, OP_Close);
309     sqlite3ReleaseTempReg(pParse, iRec);
310   }
311 }
312 #else
313 /*
314 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
315 ** above are all no-ops
316 */
317 # define autoIncBegin(A,B,C) (0)
318 # define autoIncStep(A,B,C)
319 #endif /* SQLITE_OMIT_AUTOINCREMENT */
320 
321 
322 /* Forward declaration */
323 static int xferOptimization(
324   Parse *pParse,        /* Parser context */
325   Table *pDest,         /* The table we are inserting into */
326   Select *pSelect,      /* A SELECT statement to use as the data source */
327   int onError,          /* How to handle constraint errors */
328   int iDbDest           /* The database of pDest */
329 );
330 
331 /*
332 ** This routine is call to handle SQL of the following forms:
333 **
334 **    insert into TABLE (IDLIST) values(EXPRLIST)
335 **    insert into TABLE (IDLIST) select
336 **
337 ** The IDLIST following the table name is always optional.  If omitted,
338 ** then a list of all columns for the table is substituted.  The IDLIST
339 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
340 **
341 ** The pList parameter holds EXPRLIST in the first form of the INSERT
342 ** statement above, and pSelect is NULL.  For the second form, pList is
343 ** NULL and pSelect is a pointer to the select statement used to generate
344 ** data for the insert.
345 **
346 ** The code generated follows one of four templates.  For a simple
347 ** select with data coming from a VALUES clause, the code executes
348 ** once straight down through.  Pseudo-code follows (we call this
349 ** the "1st template"):
350 **
351 **         open write cursor to <table> and its indices
352 **         puts VALUES clause expressions onto the stack
353 **         write the resulting record into <table>
354 **         cleanup
355 **
356 ** The three remaining templates assume the statement is of the form
357 **
358 **   INSERT INTO <table> SELECT ...
359 **
360 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
361 ** in other words if the SELECT pulls all columns from a single table
362 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
363 ** if <table2> and <table1> are distinct tables but have identical
364 ** schemas, including all the same indices, then a special optimization
365 ** is invoked that copies raw records from <table2> over to <table1>.
366 ** See the xferOptimization() function for the implementation of this
367 ** template.  This is the 2nd template.
368 **
369 **         open a write cursor to <table>
370 **         open read cursor on <table2>
371 **         transfer all records in <table2> over to <table>
372 **         close cursors
373 **         foreach index on <table>
374 **           open a write cursor on the <table> index
375 **           open a read cursor on the corresponding <table2> index
376 **           transfer all records from the read to the write cursors
377 **           close cursors
378 **         end foreach
379 **
380 ** The 3rd template is for when the second template does not apply
381 ** and the SELECT clause does not read from <table> at any time.
382 ** The generated code follows this template:
383 **
384 **         EOF <- 0
385 **         X <- A
386 **         goto B
387 **      A: setup for the SELECT
388 **         loop over the rows in the SELECT
389 **           load values into registers R..R+n
390 **           yield X
391 **         end loop
392 **         cleanup after the SELECT
393 **         EOF <- 1
394 **         yield X
395 **         goto A
396 **      B: open write cursor to <table> and its indices
397 **      C: yield X
398 **         if EOF goto D
399 **         insert the select result into <table> from R..R+n
400 **         goto C
401 **      D: cleanup
402 **
403 ** The 4th template is used if the insert statement takes its
404 ** values from a SELECT but the data is being inserted into a table
405 ** that is also read as part of the SELECT.  In the third form,
406 ** we have to use a intermediate table to store the results of
407 ** the select.  The template is like this:
408 **
409 **         EOF <- 0
410 **         X <- A
411 **         goto B
412 **      A: setup for the SELECT
413 **         loop over the tables in the SELECT
414 **           load value into register R..R+n
415 **           yield X
416 **         end loop
417 **         cleanup after the SELECT
418 **         EOF <- 1
419 **         yield X
420 **         halt-error
421 **      B: open temp table
422 **      L: yield X
423 **         if EOF goto M
424 **         insert row from R..R+n into temp table
425 **         goto L
426 **      M: open write cursor to <table> and its indices
427 **         rewind temp table
428 **      C: loop over rows of intermediate table
429 **           transfer values form intermediate table into <table>
430 **         end loop
431 **      D: cleanup
432 */
433 void sqlite3Insert(
434   Parse *pParse,        /* Parser context */
435   SrcList *pTabList,    /* Name of table into which we are inserting */
436   ExprList *pList,      /* List of values to be inserted */
437   Select *pSelect,      /* A SELECT statement to use as the data source */
438   IdList *pColumn,      /* Column names corresponding to IDLIST. */
439   int onError           /* How to handle constraint errors */
440 ){
441   sqlite3 *db;          /* The main database structure */
442   Table *pTab;          /* The table to insert into.  aka TABLE */
443   char *zTab;           /* Name of the table into which we are inserting */
444   const char *zDb;      /* Name of the database holding this table */
445   int i, j, idx;        /* Loop counters */
446   Vdbe *v;              /* Generate code into this virtual machine */
447   Index *pIdx;          /* For looping over indices of the table */
448   int nColumn;          /* Number of columns in the data */
449   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
450   int baseCur = 0;      /* VDBE Cursor number for pTab */
451   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
452   int endOfLoop;        /* Label for the end of the insertion loop */
453   int useTempTable = 0; /* Store SELECT results in intermediate table */
454   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
455   int addrInsTop = 0;   /* Jump to label "D" */
456   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
457   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
458   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
459   int iDb;              /* Index of database holding TABLE */
460   Db *pDb;              /* The database containing table being inserted into */
461   int appendFlag = 0;   /* True if the insert is likely to be an append */
462 
463   /* Register allocations */
464   int regFromSelect = 0;/* Base register for data coming from SELECT */
465   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
466   int regRowCount = 0;  /* Memory cell used for the row counter */
467   int regIns;           /* Block of regs holding rowid+data being inserted */
468   int regRowid;         /* registers holding insert rowid */
469   int regData;          /* register holding first column to insert */
470   int regRecord;        /* Holds the assemblied row record */
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->nErr++;
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   regRecord = ++pParse->nMem;
800   regRowid = regIns = pParse->nMem+1;
801   pParse->nMem += pTab->nCol + 1;
802   if( IsVirtual(pTab) ){
803     regRowid++;
804     pParse->nMem++;
805   }
806   regData = regRowid+1;
807 
808   /* Run the BEFORE and INSTEAD OF triggers, if there are any
809   */
810   endOfLoop = sqlite3VdbeMakeLabel(v);
811   if( tmask & TRIGGER_BEFORE ){
812     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
813 
814     /* build the NEW.* reference row.  Note that if there is an INTEGER
815     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
816     ** translated into a unique ID for the row.  But on a BEFORE trigger,
817     ** we do not know what the unique ID will be (because the insert has
818     ** not happened yet) so we substitute a rowid of -1
819     */
820     if( keyColumn<0 ){
821       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
822     }else{
823       int j1;
824       if( useTempTable ){
825         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
826       }else{
827         assert( pSelect==0 );  /* Otherwise useTempTable is true */
828         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
829       }
830       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
831       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
832       sqlite3VdbeJumpHere(v, j1);
833       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
834     }
835 
836     /* Cannot have triggers on a virtual table. If it were possible,
837     ** this block would have to account for hidden column.
838     */
839     assert( !IsVirtual(pTab) );
840 
841     /* Create the new column data
842     */
843     for(i=0; i<pTab->nCol; i++){
844       if( pColumn==0 ){
845         j = i;
846       }else{
847         for(j=0; j<pColumn->nId; j++){
848           if( pColumn->a[j].idx==i ) break;
849         }
850       }
851       if( pColumn && j>=pColumn->nId ){
852         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
853       }else if( useTempTable ){
854         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
855       }else{
856         assert( pSelect==0 ); /* Otherwise useTempTable is true */
857         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
858       }
859     }
860 
861     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
862     ** do not attempt any conversions before assembling the record.
863     ** If this is a real table, attempt conversions as required by the
864     ** table column affinities.
865     */
866     if( !isView ){
867       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
868       sqlite3TableAffinityStr(v, pTab);
869     }
870 
871     /* Fire BEFORE or INSTEAD OF triggers */
872     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
873         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
874 
875     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
876   }
877 
878   /* Push the record number for the new entry onto the stack.  The
879   ** record number is a randomly generate integer created by NewRowid
880   ** except when the table has an INTEGER PRIMARY KEY column, in which
881   ** case the record number is the same as that column.
882   */
883   if( !isView ){
884     if( IsVirtual(pTab) ){
885       /* The row that the VUpdate opcode will delete: none */
886       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
887     }
888     if( keyColumn>=0 ){
889       if( useTempTable ){
890         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
891       }else if( pSelect ){
892         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
893       }else{
894         VdbeOp *pOp;
895         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
896         pOp = sqlite3VdbeGetOp(v, -1);
897         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
898           appendFlag = 1;
899           pOp->opcode = OP_NewRowid;
900           pOp->p1 = baseCur;
901           pOp->p2 = regRowid;
902           pOp->p3 = regAutoinc;
903         }
904       }
905       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
906       ** to generate a unique primary key value.
907       */
908       if( !appendFlag ){
909         int j1;
910         if( !IsVirtual(pTab) ){
911           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
912           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
913           sqlite3VdbeJumpHere(v, j1);
914         }else{
915           j1 = sqlite3VdbeCurrentAddr(v);
916           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
917         }
918         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
919       }
920     }else if( IsVirtual(pTab) ){
921       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
922     }else{
923       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
924       appendFlag = 1;
925     }
926     autoIncStep(pParse, regAutoinc, regRowid);
927 
928     /* Push onto the stack, data for all columns of the new entry, beginning
929     ** with the first column.
930     */
931     nHidden = 0;
932     for(i=0; i<pTab->nCol; i++){
933       int iRegStore = regRowid+1+i;
934       if( i==pTab->iPKey ){
935         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
936         ** Whenever this column is read, the record number will be substituted
937         ** in its place.  So will fill this column with a NULL to avoid
938         ** taking up data space with information that will never be used. */
939         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
940         continue;
941       }
942       if( pColumn==0 ){
943         if( IsHiddenColumn(&pTab->aCol[i]) ){
944           assert( IsVirtual(pTab) );
945           j = -1;
946           nHidden++;
947         }else{
948           j = i - nHidden;
949         }
950       }else{
951         for(j=0; j<pColumn->nId; j++){
952           if( pColumn->a[j].idx==i ) break;
953         }
954       }
955       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
956         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
957       }else if( useTempTable ){
958         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
959       }else if( pSelect ){
960         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
961       }else{
962         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
963       }
964     }
965 
966     /* Generate code to check constraints and generate index keys and
967     ** do the insertion.
968     */
969 #ifndef SQLITE_OMIT_VIRTUALTABLE
970     if( IsVirtual(pTab) ){
971       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
972       sqlite3VtabMakeWritable(pParse, pTab);
973       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
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         Sqlite_exec() returns immediately with a
1111 **                                return code of SQLITE_CONSTRAINT.  The
1112 **                                transaction is not rolled back and any
1113 **                                prior changes are retained.
1114 **
1115 **  any              IGNORE       The record number and data is popped from
1116 **                                the stack and there is an immediate jump
1117 **                                to label ignoreDest.
1118 **
1119 **  NOT NULL         REPLACE      The NULL value is replace by the default
1120 **                                value for that column.  If the default value
1121 **                                is NULL, the action is the same as ABORT.
1122 **
1123 **  UNIQUE           REPLACE      The other row that conflicts with the row
1124 **                                being inserted is removed.
1125 **
1126 **  CHECK            REPLACE      Illegal.  The results in an exception.
1127 **
1128 ** Which action to take is determined by the overrideError parameter.
1129 ** Or if overrideError==OE_Default, then the pParse->onError parameter
1130 ** is used.  Or if pParse->onError==OE_Default then the onError value
1131 ** for the constraint is used.
1132 **
1133 ** The calling routine must open a read/write cursor for pTab with
1134 ** cursor number "baseCur".  All indices of pTab must also have open
1135 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
1136 ** Except, if there is no possibility of a REPLACE action then
1137 ** cursors do not need to be open for indices where aRegIdx[i]==0.
1138 */
1139 void sqlite3GenerateConstraintChecks(
1140   Parse *pParse,      /* The parser context */
1141   Table *pTab,        /* the table into which we are inserting */
1142   int baseCur,        /* Index of a read/write cursor pointing at pTab */
1143   int regRowid,       /* Index of the range of input registers */
1144   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1145   int rowidChng,      /* True if the rowid might collide with existing entry */
1146   int isUpdate,       /* True for UPDATE, False for INSERT */
1147   int overrideError,  /* Override onError to this if not OE_Default */
1148   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
1149   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
1150 ){
1151   int i;              /* loop counter */
1152   Vdbe *v;            /* VDBE under constrution */
1153   int nCol;           /* Number of columns */
1154   int onError;        /* Conflict resolution strategy */
1155   int j1;             /* Addresss of jump instruction */
1156   int j2 = 0, j3;     /* Addresses of jump instructions */
1157   int regData;        /* Register containing first data column */
1158   int iCur;           /* Table cursor number */
1159   Index *pIdx;         /* Pointer to one of the indices */
1160   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
1161   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
1162 
1163   v = sqlite3GetVdbe(pParse);
1164   assert( v!=0 );
1165   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1166   nCol = pTab->nCol;
1167   regData = regRowid + 1;
1168 
1169   /* Test all NOT NULL constraints.
1170   */
1171   for(i=0; i<nCol; i++){
1172     if( i==pTab->iPKey ){
1173       continue;
1174     }
1175     onError = pTab->aCol[i].notNull;
1176     if( onError==OE_None ) continue;
1177     if( overrideError!=OE_Default ){
1178       onError = overrideError;
1179     }else if( onError==OE_Default ){
1180       onError = OE_Abort;
1181     }
1182     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
1183       onError = OE_Abort;
1184     }
1185     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1186         || onError==OE_Ignore || onError==OE_Replace );
1187     switch( onError ){
1188       case OE_Abort:
1189         sqlite3MayAbort(pParse);
1190       case OE_Rollback:
1191       case OE_Fail: {
1192         char *zMsg;
1193         j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
1194                                   SQLITE_CONSTRAINT, onError, regData+i);
1195         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
1196                               pTab->zName, pTab->aCol[i].zName);
1197         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
1198         break;
1199       }
1200       case OE_Ignore: {
1201         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
1202         break;
1203       }
1204       default: {
1205         assert( onError==OE_Replace );
1206         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
1207         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
1208         sqlite3VdbeJumpHere(v, j1);
1209         break;
1210       }
1211     }
1212   }
1213 
1214   /* Test all CHECK constraints
1215   */
1216 #ifndef SQLITE_OMIT_CHECK
1217   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
1218     int allOk = sqlite3VdbeMakeLabel(v);
1219     pParse->ckBase = regData;
1220     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
1221     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
1222     if( onError==OE_Ignore ){
1223       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1224     }else{
1225       sqlite3HaltConstraint(pParse, onError, 0, 0);
1226     }
1227     sqlite3VdbeResolveLabel(v, allOk);
1228   }
1229 #endif /* !defined(SQLITE_OMIT_CHECK) */
1230 
1231   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1232   ** of the new record does not previously exist.  Except, if this
1233   ** is an UPDATE and the primary key is not changing, that is OK.
1234   */
1235   if( rowidChng ){
1236     onError = pTab->keyConf;
1237     if( overrideError!=OE_Default ){
1238       onError = overrideError;
1239     }else if( onError==OE_Default ){
1240       onError = OE_Abort;
1241     }
1242 
1243     if( isUpdate ){
1244       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
1245     }
1246     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
1247     switch( onError ){
1248       default: {
1249         onError = OE_Abort;
1250         /* Fall thru into the next case */
1251       }
1252       case OE_Rollback:
1253       case OE_Abort:
1254       case OE_Fail: {
1255         sqlite3HaltConstraint(
1256           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
1257         break;
1258       }
1259       case OE_Replace: {
1260         /* If there are DELETE triggers on this table and the
1261         ** recursive-triggers flag is set, call GenerateRowDelete() to
1262         ** remove the conflicting row from the the table. This will fire
1263         ** the triggers and remove both the table and index b-tree entries.
1264         **
1265         ** Otherwise, if there are no triggers or the recursive-triggers
1266         ** flag is not set, call GenerateRowIndexDelete(). This removes
1267         ** the index b-tree entries only. The table b-tree entry will be
1268         ** replaced by the new entry when it is inserted.  */
1269         Trigger *pTrigger = 0;
1270         if( pParse->db->flags&SQLITE_RecTriggers ){
1271           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1272         }
1273         sqlite3MultiWrite(pParse);
1274         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1275           sqlite3GenerateRowDelete(
1276               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
1277           );
1278         }else{
1279           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
1280         }
1281         seenReplace = 1;
1282         break;
1283       }
1284       case OE_Ignore: {
1285         assert( seenReplace==0 );
1286         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1287         break;
1288       }
1289     }
1290     sqlite3VdbeJumpHere(v, j3);
1291     if( isUpdate ){
1292       sqlite3VdbeJumpHere(v, j2);
1293     }
1294   }
1295 
1296   /* Test all UNIQUE constraints by creating entries for each UNIQUE
1297   ** index and making sure that duplicate entries do not already exist.
1298   ** Add the new records to the indices as we go.
1299   */
1300   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1301     int regIdx;
1302     int regR;
1303 
1304     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
1305 
1306     /* Create a key for accessing the index entry */
1307     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
1308     for(i=0; i<pIdx->nColumn; i++){
1309       int idx = pIdx->aiColumn[i];
1310       if( idx==pTab->iPKey ){
1311         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
1312       }else{
1313         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
1314       }
1315     }
1316     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
1317     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
1318     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
1319     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
1320 
1321     /* Find out what action to take in case there is an indexing conflict */
1322     onError = pIdx->onError;
1323     if( onError==OE_None ){
1324       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
1325       continue;  /* pIdx is not a UNIQUE index */
1326     }
1327     if( overrideError!=OE_Default ){
1328       onError = overrideError;
1329     }else if( onError==OE_Default ){
1330       onError = OE_Abort;
1331     }
1332     if( seenReplace ){
1333       if( onError==OE_Ignore ) onError = OE_Replace;
1334       else if( onError==OE_Fail ) onError = OE_Abort;
1335     }
1336 
1337     /* Check to see if the new index entry will be unique */
1338     regR = sqlite3GetTempReg(pParse);
1339     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
1340     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
1341                            regR, SQLITE_INT_TO_PTR(regIdx),
1342                            P4_INT32);
1343     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
1344 
1345     /* Generate code that executes if the new index entry is not unique */
1346     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1347         || onError==OE_Ignore || onError==OE_Replace );
1348     switch( onError ){
1349       case OE_Rollback:
1350       case OE_Abort:
1351       case OE_Fail: {
1352         int j;
1353         StrAccum errMsg;
1354         const char *zSep;
1355         char *zErr;
1356 
1357         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
1358         errMsg.db = pParse->db;
1359         zSep = pIdx->nColumn>1 ? "columns " : "column ";
1360         for(j=0; j<pIdx->nColumn; j++){
1361           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1362           sqlite3StrAccumAppend(&errMsg, zSep, -1);
1363           zSep = ", ";
1364           sqlite3StrAccumAppend(&errMsg, zCol, -1);
1365         }
1366         sqlite3StrAccumAppend(&errMsg,
1367             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
1368         zErr = sqlite3StrAccumFinish(&errMsg);
1369         sqlite3HaltConstraint(pParse, onError, zErr, 0);
1370         sqlite3DbFree(errMsg.db, zErr);
1371         break;
1372       }
1373       case OE_Ignore: {
1374         assert( seenReplace==0 );
1375         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1376         break;
1377       }
1378       default: {
1379         Trigger *pTrigger = 0;
1380         assert( onError==OE_Replace );
1381         sqlite3MultiWrite(pParse);
1382         if( pParse->db->flags&SQLITE_RecTriggers ){
1383           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1384         }
1385         sqlite3GenerateRowDelete(
1386             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
1387         );
1388         seenReplace = 1;
1389         break;
1390       }
1391     }
1392     sqlite3VdbeJumpHere(v, j3);
1393     sqlite3ReleaseTempReg(pParse, regR);
1394   }
1395 
1396   if( pbMayReplace ){
1397     *pbMayReplace = seenReplace;
1398   }
1399 }
1400 
1401 /*
1402 ** This routine generates code to finish the INSERT or UPDATE operation
1403 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
1404 ** A consecutive range of registers starting at regRowid contains the
1405 ** rowid and the content to be inserted.
1406 **
1407 ** The arguments to this routine should be the same as the first six
1408 ** arguments to sqlite3GenerateConstraintChecks.
1409 */
1410 void sqlite3CompleteInsertion(
1411   Parse *pParse,      /* The parser context */
1412   Table *pTab,        /* the table into which we are inserting */
1413   int baseCur,        /* Index of a read/write cursor pointing at pTab */
1414   int regRowid,       /* Range of content */
1415   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1416   int isUpdate,       /* True for UPDATE, False for INSERT */
1417   int appendBias,     /* True if this is likely to be an append */
1418   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
1419 ){
1420   int i;
1421   Vdbe *v;
1422   int nIdx;
1423   Index *pIdx;
1424   u8 pik_flags;
1425   int regData;
1426   int regRec;
1427 
1428   v = sqlite3GetVdbe(pParse);
1429   assert( v!=0 );
1430   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1431   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1432   for(i=nIdx-1; i>=0; i--){
1433     if( aRegIdx[i]==0 ) continue;
1434     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
1435     if( useSeekResult ){
1436       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1437     }
1438   }
1439   regData = regRowid + 1;
1440   regRec = sqlite3GetTempReg(pParse);
1441   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1442   sqlite3TableAffinityStr(v, pTab);
1443   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
1444   if( pParse->nested ){
1445     pik_flags = 0;
1446   }else{
1447     pik_flags = OPFLAG_NCHANGE;
1448     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
1449   }
1450   if( appendBias ){
1451     pik_flags |= OPFLAG_APPEND;
1452   }
1453   if( useSeekResult ){
1454     pik_flags |= OPFLAG_USESEEKRESULT;
1455   }
1456   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
1457   if( !pParse->nested ){
1458     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
1459   }
1460   sqlite3VdbeChangeP5(v, pik_flags);
1461 }
1462 
1463 /*
1464 ** Generate code that will open cursors for a table and for all
1465 ** indices of that table.  The "baseCur" parameter is the cursor number used
1466 ** for the table.  Indices are opened on subsequent cursors.
1467 **
1468 ** Return the number of indices on the table.
1469 */
1470 int sqlite3OpenTableAndIndices(
1471   Parse *pParse,   /* Parsing context */
1472   Table *pTab,     /* Table to be opened */
1473   int baseCur,     /* Cursor number assigned to the table */
1474   int op           /* OP_OpenRead or OP_OpenWrite */
1475 ){
1476   int i;
1477   int iDb;
1478   Index *pIdx;
1479   Vdbe *v;
1480 
1481   if( IsVirtual(pTab) ) return 0;
1482   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1483   v = sqlite3GetVdbe(pParse);
1484   assert( v!=0 );
1485   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
1486   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1487     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1488     assert( pIdx->pSchema==pTab->pSchema );
1489     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
1490                       (char*)pKey, P4_KEYINFO_HANDOFF);
1491     VdbeComment((v, "%s", pIdx->zName));
1492   }
1493   if( pParse->nTab<baseCur+i ){
1494     pParse->nTab = baseCur+i;
1495   }
1496   return i-1;
1497 }
1498 
1499 
1500 #ifdef SQLITE_TEST
1501 /*
1502 ** The following global variable is incremented whenever the
1503 ** transfer optimization is used.  This is used for testing
1504 ** purposes only - to make sure the transfer optimization really
1505 ** is happening when it is suppose to.
1506 */
1507 int sqlite3_xferopt_count;
1508 #endif /* SQLITE_TEST */
1509 
1510 
1511 #ifndef SQLITE_OMIT_XFER_OPT
1512 /*
1513 ** Check to collation names to see if they are compatible.
1514 */
1515 static int xferCompatibleCollation(const char *z1, const char *z2){
1516   if( z1==0 ){
1517     return z2==0;
1518   }
1519   if( z2==0 ){
1520     return 0;
1521   }
1522   return sqlite3StrICmp(z1, z2)==0;
1523 }
1524 
1525 
1526 /*
1527 ** Check to see if index pSrc is compatible as a source of data
1528 ** for index pDest in an insert transfer optimization.  The rules
1529 ** for a compatible index:
1530 **
1531 **    *   The index is over the same set of columns
1532 **    *   The same DESC and ASC markings occurs on all columns
1533 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
1534 **    *   The same collating sequence on each column
1535 */
1536 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1537   int i;
1538   assert( pDest && pSrc );
1539   assert( pDest->pTable!=pSrc->pTable );
1540   if( pDest->nColumn!=pSrc->nColumn ){
1541     return 0;   /* Different number of columns */
1542   }
1543   if( pDest->onError!=pSrc->onError ){
1544     return 0;   /* Different conflict resolution strategies */
1545   }
1546   for(i=0; i<pSrc->nColumn; i++){
1547     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1548       return 0;   /* Different columns indexed */
1549     }
1550     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1551       return 0;   /* Different sort orders */
1552     }
1553     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
1554       return 0;   /* Different collating sequences */
1555     }
1556   }
1557 
1558   /* If no test above fails then the indices must be compatible */
1559   return 1;
1560 }
1561 
1562 /*
1563 ** Attempt the transfer optimization on INSERTs of the form
1564 **
1565 **     INSERT INTO tab1 SELECT * FROM tab2;
1566 **
1567 ** This optimization is only attempted if
1568 **
1569 **    (1)  tab1 and tab2 have identical schemas including all the
1570 **         same indices and constraints
1571 **
1572 **    (2)  tab1 and tab2 are different tables
1573 **
1574 **    (3)  There must be no triggers on tab1
1575 **
1576 **    (4)  The result set of the SELECT statement is "*"
1577 **
1578 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1579 **         or LIMIT clause.
1580 **
1581 **    (6)  The SELECT statement is a simple (not a compound) select that
1582 **         contains only tab2 in its FROM clause
1583 **
1584 ** This method for implementing the INSERT transfers raw records from
1585 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
1586 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
1587 ** the resulting tab1 has much less fragmentation.
1588 **
1589 ** This routine returns TRUE if the optimization is attempted.  If any
1590 ** of the conditions above fail so that the optimization should not
1591 ** be attempted, then this routine returns FALSE.
1592 */
1593 static int xferOptimization(
1594   Parse *pParse,        /* Parser context */
1595   Table *pDest,         /* The table we are inserting into */
1596   Select *pSelect,      /* A SELECT statement to use as the data source */
1597   int onError,          /* How to handle constraint errors */
1598   int iDbDest           /* The database of pDest */
1599 ){
1600   ExprList *pEList;                /* The result set of the SELECT */
1601   Table *pSrc;                     /* The table in the FROM clause of SELECT */
1602   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
1603   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
1604   int i;                           /* Loop counter */
1605   int iDbSrc;                      /* The database of pSrc */
1606   int iSrc, iDest;                 /* Cursors from source and destination */
1607   int addr1, addr2;                /* Loop addresses */
1608   int emptyDestTest;               /* Address of test for empty pDest */
1609   int emptySrcTest;                /* Address of test for empty pSrc */
1610   Vdbe *v;                         /* The VDBE we are building */
1611   KeyInfo *pKey;                   /* Key information for an index */
1612   int regAutoinc;                  /* Memory register used by AUTOINC */
1613   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1614   int regData, regRowid;           /* Registers holding data and rowid */
1615 
1616   if( pSelect==0 ){
1617     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
1618   }
1619   if( sqlite3TriggerList(pParse, pDest) ){
1620     return 0;   /* tab1 must not have triggers */
1621   }
1622 #ifndef SQLITE_OMIT_VIRTUALTABLE
1623   if( pDest->tabFlags & TF_Virtual ){
1624     return 0;   /* tab1 must not be a virtual table */
1625   }
1626 #endif
1627   if( onError==OE_Default ){
1628     onError = OE_Abort;
1629   }
1630   if( onError!=OE_Abort && onError!=OE_Rollback ){
1631     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1632   }
1633   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
1634   if( pSelect->pSrc->nSrc!=1 ){
1635     return 0;   /* FROM clause must have exactly one term */
1636   }
1637   if( pSelect->pSrc->a[0].pSelect ){
1638     return 0;   /* FROM clause cannot contain a subquery */
1639   }
1640   if( pSelect->pWhere ){
1641     return 0;   /* SELECT may not have a WHERE clause */
1642   }
1643   if( pSelect->pOrderBy ){
1644     return 0;   /* SELECT may not have an ORDER BY clause */
1645   }
1646   /* Do not need to test for a HAVING clause.  If HAVING is present but
1647   ** there is no ORDER BY, we will get an error. */
1648   if( pSelect->pGroupBy ){
1649     return 0;   /* SELECT may not have a GROUP BY clause */
1650   }
1651   if( pSelect->pLimit ){
1652     return 0;   /* SELECT may not have a LIMIT clause */
1653   }
1654   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
1655   if( pSelect->pPrior ){
1656     return 0;   /* SELECT may not be a compound query */
1657   }
1658   if( pSelect->selFlags & SF_Distinct ){
1659     return 0;   /* SELECT may not be DISTINCT */
1660   }
1661   pEList = pSelect->pEList;
1662   assert( pEList!=0 );
1663   if( pEList->nExpr!=1 ){
1664     return 0;   /* The result set must have exactly one column */
1665   }
1666   assert( pEList->a[0].pExpr );
1667   if( pEList->a[0].pExpr->op!=TK_ALL ){
1668     return 0;   /* The result set must be the special operator "*" */
1669   }
1670 
1671   /* At this point we have established that the statement is of the
1672   ** correct syntactic form to participate in this optimization.  Now
1673   ** we have to check the semantics.
1674   */
1675   pItem = pSelect->pSrc->a;
1676   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
1677   if( pSrc==0 ){
1678     return 0;   /* FROM clause does not contain a real table */
1679   }
1680   if( pSrc==pDest ){
1681     return 0;   /* tab1 and tab2 may not be the same table */
1682   }
1683 #ifndef SQLITE_OMIT_VIRTUALTABLE
1684   if( pSrc->tabFlags & TF_Virtual ){
1685     return 0;   /* tab2 must not be a virtual table */
1686   }
1687 #endif
1688   if( pSrc->pSelect ){
1689     return 0;   /* tab2 may not be a view */
1690   }
1691   if( pDest->nCol!=pSrc->nCol ){
1692     return 0;   /* Number of columns must be the same in tab1 and tab2 */
1693   }
1694   if( pDest->iPKey!=pSrc->iPKey ){
1695     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
1696   }
1697   for(i=0; i<pDest->nCol; i++){
1698     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1699       return 0;    /* Affinity must be the same on all columns */
1700     }
1701     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1702       return 0;    /* Collating sequence must be the same on all columns */
1703     }
1704     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1705       return 0;    /* tab2 must be NOT NULL if tab1 is */
1706     }
1707   }
1708   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1709     if( pDestIdx->onError!=OE_None ){
1710       destHasUniqueIdx = 1;
1711     }
1712     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1713       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1714     }
1715     if( pSrcIdx==0 ){
1716       return 0;    /* pDestIdx has no corresponding index in pSrc */
1717     }
1718   }
1719 #ifndef SQLITE_OMIT_CHECK
1720   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
1721     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
1722   }
1723 #endif
1724 
1725   /* If we get this far, it means either:
1726   **
1727   **    *   We can always do the transfer if the table contains an
1728   **        an integer primary key
1729   **
1730   **    *   We can conditionally do the transfer if the destination
1731   **        table is empty.
1732   */
1733 #ifdef SQLITE_TEST
1734   sqlite3_xferopt_count++;
1735 #endif
1736   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1737   v = sqlite3GetVdbe(pParse);
1738   sqlite3CodeVerifySchema(pParse, iDbSrc);
1739   iSrc = pParse->nTab++;
1740   iDest = pParse->nTab++;
1741   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
1742   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1743   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
1744     /* If tables do not have an INTEGER PRIMARY KEY and there
1745     ** are indices to be copied and the destination is not empty,
1746     ** we have to disallow the transfer optimization because the
1747     ** the rowids might change which will mess up indexing.
1748     **
1749     ** Or if the destination has a UNIQUE index and is not empty,
1750     ** we also disallow the transfer optimization because we cannot
1751     ** insure that all entries in the union of DEST and SRC will be
1752     ** unique.
1753     */
1754     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1755     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
1756     sqlite3VdbeJumpHere(v, addr1);
1757   }else{
1758     emptyDestTest = 0;
1759   }
1760   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
1761   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1762   regData = sqlite3GetTempReg(pParse);
1763   regRowid = sqlite3GetTempReg(pParse);
1764   if( pDest->iPKey>=0 ){
1765     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1766     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
1767     sqlite3HaltConstraint(
1768         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
1769     sqlite3VdbeJumpHere(v, addr2);
1770     autoIncStep(pParse, regAutoinc, regRowid);
1771   }else if( pDest->pIndex==0 ){
1772     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
1773   }else{
1774     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1775     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
1776   }
1777   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1778   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1779   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
1780   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
1781   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
1782   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1783     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
1784       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1785     }
1786     assert( pSrcIdx );
1787     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1788     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
1789     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1790     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1791                       (char*)pKey, P4_KEYINFO_HANDOFF);
1792     VdbeComment((v, "%s", pSrcIdx->zName));
1793     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1794     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
1795                       (char*)pKey, P4_KEYINFO_HANDOFF);
1796     VdbeComment((v, "%s", pDestIdx->zName));
1797     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1798     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1799     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
1800     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
1801     sqlite3VdbeJumpHere(v, addr1);
1802   }
1803   sqlite3VdbeJumpHere(v, emptySrcTest);
1804   sqlite3ReleaseTempReg(pParse, regRowid);
1805   sqlite3ReleaseTempReg(pParse, regData);
1806   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1807   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
1808   if( emptyDestTest ){
1809     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
1810     sqlite3VdbeJumpHere(v, emptyDestTest);
1811     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
1812     return 0;
1813   }else{
1814     return 1;
1815   }
1816 }
1817 #endif /* SQLITE_OMIT_XFER_OPT */
1818