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