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