Prevent deep recursions on nested COLLATE operators.
[sqlite.git] / src / insert.c
blobd2ac028d91dde57a632c27edc5c1f4b40d4fd666
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.
11 *************************************************************************
12 ** This file contains C code routines that are called by the parser
13 ** to handle INSERT statements in SQLite.
15 #include "sqliteInt.h"
18 ** Generate code that will
20 ** (1) acquire a lock for table pTab then
21 ** (2) open pTab as cursor iCur.
23 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
24 ** for that table that is actually opened.
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 */
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));
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:
57 ** Character Column affinity
58 ** ------------------------------
59 ** 'A' BLOB
60 ** 'B' TEXT
61 ** 'C' NUMERIC
62 ** 'D' INTEGER
63 ** 'F' REAL
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.
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.
72 const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
73 if( !pIdx->zColAff ){
74 /* The first time a column affinity string for a particular index is
75 ** required, it is allocated and populated here. It is then stored as
76 ** a member of the Index structure for subsequent use.
78 ** The column affinity string will eventually be deleted by
79 ** sqliteDeleteIndex() when the Index structure itself is cleaned
80 ** up.
82 int n;
83 Table *pTab = pIdx->pTable;
84 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
85 if( !pIdx->zColAff ){
86 sqlite3OomFault(db);
87 return 0;
89 for(n=0; n<pIdx->nColumn; n++){
90 i16 x = pIdx->aiColumn[n];
91 if( x>=0 ){
92 pIdx->zColAff[n] = pTab->aCol[x].affinity;
93 }else if( x==XN_ROWID ){
94 pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
95 }else{
96 char aff;
97 assert( x==XN_EXPR );
98 assert( pIdx->aColExpr!=0 );
99 aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
100 if( aff==0 ) aff = SQLITE_AFF_BLOB;
101 pIdx->zColAff[n] = aff;
104 pIdx->zColAff[n] = 0;
107 return pIdx->zColAff;
111 ** Compute the affinity string for table pTab, if it has not already been
112 ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
114 ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
115 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
116 ** for register iReg and following. Or if affinities exists and iReg==0,
117 ** then just set the P4 operand of the previous opcode (which should be
118 ** an OP_MakeRecord) to the affinity string.
120 ** A column affinity string has one character per column:
122 ** Character Column affinity
123 ** ------------------------------
124 ** 'A' BLOB
125 ** 'B' TEXT
126 ** 'C' NUMERIC
127 ** 'D' INTEGER
128 ** 'E' REAL
130 void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
131 int i;
132 char *zColAff = pTab->zColAff;
133 if( zColAff==0 ){
134 sqlite3 *db = sqlite3VdbeDb(v);
135 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
136 if( !zColAff ){
137 sqlite3OomFault(db);
138 return;
141 for(i=0; i<pTab->nCol; i++){
142 zColAff[i] = pTab->aCol[i].affinity;
145 zColAff[i--] = 0;
146 }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
147 pTab->zColAff = zColAff;
149 i = sqlite3Strlen30(zColAff);
150 if( i ){
151 if( iReg ){
152 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
153 }else{
154 sqlite3VdbeChangeP4(v, -1, zColAff, i);
160 ** Return non-zero if the table pTab in database iDb or any of its indices
161 ** have been opened at any point in the VDBE program. This is used to see if
162 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
163 ** run without using a temporary table for the results of the SELECT.
165 static int readsTable(Parse *p, int iDb, Table *pTab){
166 Vdbe *v = sqlite3GetVdbe(p);
167 int i;
168 int iEnd = sqlite3VdbeCurrentAddr(v);
169 #ifndef SQLITE_OMIT_VIRTUALTABLE
170 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
171 #endif
173 for(i=1; i<iEnd; i++){
174 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
175 assert( pOp!=0 );
176 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
177 Index *pIndex;
178 int tnum = pOp->p2;
179 if( tnum==pTab->tnum ){
180 return 1;
182 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
183 if( tnum==pIndex->tnum ){
184 return 1;
188 #ifndef SQLITE_OMIT_VIRTUALTABLE
189 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
190 assert( pOp->p4.pVtab!=0 );
191 assert( pOp->p4type==P4_VTAB );
192 return 1;
194 #endif
196 return 0;
199 #ifndef SQLITE_OMIT_AUTOINCREMENT
201 ** Locate or create an AutoincInfo structure associated with table pTab
202 ** which is in database iDb. Return the register number for the register
203 ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
204 ** table. (Also return zero when doing a VACUUM since we do not want to
205 ** update the AUTOINCREMENT counters during a VACUUM.)
207 ** There is at most one AutoincInfo structure per table even if the
208 ** same table is autoincremented multiple times due to inserts within
209 ** triggers. A new AutoincInfo structure is created if this is the
210 ** first use of table pTab. On 2nd and subsequent uses, the original
211 ** AutoincInfo structure is used.
213 ** Four consecutive registers are allocated:
215 ** (1) The name of the pTab table.
216 ** (2) The maximum ROWID of pTab.
217 ** (3) The rowid in sqlite_sequence of pTab
218 ** (4) The original value of the max ROWID in pTab, or NULL if none
220 ** The 2nd register is the one that is returned. That is all the
221 ** insert routine needs to know about.
223 static int autoIncBegin(
224 Parse *pParse, /* Parsing context */
225 int iDb, /* Index of the database holding pTab */
226 Table *pTab /* The table we are writing to */
228 int memId = 0; /* Register holding maximum rowid */
229 if( (pTab->tabFlags & TF_Autoincrement)!=0
230 && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
232 Parse *pToplevel = sqlite3ParseToplevel(pParse);
233 AutoincInfo *pInfo;
235 pInfo = pToplevel->pAinc;
236 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
237 if( pInfo==0 ){
238 pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
239 if( pInfo==0 ) return 0;
240 pInfo->pNext = pToplevel->pAinc;
241 pToplevel->pAinc = pInfo;
242 pInfo->pTab = pTab;
243 pInfo->iDb = iDb;
244 pToplevel->nMem++; /* Register to hold name of table */
245 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
246 pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
248 memId = pInfo->regCtr;
250 return memId;
254 ** This routine generates code that will initialize all of the
255 ** register used by the autoincrement tracker.
257 void sqlite3AutoincrementBegin(Parse *pParse){
258 AutoincInfo *p; /* Information about an AUTOINCREMENT */
259 sqlite3 *db = pParse->db; /* The database connection */
260 Db *pDb; /* Database only autoinc table */
261 int memId; /* Register holding max rowid */
262 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
264 /* This routine is never called during trigger-generation. It is
265 ** only called from the top-level */
266 assert( pParse->pTriggerTab==0 );
267 assert( sqlite3IsToplevel(pParse) );
269 assert( v ); /* We failed long ago if this is not so */
270 for(p = pParse->pAinc; p; p = p->pNext){
271 static const int iLn = VDBE_OFFSET_LINENO(2);
272 static const VdbeOpList autoInc[] = {
273 /* 0 */ {OP_Null, 0, 0, 0},
274 /* 1 */ {OP_Rewind, 0, 10, 0},
275 /* 2 */ {OP_Column, 0, 0, 0},
276 /* 3 */ {OP_Ne, 0, 9, 0},
277 /* 4 */ {OP_Rowid, 0, 0, 0},
278 /* 5 */ {OP_Column, 0, 1, 0},
279 /* 6 */ {OP_AddImm, 0, 0, 0},
280 /* 7 */ {OP_Copy, 0, 0, 0},
281 /* 8 */ {OP_Goto, 0, 11, 0},
282 /* 9 */ {OP_Next, 0, 2, 0},
283 /* 10 */ {OP_Integer, 0, 0, 0},
284 /* 11 */ {OP_Close, 0, 0, 0}
286 VdbeOp *aOp;
287 pDb = &db->aDb[p->iDb];
288 memId = p->regCtr;
289 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
290 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
291 sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
292 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
293 if( aOp==0 ) break;
294 aOp[0].p2 = memId;
295 aOp[0].p3 = memId+2;
296 aOp[2].p3 = memId;
297 aOp[3].p1 = memId-1;
298 aOp[3].p3 = memId;
299 aOp[3].p5 = SQLITE_JUMPIFNULL;
300 aOp[4].p2 = memId+1;
301 aOp[5].p3 = memId;
302 aOp[6].p1 = memId;
303 aOp[7].p2 = memId+2;
304 aOp[7].p1 = memId;
305 aOp[10].p2 = memId;
310 ** Update the maximum rowid for an autoincrement calculation.
312 ** This routine should be called when the regRowid register holds a
313 ** new rowid that is about to be inserted. If that new rowid is
314 ** larger than the maximum rowid in the memId memory cell, then the
315 ** memory cell is updated.
317 static void autoIncStep(Parse *pParse, int memId, int regRowid){
318 if( memId>0 ){
319 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
324 ** This routine generates the code needed to write autoincrement
325 ** maximum rowid values back into the sqlite_sequence register.
326 ** Every statement that might do an INSERT into an autoincrement
327 ** table (either directly or through triggers) needs to call this
328 ** routine just before the "exit" code.
330 static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
331 AutoincInfo *p;
332 Vdbe *v = pParse->pVdbe;
333 sqlite3 *db = pParse->db;
335 assert( v );
336 for(p = pParse->pAinc; p; p = p->pNext){
337 static const int iLn = VDBE_OFFSET_LINENO(2);
338 static const VdbeOpList autoIncEnd[] = {
339 /* 0 */ {OP_NotNull, 0, 2, 0},
340 /* 1 */ {OP_NewRowid, 0, 0, 0},
341 /* 2 */ {OP_MakeRecord, 0, 2, 0},
342 /* 3 */ {OP_Insert, 0, 0, 0},
343 /* 4 */ {OP_Close, 0, 0, 0}
345 VdbeOp *aOp;
346 Db *pDb = &db->aDb[p->iDb];
347 int iRec;
348 int memId = p->regCtr;
350 iRec = sqlite3GetTempReg(pParse);
351 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
352 sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
353 VdbeCoverage(v);
354 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
355 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
356 if( aOp==0 ) break;
357 aOp[0].p1 = memId+1;
358 aOp[1].p2 = memId+1;
359 aOp[2].p1 = memId-1;
360 aOp[2].p3 = iRec;
361 aOp[3].p2 = iRec;
362 aOp[3].p3 = memId+1;
363 aOp[3].p5 = OPFLAG_APPEND;
364 sqlite3ReleaseTempReg(pParse, iRec);
367 void sqlite3AutoincrementEnd(Parse *pParse){
368 if( pParse->pAinc ) autoIncrementEnd(pParse);
370 #else
372 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
373 ** above are all no-ops
375 # define autoIncBegin(A,B,C) (0)
376 # define autoIncStep(A,B,C)
377 #endif /* SQLITE_OMIT_AUTOINCREMENT */
380 /* Forward declaration */
381 static int xferOptimization(
382 Parse *pParse, /* Parser context */
383 Table *pDest, /* The table we are inserting into */
384 Select *pSelect, /* A SELECT statement to use as the data source */
385 int onError, /* How to handle constraint errors */
386 int iDbDest /* The database of pDest */
390 ** This routine is called to handle SQL of the following forms:
392 ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
393 ** insert into TABLE (IDLIST) select
394 ** insert into TABLE (IDLIST) default values
396 ** The IDLIST following the table name is always optional. If omitted,
397 ** then a list of all (non-hidden) columns for the table is substituted.
398 ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
399 ** is omitted.
401 ** For the pSelect parameter holds the values to be inserted for the
402 ** first two forms shown above. A VALUES clause is really just short-hand
403 ** for a SELECT statement that omits the FROM clause and everything else
404 ** that follows. If the pSelect parameter is NULL, that means that the
405 ** DEFAULT VALUES form of the INSERT statement is intended.
407 ** The code generated follows one of four templates. For a simple
408 ** insert with data coming from a single-row VALUES clause, the code executes
409 ** once straight down through. Pseudo-code follows (we call this
410 ** the "1st template"):
412 ** open write cursor to <table> and its indices
413 ** put VALUES clause expressions into registers
414 ** write the resulting record into <table>
415 ** cleanup
417 ** The three remaining templates assume the statement is of the form
419 ** INSERT INTO <table> SELECT ...
421 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
422 ** in other words if the SELECT pulls all columns from a single table
423 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
424 ** if <table2> and <table1> are distinct tables but have identical
425 ** schemas, including all the same indices, then a special optimization
426 ** is invoked that copies raw records from <table2> over to <table1>.
427 ** See the xferOptimization() function for the implementation of this
428 ** template. This is the 2nd template.
430 ** open a write cursor to <table>
431 ** open read cursor on <table2>
432 ** transfer all records in <table2> over to <table>
433 ** close cursors
434 ** foreach index on <table>
435 ** open a write cursor on the <table> index
436 ** open a read cursor on the corresponding <table2> index
437 ** transfer all records from the read to the write cursors
438 ** close cursors
439 ** end foreach
441 ** The 3rd template is for when the second template does not apply
442 ** and the SELECT clause does not read from <table> at any time.
443 ** The generated code follows this template:
445 ** X <- A
446 ** goto B
447 ** A: setup for the SELECT
448 ** loop over the rows in the SELECT
449 ** load values into registers R..R+n
450 ** yield X
451 ** end loop
452 ** cleanup after the SELECT
453 ** end-coroutine X
454 ** B: open write cursor to <table> and its indices
455 ** C: yield X, at EOF goto D
456 ** insert the select result into <table> from R..R+n
457 ** goto C
458 ** D: cleanup
460 ** The 4th template is used if the insert statement takes its
461 ** values from a SELECT but the data is being inserted into a table
462 ** that is also read as part of the SELECT. In the third form,
463 ** we have to use an intermediate table to store the results of
464 ** the select. The template is like this:
466 ** X <- A
467 ** goto B
468 ** A: setup for the SELECT
469 ** loop over the tables in the SELECT
470 ** load value into register R..R+n
471 ** yield X
472 ** end loop
473 ** cleanup after the SELECT
474 ** end co-routine R
475 ** B: open temp table
476 ** L: yield X, at EOF goto M
477 ** insert row from R..R+n into temp table
478 ** goto L
479 ** M: open write cursor to <table> and its indices
480 ** rewind temp table
481 ** C: loop over rows of intermediate table
482 ** transfer values form intermediate table into <table>
483 ** end loop
484 ** D: cleanup
486 void sqlite3Insert(
487 Parse *pParse, /* Parser context */
488 SrcList *pTabList, /* Name of table into which we are inserting */
489 Select *pSelect, /* A SELECT statement to use as the data source */
490 IdList *pColumn, /* Column names corresponding to IDLIST. */
491 int onError, /* How to handle constraint errors */
492 Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
494 sqlite3 *db; /* The main database structure */
495 Table *pTab; /* The table to insert into. aka TABLE */
496 int i, j; /* Loop counters */
497 Vdbe *v; /* Generate code into this virtual machine */
498 Index *pIdx; /* For looping over indices of the table */
499 int nColumn; /* Number of columns in the data */
500 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
501 int iDataCur = 0; /* VDBE cursor that is the main data repository */
502 int iIdxCur = 0; /* First index cursor */
503 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
504 int endOfLoop; /* Label for the end of the insertion loop */
505 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
506 int addrInsTop = 0; /* Jump to label "D" */
507 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
508 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
509 int iDb; /* Index of database holding TABLE */
510 u8 useTempTable = 0; /* Store SELECT results in intermediate table */
511 u8 appendFlag = 0; /* True if the insert is likely to be an append */
512 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
513 u8 bIdListInOrder; /* True if IDLIST is in table order */
514 ExprList *pList = 0; /* List of VALUES() to be inserted */
516 /* Register allocations */
517 int regFromSelect = 0;/* Base register for data coming from SELECT */
518 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
519 int regRowCount = 0; /* Memory cell used for the row counter */
520 int regIns; /* Block of regs holding rowid+data being inserted */
521 int regRowid; /* registers holding insert rowid */
522 int regData; /* register holding first column to insert */
523 int *aRegIdx = 0; /* One register allocated to each index */
525 #ifndef SQLITE_OMIT_TRIGGER
526 int isView; /* True if attempting to insert into a view */
527 Trigger *pTrigger; /* List of triggers on pTab, if required */
528 int tmask; /* Mask of trigger times */
529 #endif
531 db = pParse->db;
532 if( pParse->nErr || db->mallocFailed ){
533 goto insert_cleanup;
535 dest.iSDParm = 0; /* Suppress a harmless compiler warning */
537 /* If the Select object is really just a simple VALUES() list with a
538 ** single row (the common case) then keep that one row of values
539 ** and discard the other (unused) parts of the pSelect object
541 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
542 pList = pSelect->pEList;
543 pSelect->pEList = 0;
544 sqlite3SelectDelete(db, pSelect);
545 pSelect = 0;
548 /* Locate the table into which we will be inserting new information.
550 assert( pTabList->nSrc==1 );
551 pTab = sqlite3SrcListLookup(pParse, pTabList);
552 if( pTab==0 ){
553 goto insert_cleanup;
555 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
556 assert( iDb<db->nDb );
557 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
558 db->aDb[iDb].zDbSName) ){
559 goto insert_cleanup;
561 withoutRowid = !HasRowid(pTab);
563 /* Figure out if we have any triggers and if the table being
564 ** inserted into is a view
566 #ifndef SQLITE_OMIT_TRIGGER
567 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
568 isView = pTab->pSelect!=0;
569 #else
570 # define pTrigger 0
571 # define tmask 0
572 # define isView 0
573 #endif
574 #ifdef SQLITE_OMIT_VIEW
575 # undef isView
576 # define isView 0
577 #endif
578 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
580 /* If pTab is really a view, make sure it has been initialized.
581 ** ViewGetColumnNames() is a no-op if pTab is not a view.
583 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
584 goto insert_cleanup;
587 /* Cannot insert into a read-only table.
589 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
590 goto insert_cleanup;
593 /* Allocate a VDBE
595 v = sqlite3GetVdbe(pParse);
596 if( v==0 ) goto insert_cleanup;
597 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
598 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
600 #ifndef SQLITE_OMIT_XFER_OPT
601 /* If the statement is of the form
603 ** INSERT INTO <table1> SELECT * FROM <table2>;
605 ** Then special optimizations can be applied that make the transfer
606 ** very fast and which reduce fragmentation of indices.
608 ** This is the 2nd template.
610 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
611 assert( !pTrigger );
612 assert( pList==0 );
613 goto insert_end;
615 #endif /* SQLITE_OMIT_XFER_OPT */
617 /* If this is an AUTOINCREMENT table, look up the sequence number in the
618 ** sqlite_sequence table and store it in memory cell regAutoinc.
620 regAutoinc = autoIncBegin(pParse, iDb, pTab);
622 /* Allocate registers for holding the rowid of the new row,
623 ** the content of the new row, and the assembled row record.
625 regRowid = regIns = pParse->nMem+1;
626 pParse->nMem += pTab->nCol + 1;
627 if( IsVirtual(pTab) ){
628 regRowid++;
629 pParse->nMem++;
631 regData = regRowid+1;
633 /* If the INSERT statement included an IDLIST term, then make sure
634 ** all elements of the IDLIST really are columns of the table and
635 ** remember the column indices.
637 ** If the table has an INTEGER PRIMARY KEY column and that column
638 ** is named in the IDLIST, then record in the ipkColumn variable
639 ** the index into IDLIST of the primary key column. ipkColumn is
640 ** the index of the primary key as it appears in IDLIST, not as
641 ** is appears in the original table. (The index of the INTEGER
642 ** PRIMARY KEY in the original table is pTab->iPKey.)
644 bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
645 if( pColumn ){
646 for(i=0; i<pColumn->nId; i++){
647 pColumn->a[i].idx = -1;
649 for(i=0; i<pColumn->nId; i++){
650 for(j=0; j<pTab->nCol; j++){
651 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
652 pColumn->a[i].idx = j;
653 if( i!=j ) bIdListInOrder = 0;
654 if( j==pTab->iPKey ){
655 ipkColumn = i; assert( !withoutRowid );
657 break;
660 if( j>=pTab->nCol ){
661 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
662 ipkColumn = i;
663 bIdListInOrder = 0;
664 }else{
665 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
666 pTabList, 0, pColumn->a[i].zName);
667 pParse->checkSchema = 1;
668 goto insert_cleanup;
674 /* Figure out how many columns of data are supplied. If the data
675 ** is coming from a SELECT statement, then generate a co-routine that
676 ** produces a single row of the SELECT on each invocation. The
677 ** co-routine is the common header to the 3rd and 4th templates.
679 if( pSelect ){
680 /* Data is coming from a SELECT or from a multi-row VALUES clause.
681 ** Generate a co-routine to run the SELECT. */
682 int regYield; /* Register holding co-routine entry-point */
683 int addrTop; /* Top of the co-routine */
684 int rc; /* Result code */
686 regYield = ++pParse->nMem;
687 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
688 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
689 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
690 dest.iSdst = bIdListInOrder ? regData : 0;
691 dest.nSdst = pTab->nCol;
692 rc = sqlite3Select(pParse, pSelect, &dest);
693 regFromSelect = dest.iSdst;
694 if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
695 sqlite3VdbeEndCoroutine(v, regYield);
696 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
697 assert( pSelect->pEList );
698 nColumn = pSelect->pEList->nExpr;
700 /* Set useTempTable to TRUE if the result of the SELECT statement
701 ** should be written into a temporary table (template 4). Set to
702 ** FALSE if each output row of the SELECT can be written directly into
703 ** the destination table (template 3).
705 ** A temp table must be used if the table being updated is also one
706 ** of the tables being read by the SELECT statement. Also use a
707 ** temp table in the case of row triggers.
709 if( pTrigger || readsTable(pParse, iDb, pTab) ){
710 useTempTable = 1;
713 if( useTempTable ){
714 /* Invoke the coroutine to extract information from the SELECT
715 ** and add it to a transient table srcTab. The code generated
716 ** here is from the 4th template:
718 ** B: open temp table
719 ** L: yield X, goto M at EOF
720 ** insert row from R..R+n into temp table
721 ** goto L
722 ** M: ...
724 int regRec; /* Register to hold packed record */
725 int regTempRowid; /* Register to hold temp table ROWID */
726 int addrL; /* Label "L" */
728 srcTab = pParse->nTab++;
729 regRec = sqlite3GetTempReg(pParse);
730 regTempRowid = sqlite3GetTempReg(pParse);
731 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
732 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
733 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
734 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
735 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
736 sqlite3VdbeGoto(v, addrL);
737 sqlite3VdbeJumpHere(v, addrL);
738 sqlite3ReleaseTempReg(pParse, regRec);
739 sqlite3ReleaseTempReg(pParse, regTempRowid);
741 }else{
742 /* This is the case if the data for the INSERT is coming from a
743 ** single-row VALUES clause
745 NameContext sNC;
746 memset(&sNC, 0, sizeof(sNC));
747 sNC.pParse = pParse;
748 srcTab = -1;
749 assert( useTempTable==0 );
750 if( pList ){
751 nColumn = pList->nExpr;
752 if( sqlite3ResolveExprListNames(&sNC, pList) ){
753 goto insert_cleanup;
755 }else{
756 nColumn = 0;
760 /* If there is no IDLIST term but the table has an integer primary
761 ** key, the set the ipkColumn variable to the integer primary key
762 ** column index in the original table definition.
764 if( pColumn==0 && nColumn>0 ){
765 ipkColumn = pTab->iPKey;
768 /* Make sure the number of columns in the source data matches the number
769 ** of columns to be inserted into the table.
771 for(i=0; i<pTab->nCol; i++){
772 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
774 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
775 sqlite3ErrorMsg(pParse,
776 "table %S has %d columns but %d values were supplied",
777 pTabList, 0, pTab->nCol-nHidden, nColumn);
778 goto insert_cleanup;
780 if( pColumn!=0 && nColumn!=pColumn->nId ){
781 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
782 goto insert_cleanup;
785 /* Initialize the count of rows to be inserted
787 if( (db->flags & SQLITE_CountRows)!=0
788 && !pParse->nested
789 && !pParse->pTriggerTab
791 regRowCount = ++pParse->nMem;
792 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
795 /* If this is not a view, open the table and and all indices */
796 if( !isView ){
797 int nIdx;
798 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
799 &iDataCur, &iIdxCur);
800 aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
801 if( aRegIdx==0 ){
802 goto insert_cleanup;
804 for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
805 assert( pIdx );
806 aRegIdx[i] = ++pParse->nMem;
807 pParse->nMem += pIdx->nColumn;
810 #ifndef SQLITE_OMIT_UPSERT
811 if( pUpsert ){
812 pTabList->a[0].iCursor = iDataCur;
813 pUpsert->pUpsertSrc = pTabList;
814 pUpsert->regData = regData;
815 pUpsert->iDataCur = iDataCur;
816 pUpsert->iIdxCur = iIdxCur;
817 if( pUpsert->pUpsertTarget ){
818 sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
821 #endif
824 /* This is the top of the main insertion loop */
825 if( useTempTable ){
826 /* This block codes the top of loop only. The complete loop is the
827 ** following pseudocode (template 4):
829 ** rewind temp table, if empty goto D
830 ** C: loop over rows of intermediate table
831 ** transfer values form intermediate table into <table>
832 ** end loop
833 ** D: ...
835 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
836 addrCont = sqlite3VdbeCurrentAddr(v);
837 }else if( pSelect ){
838 /* This block codes the top of loop only. The complete loop is the
839 ** following pseudocode (template 3):
841 ** C: yield X, at EOF goto D
842 ** insert the select result into <table> from R..R+n
843 ** goto C
844 ** D: ...
846 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
847 VdbeCoverage(v);
850 /* Run the BEFORE and INSTEAD OF triggers, if there are any
852 endOfLoop = sqlite3VdbeMakeLabel(v);
853 if( tmask & TRIGGER_BEFORE ){
854 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
856 /* build the NEW.* reference row. Note that if there is an INTEGER
857 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
858 ** translated into a unique ID for the row. But on a BEFORE trigger,
859 ** we do not know what the unique ID will be (because the insert has
860 ** not happened yet) so we substitute a rowid of -1
862 if( ipkColumn<0 ){
863 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
864 }else{
865 int addr1;
866 assert( !withoutRowid );
867 if( useTempTable ){
868 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
869 }else{
870 assert( pSelect==0 ); /* Otherwise useTempTable is true */
871 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
873 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
874 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
875 sqlite3VdbeJumpHere(v, addr1);
876 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
879 /* Cannot have triggers on a virtual table. If it were possible,
880 ** this block would have to account for hidden column.
882 assert( !IsVirtual(pTab) );
884 /* Create the new column data
886 for(i=j=0; i<pTab->nCol; i++){
887 if( pColumn ){
888 for(j=0; j<pColumn->nId; j++){
889 if( pColumn->a[j].idx==i ) break;
892 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
893 || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
894 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
895 }else if( useTempTable ){
896 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
897 }else{
898 assert( pSelect==0 ); /* Otherwise useTempTable is true */
899 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
901 if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
904 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
905 ** do not attempt any conversions before assembling the record.
906 ** If this is a real table, attempt conversions as required by the
907 ** table column affinities.
909 if( !isView ){
910 sqlite3TableAffinity(v, pTab, regCols+1);
913 /* Fire BEFORE or INSTEAD OF triggers */
914 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
915 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
917 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
920 /* Compute the content of the next row to insert into a range of
921 ** registers beginning at regIns.
923 if( !isView ){
924 if( IsVirtual(pTab) ){
925 /* The row that the VUpdate opcode will delete: none */
926 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
928 if( ipkColumn>=0 ){
929 if( useTempTable ){
930 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
931 }else if( pSelect ){
932 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
933 }else{
934 VdbeOp *pOp;
935 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
936 pOp = sqlite3VdbeGetOp(v, -1);
937 assert( pOp!=0 );
938 if( pOp->opcode==OP_Null && !IsVirtual(pTab) ){
939 appendFlag = 1;
940 pOp->opcode = OP_NewRowid;
941 pOp->p1 = iDataCur;
942 pOp->p2 = regRowid;
943 pOp->p3 = regAutoinc;
946 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
947 ** to generate a unique primary key value.
949 if( !appendFlag ){
950 int addr1;
951 if( !IsVirtual(pTab) ){
952 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
953 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
954 sqlite3VdbeJumpHere(v, addr1);
955 }else{
956 addr1 = sqlite3VdbeCurrentAddr(v);
957 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
959 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
961 }else if( IsVirtual(pTab) || withoutRowid ){
962 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
963 }else{
964 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
965 appendFlag = 1;
967 autoIncStep(pParse, regAutoinc, regRowid);
969 /* Compute data for all columns of the new entry, beginning
970 ** with the first column.
972 nHidden = 0;
973 for(i=0; i<pTab->nCol; i++){
974 int iRegStore = regRowid+1+i;
975 if( i==pTab->iPKey ){
976 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
977 ** Whenever this column is read, the rowid will be substituted
978 ** in its place. Hence, fill this column with a NULL to avoid
979 ** taking up data space with information that will never be used.
980 ** As there may be shallow copies of this value, make it a soft-NULL */
981 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
982 continue;
984 if( pColumn==0 ){
985 if( IsHiddenColumn(&pTab->aCol[i]) ){
986 j = -1;
987 nHidden++;
988 }else{
989 j = i - nHidden;
991 }else{
992 for(j=0; j<pColumn->nId; j++){
993 if( pColumn->a[j].idx==i ) break;
996 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
997 sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
998 }else if( useTempTable ){
999 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
1000 }else if( pSelect ){
1001 if( regFromSelect!=regData ){
1002 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
1004 }else{
1005 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
1009 /* Generate code to check constraints and generate index keys and
1010 ** do the insertion.
1012 #ifndef SQLITE_OMIT_VIRTUALTABLE
1013 if( IsVirtual(pTab) ){
1014 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
1015 sqlite3VtabMakeWritable(pParse, pTab);
1016 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1017 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1018 sqlite3MayAbort(pParse);
1019 }else
1020 #endif
1022 int isReplace; /* Set to true if constraints may cause a replace */
1023 int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
1024 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1025 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
1027 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
1029 /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
1030 ** constraints or (b) there are no triggers and this table is not a
1031 ** parent table in a foreign key constraint. It is safe to set the
1032 ** flag in the second case as if any REPLACE constraint is hit, an
1033 ** OP_Delete or OP_IdxDelete instruction will be executed on each
1034 ** cursor that is disturbed. And these instructions both clear the
1035 ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
1036 ** functionality. */
1037 bUseSeek = (isReplace==0 || (pTrigger==0 &&
1038 ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
1040 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
1041 regIns, aRegIdx, 0, appendFlag, bUseSeek
1046 /* Update the count of rows that are inserted
1048 if( regRowCount ){
1049 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
1052 if( pTrigger ){
1053 /* Code AFTER triggers */
1054 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
1055 pTab, regData-2-pTab->nCol, onError, endOfLoop);
1058 /* The bottom of the main insertion loop, if the data source
1059 ** is a SELECT statement.
1061 sqlite3VdbeResolveLabel(v, endOfLoop);
1062 if( useTempTable ){
1063 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1064 sqlite3VdbeJumpHere(v, addrInsTop);
1065 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1066 }else if( pSelect ){
1067 sqlite3VdbeGoto(v, addrCont);
1068 sqlite3VdbeJumpHere(v, addrInsTop);
1071 insert_end:
1072 /* Update the sqlite_sequence table by storing the content of the
1073 ** maximum rowid counter values recorded while inserting into
1074 ** autoincrement tables.
1076 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
1077 sqlite3AutoincrementEnd(pParse);
1081 ** Return the number of rows inserted. If this routine is
1082 ** generating code because of a call to sqlite3NestedParse(), do not
1083 ** invoke the callback function.
1085 if( regRowCount ){
1086 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
1087 sqlite3VdbeSetNumCols(v, 1);
1088 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
1091 insert_cleanup:
1092 sqlite3SrcListDelete(db, pTabList);
1093 sqlite3ExprListDelete(db, pList);
1094 sqlite3UpsertDelete(db, pUpsert);
1095 sqlite3SelectDelete(db, pSelect);
1096 sqlite3IdListDelete(db, pColumn);
1097 sqlite3DbFree(db, aRegIdx);
1100 /* Make sure "isView" and other macros defined above are undefined. Otherwise
1101 ** they may interfere with compilation of other functions in this file
1102 ** (or in another file, if this file becomes part of the amalgamation). */
1103 #ifdef isView
1104 #undef isView
1105 #endif
1106 #ifdef pTrigger
1107 #undef pTrigger
1108 #endif
1109 #ifdef tmask
1110 #undef tmask
1111 #endif
1114 ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
1116 #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
1117 #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
1119 /* This is the Walker callback from checkConstraintUnchanged(). Set
1120 ** bit 0x01 of pWalker->eCode if
1121 ** pWalker->eCode to 0 if this expression node references any of the
1122 ** columns that are being modifed by an UPDATE statement.
1124 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
1125 if( pExpr->op==TK_COLUMN ){
1126 assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
1127 if( pExpr->iColumn>=0 ){
1128 if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
1129 pWalker->eCode |= CKCNSTRNT_COLUMN;
1131 }else{
1132 pWalker->eCode |= CKCNSTRNT_ROWID;
1135 return WRC_Continue;
1139 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
1140 ** only columns that are modified by the UPDATE are those for which
1141 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
1143 ** Return true if CHECK constraint pExpr does not use any of the
1144 ** changing columns (or the rowid if it is changing). In other words,
1145 ** return true if this CHECK constraint can be skipped when validating
1146 ** the new row in the UPDATE statement.
1148 static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
1149 Walker w;
1150 memset(&w, 0, sizeof(w));
1151 w.eCode = 0;
1152 w.xExprCallback = checkConstraintExprNode;
1153 w.u.aiCol = aiChng;
1154 sqlite3WalkExpr(&w, pExpr);
1155 if( !chngRowid ){
1156 testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
1157 w.eCode &= ~CKCNSTRNT_ROWID;
1159 testcase( w.eCode==0 );
1160 testcase( w.eCode==CKCNSTRNT_COLUMN );
1161 testcase( w.eCode==CKCNSTRNT_ROWID );
1162 testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
1163 return !w.eCode;
1167 ** An instance of the ConstraintAddr object remembers the byte-code addresses
1168 ** for sections of the constraint checks that deal with uniqueness constraints
1169 ** on the rowid and on the upsert constraint.
1171 ** This information is passed into checkReorderConstraintChecks() to insert
1172 ** some OP_Goto operations so that the rowid and upsert constraints occur
1173 ** in the correct order relative to other constraints.
1175 typedef struct ConstraintAddr ConstraintAddr;
1176 struct ConstraintAddr {
1177 int ipkTop; /* Subroutine for rowid constraint check */
1178 int upsertTop; /* Label for upsert constraint check subroutine */
1179 int upsertTop2; /* Copy of upsertTop not cleared by the call */
1180 int upsertBtm; /* upsert constraint returns to this label */
1181 int ipkBtm; /* Return opcode rowid constraint check */
1185 ** Generate any OP_Goto operations needed to cause constraints to be
1186 ** run that haven't already been run.
1188 static void reorderConstraintChecks(Vdbe *v, ConstraintAddr *p){
1189 if( p->upsertTop ){
1190 testcase( sqlite3VdbeLabelHasBeenResolved(v, p->upsertTop) );
1191 sqlite3VdbeGoto(v, p->upsertTop);
1192 VdbeComment((v, "call upsert subroutine"));
1193 sqlite3VdbeResolveLabel(v, p->upsertBtm);
1194 p->upsertTop = 0;
1196 if( p->ipkTop ){
1197 sqlite3VdbeGoto(v, p->ipkTop);
1198 VdbeComment((v, "call rowid unique-check subroutine"));
1199 sqlite3VdbeJumpHere(v, p->ipkBtm);
1200 p->ipkTop = 0;
1205 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
1206 ** on table pTab.
1208 ** The regNewData parameter is the first register in a range that contains
1209 ** the data to be inserted or the data after the update. There will be
1210 ** pTab->nCol+1 registers in this range. The first register (the one
1211 ** that regNewData points to) will contain the new rowid, or NULL in the
1212 ** case of a WITHOUT ROWID table. The second register in the range will
1213 ** contain the content of the first table column. The third register will
1214 ** contain the content of the second table column. And so forth.
1216 ** The regOldData parameter is similar to regNewData except that it contains
1217 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
1218 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
1219 ** checking regOldData for zero.
1221 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1222 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1223 ** might be modified by the UPDATE. If pkChng is false, then the key of
1224 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1226 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1227 ** was explicitly specified as part of the INSERT statement. If pkChng
1228 ** is zero, it means that the either rowid is computed automatically or
1229 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
1230 ** pkChng will only be true if the INSERT statement provides an integer
1231 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
1233 ** The code generated by this routine will store new index entries into
1234 ** registers identified by aRegIdx[]. No index entry is created for
1235 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1236 ** the same as the order of indices on the linked list of indices
1237 ** at pTab->pIndex.
1239 ** The caller must have already opened writeable cursors on the main
1240 ** table and all applicable indices (that is to say, all indices for which
1241 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
1242 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
1243 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
1244 ** for the first index in the pTab->pIndex list. Cursors for other indices
1245 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
1247 ** This routine also generates code to check constraints. NOT NULL,
1248 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
1249 ** then the appropriate action is performed. There are five possible
1250 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
1252 ** Constraint type Action What Happens
1253 ** --------------- ---------- ----------------------------------------
1254 ** any ROLLBACK The current transaction is rolled back and
1255 ** sqlite3_step() returns immediately with a
1256 ** return code of SQLITE_CONSTRAINT.
1258 ** any ABORT Back out changes from the current command
1259 ** only (do not do a complete rollback) then
1260 ** cause sqlite3_step() to return immediately
1261 ** with SQLITE_CONSTRAINT.
1263 ** any FAIL Sqlite3_step() returns immediately with a
1264 ** return code of SQLITE_CONSTRAINT. The
1265 ** transaction is not rolled back and any
1266 ** changes to prior rows are retained.
1268 ** any IGNORE The attempt in insert or update the current
1269 ** row is skipped, without throwing an error.
1270 ** Processing continues with the next row.
1271 ** (There is an immediate jump to ignoreDest.)
1273 ** NOT NULL REPLACE The NULL value is replace by the default
1274 ** value for that column. If the default value
1275 ** is NULL, the action is the same as ABORT.
1277 ** UNIQUE REPLACE The other row that conflicts with the row
1278 ** being inserted is removed.
1280 ** CHECK REPLACE Illegal. The results in an exception.
1282 ** Which action to take is determined by the overrideError parameter.
1283 ** Or if overrideError==OE_Default, then the pParse->onError parameter
1284 ** is used. Or if pParse->onError==OE_Default then the onError value
1285 ** for the constraint is used.
1287 void sqlite3GenerateConstraintChecks(
1288 Parse *pParse, /* The parser context */
1289 Table *pTab, /* The table being inserted or updated */
1290 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
1291 int iDataCur, /* Canonical data cursor (main table or PK index) */
1292 int iIdxCur, /* First index cursor */
1293 int regNewData, /* First register in a range holding values to insert */
1294 int regOldData, /* Previous content. 0 for INSERTs */
1295 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
1296 u8 overrideError, /* Override onError to this if not OE_Default */
1297 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
1298 int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
1299 int *aiChng, /* column i is unchanged if aiChng[i]<0 */
1300 Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
1302 Vdbe *v; /* VDBE under constrution */
1303 Index *pIdx; /* Pointer to one of the indices */
1304 Index *pPk = 0; /* The PRIMARY KEY index */
1305 sqlite3 *db; /* Database connection */
1306 int i; /* loop counter */
1307 int ix; /* Index loop counter */
1308 int nCol; /* Number of columns */
1309 int onError; /* Conflict resolution strategy */
1310 int addr1; /* Address of jump instruction */
1311 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
1312 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
1313 ConstraintAddr sAddr;/* Address information for constraint reordering */
1314 Index *pUpIdx = 0; /* Index to which to apply the upsert */
1315 u8 isUpdate; /* True if this is an UPDATE operation */
1316 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
1317 int upsertBypass = 0; /* Address of Goto to bypass upsert subroutine */
1319 isUpdate = regOldData!=0;
1320 db = pParse->db;
1321 v = sqlite3GetVdbe(pParse);
1322 assert( v!=0 );
1323 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
1324 nCol = pTab->nCol;
1325 memset(&sAddr, 0, sizeof(sAddr));
1327 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
1328 ** normal rowid tables. nPkField is the number of key fields in the
1329 ** pPk index or 1 for a rowid table. In other words, nPkField is the
1330 ** number of fields in the true primary key of the table. */
1331 if( HasRowid(pTab) ){
1332 pPk = 0;
1333 nPkField = 1;
1334 }else{
1335 pPk = sqlite3PrimaryKeyIndex(pTab);
1336 nPkField = pPk->nKeyCol;
1339 /* Record that this module has started */
1340 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
1341 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
1343 /* Test all NOT NULL constraints.
1345 for(i=0; i<nCol; i++){
1346 if( i==pTab->iPKey ){
1347 continue; /* ROWID is never NULL */
1349 if( aiChng && aiChng[i]<0 ){
1350 /* Don't bother checking for NOT NULL on columns that do not change */
1351 continue;
1353 onError = pTab->aCol[i].notNull;
1354 if( onError==OE_None ) continue; /* This column is allowed to be NULL */
1355 if( overrideError!=OE_Default ){
1356 onError = overrideError;
1357 }else if( onError==OE_Default ){
1358 onError = OE_Abort;
1360 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
1361 onError = OE_Abort;
1363 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1364 || onError==OE_Ignore || onError==OE_Replace );
1365 switch( onError ){
1366 case OE_Abort:
1367 sqlite3MayAbort(pParse);
1368 /* Fall through */
1369 case OE_Rollback:
1370 case OE_Fail: {
1371 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1372 pTab->aCol[i].zName);
1373 sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
1374 regNewData+1+i);
1375 sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
1376 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
1377 VdbeCoverage(v);
1378 break;
1380 case OE_Ignore: {
1381 sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
1382 VdbeCoverage(v);
1383 break;
1385 default: {
1386 assert( onError==OE_Replace );
1387 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
1388 VdbeCoverage(v);
1389 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
1390 sqlite3VdbeJumpHere(v, addr1);
1391 break;
1396 /* Test all CHECK constraints
1398 #ifndef SQLITE_OMIT_CHECK
1399 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
1400 ExprList *pCheck = pTab->pCheck;
1401 pParse->iSelfTab = -(regNewData+1);
1402 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
1403 for(i=0; i<pCheck->nExpr; i++){
1404 int allOk;
1405 Expr *pExpr = pCheck->a[i].pExpr;
1406 if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
1407 allOk = sqlite3VdbeMakeLabel(v);
1408 sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
1409 if( onError==OE_Ignore ){
1410 sqlite3VdbeGoto(v, ignoreDest);
1411 }else{
1412 char *zName = pCheck->a[i].zName;
1413 if( zName==0 ) zName = pTab->zName;
1414 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
1415 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1416 onError, zName, P4_TRANSIENT,
1417 P5_ConstraintCheck);
1419 sqlite3VdbeResolveLabel(v, allOk);
1421 pParse->iSelfTab = 0;
1423 #endif /* !defined(SQLITE_OMIT_CHECK) */
1425 /* UNIQUE and PRIMARY KEY constraints should be handled in the following
1426 ** order:
1428 ** (1) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
1429 ** (2) OE_Update
1430 ** (3) OE_Replace
1432 ** OE_Fail and OE_Ignore must happen before any changes are made.
1433 ** OE_Update guarantees that only a single row will change, so it
1434 ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
1435 ** could happen in any order, but they are grouped up front for
1436 ** convenience.
1438 ** Constraint checking code is generated in this order:
1439 ** (A) The rowid constraint
1440 ** (B) Unique index constraints that do not have OE_Replace as their
1441 ** default conflict resolution strategy
1442 ** (C) Unique index that do use OE_Replace by default.
1444 ** The ordering of (2) and (3) is accomplished by making sure the linked
1445 ** list of indexes attached to a table puts all OE_Replace indexes last
1446 ** in the list. See sqlite3CreateIndex() for where that happens.
1449 if( pUpsert ){
1450 if( pUpsert->pUpsertTarget==0 ){
1451 /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
1452 ** Make all unique constraint resolution be OE_Ignore */
1453 assert( pUpsert->pUpsertSet==0 );
1454 overrideError = OE_Ignore;
1455 pUpsert = 0;
1456 }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
1457 /* If the constraint-target is on some column other than
1458 ** then ROWID, then we might need to move the UPSERT around
1459 ** so that it occurs in the correct order. */
1460 sAddr.upsertTop = sAddr.upsertTop2 = sqlite3VdbeMakeLabel(v);
1461 sAddr.upsertBtm = sqlite3VdbeMakeLabel(v);
1465 /* If rowid is changing, make sure the new rowid does not previously
1466 ** exist in the table.
1468 if( pkChng && pPk==0 ){
1469 int addrRowidOk = sqlite3VdbeMakeLabel(v);
1471 /* Figure out what action to take in case of a rowid collision */
1472 onError = pTab->keyConf;
1473 if( overrideError!=OE_Default ){
1474 onError = overrideError;
1475 }else if( onError==OE_Default ){
1476 onError = OE_Abort;
1479 /* figure out whether or not upsert applies in this case */
1480 if( pUpsert && pUpsert->pUpsertIdx==0 ){
1481 if( pUpsert->pUpsertSet==0 ){
1482 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
1483 }else{
1484 onError = OE_Update; /* DO UPDATE */
1488 /* If the response to a rowid conflict is REPLACE but the response
1489 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
1490 ** to defer the running of the rowid conflict checking until after
1491 ** the UNIQUE constraints have run.
1493 assert( OE_Update>OE_Replace );
1494 assert( OE_Ignore<OE_Replace );
1495 assert( OE_Fail<OE_Replace );
1496 assert( OE_Abort<OE_Replace );
1497 assert( OE_Rollback<OE_Replace );
1498 if( onError>=OE_Replace
1499 && (pUpsert || onError!=overrideError)
1500 && pTab->pIndex
1502 sAddr.ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
1505 if( isUpdate ){
1506 /* pkChng!=0 does not mean that the rowid has changed, only that
1507 ** it might have changed. Skip the conflict logic below if the rowid
1508 ** is unchanged. */
1509 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
1510 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1511 VdbeCoverage(v);
1514 /* Check to see if the new rowid already exists in the table. Skip
1515 ** the following conflict logic if it does not. */
1516 VdbeNoopComment((v, "uniqueness check for ROWID"));
1517 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
1518 VdbeCoverage(v);
1520 switch( onError ){
1521 default: {
1522 onError = OE_Abort;
1523 /* Fall thru into the next case */
1525 case OE_Rollback:
1526 case OE_Abort:
1527 case OE_Fail: {
1528 testcase( onError==OE_Rollback );
1529 testcase( onError==OE_Abort );
1530 testcase( onError==OE_Fail );
1531 sqlite3RowidConstraint(pParse, onError, pTab);
1532 break;
1534 case OE_Replace: {
1535 /* If there are DELETE triggers on this table and the
1536 ** recursive-triggers flag is set, call GenerateRowDelete() to
1537 ** remove the conflicting row from the table. This will fire
1538 ** the triggers and remove both the table and index b-tree entries.
1540 ** Otherwise, if there are no triggers or the recursive-triggers
1541 ** flag is not set, but the table has one or more indexes, call
1542 ** GenerateRowIndexDelete(). This removes the index b-tree entries
1543 ** only. The table b-tree entry will be replaced by the new entry
1544 ** when it is inserted.
1546 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1547 ** also invoke MultiWrite() to indicate that this VDBE may require
1548 ** statement rollback (if the statement is aborted after the delete
1549 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1550 ** but being more selective here allows statements like:
1552 ** REPLACE INTO t(rowid) VALUES($newrowid)
1554 ** to run without a statement journal if there are no indexes on the
1555 ** table.
1557 Trigger *pTrigger = 0;
1558 if( db->flags&SQLITE_RecTriggers ){
1559 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1561 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1562 sqlite3MultiWrite(pParse);
1563 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1564 regNewData, 1, 0, OE_Replace, 1, -1);
1565 }else{
1566 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1567 assert( HasRowid(pTab) );
1568 /* This OP_Delete opcode fires the pre-update-hook only. It does
1569 ** not modify the b-tree. It is more efficient to let the coming
1570 ** OP_Insert replace the existing entry than it is to delete the
1571 ** existing entry and then insert a new one. */
1572 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
1573 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
1574 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
1575 if( pTab->pIndex ){
1576 sqlite3MultiWrite(pParse);
1577 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
1580 seenReplace = 1;
1581 break;
1583 #ifndef SQLITE_OMIT_UPSERT
1584 case OE_Update: {
1585 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
1586 /* Fall through */
1588 #endif
1589 case OE_Ignore: {
1590 testcase( onError==OE_Ignore );
1591 sqlite3VdbeGoto(v, ignoreDest);
1592 break;
1595 sqlite3VdbeResolveLabel(v, addrRowidOk);
1596 if( sAddr.ipkTop ){
1597 sAddr.ipkBtm = sqlite3VdbeAddOp0(v, OP_Goto);
1598 sqlite3VdbeJumpHere(v, sAddr.ipkTop-1);
1602 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1603 ** index and making sure that duplicate entries do not already exist.
1604 ** Compute the revised record entries for indices as we go.
1606 ** This loop also handles the case of the PRIMARY KEY index for a
1607 ** WITHOUT ROWID table.
1609 for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
1610 int regIdx; /* Range of registers hold conent for pIdx */
1611 int regR; /* Range of registers holding conflicting PK */
1612 int iThisCur; /* Cursor for this UNIQUE index */
1613 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
1615 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
1616 if( pUpIdx==pIdx ){
1617 addrUniqueOk = sAddr.upsertBtm;
1618 upsertBypass = sqlite3VdbeGoto(v, 0);
1619 VdbeComment((v, "Skip upsert subroutine"));
1620 sqlite3VdbeResolveLabel(v, sAddr.upsertTop2);
1621 }else{
1622 addrUniqueOk = sqlite3VdbeMakeLabel(v);
1624 VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName));
1625 if( bAffinityDone==0 ){
1626 sqlite3TableAffinity(v, pTab, regNewData+1);
1627 bAffinityDone = 1;
1629 iThisCur = iIdxCur+ix;
1632 /* Skip partial indices for which the WHERE clause is not true */
1633 if( pIdx->pPartIdxWhere ){
1634 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
1635 pParse->iSelfTab = -(regNewData+1);
1636 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
1637 SQLITE_JUMPIFNULL);
1638 pParse->iSelfTab = 0;
1641 /* Create a record for this index entry as it should appear after
1642 ** the insert or update. Store that record in the aRegIdx[ix] register
1644 regIdx = aRegIdx[ix]+1;
1645 for(i=0; i<pIdx->nColumn; i++){
1646 int iField = pIdx->aiColumn[i];
1647 int x;
1648 if( iField==XN_EXPR ){
1649 pParse->iSelfTab = -(regNewData+1);
1650 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
1651 pParse->iSelfTab = 0;
1652 VdbeComment((v, "%s column %d", pIdx->zName, i));
1653 }else{
1654 if( iField==XN_ROWID || iField==pTab->iPKey ){
1655 x = regNewData;
1656 }else{
1657 x = iField + regNewData + 1;
1659 sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
1660 VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
1663 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
1664 VdbeComment((v, "for %s", pIdx->zName));
1665 #ifdef SQLITE_ENABLE_NULL_TRIM
1666 if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
1667 #endif
1669 /* In an UPDATE operation, if this index is the PRIMARY KEY index
1670 ** of a WITHOUT ROWID table and there has been no change the
1671 ** primary key, then no collision is possible. The collision detection
1672 ** logic below can all be skipped. */
1673 if( isUpdate && pPk==pIdx && pkChng==0 ){
1674 sqlite3VdbeResolveLabel(v, addrUniqueOk);
1675 continue;
1678 /* Find out what action to take in case there is a uniqueness conflict */
1679 onError = pIdx->onError;
1680 if( onError==OE_None ){
1681 sqlite3VdbeResolveLabel(v, addrUniqueOk);
1682 continue; /* pIdx is not a UNIQUE index */
1684 if( overrideError!=OE_Default ){
1685 onError = overrideError;
1686 }else if( onError==OE_Default ){
1687 onError = OE_Abort;
1690 /* Figure out if the upsert clause applies to this index */
1691 if( pUpIdx==pIdx ){
1692 if( pUpsert->pUpsertSet==0 ){
1693 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
1694 }else{
1695 onError = OE_Update; /* DO UPDATE */
1699 /* Invoke subroutines to handle IPK replace and upsert prior to running
1700 ** the first REPLACE constraint check. */
1701 if( onError==OE_Replace ){
1702 testcase( sAddr.ipkTop );
1703 testcase( sAddr.upsertTop
1704 && sqlite3VdbeLabelHasBeenResolved(v,sAddr.upsertTop) );
1705 reorderConstraintChecks(v, &sAddr);
1708 /* Collision detection may be omitted if all of the following are true:
1709 ** (1) The conflict resolution algorithm is REPLACE
1710 ** (2) The table is a WITHOUT ROWID table
1711 ** (3) There are no secondary indexes on the table
1712 ** (4) No delete triggers need to be fired if there is a conflict
1713 ** (5) No FK constraint counters need to be updated if a conflict occurs.
1715 if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
1716 && pPk==pIdx /* Condition 2 */
1717 && onError==OE_Replace /* Condition 1 */
1718 && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
1719 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
1720 && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
1721 (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
1723 sqlite3VdbeResolveLabel(v, addrUniqueOk);
1724 continue;
1727 /* Check to see if the new index entry will be unique */
1728 sqlite3ExprCachePush(pParse);
1729 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
1730 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
1732 /* Generate code to handle collisions */
1733 regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
1734 if( isUpdate || onError==OE_Replace ){
1735 if( HasRowid(pTab) ){
1736 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
1737 /* Conflict only if the rowid of the existing index entry
1738 ** is different from old-rowid */
1739 if( isUpdate ){
1740 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
1741 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1742 VdbeCoverage(v);
1744 }else{
1745 int x;
1746 /* Extract the PRIMARY KEY from the end of the index entry and
1747 ** store it in registers regR..regR+nPk-1 */
1748 if( pIdx!=pPk ){
1749 for(i=0; i<pPk->nKeyCol; i++){
1750 assert( pPk->aiColumn[i]>=0 );
1751 x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
1752 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
1753 VdbeComment((v, "%s.%s", pTab->zName,
1754 pTab->aCol[pPk->aiColumn[i]].zName));
1757 if( isUpdate ){
1758 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
1759 ** table, only conflict if the new PRIMARY KEY values are actually
1760 ** different from the old.
1762 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
1763 ** of the matched index row are different from the original PRIMARY
1764 ** KEY values of this row before the update. */
1765 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
1766 int op = OP_Ne;
1767 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
1769 for(i=0; i<pPk->nKeyCol; i++){
1770 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
1771 x = pPk->aiColumn[i];
1772 assert( x>=0 );
1773 if( i==(pPk->nKeyCol-1) ){
1774 addrJump = addrUniqueOk;
1775 op = OP_Eq;
1777 sqlite3VdbeAddOp4(v, op,
1778 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
1780 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
1781 VdbeCoverageIf(v, op==OP_Eq);
1782 VdbeCoverageIf(v, op==OP_Ne);
1788 /* Generate code that executes if the new index entry is not unique */
1789 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1790 || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
1791 switch( onError ){
1792 case OE_Rollback:
1793 case OE_Abort:
1794 case OE_Fail: {
1795 testcase( onError==OE_Rollback );
1796 testcase( onError==OE_Abort );
1797 testcase( onError==OE_Fail );
1798 sqlite3UniqueConstraint(pParse, onError, pIdx);
1799 break;
1801 #ifndef SQLITE_OMIT_UPSERT
1802 case OE_Update: {
1803 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
1804 /* Fall through */
1806 #endif
1807 case OE_Ignore: {
1808 testcase( onError==OE_Ignore );
1809 sqlite3VdbeGoto(v, ignoreDest);
1810 break;
1812 default: {
1813 Trigger *pTrigger = 0;
1814 assert( onError==OE_Replace );
1815 sqlite3MultiWrite(pParse);
1816 if( db->flags&SQLITE_RecTriggers ){
1817 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1819 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
1820 regR, nPkField, 0, OE_Replace,
1821 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
1822 seenReplace = 1;
1823 break;
1826 if( pUpIdx==pIdx ){
1827 sqlite3VdbeJumpHere(v, upsertBypass);
1828 }else{
1829 sqlite3VdbeResolveLabel(v, addrUniqueOk);
1831 sqlite3ExprCachePop(pParse);
1832 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
1835 testcase( sAddr.ipkTop!=0 );
1836 testcase( sAddr.upsertTop
1837 && sqlite3VdbeLabelHasBeenResolved(v,sAddr.upsertTop) );
1838 reorderConstraintChecks(v, &sAddr);
1840 *pbMayReplace = seenReplace;
1841 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
1844 #ifdef SQLITE_ENABLE_NULL_TRIM
1846 ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
1847 ** to be the number of columns in table pTab that must not be NULL-trimmed.
1849 ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
1851 void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
1852 u16 i;
1854 /* Records with omitted columns are only allowed for schema format
1855 ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
1856 if( pTab->pSchema->file_format<2 ) return;
1858 for(i=pTab->nCol-1; i>0; i--){
1859 if( pTab->aCol[i].pDflt!=0 ) break;
1860 if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
1862 sqlite3VdbeChangeP5(v, i+1);
1864 #endif
1867 ** This routine generates code to finish the INSERT or UPDATE operation
1868 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
1869 ** A consecutive range of registers starting at regNewData contains the
1870 ** rowid and the content to be inserted.
1872 ** The arguments to this routine should be the same as the first six
1873 ** arguments to sqlite3GenerateConstraintChecks.
1875 void sqlite3CompleteInsertion(
1876 Parse *pParse, /* The parser context */
1877 Table *pTab, /* the table into which we are inserting */
1878 int iDataCur, /* Cursor of the canonical data source */
1879 int iIdxCur, /* First index cursor */
1880 int regNewData, /* Range of content */
1881 int *aRegIdx, /* Register used by each index. 0 for unused indices */
1882 int update_flags, /* True for UPDATE, False for INSERT */
1883 int appendBias, /* True if this is likely to be an append */
1884 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
1886 Vdbe *v; /* Prepared statements under construction */
1887 Index *pIdx; /* An index being inserted or updated */
1888 u8 pik_flags; /* flag values passed to the btree insert */
1889 int regData; /* Content registers (after the rowid) */
1890 int regRec; /* Register holding assembled record for the table */
1891 int i; /* Loop counter */
1892 u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
1894 assert( update_flags==0
1895 || update_flags==OPFLAG_ISUPDATE
1896 || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
1899 v = sqlite3GetVdbe(pParse);
1900 assert( v!=0 );
1901 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
1902 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1903 if( aRegIdx[i]==0 ) continue;
1904 bAffinityDone = 1;
1905 if( pIdx->pPartIdxWhere ){
1906 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
1907 VdbeCoverage(v);
1909 pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
1910 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
1911 assert( pParse->nested==0 );
1912 pik_flags |= OPFLAG_NCHANGE;
1913 pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
1914 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1915 if( update_flags==0 ){
1916 sqlite3VdbeAddOp4(v, OP_InsertInt,
1917 iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
1919 sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
1921 #endif
1923 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
1924 aRegIdx[i]+1,
1925 pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
1926 sqlite3VdbeChangeP5(v, pik_flags);
1928 if( !HasRowid(pTab) ) return;
1929 regData = regNewData + 1;
1930 regRec = sqlite3GetTempReg(pParse);
1931 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1932 sqlite3SetMakeRecordP5(v, pTab);
1933 if( !bAffinityDone ){
1934 sqlite3TableAffinity(v, pTab, 0);
1935 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
1937 if( pParse->nested ){
1938 pik_flags = 0;
1939 }else{
1940 pik_flags = OPFLAG_NCHANGE;
1941 pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
1943 if( appendBias ){
1944 pik_flags |= OPFLAG_APPEND;
1946 if( useSeekResult ){
1947 pik_flags |= OPFLAG_USESEEKRESULT;
1949 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
1950 if( !pParse->nested ){
1951 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
1953 sqlite3VdbeChangeP5(v, pik_flags);
1957 ** Allocate cursors for the pTab table and all its indices and generate
1958 ** code to open and initialized those cursors.
1960 ** The cursor for the object that contains the complete data (normally
1961 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
1962 ** ROWID table) is returned in *piDataCur. The first index cursor is
1963 ** returned in *piIdxCur. The number of indices is returned.
1965 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
1966 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
1967 ** If iBase is negative, then allocate the next available cursor.
1969 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
1970 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
1971 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
1972 ** pTab->pIndex list.
1974 ** If pTab is a virtual table, then this routine is a no-op and the
1975 ** *piDataCur and *piIdxCur values are left uninitialized.
1977 int sqlite3OpenTableAndIndices(
1978 Parse *pParse, /* Parsing context */
1979 Table *pTab, /* Table to be opened */
1980 int op, /* OP_OpenRead or OP_OpenWrite */
1981 u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
1982 int iBase, /* Use this for the table cursor, if there is one */
1983 u8 *aToOpen, /* If not NULL: boolean for each table and index */
1984 int *piDataCur, /* Write the database source cursor number here */
1985 int *piIdxCur /* Write the first index cursor number here */
1987 int i;
1988 int iDb;
1989 int iDataCur;
1990 Index *pIdx;
1991 Vdbe *v;
1993 assert( op==OP_OpenRead || op==OP_OpenWrite );
1994 assert( op==OP_OpenWrite || p5==0 );
1995 if( IsVirtual(pTab) ){
1996 /* This routine is a no-op for virtual tables. Leave the output
1997 ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
1998 ** can detect if they are used by mistake in the caller. */
1999 return 0;
2001 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2002 v = sqlite3GetVdbe(pParse);
2003 assert( v!=0 );
2004 if( iBase<0 ) iBase = pParse->nTab;
2005 iDataCur = iBase++;
2006 if( piDataCur ) *piDataCur = iDataCur;
2007 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
2008 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
2009 }else{
2010 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
2012 if( piIdxCur ) *piIdxCur = iBase;
2013 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2014 int iIdxCur = iBase++;
2015 assert( pIdx->pSchema==pTab->pSchema );
2016 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2017 if( piDataCur ) *piDataCur = iIdxCur;
2018 p5 = 0;
2020 if( aToOpen==0 || aToOpen[i+1] ){
2021 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
2022 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2023 sqlite3VdbeChangeP5(v, p5);
2024 VdbeComment((v, "%s", pIdx->zName));
2027 if( iBase>pParse->nTab ) pParse->nTab = iBase;
2028 return i;
2032 #ifdef SQLITE_TEST
2034 ** The following global variable is incremented whenever the
2035 ** transfer optimization is used. This is used for testing
2036 ** purposes only - to make sure the transfer optimization really
2037 ** is happening when it is supposed to.
2039 int sqlite3_xferopt_count;
2040 #endif /* SQLITE_TEST */
2043 #ifndef SQLITE_OMIT_XFER_OPT
2045 ** Check to see if index pSrc is compatible as a source of data
2046 ** for index pDest in an insert transfer optimization. The rules
2047 ** for a compatible index:
2049 ** * The index is over the same set of columns
2050 ** * The same DESC and ASC markings occurs on all columns
2051 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
2052 ** * The same collating sequence on each column
2053 ** * The index has the exact same WHERE clause
2055 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
2056 int i;
2057 assert( pDest && pSrc );
2058 assert( pDest->pTable!=pSrc->pTable );
2059 if( pDest->nKeyCol!=pSrc->nKeyCol ){
2060 return 0; /* Different number of columns */
2062 if( pDest->onError!=pSrc->onError ){
2063 return 0; /* Different conflict resolution strategies */
2065 for(i=0; i<pSrc->nKeyCol; i++){
2066 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
2067 return 0; /* Different columns indexed */
2069 if( pSrc->aiColumn[i]==XN_EXPR ){
2070 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
2071 if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
2072 pDest->aColExpr->a[i].pExpr, -1)!=0 ){
2073 return 0; /* Different expressions in the index */
2076 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
2077 return 0; /* Different sort orders */
2079 if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
2080 return 0; /* Different collating sequences */
2083 if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
2084 return 0; /* Different WHERE clauses */
2087 /* If no test above fails then the indices must be compatible */
2088 return 1;
2092 ** Attempt the transfer optimization on INSERTs of the form
2094 ** INSERT INTO tab1 SELECT * FROM tab2;
2096 ** The xfer optimization transfers raw records from tab2 over to tab1.
2097 ** Columns are not decoded and reassembled, which greatly improves
2098 ** performance. Raw index records are transferred in the same way.
2100 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
2101 ** There are lots of rules for determining compatibility - see comments
2102 ** embedded in the code for details.
2104 ** This routine returns TRUE if the optimization is guaranteed to be used.
2105 ** Sometimes the xfer optimization will only work if the destination table
2106 ** is empty - a factor that can only be determined at run-time. In that
2107 ** case, this routine generates code for the xfer optimization but also
2108 ** does a test to see if the destination table is empty and jumps over the
2109 ** xfer optimization code if the test fails. In that case, this routine
2110 ** returns FALSE so that the caller will know to go ahead and generate
2111 ** an unoptimized transfer. This routine also returns FALSE if there
2112 ** is no chance that the xfer optimization can be applied.
2114 ** This optimization is particularly useful at making VACUUM run faster.
2116 static int xferOptimization(
2117 Parse *pParse, /* Parser context */
2118 Table *pDest, /* The table we are inserting into */
2119 Select *pSelect, /* A SELECT statement to use as the data source */
2120 int onError, /* How to handle constraint errors */
2121 int iDbDest /* The database of pDest */
2123 sqlite3 *db = pParse->db;
2124 ExprList *pEList; /* The result set of the SELECT */
2125 Table *pSrc; /* The table in the FROM clause of SELECT */
2126 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
2127 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
2128 int i; /* Loop counter */
2129 int iDbSrc; /* The database of pSrc */
2130 int iSrc, iDest; /* Cursors from source and destination */
2131 int addr1, addr2; /* Loop addresses */
2132 int emptyDestTest = 0; /* Address of test for empty pDest */
2133 int emptySrcTest = 0; /* Address of test for empty pSrc */
2134 Vdbe *v; /* The VDBE we are building */
2135 int regAutoinc; /* Memory register used by AUTOINC */
2136 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
2137 int regData, regRowid; /* Registers holding data and rowid */
2139 if( pSelect==0 ){
2140 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
2142 if( pParse->pWith || pSelect->pWith ){
2143 /* Do not attempt to process this query if there are an WITH clauses
2144 ** attached to it. Proceeding may generate a false "no such table: xxx"
2145 ** error if pSelect reads from a CTE named "xxx". */
2146 return 0;
2148 if( sqlite3TriggerList(pParse, pDest) ){
2149 return 0; /* tab1 must not have triggers */
2151 #ifndef SQLITE_OMIT_VIRTUALTABLE
2152 if( IsVirtual(pDest) ){
2153 return 0; /* tab1 must not be a virtual table */
2155 #endif
2156 if( onError==OE_Default ){
2157 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
2158 if( onError==OE_Default ) onError = OE_Abort;
2160 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
2161 if( pSelect->pSrc->nSrc!=1 ){
2162 return 0; /* FROM clause must have exactly one term */
2164 if( pSelect->pSrc->a[0].pSelect ){
2165 return 0; /* FROM clause cannot contain a subquery */
2167 if( pSelect->pWhere ){
2168 return 0; /* SELECT may not have a WHERE clause */
2170 if( pSelect->pOrderBy ){
2171 return 0; /* SELECT may not have an ORDER BY clause */
2173 /* Do not need to test for a HAVING clause. If HAVING is present but
2174 ** there is no ORDER BY, we will get an error. */
2175 if( pSelect->pGroupBy ){
2176 return 0; /* SELECT may not have a GROUP BY clause */
2178 if( pSelect->pLimit ){
2179 return 0; /* SELECT may not have a LIMIT clause */
2181 if( pSelect->pPrior ){
2182 return 0; /* SELECT may not be a compound query */
2184 if( pSelect->selFlags & SF_Distinct ){
2185 return 0; /* SELECT may not be DISTINCT */
2187 pEList = pSelect->pEList;
2188 assert( pEList!=0 );
2189 if( pEList->nExpr!=1 ){
2190 return 0; /* The result set must have exactly one column */
2192 assert( pEList->a[0].pExpr );
2193 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
2194 return 0; /* The result set must be the special operator "*" */
2197 /* At this point we have established that the statement is of the
2198 ** correct syntactic form to participate in this optimization. Now
2199 ** we have to check the semantics.
2201 pItem = pSelect->pSrc->a;
2202 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
2203 if( pSrc==0 ){
2204 return 0; /* FROM clause does not contain a real table */
2206 if( pSrc==pDest ){
2207 return 0; /* tab1 and tab2 may not be the same table */
2209 if( HasRowid(pDest)!=HasRowid(pSrc) ){
2210 return 0; /* source and destination must both be WITHOUT ROWID or not */
2212 #ifndef SQLITE_OMIT_VIRTUALTABLE
2213 if( IsVirtual(pSrc) ){
2214 return 0; /* tab2 must not be a virtual table */
2216 #endif
2217 if( pSrc->pSelect ){
2218 return 0; /* tab2 may not be a view */
2220 if( pDest->nCol!=pSrc->nCol ){
2221 return 0; /* Number of columns must be the same in tab1 and tab2 */
2223 if( pDest->iPKey!=pSrc->iPKey ){
2224 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
2226 for(i=0; i<pDest->nCol; i++){
2227 Column *pDestCol = &pDest->aCol[i];
2228 Column *pSrcCol = &pSrc->aCol[i];
2229 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
2230 if( (db->mDbFlags & DBFLAG_Vacuum)==0
2231 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
2233 return 0; /* Neither table may have __hidden__ columns */
2235 #endif
2236 if( pDestCol->affinity!=pSrcCol->affinity ){
2237 return 0; /* Affinity must be the same on all columns */
2239 if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
2240 return 0; /* Collating sequence must be the same on all columns */
2242 if( pDestCol->notNull && !pSrcCol->notNull ){
2243 return 0; /* tab2 must be NOT NULL if tab1 is */
2245 /* Default values for second and subsequent columns need to match. */
2246 if( i>0 ){
2247 assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
2248 assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
2249 if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
2250 || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
2251 pSrcCol->pDflt->u.zToken)!=0)
2253 return 0; /* Default values must be the same for all columns */
2257 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
2258 if( IsUniqueIndex(pDestIdx) ){
2259 destHasUniqueIdx = 1;
2261 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
2262 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
2264 if( pSrcIdx==0 ){
2265 return 0; /* pDestIdx has no corresponding index in pSrc */
2268 #ifndef SQLITE_OMIT_CHECK
2269 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
2270 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
2272 #endif
2273 #ifndef SQLITE_OMIT_FOREIGN_KEY
2274 /* Disallow the transfer optimization if the destination table constains
2275 ** any foreign key constraints. This is more restrictive than necessary.
2276 ** But the main beneficiary of the transfer optimization is the VACUUM
2277 ** command, and the VACUUM command disables foreign key constraints. So
2278 ** the extra complication to make this rule less restrictive is probably
2279 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
2281 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
2282 return 0;
2284 #endif
2285 if( (db->flags & SQLITE_CountRows)!=0 ){
2286 return 0; /* xfer opt does not play well with PRAGMA count_changes */
2289 /* If we get this far, it means that the xfer optimization is at
2290 ** least a possibility, though it might only work if the destination
2291 ** table (tab1) is initially empty.
2293 #ifdef SQLITE_TEST
2294 sqlite3_xferopt_count++;
2295 #endif
2296 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
2297 v = sqlite3GetVdbe(pParse);
2298 sqlite3CodeVerifySchema(pParse, iDbSrc);
2299 iSrc = pParse->nTab++;
2300 iDest = pParse->nTab++;
2301 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
2302 regData = sqlite3GetTempReg(pParse);
2303 regRowid = sqlite3GetTempReg(pParse);
2304 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
2305 assert( HasRowid(pDest) || destHasUniqueIdx );
2306 if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
2307 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
2308 || destHasUniqueIdx /* (2) */
2309 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
2311 /* In some circumstances, we are able to run the xfer optimization
2312 ** only if the destination table is initially empty. Unless the
2313 ** DBFLAG_Vacuum flag is set, this block generates code to make
2314 ** that determination. If DBFLAG_Vacuum is set, then the destination
2315 ** table is always empty.
2317 ** Conditions under which the destination must be empty:
2319 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
2320 ** (If the destination is not initially empty, the rowid fields
2321 ** of index entries might need to change.)
2323 ** (2) The destination has a unique index. (The xfer optimization
2324 ** is unable to test uniqueness.)
2326 ** (3) onError is something other than OE_Abort and OE_Rollback.
2328 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
2329 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
2330 sqlite3VdbeJumpHere(v, addr1);
2332 if( HasRowid(pSrc) ){
2333 u8 insFlags;
2334 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
2335 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
2336 if( pDest->iPKey>=0 ){
2337 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
2338 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
2339 VdbeCoverage(v);
2340 sqlite3RowidConstraint(pParse, onError, pDest);
2341 sqlite3VdbeJumpHere(v, addr2);
2342 autoIncStep(pParse, regAutoinc, regRowid);
2343 }else if( pDest->pIndex==0 ){
2344 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
2345 }else{
2346 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
2347 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
2349 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
2350 if( db->mDbFlags & DBFLAG_Vacuum ){
2351 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
2352 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
2353 OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
2354 }else{
2355 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
2357 sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
2358 (char*)pDest, P4_TABLE);
2359 sqlite3VdbeChangeP5(v, insFlags);
2360 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
2361 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
2362 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2363 }else{
2364 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
2365 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
2367 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
2368 u8 idxInsFlags = 0;
2369 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
2370 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
2372 assert( pSrcIdx );
2373 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
2374 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
2375 VdbeComment((v, "%s", pSrcIdx->zName));
2376 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
2377 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
2378 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
2379 VdbeComment((v, "%s", pDestIdx->zName));
2380 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
2381 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
2382 if( db->mDbFlags & DBFLAG_Vacuum ){
2383 /* This INSERT command is part of a VACUUM operation, which guarantees
2384 ** that the destination table is empty. If all indexed columns use
2385 ** collation sequence BINARY, then it can also be assumed that the
2386 ** index will be populated by inserting keys in strictly sorted
2387 ** order. In this case, instead of seeking within the b-tree as part
2388 ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
2389 ** OP_IdxInsert to seek to the point within the b-tree where each key
2390 ** should be inserted. This is faster.
2392 ** If any of the indexed columns use a collation sequence other than
2393 ** BINARY, this optimization is disabled. This is because the user
2394 ** might change the definition of a collation sequence and then run
2395 ** a VACUUM command. In that case keys may not be written in strictly
2396 ** sorted order. */
2397 for(i=0; i<pSrcIdx->nColumn; i++){
2398 const char *zColl = pSrcIdx->azColl[i];
2399 if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
2401 if( i==pSrcIdx->nColumn ){
2402 idxInsFlags = OPFLAG_USESEEKRESULT;
2403 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
2406 if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
2407 idxInsFlags |= OPFLAG_NCHANGE;
2409 sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
2410 sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
2411 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
2412 sqlite3VdbeJumpHere(v, addr1);
2413 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
2414 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2416 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
2417 sqlite3ReleaseTempReg(pParse, regRowid);
2418 sqlite3ReleaseTempReg(pParse, regData);
2419 if( emptyDestTest ){
2420 sqlite3AutoincrementEnd(pParse);
2421 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
2422 sqlite3VdbeJumpHere(v, emptyDestTest);
2423 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
2424 return 0;
2425 }else{
2426 return 1;
2429 #endif /* SQLITE_OMIT_XFER_OPT */