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