xref: /sqlite-3.40.0/src/insert.c (revision 9f8a4b43)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains C code routines that are called by the parser
13 ** to handle INSERT statements in SQLite.
14 **
15 ** $Id: insert.c,v 1.188 2007/07/23 19:39:47 drh Exp $
16 */
17 #include "sqliteInt.h"
18 
19 /*
20 ** Set P3 of the most recently inserted opcode to a column affinity
21 ** string for index pIdx. A column affinity string has one character
22 ** for each column in the table, according to the affinity of the column:
23 **
24 **  Character      Column affinity
25 **  ------------------------------
26 **  'a'            TEXT
27 **  'b'            NONE
28 **  'c'            NUMERIC
29 **  'd'            INTEGER
30 **  'e'            REAL
31 */
32 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
33   if( !pIdx->zColAff ){
34     /* The first time a column affinity string for a particular index is
35     ** required, it is allocated and populated here. It is then stored as
36     ** a member of the Index structure for subsequent use.
37     **
38     ** The column affinity string will eventually be deleted by
39     ** sqliteDeleteIndex() when the Index structure itself is cleaned
40     ** up.
41     */
42     int n;
43     Table *pTab = pIdx->pTable;
44     pIdx->zColAff = (char *)sqliteMalloc(pIdx->nColumn+1);
45     if( !pIdx->zColAff ){
46       return;
47     }
48     for(n=0; n<pIdx->nColumn; n++){
49       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
50     }
51     pIdx->zColAff[pIdx->nColumn] = '\0';
52   }
53 
54   sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
55 }
56 
57 /*
58 ** Set P3 of the most recently inserted opcode to a column affinity
59 ** string for table pTab. A column affinity string has one character
60 ** for each column indexed by the index, according to the affinity of the
61 ** column:
62 **
63 **  Character      Column affinity
64 **  ------------------------------
65 **  'a'            TEXT
66 **  'b'            NONE
67 **  'c'            NUMERIC
68 **  'd'            INTEGER
69 **  'e'            REAL
70 */
71 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
72   /* The first time a column affinity string for a particular table
73   ** is required, it is allocated and populated here. It is then
74   ** stored as a member of the Table structure for subsequent use.
75   **
76   ** The column affinity string will eventually be deleted by
77   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
78   */
79   if( !pTab->zColAff ){
80     char *zColAff;
81     int i;
82 
83     zColAff = (char *)sqliteMalloc(pTab->nCol+1);
84     if( !zColAff ){
85       return;
86     }
87 
88     for(i=0; i<pTab->nCol; i++){
89       zColAff[i] = pTab->aCol[i].affinity;
90     }
91     zColAff[pTab->nCol] = '\0';
92 
93     pTab->zColAff = zColAff;
94   }
95 
96   sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
97 }
98 
99 /*
100 ** Return non-zero if SELECT statement p opens the table with rootpage
101 ** iTab in database iDb.  This is used to see if a statement of the form
102 ** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
103 ** table for the results of the SELECT.
104 **
105 ** No checking is done for sub-selects that are part of expressions.
106 */
107 static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
108   int i;
109   struct SrcList_item *pItem;
110   if( p->pSrc==0 ) return 0;
111   for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
112     if( pItem->pSelect ){
113       if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
114     }else{
115       if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
116     }
117   }
118   return 0;
119 }
120 
121 #ifndef SQLITE_OMIT_AUTOINCREMENT
122 /*
123 ** Write out code to initialize the autoincrement logic.  This code
124 ** looks up the current autoincrement value in the sqlite_sequence
125 ** table and stores that value in a memory cell.  Code generated by
126 ** autoIncStep() will keep that memory cell holding the largest
127 ** rowid value.  Code generated by autoIncEnd() will write the new
128 ** largest value of the counter back into the sqlite_sequence table.
129 **
130 ** This routine returns the index of the mem[] cell that contains
131 ** the maximum rowid counter.
132 **
133 ** Two memory cells are allocated.  The next memory cell after the
134 ** one returned holds the rowid in sqlite_sequence where we will
135 ** write back the revised maximum rowid.
136 */
137 static int autoIncBegin(
138   Parse *pParse,      /* Parsing context */
139   int iDb,            /* Index of the database holding pTab */
140   Table *pTab         /* The table we are writing to */
141 ){
142   int memId = 0;
143   if( pTab->autoInc ){
144     Vdbe *v = pParse->pVdbe;
145     Db *pDb = &pParse->db->aDb[iDb];
146     int iCur = pParse->nTab;
147     int addr;
148     assert( v );
149     addr = sqlite3VdbeCurrentAddr(v);
150     memId = pParse->nMem+1;
151     pParse->nMem += 2;
152     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
153     sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
154     sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
155     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
156     sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
157     sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
158     sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
159     sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
160     sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
161     sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
162     sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
163     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
164   }
165   return memId;
166 }
167 
168 /*
169 ** Update the maximum rowid for an autoincrement calculation.
170 **
171 ** This routine should be called when the top of the stack holds a
172 ** new rowid that is about to be inserted.  If that new rowid is
173 ** larger than the maximum rowid in the memId memory cell, then the
174 ** memory cell is updated.  The stack is unchanged.
175 */
176 static void autoIncStep(Parse *pParse, int memId){
177   if( memId>0 ){
178     sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
179   }
180 }
181 
182 /*
183 ** After doing one or more inserts, the maximum rowid is stored
184 ** in mem[memId].  Generate code to write this value back into the
185 ** the sqlite_sequence table.
186 */
187 static void autoIncEnd(
188   Parse *pParse,     /* The parsing context */
189   int iDb,           /* Index of the database holding pTab */
190   Table *pTab,       /* Table we are inserting into */
191   int memId          /* Memory cell holding the maximum rowid */
192 ){
193   if( pTab->autoInc ){
194     int iCur = pParse->nTab;
195     Vdbe *v = pParse->pVdbe;
196     Db *pDb = &pParse->db->aDb[iDb];
197     int addr;
198     assert( v );
199     addr = sqlite3VdbeCurrentAddr(v);
200     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
201     sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
202     sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
203     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
204     sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
205     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
206     sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
207     sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
208     sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
209     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
210   }
211 }
212 #else
213 /*
214 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
215 ** above are all no-ops
216 */
217 # define autoIncBegin(A,B,C) (0)
218 # define autoIncStep(A,B)
219 # define autoIncEnd(A,B,C,D)
220 #endif /* SQLITE_OMIT_AUTOINCREMENT */
221 
222 
223 /* Forward declaration */
224 static int xferOptimization(
225   Parse *pParse,        /* Parser context */
226   Table *pDest,         /* The table we are inserting into */
227   Select *pSelect,      /* A SELECT statement to use as the data source */
228   int onError,          /* How to handle constraint errors */
229   int iDbDest           /* The database of pDest */
230 );
231 
232 /*
233 ** This routine is call to handle SQL of the following forms:
234 **
235 **    insert into TABLE (IDLIST) values(EXPRLIST)
236 **    insert into TABLE (IDLIST) select
237 **
238 ** The IDLIST following the table name is always optional.  If omitted,
239 ** then a list of all columns for the table is substituted.  The IDLIST
240 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
241 **
242 ** The pList parameter holds EXPRLIST in the first form of the INSERT
243 ** statement above, and pSelect is NULL.  For the second form, pList is
244 ** NULL and pSelect is a pointer to the select statement used to generate
245 ** data for the insert.
246 **
247 ** The code generated follows one of four templates.  For a simple
248 ** select with data coming from a VALUES clause, the code executes
249 ** once straight down through.  The template looks like this:
250 **
251 **         open write cursor to <table> and its indices
252 **         puts VALUES clause expressions onto the stack
253 **         write the resulting record into <table>
254 **         cleanup
255 **
256 ** The three remaining templates assume the statement is of the form
257 **
258 **   INSERT INTO <table> SELECT ...
259 **
260 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
261 ** in other words if the SELECT pulls all columns from a single table
262 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
263 ** if <table2> and <table1> are distinct tables but have identical
264 ** schemas, including all the same indices, then a special optimization
265 ** is invoked that copies raw records from <table2> over to <table1>.
266 ** See the xferOptimization() function for the implementation of this
267 ** template.  This is the second template.
268 **
269 **         open a write cursor to <table>
270 **         open read cursor on <table2>
271 **         transfer all records in <table2> over to <table>
272 **         close cursors
273 **         foreach index on <table>
274 **           open a write cursor on the <table> index
275 **           open a read cursor on the corresponding <table2> index
276 **           transfer all records from the read to the write cursors
277 **           close cursors
278 **         end foreach
279 **
280 ** The third template is for when the second template does not apply
281 ** and the SELECT clause does not read from <table> at any time.
282 ** The generated code follows this template:
283 **
284 **         goto B
285 **      A: setup for the SELECT
286 **         loop over the rows in the SELECT
287 **           gosub C
288 **         end loop
289 **         cleanup after the SELECT
290 **         goto D
291 **      B: open write cursor to <table> and its indices
292 **         goto A
293 **      C: insert the select result into <table>
294 **         return
295 **      D: cleanup
296 **
297 ** The fourth template is used if the insert statement takes its
298 ** values from a SELECT but the data is being inserted into a table
299 ** that is also read as part of the SELECT.  In the third form,
300 ** we have to use a intermediate table to store the results of
301 ** the select.  The template is like this:
302 **
303 **         goto B
304 **      A: setup for the SELECT
305 **         loop over the tables in the SELECT
306 **           gosub C
307 **         end loop
308 **         cleanup after the SELECT
309 **         goto D
310 **      C: insert the select result into the intermediate table
311 **         return
312 **      B: open a cursor to an intermediate table
313 **         goto A
314 **      D: open write cursor to <table> and its indices
315 **         loop over the intermediate table
316 **           transfer values form intermediate table into <table>
317 **         end the loop
318 **         cleanup
319 */
320 void sqlite3Insert(
321   Parse *pParse,        /* Parser context */
322   SrcList *pTabList,    /* Name of table into which we are inserting */
323   ExprList *pList,      /* List of values to be inserted */
324   Select *pSelect,      /* A SELECT statement to use as the data source */
325   IdList *pColumn,      /* Column names corresponding to IDLIST. */
326   int onError           /* How to handle constraint errors */
327 ){
328   Table *pTab;          /* The table to insert into */
329   char *zTab;           /* Name of the table into which we are inserting */
330   const char *zDb;      /* Name of the database holding this table */
331   int i, j, idx;        /* Loop counters */
332   Vdbe *v;              /* Generate code into this virtual machine */
333   Index *pIdx;          /* For looping over indices of the table */
334   int nColumn;          /* Number of columns in the data */
335   int base = 0;         /* VDBE Cursor number for pTab */
336   int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
337   sqlite3 *db;          /* The main database structure */
338   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
339   int endOfLoop;        /* Label for the end of the insertion loop */
340   int useTempTable = 0; /* Store SELECT results in intermediate table */
341   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
342   int iSelectLoop = 0;  /* Address of code that implements the SELECT */
343   int iCleanup = 0;     /* Address of the cleanup code */
344   int iInsertBlock = 0; /* Address of the subroutine used to insert data */
345   int iCntMem = 0;      /* Memory cell used for the row counter */
346   int newIdx = -1;      /* Cursor for the NEW table */
347   Db *pDb;              /* The database containing table being inserted into */
348   int counterMem = 0;   /* Memory cell holding AUTOINCREMENT counter */
349   int appendFlag = 0;   /* True if the insert is likely to be an append */
350   int iDb;
351 
352   int nHidden = 0;
353 
354 #ifndef SQLITE_OMIT_TRIGGER
355   int isView;                 /* True if attempting to insert into a view */
356   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
357 #endif
358 
359   if( pParse->nErr || sqlite3MallocFailed() ){
360     goto insert_cleanup;
361   }
362   db = pParse->db;
363 
364   /* Locate the table into which we will be inserting new information.
365   */
366   assert( pTabList->nSrc==1 );
367   zTab = pTabList->a[0].zName;
368   if( zTab==0 ) goto insert_cleanup;
369   pTab = sqlite3SrcListLookup(pParse, pTabList);
370   if( pTab==0 ){
371     goto insert_cleanup;
372   }
373   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
374   assert( iDb<db->nDb );
375   pDb = &db->aDb[iDb];
376   zDb = pDb->zName;
377   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
378     goto insert_cleanup;
379   }
380 
381   /* Figure out if we have any triggers and if the table being
382   ** inserted into is a view
383   */
384 #ifndef SQLITE_OMIT_TRIGGER
385   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
386   isView = pTab->pSelect!=0;
387 #else
388 # define triggers_exist 0
389 # define isView 0
390 #endif
391 #ifdef SQLITE_OMIT_VIEW
392 # undef isView
393 # define isView 0
394 #endif
395 
396   /* Ensure that:
397   *  (a) the table is not read-only,
398   *  (b) that if it is a view then ON INSERT triggers exist
399   */
400   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
401     goto insert_cleanup;
402   }
403   assert( pTab!=0 );
404 
405   /* If pTab is really a view, make sure it has been initialized.
406   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
407   ** module table).
408   */
409   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
410     goto insert_cleanup;
411   }
412 
413   /* Allocate a VDBE
414   */
415   v = sqlite3GetVdbe(pParse);
416   if( v==0 ) goto insert_cleanup;
417   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
418   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
419 
420   /* if there are row triggers, allocate a temp table for new.* references. */
421   if( triggers_exist ){
422     newIdx = pParse->nTab++;
423   }
424 
425 #ifndef SQLITE_OMIT_XFER_OPT
426   /* If the statement is of the form
427   **
428   **       INSERT INTO <table1> SELECT * FROM <table2>;
429   **
430   ** Then special optimizations can be applied that make the transfer
431   ** very fast and which reduce fragmentation of indices.
432   */
433   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
434     assert( !triggers_exist );
435     assert( pList==0 );
436     goto insert_cleanup;
437   }
438 #endif /* SQLITE_OMIT_XFER_OPT */
439 
440   /* If this is an AUTOINCREMENT table, look up the sequence number in the
441   ** sqlite_sequence table and store it in memory cell counterMem.  Also
442   ** remember the rowid of the sqlite_sequence table entry in memory cell
443   ** counterRowid.
444   */
445   counterMem = autoIncBegin(pParse, iDb, pTab);
446 
447   /* Figure out how many columns of data are supplied.  If the data
448   ** is coming from a SELECT statement, then this step also generates
449   ** all the code to implement the SELECT statement and invoke a subroutine
450   ** to process each row of the result. (Template 2.) If the SELECT
451   ** statement uses the the table that is being inserted into, then the
452   ** subroutine is also coded here.  That subroutine stores the SELECT
453   ** results in a temporary table. (Template 3.)
454   */
455   if( pSelect ){
456     /* Data is coming from a SELECT.  Generate code to implement that SELECT
457     */
458     int rc, iInitCode;
459     iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
460     iSelectLoop = sqlite3VdbeCurrentAddr(v);
461     iInsertBlock = sqlite3VdbeMakeLabel(v);
462 
463     /* Resolve the expressions in the SELECT statement and execute it. */
464     rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
465     if( rc || pParse->nErr || sqlite3MallocFailed() ){
466       goto insert_cleanup;
467     }
468 
469     iCleanup = sqlite3VdbeMakeLabel(v);
470     sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
471     assert( pSelect->pEList );
472     nColumn = pSelect->pEList->nExpr;
473 
474     /* Set useTempTable to TRUE if the result of the SELECT statement
475     ** should be written into a temporary table.  Set to FALSE if each
476     ** row of the SELECT can be written directly into the result table.
477     **
478     ** A temp table must be used if the table being updated is also one
479     ** of the tables being read by the SELECT statement.  Also use a
480     ** temp table in the case of row triggers.
481     */
482     if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
483       useTempTable = 1;
484     }
485 
486     if( useTempTable ){
487       /* Generate the subroutine that SELECT calls to process each row of
488       ** the result.  Store the result in a temporary table
489       */
490       srcTab = pParse->nTab++;
491       sqlite3VdbeResolveLabel(v, iInsertBlock);
492       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
493       sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
494       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
495       sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
496       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
497 
498       /* The following code runs first because the GOTO at the very top
499       ** of the program jumps to it.  Create the temporary table, then jump
500       ** back up and execute the SELECT code above.
501       */
502       sqlite3VdbeJumpHere(v, iInitCode);
503       sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
504       sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
505       sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
506       sqlite3VdbeResolveLabel(v, iCleanup);
507     }else{
508       sqlite3VdbeJumpHere(v, iInitCode);
509     }
510   }else{
511     /* This is the case if the data for the INSERT is coming from a VALUES
512     ** clause
513     */
514     NameContext sNC;
515     memset(&sNC, 0, sizeof(sNC));
516     sNC.pParse = pParse;
517     srcTab = -1;
518     useTempTable = 0;
519     nColumn = pList ? pList->nExpr : 0;
520     for(i=0; i<nColumn; i++){
521       if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
522         goto insert_cleanup;
523       }
524     }
525   }
526 
527   /* Make sure the number of columns in the source data matches the number
528   ** of columns to be inserted into the table.
529   */
530   if( IsVirtual(pTab) ){
531     for(i=0; i<pTab->nCol; i++){
532       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
533     }
534   }
535   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
536     sqlite3ErrorMsg(pParse,
537        "table %S has %d columns but %d values were supplied",
538        pTabList, 0, pTab->nCol, nColumn);
539     goto insert_cleanup;
540   }
541   if( pColumn!=0 && nColumn!=pColumn->nId ){
542     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
543     goto insert_cleanup;
544   }
545 
546   /* If the INSERT statement included an IDLIST term, then make sure
547   ** all elements of the IDLIST really are columns of the table and
548   ** remember the column indices.
549   **
550   ** If the table has an INTEGER PRIMARY KEY column and that column
551   ** is named in the IDLIST, then record in the keyColumn variable
552   ** the index into IDLIST of the primary key column.  keyColumn is
553   ** the index of the primary key as it appears in IDLIST, not as
554   ** is appears in the original table.  (The index of the primary
555   ** key in the original table is pTab->iPKey.)
556   */
557   if( pColumn ){
558     for(i=0; i<pColumn->nId; i++){
559       pColumn->a[i].idx = -1;
560     }
561     for(i=0; i<pColumn->nId; i++){
562       for(j=0; j<pTab->nCol; j++){
563         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
564           pColumn->a[i].idx = j;
565           if( j==pTab->iPKey ){
566             keyColumn = i;
567           }
568           break;
569         }
570       }
571       if( j>=pTab->nCol ){
572         if( sqlite3IsRowid(pColumn->a[i].zName) ){
573           keyColumn = i;
574         }else{
575           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
576               pTabList, 0, pColumn->a[i].zName);
577           pParse->nErr++;
578           goto insert_cleanup;
579         }
580       }
581     }
582   }
583 
584   /* If there is no IDLIST term but the table has an integer primary
585   ** key, the set the keyColumn variable to the primary key column index
586   ** in the original table definition.
587   */
588   if( pColumn==0 && nColumn>0 ){
589     keyColumn = pTab->iPKey;
590   }
591 
592   /* Open the temp table for FOR EACH ROW triggers
593   */
594   if( triggers_exist ){
595     sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
596     sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
597   }
598 
599   /* Initialize the count of rows to be inserted
600   */
601   if( db->flags & SQLITE_CountRows ){
602     iCntMem = pParse->nMem++;
603     sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
604   }
605 
606   /* Open tables and indices if there are no row triggers */
607   if( !triggers_exist ){
608     base = pParse->nTab;
609     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
610   }
611 
612   /* If the data source is a temporary table, then we have to create
613   ** a loop because there might be multiple rows of data.  If the data
614   ** source is a subroutine call from the SELECT statement, then we need
615   ** to launch the SELECT statement processing.
616   */
617   if( useTempTable ){
618     iBreak = sqlite3VdbeMakeLabel(v);
619     sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
620     iCont = sqlite3VdbeCurrentAddr(v);
621   }else if( pSelect ){
622     sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
623     sqlite3VdbeResolveLabel(v, iInsertBlock);
624   }
625 
626   /* Run the BEFORE and INSTEAD OF triggers, if there are any
627   */
628   endOfLoop = sqlite3VdbeMakeLabel(v);
629   if( triggers_exist & TRIGGER_BEFORE ){
630 
631     /* build the NEW.* reference row.  Note that if there is an INTEGER
632     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
633     ** translated into a unique ID for the row.  But on a BEFORE trigger,
634     ** we do not know what the unique ID will be (because the insert has
635     ** not happened yet) so we substitute a rowid of -1
636     */
637     if( keyColumn<0 ){
638       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
639     }else if( useTempTable ){
640       sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
641     }else{
642       assert( pSelect==0 );  /* Otherwise useTempTable is true */
643       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
644       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
645       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
646       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
647       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
648     }
649 
650     /* Cannot have triggers on a virtual table. If it were possible,
651     ** this block would have to account for hidden column.
652     */
653     assert(!IsVirtual(pTab));
654 
655     /* Create the new column data
656     */
657     for(i=0; i<pTab->nCol; i++){
658       if( pColumn==0 ){
659         j = i;
660       }else{
661         for(j=0; j<pColumn->nId; j++){
662           if( pColumn->a[j].idx==i ) break;
663         }
664       }
665       if( pColumn && j>=pColumn->nId ){
666         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
667       }else if( useTempTable ){
668         sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
669       }else{
670         assert( pSelect==0 ); /* Otherwise useTempTable is true */
671         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
672       }
673     }
674     sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
675 
676     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
677     ** do not attempt any conversions before assembling the record.
678     ** If this is a real table, attempt conversions as required by the
679     ** table column affinities.
680     */
681     if( !isView ){
682       sqlite3TableAffinityStr(v, pTab);
683     }
684     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
685 
686     /* Fire BEFORE or INSTEAD OF triggers */
687     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
688         newIdx, -1, onError, endOfLoop) ){
689       goto insert_cleanup;
690     }
691   }
692 
693   /* If any triggers exists, the opening of tables and indices is deferred
694   ** until now.
695   */
696   if( triggers_exist && !isView ){
697     base = pParse->nTab;
698     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
699   }
700 
701   /* Push the record number for the new entry onto the stack.  The
702   ** record number is a randomly generate integer created by NewRowid
703   ** except when the table has an INTEGER PRIMARY KEY column, in which
704   ** case the record number is the same as that column.
705   */
706   if( !isView ){
707     if( IsVirtual(pTab) ){
708       /* The row that the VUpdate opcode will delete:  none */
709       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
710     }
711     if( keyColumn>=0 ){
712       if( useTempTable ){
713         sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
714       }else if( pSelect ){
715         sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
716       }else{
717         VdbeOp *pOp;
718         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
719         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
720         if( pOp && pOp->opcode==OP_Null ){
721           appendFlag = 1;
722           pOp->opcode = OP_NewRowid;
723           pOp->p1 = base;
724           pOp->p2 = counterMem;
725         }
726       }
727       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
728       ** to generate a unique primary key value.
729       */
730       if( !appendFlag ){
731         sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
732         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
733         sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
734         sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
735       }
736     }else if( IsVirtual(pTab) ){
737       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
738     }else{
739       sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
740       appendFlag = 1;
741     }
742     autoIncStep(pParse, counterMem);
743 
744     /* Push onto the stack, data for all columns of the new entry, beginning
745     ** with the first column.
746     */
747     nHidden = 0;
748     for(i=0; i<pTab->nCol; i++){
749       if( i==pTab->iPKey ){
750         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
751         ** Whenever this column is read, the record number will be substituted
752         ** in its place.  So will fill this column with a NULL to avoid
753         ** taking up data space with information that will never be used. */
754         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
755         continue;
756       }
757       if( pColumn==0 ){
758         if( IsHiddenColumn(&pTab->aCol[i]) ){
759           assert( IsVirtual(pTab) );
760           j = -1;
761           nHidden++;
762         }else{
763           j = i - nHidden;
764         }
765       }else{
766         for(j=0; j<pColumn->nId; j++){
767           if( pColumn->a[j].idx==i ) break;
768         }
769       }
770       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
771         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
772       }else if( useTempTable ){
773         sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
774       }else if( pSelect ){
775         sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
776       }else{
777         sqlite3ExprCode(pParse, pList->a[j].pExpr);
778       }
779     }
780 
781     /* Generate code to check constraints and generate index keys and
782     ** do the insertion.
783     */
784 #ifndef SQLITE_OMIT_VIRTUALTABLE
785     if( IsVirtual(pTab) ){
786       pParse->pVirtualLock = pTab;
787       sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
788                      (const char*)pTab->pVtab, P3_VTAB);
789     }else
790 #endif
791     {
792       sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
793                                      0, onError, endOfLoop);
794       sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
795                             (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
796                             appendFlag);
797     }
798   }
799 
800   /* Update the count of rows that are inserted
801   */
802   if( (db->flags & SQLITE_CountRows)!=0 ){
803     sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
804   }
805 
806   if( triggers_exist ){
807     /* Close all tables opened */
808     if( !isView ){
809       sqlite3VdbeAddOp(v, OP_Close, base, 0);
810       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
811         sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
812       }
813     }
814 
815     /* Code AFTER triggers */
816     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
817           newIdx, -1, onError, endOfLoop) ){
818       goto insert_cleanup;
819     }
820   }
821 
822   /* The bottom of the loop, if the data source is a SELECT statement
823   */
824   sqlite3VdbeResolveLabel(v, endOfLoop);
825   if( useTempTable ){
826     sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
827     sqlite3VdbeResolveLabel(v, iBreak);
828     sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
829   }else if( pSelect ){
830     sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
831     sqlite3VdbeAddOp(v, OP_Return, 0, 0);
832     sqlite3VdbeResolveLabel(v, iCleanup);
833   }
834 
835   if( !triggers_exist && !IsVirtual(pTab) ){
836     /* Close all tables opened */
837     sqlite3VdbeAddOp(v, OP_Close, base, 0);
838     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
839       sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
840     }
841   }
842 
843   /* Update the sqlite_sequence table by storing the content of the
844   ** counter value in memory counterMem back into the sqlite_sequence
845   ** table.
846   */
847   autoIncEnd(pParse, iDb, pTab, counterMem);
848 
849   /*
850   ** Return the number of rows inserted. If this routine is
851   ** generating code because of a call to sqlite3NestedParse(), do not
852   ** invoke the callback function.
853   */
854   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
855     sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
856     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
857     sqlite3VdbeSetNumCols(v, 1);
858     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
859   }
860 
861 insert_cleanup:
862   sqlite3SrcListDelete(pTabList);
863   sqlite3ExprListDelete(pList);
864   sqlite3SelectDelete(pSelect);
865   sqlite3IdListDelete(pColumn);
866 }
867 
868 /*
869 ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
870 **
871 ** When this routine is called, the stack contains (from bottom to top)
872 ** the following values:
873 **
874 **    1.  The rowid of the row to be updated before the update.  This
875 **        value is omitted unless we are doing an UPDATE that involves a
876 **        change to the record number.
877 **
878 **    2.  The rowid of the row after the update.
879 **
880 **    3.  The data in the first column of the entry after the update.
881 **
882 **    i.  Data from middle columns...
883 **
884 **    N.  The data in the last column of the entry after the update.
885 **
886 ** The old rowid shown as entry (1) above is omitted unless both isUpdate
887 ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
888 ** INSERTs and rowidChng is true if the record number is being changed.
889 **
890 ** The code generated by this routine pushes additional entries onto
891 ** the stack which are the keys for new index entries for the new record.
892 ** The order of index keys is the same as the order of the indices on
893 ** the pTable->pIndex list.  A key is only created for index i if
894 ** aIdxUsed!=0 and aIdxUsed[i]!=0.
895 **
896 ** This routine also generates code to check constraints.  NOT NULL,
897 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
898 ** then the appropriate action is performed.  There are five possible
899 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
900 **
901 **  Constraint type  Action       What Happens
902 **  ---------------  ----------   ----------------------------------------
903 **  any              ROLLBACK     The current transaction is rolled back and
904 **                                sqlite3_exec() returns immediately with a
905 **                                return code of SQLITE_CONSTRAINT.
906 **
907 **  any              ABORT        Back out changes from the current command
908 **                                only (do not do a complete rollback) then
909 **                                cause sqlite3_exec() to return immediately
910 **                                with SQLITE_CONSTRAINT.
911 **
912 **  any              FAIL         Sqlite_exec() returns immediately with a
913 **                                return code of SQLITE_CONSTRAINT.  The
914 **                                transaction is not rolled back and any
915 **                                prior changes are retained.
916 **
917 **  any              IGNORE       The record number and data is popped from
918 **                                the stack and there is an immediate jump
919 **                                to label ignoreDest.
920 **
921 **  NOT NULL         REPLACE      The NULL value is replace by the default
922 **                                value for that column.  If the default value
923 **                                is NULL, the action is the same as ABORT.
924 **
925 **  UNIQUE           REPLACE      The other row that conflicts with the row
926 **                                being inserted is removed.
927 **
928 **  CHECK            REPLACE      Illegal.  The results in an exception.
929 **
930 ** Which action to take is determined by the overrideError parameter.
931 ** Or if overrideError==OE_Default, then the pParse->onError parameter
932 ** is used.  Or if pParse->onError==OE_Default then the onError value
933 ** for the constraint is used.
934 **
935 ** The calling routine must open a read/write cursor for pTab with
936 ** cursor number "base".  All indices of pTab must also have open
937 ** read/write cursors with cursor number base+i for the i-th cursor.
938 ** Except, if there is no possibility of a REPLACE action then
939 ** cursors do not need to be open for indices where aIdxUsed[i]==0.
940 **
941 ** If the isUpdate flag is true, it means that the "base" cursor is
942 ** initially pointing to an entry that is being updated.  The isUpdate
943 ** flag causes extra code to be generated so that the "base" cursor
944 ** is still pointing at the same entry after the routine returns.
945 ** Without the isUpdate flag, the "base" cursor might be moved.
946 */
947 void sqlite3GenerateConstraintChecks(
948   Parse *pParse,      /* The parser context */
949   Table *pTab,        /* the table into which we are inserting */
950   int base,           /* Index of a read/write cursor pointing at pTab */
951   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
952   int rowidChng,      /* True if the record number will change */
953   int isUpdate,       /* True for UPDATE, False for INSERT */
954   int overrideError,  /* Override onError to this if not OE_Default */
955   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
956 ){
957   int i;
958   Vdbe *v;
959   int nCol;
960   int onError;
961   int addr;
962   int extra;
963   int iCur;
964   Index *pIdx;
965   int seenReplace = 0;
966   int jumpInst1=0, jumpInst2;
967   int hasTwoRowids = (isUpdate && rowidChng);
968 
969   v = sqlite3GetVdbe(pParse);
970   assert( v!=0 );
971   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
972   nCol = pTab->nCol;
973 
974   /* Test all NOT NULL constraints.
975   */
976   for(i=0; i<nCol; i++){
977     if( i==pTab->iPKey ){
978       continue;
979     }
980     onError = pTab->aCol[i].notNull;
981     if( onError==OE_None ) continue;
982     if( overrideError!=OE_Default ){
983       onError = overrideError;
984     }else if( onError==OE_Default ){
985       onError = OE_Abort;
986     }
987     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
988       onError = OE_Abort;
989     }
990     sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
991     addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
992     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
993         || onError==OE_Ignore || onError==OE_Replace );
994     switch( onError ){
995       case OE_Rollback:
996       case OE_Abort:
997       case OE_Fail: {
998         char *zMsg = 0;
999         sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1000         sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
1001                         " may not be NULL", (char*)0);
1002         sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
1003         break;
1004       }
1005       case OE_Ignore: {
1006         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1007         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1008         break;
1009       }
1010       case OE_Replace: {
1011         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
1012         sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
1013         break;
1014       }
1015     }
1016     sqlite3VdbeJumpHere(v, addr);
1017   }
1018 
1019   /* Test all CHECK constraints
1020   */
1021 #ifndef SQLITE_OMIT_CHECK
1022   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
1023     int allOk = sqlite3VdbeMakeLabel(v);
1024     assert( pParse->ckOffset==0 );
1025     pParse->ckOffset = nCol;
1026     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
1027     assert( pParse->ckOffset==nCol );
1028     pParse->ckOffset = 0;
1029     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
1030     if( onError==OE_Ignore ){
1031       sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1032       sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1033     }else{
1034       sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1035     }
1036     sqlite3VdbeResolveLabel(v, allOk);
1037   }
1038 #endif /* !defined(SQLITE_OMIT_CHECK) */
1039 
1040   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1041   ** of the new record does not previously exist.  Except, if this
1042   ** is an UPDATE and the primary key is not changing, that is OK.
1043   */
1044   if( rowidChng ){
1045     onError = pTab->keyConf;
1046     if( overrideError!=OE_Default ){
1047       onError = overrideError;
1048     }else if( onError==OE_Default ){
1049       onError = OE_Abort;
1050     }
1051 
1052     if( isUpdate ){
1053       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1054       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1055       jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
1056     }
1057     sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
1058     jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
1059     switch( onError ){
1060       default: {
1061         onError = OE_Abort;
1062         /* Fall thru into the next case */
1063       }
1064       case OE_Rollback:
1065       case OE_Abort:
1066       case OE_Fail: {
1067         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1068                          "PRIMARY KEY must be unique", P3_STATIC);
1069         break;
1070       }
1071       case OE_Replace: {
1072         sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
1073         if( isUpdate ){
1074           sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
1075           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
1076         }
1077         seenReplace = 1;
1078         break;
1079       }
1080       case OE_Ignore: {
1081         assert( seenReplace==0 );
1082         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1083         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1084         break;
1085       }
1086     }
1087     sqlite3VdbeJumpHere(v, jumpInst2);
1088     if( isUpdate ){
1089       sqlite3VdbeJumpHere(v, jumpInst1);
1090       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1091       sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
1092     }
1093   }
1094 
1095   /* Test all UNIQUE constraints by creating entries for each UNIQUE
1096   ** index and making sure that duplicate entries do not already exist.
1097   ** Add the new records to the indices as we go.
1098   */
1099   extra = -1;
1100   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1101     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;  /* Skip unused indices */
1102     extra++;
1103 
1104     /* Create a key for accessing the index entry */
1105     sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
1106     for(i=0; i<pIdx->nColumn; i++){
1107       int idx = pIdx->aiColumn[i];
1108       if( idx==pTab->iPKey ){
1109         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
1110       }else{
1111         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
1112       }
1113     }
1114     jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
1115     sqlite3IndexAffinityStr(v, pIdx);
1116 
1117     /* Find out what action to take in case there is an indexing conflict */
1118     onError = pIdx->onError;
1119     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
1120     if( overrideError!=OE_Default ){
1121       onError = overrideError;
1122     }else if( onError==OE_Default ){
1123       onError = OE_Abort;
1124     }
1125     if( seenReplace ){
1126       if( onError==OE_Ignore ) onError = OE_Replace;
1127       else if( onError==OE_Fail ) onError = OE_Abort;
1128     }
1129 
1130 
1131     /* Check to see if the new index entry will be unique */
1132     sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
1133     jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
1134 
1135     /* Generate code that executes if the new index entry is not unique */
1136     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1137         || onError==OE_Ignore || onError==OE_Replace );
1138     switch( onError ){
1139       case OE_Rollback:
1140       case OE_Abort:
1141       case OE_Fail: {
1142         int j, n1, n2;
1143         char zErrMsg[200];
1144         sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1145                          pIdx->nColumn>1 ? "columns " : "column ");
1146         n1 = strlen(zErrMsg);
1147         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1148           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1149           n2 = strlen(zCol);
1150           if( j>0 ){
1151             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
1152             n1 += 2;
1153           }
1154           if( n1+n2>sizeof(zErrMsg)-30 ){
1155             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
1156             n1 += 3;
1157             break;
1158           }else{
1159             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
1160             n1 += n2;
1161           }
1162         }
1163         sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
1164             pIdx->nColumn>1 ? " are not unique" : " is not unique");
1165         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
1166         break;
1167       }
1168       case OE_Ignore: {
1169         assert( seenReplace==0 );
1170         sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
1171         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1172         break;
1173       }
1174       case OE_Replace: {
1175         sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
1176         if( isUpdate ){
1177           sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
1178           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
1179         }
1180         seenReplace = 1;
1181         break;
1182       }
1183     }
1184 #if NULL_DISTINCT_FOR_UNIQUE
1185     sqlite3VdbeJumpHere(v, jumpInst1);
1186 #endif
1187     sqlite3VdbeJumpHere(v, jumpInst2);
1188   }
1189 }
1190 
1191 /*
1192 ** This routine generates code to finish the INSERT or UPDATE operation
1193 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
1194 ** The stack must contain keys for all active indices followed by data
1195 ** and the rowid for the new entry.  This routine creates the new
1196 ** entries in all indices and in the main table.
1197 **
1198 ** The arguments to this routine should be the same as the first six
1199 ** arguments to sqlite3GenerateConstraintChecks.
1200 */
1201 void sqlite3CompleteInsertion(
1202   Parse *pParse,      /* The parser context */
1203   Table *pTab,        /* the table into which we are inserting */
1204   int base,           /* Index of a read/write cursor pointing at pTab */
1205   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
1206   int rowidChng,      /* True if the record number will change */
1207   int isUpdate,       /* True for UPDATE, False for INSERT */
1208   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
1209   int appendBias      /* True if this is likely to be an append */
1210 ){
1211   int i;
1212   Vdbe *v;
1213   int nIdx;
1214   Index *pIdx;
1215   int pik_flags;
1216 
1217   v = sqlite3GetVdbe(pParse);
1218   assert( v!=0 );
1219   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
1220   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1221   for(i=nIdx-1; i>=0; i--){
1222     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
1223     sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
1224   }
1225   sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
1226   sqlite3TableAffinityStr(v, pTab);
1227 #ifndef SQLITE_OMIT_TRIGGER
1228   if( newIdx>=0 ){
1229     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1230     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1231     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
1232   }
1233 #endif
1234   if( pParse->nested ){
1235     pik_flags = 0;
1236   }else{
1237     pik_flags = OPFLAG_NCHANGE;
1238     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
1239   }
1240   if( appendBias ){
1241     pik_flags |= OPFLAG_APPEND;
1242   }
1243   sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
1244   if( !pParse->nested ){
1245     sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
1246   }
1247 
1248   if( isUpdate && rowidChng ){
1249     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1250   }
1251 }
1252 
1253 /*
1254 ** Generate code that will open cursors for a table and for all
1255 ** indices of that table.  The "base" parameter is the cursor number used
1256 ** for the table.  Indices are opened on subsequent cursors.
1257 */
1258 void sqlite3OpenTableAndIndices(
1259   Parse *pParse,   /* Parsing context */
1260   Table *pTab,     /* Table to be opened */
1261   int base,        /* Cursor number assigned to the table */
1262   int op           /* OP_OpenRead or OP_OpenWrite */
1263 ){
1264   int i;
1265   int iDb;
1266   Index *pIdx;
1267   Vdbe *v;
1268 
1269   if( IsVirtual(pTab) ) return;
1270   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1271   v = sqlite3GetVdbe(pParse);
1272   assert( v!=0 );
1273   sqlite3OpenTable(pParse, base, iDb, pTab, op);
1274   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1275     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1276     assert( pIdx->pSchema==pTab->pSchema );
1277     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
1278     VdbeComment((v, "# %s", pIdx->zName));
1279     sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
1280   }
1281   if( pParse->nTab<=base+i ){
1282     pParse->nTab = base+i;
1283   }
1284 }
1285 
1286 
1287 #ifdef SQLITE_TEST
1288 /*
1289 ** The following global variable is incremented whenever the
1290 ** transfer optimization is used.  This is used for testing
1291 ** purposes only - to make sure the transfer optimization really
1292 ** is happening when it is suppose to.
1293 */
1294 int sqlite3_xferopt_count;
1295 #endif /* SQLITE_TEST */
1296 
1297 
1298 #ifndef SQLITE_OMIT_XFER_OPT
1299 /*
1300 ** Check to collation names to see if they are compatible.
1301 */
1302 static int xferCompatibleCollation(const char *z1, const char *z2){
1303   if( z1==0 ){
1304     return z2==0;
1305   }
1306   if( z2==0 ){
1307     return 0;
1308   }
1309   return sqlite3StrICmp(z1, z2)==0;
1310 }
1311 
1312 
1313 /*
1314 ** Check to see if index pSrc is compatible as a source of data
1315 ** for index pDest in an insert transfer optimization.  The rules
1316 ** for a compatible index:
1317 **
1318 **    *   The index is over the same set of columns
1319 **    *   The same DESC and ASC markings occurs on all columns
1320 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
1321 **    *   The same collating sequence on each column
1322 */
1323 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1324   int i;
1325   assert( pDest && pSrc );
1326   assert( pDest->pTable!=pSrc->pTable );
1327   if( pDest->nColumn!=pSrc->nColumn ){
1328     return 0;   /* Different number of columns */
1329   }
1330   if( pDest->onError!=pSrc->onError ){
1331     return 0;   /* Different conflict resolution strategies */
1332   }
1333   for(i=0; i<pSrc->nColumn; i++){
1334     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1335       return 0;   /* Different columns indexed */
1336     }
1337     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1338       return 0;   /* Different sort orders */
1339     }
1340     if( pSrc->azColl[i]!=pDest->azColl[i] ){
1341       return 0;   /* Different sort orders */
1342     }
1343   }
1344 
1345   /* If no test above fails then the indices must be compatible */
1346   return 1;
1347 }
1348 
1349 /*
1350 ** Attempt the transfer optimization on INSERTs of the form
1351 **
1352 **     INSERT INTO tab1 SELECT * FROM tab2;
1353 **
1354 ** This optimization is only attempted if
1355 **
1356 **    (1)  tab1 and tab2 have identical schemas including all the
1357 **         same indices and constraints
1358 **
1359 **    (2)  tab1 and tab2 are different tables
1360 **
1361 **    (3)  There must be no triggers on tab1
1362 **
1363 **    (4)  The result set of the SELECT statement is "*"
1364 **
1365 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1366 **         or LIMIT clause.
1367 **
1368 **    (6)  The SELECT statement is a simple (not a compound) select that
1369 **         contains only tab2 in its FROM clause
1370 **
1371 ** This method for implementing the INSERT transfers raw records from
1372 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
1373 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
1374 ** the resulting tab1 has much less fragmentation.
1375 **
1376 ** This routine returns TRUE if the optimization is attempted.  If any
1377 ** of the conditions above fail so that the optimization should not
1378 ** be attempted, then this routine returns FALSE.
1379 */
1380 static int xferOptimization(
1381   Parse *pParse,        /* Parser context */
1382   Table *pDest,         /* The table we are inserting into */
1383   Select *pSelect,      /* A SELECT statement to use as the data source */
1384   int onError,          /* How to handle constraint errors */
1385   int iDbDest           /* The database of pDest */
1386 ){
1387   ExprList *pEList;                /* The result set of the SELECT */
1388   Table *pSrc;                     /* The table in the FROM clause of SELECT */
1389   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
1390   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
1391   int i;                           /* Loop counter */
1392   int iDbSrc;                      /* The database of pSrc */
1393   int iSrc, iDest;                 /* Cursors from source and destination */
1394   int addr1, addr2;                /* Loop addresses */
1395   int emptyDestTest;               /* Address of test for empty pDest */
1396   int emptySrcTest;                /* Address of test for empty pSrc */
1397   Vdbe *v;                         /* The VDBE we are building */
1398   KeyInfo *pKey;                   /* Key information for an index */
1399   int counterMem;                  /* Memory register used by AUTOINC */
1400   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1401 
1402   if( pSelect==0 ){
1403     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
1404   }
1405   if( pDest->pTrigger ){
1406     return 0;   /* tab1 must not have triggers */
1407   }
1408 #ifndef SQLITE_OMIT_VIRTUALTABLE
1409   if( pDest->isVirtual ){
1410     return 0;   /* tab1 must not be a virtual table */
1411   }
1412 #endif
1413   if( onError==OE_Default ){
1414     onError = OE_Abort;
1415   }
1416   if( onError!=OE_Abort && onError!=OE_Rollback ){
1417     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1418   }
1419   if( pSelect->pSrc==0 ){
1420     return 0;   /* SELECT must have a FROM clause */
1421   }
1422   if( pSelect->pSrc->nSrc!=1 ){
1423     return 0;   /* FROM clause must have exactly one term */
1424   }
1425   if( pSelect->pSrc->a[0].pSelect ){
1426     return 0;   /* FROM clause cannot contain a subquery */
1427   }
1428   if( pSelect->pWhere ){
1429     return 0;   /* SELECT may not have a WHERE clause */
1430   }
1431   if( pSelect->pOrderBy ){
1432     return 0;   /* SELECT may not have an ORDER BY clause */
1433   }
1434   /* Do not need to test for a HAVING clause.  If HAVING is present but
1435   ** there is no ORDER BY, we will get an error. */
1436   if( pSelect->pGroupBy ){
1437     return 0;   /* SELECT may not have a GROUP BY clause */
1438   }
1439   if( pSelect->pLimit ){
1440     return 0;   /* SELECT may not have a LIMIT clause */
1441   }
1442   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
1443   if( pSelect->pPrior ){
1444     return 0;   /* SELECT may not be a compound query */
1445   }
1446   if( pSelect->isDistinct ){
1447     return 0;   /* SELECT may not be DISTINCT */
1448   }
1449   pEList = pSelect->pEList;
1450   assert( pEList!=0 );
1451   if( pEList->nExpr!=1 ){
1452     return 0;   /* The result set must have exactly one column */
1453   }
1454   assert( pEList->a[0].pExpr );
1455   if( pEList->a[0].pExpr->op!=TK_ALL ){
1456     return 0;   /* The result set must be the special operator "*" */
1457   }
1458 
1459   /* At this point we have established that the statement is of the
1460   ** correct syntactic form to participate in this optimization.  Now
1461   ** we have to check the semantics.
1462   */
1463   pItem = pSelect->pSrc->a;
1464   pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1465   if( pSrc==0 ){
1466     return 0;   /* FROM clause does not contain a real table */
1467   }
1468   if( pSrc==pDest ){
1469     return 0;   /* tab1 and tab2 may not be the same table */
1470   }
1471 #ifndef SQLITE_OMIT_VIRTUALTABLE
1472   if( pSrc->isVirtual ){
1473     return 0;   /* tab2 must not be a virtual table */
1474   }
1475 #endif
1476   if( pSrc->pSelect ){
1477     return 0;   /* tab2 may not be a view */
1478   }
1479   if( pDest->nCol!=pSrc->nCol ){
1480     return 0;   /* Number of columns must be the same in tab1 and tab2 */
1481   }
1482   if( pDest->iPKey!=pSrc->iPKey ){
1483     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
1484   }
1485   for(i=0; i<pDest->nCol; i++){
1486     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1487       return 0;    /* Affinity must be the same on all columns */
1488     }
1489     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1490       return 0;    /* Collating sequence must be the same on all columns */
1491     }
1492     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1493       return 0;    /* tab2 must be NOT NULL if tab1 is */
1494     }
1495   }
1496   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1497     if( pDestIdx->onError!=OE_None ){
1498       destHasUniqueIdx = 1;
1499     }
1500     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1501       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1502     }
1503     if( pSrcIdx==0 ){
1504       return 0;    /* pDestIdx has no corresponding index in pSrc */
1505     }
1506   }
1507 #ifndef SQLITE_OMIT_CHECK
1508   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
1509     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
1510   }
1511 #endif
1512 
1513   /* If we get this far, it means either:
1514   **
1515   **    *   We can always do the transfer if the table contains an
1516   **        an integer primary key
1517   **
1518   **    *   We can conditionally do the transfer if the destination
1519   **        table is empty.
1520   */
1521 #ifdef SQLITE_TEST
1522   sqlite3_xferopt_count++;
1523 #endif
1524   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1525   v = sqlite3GetVdbe(pParse);
1526   iSrc = pParse->nTab++;
1527   iDest = pParse->nTab++;
1528   counterMem = autoIncBegin(pParse, iDbDest, pDest);
1529   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1530   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
1531     /* If tables do not have an INTEGER PRIMARY KEY and there
1532     ** are indices to be copied and the destination is not empty,
1533     ** we have to disallow the transfer optimization because the
1534     ** the rowids might change which will mess up indexing.
1535     **
1536     ** Or if the destination has a UNIQUE index and is not empty,
1537     ** we also disallow the transfer optimization because we cannot
1538     ** insure that all entries in the union of DEST and SRC will be
1539     ** unique.
1540     */
1541     addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
1542     emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
1543     sqlite3VdbeJumpHere(v, addr1);
1544   }else{
1545     emptyDestTest = 0;
1546   }
1547   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
1548   emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
1549   if( pDest->iPKey>=0 ){
1550     addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
1551     sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1552     addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
1553     sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1554                       "PRIMARY KEY must be unique", P3_STATIC);
1555     sqlite3VdbeJumpHere(v, addr2);
1556     autoIncStep(pParse, counterMem);
1557   }else if( pDest->pIndex==0 ){
1558     addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
1559   }else{
1560     addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
1561     assert( pDest->autoInc==0 );
1562   }
1563   sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
1564   sqlite3VdbeOp3(v, OP_Insert, iDest,
1565                     OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
1566                     pDest->zName, 0);
1567   sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
1568   autoIncEnd(pParse, iDbDest, pDest, counterMem);
1569   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1570     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1571       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1572     }
1573     assert( pSrcIdx );
1574     sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1575     sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1576     sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
1577     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1578     VdbeComment((v, "# %s", pSrcIdx->zName));
1579     sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
1580                    (char*)pKey, P3_KEYINFO_HANDOFF);
1581     sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
1582     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1583     VdbeComment((v, "# %s", pDestIdx->zName));
1584     sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
1585                    (char*)pKey, P3_KEYINFO_HANDOFF);
1586     addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
1587     sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
1588     sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
1589     sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
1590     sqlite3VdbeJumpHere(v, addr1);
1591   }
1592   sqlite3VdbeJumpHere(v, emptySrcTest);
1593   sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1594   sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1595   if( emptyDestTest ){
1596     sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
1597     sqlite3VdbeJumpHere(v, emptyDestTest);
1598     sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1599     return 0;
1600   }else{
1601     return 1;
1602   }
1603 }
1604 #endif /* SQLITE_OMIT_XFER_OPT */
1605