Add tests to bestindexC.test. No changes to code.
[sqlite.git] / src / insert.c
blob072386e6560c2aa00017dda6413d6a3df7bcb61c
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 assert( pParse->pVdbe!=0 );
36 v = pParse->pVdbe;
37 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
38 if( !pParse->db->noSharedCache ){
39 sqlite3TableLock(pParse, iDb, pTab->tnum,
40 (opcode==OP_OpenWrite)?1:0, pTab->zName);
42 if( HasRowid(pTab) ){
43 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
44 VdbeComment((v, "%s", pTab->zName));
45 }else{
46 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
47 assert( pPk!=0 );
48 assert( pPk->tnum==pTab->tnum || CORRUPT_DB );
49 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
50 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
51 VdbeComment((v, "%s", pTab->zName));
56 ** Return a pointer to the column affinity string associated with index
57 ** pIdx. A column affinity string has one character for each column in
58 ** the table, according to the affinity of the column:
60 ** Character Column affinity
61 ** ------------------------------
62 ** 'A' BLOB
63 ** 'B' TEXT
64 ** 'C' NUMERIC
65 ** 'D' INTEGER
66 ** 'F' REAL
68 ** An extra 'D' is appended to the end of the string to cover the
69 ** rowid that appears as the last column in every index.
71 ** Memory for the buffer containing the column index affinity string
72 ** is managed along with the rest of the Index structure. It will be
73 ** released when sqlite3DeleteIndex() is called.
75 static SQLITE_NOINLINE const char *computeIndexAffStr(sqlite3 *db, Index *pIdx){
76 /* The first time a column affinity string for a particular index is
77 ** required, it is allocated and populated here. It is then stored as
78 ** a member of the Index structure for subsequent use.
80 ** The column affinity string will eventually be deleted by
81 ** sqliteDeleteIndex() when the Index structure itself is cleaned
82 ** up.
84 int n;
85 Table *pTab = pIdx->pTable;
86 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
87 if( !pIdx->zColAff ){
88 sqlite3OomFault(db);
89 return 0;
91 for(n=0; n<pIdx->nColumn; n++){
92 i16 x = pIdx->aiColumn[n];
93 char aff;
94 if( x>=0 ){
95 aff = pTab->aCol[x].affinity;
96 }else if( x==XN_ROWID ){
97 aff = SQLITE_AFF_INTEGER;
98 }else{
99 assert( x==XN_EXPR );
100 assert( pIdx->bHasExpr );
101 assert( pIdx->aColExpr!=0 );
102 aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
104 if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
105 if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
106 pIdx->zColAff[n] = aff;
108 pIdx->zColAff[n] = 0;
109 return pIdx->zColAff;
111 const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
112 if( !pIdx->zColAff ) return computeIndexAffStr(db, pIdx);
113 return pIdx->zColAff;
118 ** Compute an affinity string for a table. Space is obtained
119 ** from sqlite3DbMalloc(). The caller is responsible for freeing
120 ** the space when done.
122 char *sqlite3TableAffinityStr(sqlite3 *db, const Table *pTab){
123 char *zColAff;
124 zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1);
125 if( zColAff ){
126 int i, j;
127 for(i=j=0; i<pTab->nCol; i++){
128 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
129 zColAff[j++] = pTab->aCol[i].affinity;
133 zColAff[j--] = 0;
134 }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );
136 return zColAff;
140 ** Make changes to the evolving bytecode to do affinity transformations
141 ** of values that are about to be gathered into a row for table pTab.
143 ** For ordinary (legacy, non-strict) tables:
144 ** -----------------------------------------
146 ** Compute the affinity string for table pTab, if it has not already been
147 ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
149 ** If the affinity string is empty (because it was all SQLITE_AFF_BLOB entries
150 ** which were then optimized out) then this routine becomes a no-op.
152 ** Otherwise if iReg>0 then code an OP_Affinity opcode that will set the
153 ** affinities for register iReg and following. Or if iReg==0,
154 ** then just set the P4 operand of the previous opcode (which should be
155 ** an OP_MakeRecord) to the affinity string.
157 ** A column affinity string has one character per column:
159 ** Character Column affinity
160 ** --------- ---------------
161 ** 'A' BLOB
162 ** 'B' TEXT
163 ** 'C' NUMERIC
164 ** 'D' INTEGER
165 ** 'E' REAL
167 ** For STRICT tables:
168 ** ------------------
170 ** Generate an appropriate OP_TypeCheck opcode that will verify the
171 ** datatypes against the column definitions in pTab. If iReg==0, that
172 ** means an OP_MakeRecord opcode has already been generated and should be
173 ** the last opcode generated. The new OP_TypeCheck needs to be inserted
174 ** before the OP_MakeRecord. The new OP_TypeCheck should use the same
175 ** register set as the OP_MakeRecord. If iReg>0 then register iReg is
176 ** the first of a series of registers that will form the new record.
177 ** Apply the type checking to that array of registers.
179 void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
180 int i;
181 char *zColAff;
182 if( pTab->tabFlags & TF_Strict ){
183 if( iReg==0 ){
184 /* Move the previous opcode (which should be OP_MakeRecord) forward
185 ** by one slot and insert a new OP_TypeCheck where the current
186 ** OP_MakeRecord is found */
187 VdbeOp *pPrev;
188 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
189 pPrev = sqlite3VdbeGetLastOp(v);
190 assert( pPrev!=0 );
191 assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );
192 pPrev->opcode = OP_TypeCheck;
193 sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, pPrev->p3);
194 }else{
195 /* Insert an isolated OP_Typecheck */
196 sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol);
197 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
199 return;
201 zColAff = pTab->zColAff;
202 if( zColAff==0 ){
203 zColAff = sqlite3TableAffinityStr(0, pTab);
204 if( !zColAff ){
205 sqlite3OomFault(sqlite3VdbeDb(v));
206 return;
208 pTab->zColAff = zColAff;
210 assert( zColAff!=0 );
211 i = sqlite3Strlen30NN(zColAff);
212 if( i ){
213 if( iReg ){
214 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
215 }else{
216 assert( sqlite3VdbeGetLastOp(v)->opcode==OP_MakeRecord
217 || sqlite3VdbeDb(v)->mallocFailed );
218 sqlite3VdbeChangeP4(v, -1, zColAff, i);
224 ** Return non-zero if the table pTab in database iDb or any of its indices
225 ** have been opened at any point in the VDBE program. This is used to see if
226 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
227 ** run without using a temporary table for the results of the SELECT.
229 static int readsTable(Parse *p, int iDb, Table *pTab){
230 Vdbe *v = sqlite3GetVdbe(p);
231 int i;
232 int iEnd = sqlite3VdbeCurrentAddr(v);
233 #ifndef SQLITE_OMIT_VIRTUALTABLE
234 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
235 #endif
237 for(i=1; i<iEnd; i++){
238 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
239 assert( pOp!=0 );
240 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
241 Index *pIndex;
242 Pgno tnum = pOp->p2;
243 if( tnum==pTab->tnum ){
244 return 1;
246 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
247 if( tnum==pIndex->tnum ){
248 return 1;
252 #ifndef SQLITE_OMIT_VIRTUALTABLE
253 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
254 assert( pOp->p4.pVtab!=0 );
255 assert( pOp->p4type==P4_VTAB );
256 return 1;
258 #endif
260 return 0;
263 /* This walker callback will compute the union of colFlags flags for all
264 ** referenced columns in a CHECK constraint or generated column expression.
266 static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
267 if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
268 assert( pExpr->iColumn < pWalker->u.pTab->nCol );
269 pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
271 return WRC_Continue;
274 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
276 ** All regular columns for table pTab have been puts into registers
277 ** starting with iRegStore. The registers that correspond to STORED
278 ** or VIRTUAL columns have not yet been initialized. This routine goes
279 ** back and computes the values for those columns based on the previously
280 ** computed normal columns.
282 void sqlite3ComputeGeneratedColumns(
283 Parse *pParse, /* Parsing context */
284 int iRegStore, /* Register holding the first column */
285 Table *pTab /* The table */
287 int i;
288 Walker w;
289 Column *pRedo;
290 int eProgress;
291 VdbeOp *pOp;
293 assert( pTab->tabFlags & TF_HasGenerated );
294 testcase( pTab->tabFlags & TF_HasVirtual );
295 testcase( pTab->tabFlags & TF_HasStored );
297 /* Before computing generated columns, first go through and make sure
298 ** that appropriate affinity has been applied to the regular columns
300 sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
301 if( (pTab->tabFlags & TF_HasStored)!=0 ){
302 pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
303 if( pOp->opcode==OP_Affinity ){
304 /* Change the OP_Affinity argument to '@' (NONE) for all stored
305 ** columns. '@' is the no-op affinity and those columns have not
306 ** yet been computed. */
307 int ii, jj;
308 char *zP4 = pOp->p4.z;
309 assert( zP4!=0 );
310 assert( pOp->p4type==P4_DYNAMIC );
311 for(ii=jj=0; zP4[jj]; ii++){
312 if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
313 continue;
315 if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
316 zP4[jj] = SQLITE_AFF_NONE;
318 jj++;
320 }else if( pOp->opcode==OP_TypeCheck ){
321 /* If an OP_TypeCheck was generated because the table is STRICT,
322 ** then set the P3 operand to indicate that generated columns should
323 ** not be checked */
324 pOp->p3 = 1;
328 /* Because there can be multiple generated columns that refer to one another,
329 ** this is a two-pass algorithm. On the first pass, mark all generated
330 ** columns as "not available".
332 for(i=0; i<pTab->nCol; i++){
333 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
334 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
335 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
336 pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
340 w.u.pTab = pTab;
341 w.xExprCallback = exprColumnFlagUnion;
342 w.xSelectCallback = 0;
343 w.xSelectCallback2 = 0;
345 /* On the second pass, compute the value of each NOT-AVAILABLE column.
346 ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will
347 ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as
348 ** they are needed.
350 pParse->iSelfTab = -iRegStore;
352 eProgress = 0;
353 pRedo = 0;
354 for(i=0; i<pTab->nCol; i++){
355 Column *pCol = pTab->aCol + i;
356 if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
357 int x;
358 pCol->colFlags |= COLFLAG_BUSY;
359 w.eCode = 0;
360 sqlite3WalkExpr(&w, sqlite3ColumnExpr(pTab, pCol));
361 pCol->colFlags &= ~COLFLAG_BUSY;
362 if( w.eCode & COLFLAG_NOTAVAIL ){
363 pRedo = pCol;
364 continue;
366 eProgress = 1;
367 assert( pCol->colFlags & COLFLAG_GENERATED );
368 x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
369 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, x);
370 pCol->colFlags &= ~COLFLAG_NOTAVAIL;
373 }while( pRedo && eProgress );
374 if( pRedo ){
375 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zCnName);
377 pParse->iSelfTab = 0;
379 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
382 #ifndef SQLITE_OMIT_AUTOINCREMENT
384 ** Locate or create an AutoincInfo structure associated with table pTab
385 ** which is in database iDb. Return the register number for the register
386 ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
387 ** table. (Also return zero when doing a VACUUM since we do not want to
388 ** update the AUTOINCREMENT counters during a VACUUM.)
390 ** There is at most one AutoincInfo structure per table even if the
391 ** same table is autoincremented multiple times due to inserts within
392 ** triggers. A new AutoincInfo structure is created if this is the
393 ** first use of table pTab. On 2nd and subsequent uses, the original
394 ** AutoincInfo structure is used.
396 ** Four consecutive registers are allocated:
398 ** (1) The name of the pTab table.
399 ** (2) The maximum ROWID of pTab.
400 ** (3) The rowid in sqlite_sequence of pTab
401 ** (4) The original value of the max ROWID in pTab, or NULL if none
403 ** The 2nd register is the one that is returned. That is all the
404 ** insert routine needs to know about.
406 static int autoIncBegin(
407 Parse *pParse, /* Parsing context */
408 int iDb, /* Index of the database holding pTab */
409 Table *pTab /* The table we are writing to */
411 int memId = 0; /* Register holding maximum rowid */
412 assert( pParse->db->aDb[iDb].pSchema!=0 );
413 if( (pTab->tabFlags & TF_Autoincrement)!=0
414 && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
416 Parse *pToplevel = sqlite3ParseToplevel(pParse);
417 AutoincInfo *pInfo;
418 Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
420 /* Verify that the sqlite_sequence table exists and is an ordinary
421 ** rowid table with exactly two columns.
422 ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
423 if( pSeqTab==0
424 || !HasRowid(pSeqTab)
425 || NEVER(IsVirtual(pSeqTab))
426 || pSeqTab->nCol!=2
428 pParse->nErr++;
429 pParse->rc = SQLITE_CORRUPT_SEQUENCE;
430 return 0;
433 pInfo = pToplevel->pAinc;
434 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
435 if( pInfo==0 ){
436 pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
437 sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
438 testcase( pParse->earlyCleanup );
439 if( pParse->db->mallocFailed ) return 0;
440 pInfo->pNext = pToplevel->pAinc;
441 pToplevel->pAinc = pInfo;
442 pInfo->pTab = pTab;
443 pInfo->iDb = iDb;
444 pToplevel->nMem++; /* Register to hold name of table */
445 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
446 pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
448 memId = pInfo->regCtr;
450 return memId;
454 ** This routine generates code that will initialize all of the
455 ** register used by the autoincrement tracker.
457 void sqlite3AutoincrementBegin(Parse *pParse){
458 AutoincInfo *p; /* Information about an AUTOINCREMENT */
459 sqlite3 *db = pParse->db; /* The database connection */
460 Db *pDb; /* Database only autoinc table */
461 int memId; /* Register holding max rowid */
462 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
464 /* This routine is never called during trigger-generation. It is
465 ** only called from the top-level */
466 assert( pParse->pTriggerTab==0 );
467 assert( sqlite3IsToplevel(pParse) );
469 assert( v ); /* We failed long ago if this is not so */
470 for(p = pParse->pAinc; p; p = p->pNext){
471 static const int iLn = VDBE_OFFSET_LINENO(2);
472 static const VdbeOpList autoInc[] = {
473 /* 0 */ {OP_Null, 0, 0, 0},
474 /* 1 */ {OP_Rewind, 0, 10, 0},
475 /* 2 */ {OP_Column, 0, 0, 0},
476 /* 3 */ {OP_Ne, 0, 9, 0},
477 /* 4 */ {OP_Rowid, 0, 0, 0},
478 /* 5 */ {OP_Column, 0, 1, 0},
479 /* 6 */ {OP_AddImm, 0, 0, 0},
480 /* 7 */ {OP_Copy, 0, 0, 0},
481 /* 8 */ {OP_Goto, 0, 11, 0},
482 /* 9 */ {OP_Next, 0, 2, 0},
483 /* 10 */ {OP_Integer, 0, 0, 0},
484 /* 11 */ {OP_Close, 0, 0, 0}
486 VdbeOp *aOp;
487 pDb = &db->aDb[p->iDb];
488 memId = p->regCtr;
489 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
490 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
491 sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
492 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
493 if( aOp==0 ) break;
494 aOp[0].p2 = memId;
495 aOp[0].p3 = memId+2;
496 aOp[2].p3 = memId;
497 aOp[3].p1 = memId-1;
498 aOp[3].p3 = memId;
499 aOp[3].p5 = SQLITE_JUMPIFNULL;
500 aOp[4].p2 = memId+1;
501 aOp[5].p3 = memId;
502 aOp[6].p1 = memId;
503 aOp[7].p2 = memId+2;
504 aOp[7].p1 = memId;
505 aOp[10].p2 = memId;
506 if( pParse->nTab==0 ) pParse->nTab = 1;
511 ** Update the maximum rowid for an autoincrement calculation.
513 ** This routine should be called when the regRowid register holds a
514 ** new rowid that is about to be inserted. If that new rowid is
515 ** larger than the maximum rowid in the memId memory cell, then the
516 ** memory cell is updated.
518 static void autoIncStep(Parse *pParse, int memId, int regRowid){
519 if( memId>0 ){
520 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
525 ** This routine generates the code needed to write autoincrement
526 ** maximum rowid values back into the sqlite_sequence register.
527 ** Every statement that might do an INSERT into an autoincrement
528 ** table (either directly or through triggers) needs to call this
529 ** routine just before the "exit" code.
531 static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
532 AutoincInfo *p;
533 Vdbe *v = pParse->pVdbe;
534 sqlite3 *db = pParse->db;
536 assert( v );
537 for(p = pParse->pAinc; p; p = p->pNext){
538 static const int iLn = VDBE_OFFSET_LINENO(2);
539 static const VdbeOpList autoIncEnd[] = {
540 /* 0 */ {OP_NotNull, 0, 2, 0},
541 /* 1 */ {OP_NewRowid, 0, 0, 0},
542 /* 2 */ {OP_MakeRecord, 0, 2, 0},
543 /* 3 */ {OP_Insert, 0, 0, 0},
544 /* 4 */ {OP_Close, 0, 0, 0}
546 VdbeOp *aOp;
547 Db *pDb = &db->aDb[p->iDb];
548 int iRec;
549 int memId = p->regCtr;
551 iRec = sqlite3GetTempReg(pParse);
552 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
553 sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
554 VdbeCoverage(v);
555 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
556 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
557 if( aOp==0 ) break;
558 aOp[0].p1 = memId+1;
559 aOp[1].p2 = memId+1;
560 aOp[2].p1 = memId-1;
561 aOp[2].p3 = iRec;
562 aOp[3].p2 = iRec;
563 aOp[3].p3 = memId+1;
564 aOp[3].p5 = OPFLAG_APPEND;
565 sqlite3ReleaseTempReg(pParse, iRec);
568 void sqlite3AutoincrementEnd(Parse *pParse){
569 if( pParse->pAinc ) autoIncrementEnd(pParse);
571 #else
573 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
574 ** above are all no-ops
576 # define autoIncBegin(A,B,C) (0)
577 # define autoIncStep(A,B,C)
578 #endif /* SQLITE_OMIT_AUTOINCREMENT */
581 ** If argument pVal is a Select object returned by an sqlite3MultiValues()
582 ** that was able to use the co-routine optimization, finish coding the
583 ** co-routine.
585 void sqlite3MultiValuesEnd(Parse *pParse, Select *pVal){
586 if( ALWAYS(pVal) && pVal->pSrc->nSrc>0 ){
587 SrcItem *pItem = &pVal->pSrc->a[0];
588 sqlite3VdbeEndCoroutine(pParse->pVdbe, pItem->regReturn);
589 sqlite3VdbeJumpHere(pParse->pVdbe, pItem->addrFillSub - 1);
594 ** Return true if all expressions in the expression-list passed as the
595 ** only argument are constant.
597 static int exprListIsConstant(Parse *pParse, ExprList *pRow){
598 int ii;
599 for(ii=0; ii<pRow->nExpr; ii++){
600 if( 0==sqlite3ExprIsConstant(pParse, pRow->a[ii].pExpr) ) return 0;
602 return 1;
606 ** Return true if all expressions in the expression-list passed as the
607 ** only argument are both constant and have no affinity.
609 static int exprListIsNoAffinity(Parse *pParse, ExprList *pRow){
610 int ii;
611 if( exprListIsConstant(pParse,pRow)==0 ) return 0;
612 for(ii=0; ii<pRow->nExpr; ii++){
613 Expr *pExpr = pRow->a[ii].pExpr;
614 assert( pExpr->op!=TK_RAISE );
615 assert( pExpr->affExpr==0 );
616 if( 0!=sqlite3ExprAffinity(pExpr) ) return 0;
618 return 1;
623 ** This function is called by the parser for the second and subsequent
624 ** rows of a multi-row VALUES clause. Argument pLeft is the part of
625 ** the VALUES clause already parsed, argument pRow is the vector of values
626 ** for the new row. The Select object returned represents the complete
627 ** VALUES clause, including the new row.
629 ** There are two ways in which this may be achieved - by incremental
630 ** coding of a co-routine (the "co-routine" method) or by returning a
631 ** Select object equivalent to the following (the "UNION ALL" method):
633 ** "pLeft UNION ALL SELECT pRow"
635 ** If the VALUES clause contains a lot of rows, this compound Select
636 ** object may consume a lot of memory.
638 ** When the co-routine method is used, each row that will be returned
639 ** by the VALUES clause is coded into part of a co-routine as it is
640 ** passed to this function. The returned Select object is equivalent to:
642 ** SELECT * FROM (
643 ** Select object to read co-routine
644 ** )
646 ** The co-routine method is used in most cases. Exceptions are:
648 ** a) If the current statement has a WITH clause. This is to avoid
649 ** statements like:
651 ** WITH cte AS ( VALUES('x'), ('y') ... )
652 ** SELECT * FROM cte AS a, cte AS b;
654 ** This will not work, as the co-routine uses a hard-coded register
655 ** for its OP_Yield instructions, and so it is not possible for two
656 ** cursors to iterate through it concurrently.
658 ** b) The schema is currently being parsed (i.e. the VALUES clause is part
659 ** of a schema item like a VIEW or TRIGGER). In this case there is no VM
660 ** being generated when parsing is taking place, and so generating
661 ** a co-routine is not possible.
663 ** c) There are non-constant expressions in the VALUES clause (e.g.
664 ** the VALUES clause is part of a correlated sub-query).
666 ** d) One or more of the values in the first row of the VALUES clause
667 ** has an affinity (i.e. is a CAST expression). This causes problems
668 ** because the complex rules SQLite uses (see function
669 ** sqlite3SubqueryColumnTypes() in select.c) to determine the effective
670 ** affinity of such a column for all rows require access to all values in
671 ** the column simultaneously.
673 Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow){
675 if( pParse->bHasWith /* condition (a) above */
676 || pParse->db->init.busy /* condition (b) above */
677 || exprListIsConstant(pParse,pRow)==0 /* condition (c) above */
678 || (pLeft->pSrc->nSrc==0 &&
679 exprListIsNoAffinity(pParse,pLeft->pEList)==0) /* condition (d) above */
680 || IN_SPECIAL_PARSE
682 /* The co-routine method cannot be used. Fall back to UNION ALL. */
683 Select *pSelect = 0;
684 int f = SF_Values | SF_MultiValue;
685 if( pLeft->pSrc->nSrc ){
686 sqlite3MultiValuesEnd(pParse, pLeft);
687 f = SF_Values;
688 }else if( pLeft->pPrior ){
689 /* In this case set the SF_MultiValue flag only if it was set on pLeft */
690 f = (f & pLeft->selFlags);
692 pSelect = sqlite3SelectNew(pParse, pRow, 0, 0, 0, 0, 0, f, 0);
693 pLeft->selFlags &= ~SF_MultiValue;
694 if( pSelect ){
695 pSelect->op = TK_ALL;
696 pSelect->pPrior = pLeft;
697 pLeft = pSelect;
699 }else{
700 SrcItem *p = 0; /* SrcItem that reads from co-routine */
702 if( pLeft->pSrc->nSrc==0 ){
703 /* Co-routine has not yet been started and the special Select object
704 ** that accesses the co-routine has not yet been created. This block
705 ** does both those things. */
706 Vdbe *v = sqlite3GetVdbe(pParse);
707 Select *pRet = sqlite3SelectNew(pParse, 0, 0, 0, 0, 0, 0, 0, 0);
709 /* Ensure the database schema has been read. This is to ensure we have
710 ** the correct text encoding. */
711 if( (pParse->db->mDbFlags & DBFLAG_SchemaKnownOk)==0 ){
712 sqlite3ReadSchema(pParse);
715 if( pRet ){
716 SelectDest dest;
717 pRet->pSrc->nSrc = 1;
718 pRet->pPrior = pLeft->pPrior;
719 pRet->op = pLeft->op;
720 pLeft->pPrior = 0;
721 pLeft->op = TK_SELECT;
722 assert( pLeft->pNext==0 );
723 assert( pRet->pNext==0 );
724 p = &pRet->pSrc->a[0];
725 p->pSelect = pLeft;
726 p->fg.viaCoroutine = 1;
727 p->addrFillSub = sqlite3VdbeCurrentAddr(v) + 1;
728 p->regReturn = ++pParse->nMem;
729 p->iCursor = -1;
730 p->u1.nRow = 2;
731 sqlite3VdbeAddOp3(v,OP_InitCoroutine,p->regReturn,0,p->addrFillSub);
732 sqlite3SelectDestInit(&dest, SRT_Coroutine, p->regReturn);
734 /* Allocate registers for the output of the co-routine. Do so so
735 ** that there are two unused registers immediately before those
736 ** used by the co-routine. This allows the code in sqlite3Insert()
737 ** to use these registers directly, instead of copying the output
738 ** of the co-routine to a separate array for processing. */
739 dest.iSdst = pParse->nMem + 3;
740 dest.nSdst = pLeft->pEList->nExpr;
741 pParse->nMem += 2 + dest.nSdst;
743 pLeft->selFlags |= SF_MultiValue;
744 sqlite3Select(pParse, pLeft, &dest);
745 p->regResult = dest.iSdst;
746 assert( pParse->nErr || dest.iSdst>0 );
747 pLeft = pRet;
749 }else{
750 p = &pLeft->pSrc->a[0];
751 assert( !p->fg.isTabFunc && !p->fg.isIndexedBy );
752 p->u1.nRow++;
755 if( pParse->nErr==0 ){
756 assert( p!=0 );
757 if( p->pSelect->pEList->nExpr!=pRow->nExpr ){
758 sqlite3SelectWrongNumTermsError(pParse, p->pSelect);
759 }else{
760 sqlite3ExprCodeExprList(pParse, pRow, p->regResult, 0, 0);
761 sqlite3VdbeAddOp1(pParse->pVdbe, OP_Yield, p->regReturn);
764 sqlite3ExprListDelete(pParse->db, pRow);
767 return pLeft;
770 /* Forward declaration */
771 static int xferOptimization(
772 Parse *pParse, /* Parser context */
773 Table *pDest, /* The table we are inserting into */
774 Select *pSelect, /* A SELECT statement to use as the data source */
775 int onError, /* How to handle constraint errors */
776 int iDbDest /* The database of pDest */
780 ** This routine is called to handle SQL of the following forms:
782 ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
783 ** insert into TABLE (IDLIST) select
784 ** insert into TABLE (IDLIST) default values
786 ** The IDLIST following the table name is always optional. If omitted,
787 ** then a list of all (non-hidden) columns for the table is substituted.
788 ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
789 ** is omitted.
791 ** For the pSelect parameter holds the values to be inserted for the
792 ** first two forms shown above. A VALUES clause is really just short-hand
793 ** for a SELECT statement that omits the FROM clause and everything else
794 ** that follows. If the pSelect parameter is NULL, that means that the
795 ** DEFAULT VALUES form of the INSERT statement is intended.
797 ** The code generated follows one of four templates. For a simple
798 ** insert with data coming from a single-row VALUES clause, the code executes
799 ** once straight down through. Pseudo-code follows (we call this
800 ** the "1st template"):
802 ** open write cursor to <table> and its indices
803 ** put VALUES clause expressions into registers
804 ** write the resulting record into <table>
805 ** cleanup
807 ** The three remaining templates assume the statement is of the form
809 ** INSERT INTO <table> SELECT ...
811 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
812 ** in other words if the SELECT pulls all columns from a single table
813 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
814 ** if <table2> and <table1> are distinct tables but have identical
815 ** schemas, including all the same indices, then a special optimization
816 ** is invoked that copies raw records from <table2> over to <table1>.
817 ** See the xferOptimization() function for the implementation of this
818 ** template. This is the 2nd template.
820 ** open a write cursor to <table>
821 ** open read cursor on <table2>
822 ** transfer all records in <table2> over to <table>
823 ** close cursors
824 ** foreach index on <table>
825 ** open a write cursor on the <table> index
826 ** open a read cursor on the corresponding <table2> index
827 ** transfer all records from the read to the write cursors
828 ** close cursors
829 ** end foreach
831 ** The 3rd template is for when the second template does not apply
832 ** and the SELECT clause does not read from <table> at any time.
833 ** The generated code follows this template:
835 ** X <- A
836 ** goto B
837 ** A: setup for the SELECT
838 ** loop over the rows in the SELECT
839 ** load values into registers R..R+n
840 ** yield X
841 ** end loop
842 ** cleanup after the SELECT
843 ** end-coroutine X
844 ** B: open write cursor to <table> and its indices
845 ** C: yield X, at EOF goto D
846 ** insert the select result into <table> from R..R+n
847 ** goto C
848 ** D: cleanup
850 ** The 4th template is used if the insert statement takes its
851 ** values from a SELECT but the data is being inserted into a table
852 ** that is also read as part of the SELECT. In the third form,
853 ** we have to use an intermediate table to store the results of
854 ** the select. The template is like this:
856 ** X <- A
857 ** goto B
858 ** A: setup for the SELECT
859 ** loop over the tables in the SELECT
860 ** load value into register R..R+n
861 ** yield X
862 ** end loop
863 ** cleanup after the SELECT
864 ** end co-routine R
865 ** B: open temp table
866 ** L: yield X, at EOF goto M
867 ** insert row from R..R+n into temp table
868 ** goto L
869 ** M: open write cursor to <table> and its indices
870 ** rewind temp table
871 ** C: loop over rows of intermediate table
872 ** transfer values form intermediate table into <table>
873 ** end loop
874 ** D: cleanup
876 void sqlite3Insert(
877 Parse *pParse, /* Parser context */
878 SrcList *pTabList, /* Name of table into which we are inserting */
879 Select *pSelect, /* A SELECT statement to use as the data source */
880 IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */
881 int onError, /* How to handle constraint errors */
882 Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
884 sqlite3 *db; /* The main database structure */
885 Table *pTab; /* The table to insert into. aka TABLE */
886 int i, j; /* Loop counters */
887 Vdbe *v; /* Generate code into this virtual machine */
888 Index *pIdx; /* For looping over indices of the table */
889 int nColumn; /* Number of columns in the data */
890 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
891 int iDataCur = 0; /* VDBE cursor that is the main data repository */
892 int iIdxCur = 0; /* First index cursor */
893 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
894 int endOfLoop; /* Label for the end of the insertion loop */
895 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
896 int addrInsTop = 0; /* Jump to label "D" */
897 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
898 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
899 int iDb; /* Index of database holding TABLE */
900 u8 useTempTable = 0; /* Store SELECT results in intermediate table */
901 u8 appendFlag = 0; /* True if the insert is likely to be an append */
902 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
903 u8 bIdListInOrder; /* True if IDLIST is in table order */
904 ExprList *pList = 0; /* List of VALUES() to be inserted */
905 int iRegStore; /* Register in which to store next column */
907 /* Register allocations */
908 int regFromSelect = 0;/* Base register for data coming from SELECT */
909 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
910 int regRowCount = 0; /* Memory cell used for the row counter */
911 int regIns; /* Block of regs holding rowid+data being inserted */
912 int regRowid; /* registers holding insert rowid */
913 int regData; /* register holding first column to insert */
914 int *aRegIdx = 0; /* One register allocated to each index */
916 #ifndef SQLITE_OMIT_TRIGGER
917 int isView; /* True if attempting to insert into a view */
918 Trigger *pTrigger; /* List of triggers on pTab, if required */
919 int tmask; /* Mask of trigger times */
920 #endif
922 db = pParse->db;
923 assert( db->pParse==pParse );
924 if( pParse->nErr ){
925 goto insert_cleanup;
927 assert( db->mallocFailed==0 );
928 dest.iSDParm = 0; /* Suppress a harmless compiler warning */
930 /* If the Select object is really just a simple VALUES() list with a
931 ** single row (the common case) then keep that one row of values
932 ** and discard the other (unused) parts of the pSelect object
934 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
935 pList = pSelect->pEList;
936 pSelect->pEList = 0;
937 sqlite3SelectDelete(db, pSelect);
938 pSelect = 0;
941 /* Locate the table into which we will be inserting new information.
943 assert( pTabList->nSrc==1 );
944 pTab = sqlite3SrcListLookup(pParse, pTabList);
945 if( pTab==0 ){
946 goto insert_cleanup;
948 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
949 assert( iDb<db->nDb );
950 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
951 db->aDb[iDb].zDbSName) ){
952 goto insert_cleanup;
954 withoutRowid = !HasRowid(pTab);
956 /* Figure out if we have any triggers and if the table being
957 ** inserted into is a view
959 #ifndef SQLITE_OMIT_TRIGGER
960 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
961 isView = IsView(pTab);
962 #else
963 # define pTrigger 0
964 # define tmask 0
965 # define isView 0
966 #endif
967 #ifdef SQLITE_OMIT_VIEW
968 # undef isView
969 # define isView 0
970 #endif
971 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
973 #if TREETRACE_ENABLED
974 if( sqlite3TreeTrace & 0x10000 ){
975 sqlite3TreeViewLine(0, "In sqlite3Insert() at %s:%d", __FILE__, __LINE__);
976 sqlite3TreeViewInsert(pParse->pWith, pTabList, pColumn, pSelect, pList,
977 onError, pUpsert, pTrigger);
979 #endif
981 /* If pTab is really a view, make sure it has been initialized.
982 ** ViewGetColumnNames() is a no-op if pTab is not a view.
984 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
985 goto insert_cleanup;
988 /* Cannot insert into a read-only table.
990 if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
991 goto insert_cleanup;
994 /* Allocate a VDBE
996 v = sqlite3GetVdbe(pParse);
997 if( v==0 ) goto insert_cleanup;
998 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
999 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
1001 #ifndef SQLITE_OMIT_XFER_OPT
1002 /* If the statement is of the form
1004 ** INSERT INTO <table1> SELECT * FROM <table2>;
1006 ** Then special optimizations can be applied that make the transfer
1007 ** very fast and which reduce fragmentation of indices.
1009 ** This is the 2nd template.
1011 if( pColumn==0
1012 && pSelect!=0
1013 && pTrigger==0
1014 && xferOptimization(pParse, pTab, pSelect, onError, iDb)
1016 assert( !pTrigger );
1017 assert( pList==0 );
1018 goto insert_end;
1020 #endif /* SQLITE_OMIT_XFER_OPT */
1022 /* If this is an AUTOINCREMENT table, look up the sequence number in the
1023 ** sqlite_sequence table and store it in memory cell regAutoinc.
1025 regAutoinc = autoIncBegin(pParse, iDb, pTab);
1027 /* Allocate a block registers to hold the rowid and the values
1028 ** for all columns of the new row.
1030 regRowid = regIns = pParse->nMem+1;
1031 pParse->nMem += pTab->nCol + 1;
1032 if( IsVirtual(pTab) ){
1033 regRowid++;
1034 pParse->nMem++;
1036 regData = regRowid+1;
1038 /* If the INSERT statement included an IDLIST term, then make sure
1039 ** all elements of the IDLIST really are columns of the table and
1040 ** remember the column indices.
1042 ** If the table has an INTEGER PRIMARY KEY column and that column
1043 ** is named in the IDLIST, then record in the ipkColumn variable
1044 ** the index into IDLIST of the primary key column. ipkColumn is
1045 ** the index of the primary key as it appears in IDLIST, not as
1046 ** is appears in the original table. (The index of the INTEGER
1047 ** PRIMARY KEY in the original table is pTab->iPKey.) After this
1048 ** loop, if ipkColumn==(-1), that means that integer primary key
1049 ** is unspecified, and hence the table is either WITHOUT ROWID or
1050 ** it will automatically generated an integer primary key.
1052 ** bIdListInOrder is true if the columns in IDLIST are in storage
1053 ** order. This enables an optimization that avoids shuffling the
1054 ** columns into storage order. False negatives are harmless,
1055 ** but false positives will cause database corruption.
1057 bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
1058 if( pColumn ){
1059 assert( pColumn->eU4!=EU4_EXPR );
1060 pColumn->eU4 = EU4_IDX;
1061 for(i=0; i<pColumn->nId; i++){
1062 pColumn->a[i].u4.idx = -1;
1064 for(i=0; i<pColumn->nId; i++){
1065 for(j=0; j<pTab->nCol; j++){
1066 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zCnName)==0 ){
1067 pColumn->a[i].u4.idx = j;
1068 if( i!=j ) bIdListInOrder = 0;
1069 if( j==pTab->iPKey ){
1070 ipkColumn = i; assert( !withoutRowid );
1072 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1073 if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
1074 sqlite3ErrorMsg(pParse,
1075 "cannot INSERT into generated column \"%s\"",
1076 pTab->aCol[j].zCnName);
1077 goto insert_cleanup;
1079 #endif
1080 break;
1083 if( j>=pTab->nCol ){
1084 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
1085 ipkColumn = i;
1086 bIdListInOrder = 0;
1087 }else{
1088 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
1089 pTabList->a, pColumn->a[i].zName);
1090 pParse->checkSchema = 1;
1091 goto insert_cleanup;
1097 /* Figure out how many columns of data are supplied. If the data
1098 ** is coming from a SELECT statement, then generate a co-routine that
1099 ** produces a single row of the SELECT on each invocation. The
1100 ** co-routine is the common header to the 3rd and 4th templates.
1102 if( pSelect ){
1103 /* Data is coming from a SELECT or from a multi-row VALUES clause.
1104 ** Generate a co-routine to run the SELECT. */
1105 int rc; /* Result code */
1107 if( pSelect->pSrc->nSrc==1
1108 && pSelect->pSrc->a[0].fg.viaCoroutine
1109 && pSelect->pPrior==0
1111 SrcItem *pItem = &pSelect->pSrc->a[0];
1112 dest.iSDParm = pItem->regReturn;
1113 regFromSelect = pItem->regResult;
1114 nColumn = pItem->pSelect->pEList->nExpr;
1115 ExplainQueryPlan((pParse, 0, "SCAN %S", pItem));
1116 if( bIdListInOrder && nColumn==pTab->nCol ){
1117 regData = regFromSelect;
1118 regRowid = regData - 1;
1119 regIns = regRowid - (IsVirtual(pTab) ? 1 : 0);
1121 }else{
1122 int addrTop; /* Top of the co-routine */
1123 int regYield = ++pParse->nMem;
1124 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
1125 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
1126 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
1127 dest.iSdst = bIdListInOrder ? regData : 0;
1128 dest.nSdst = pTab->nCol;
1129 rc = sqlite3Select(pParse, pSelect, &dest);
1130 regFromSelect = dest.iSdst;
1131 assert( db->pParse==pParse );
1132 if( rc || pParse->nErr ) goto insert_cleanup;
1133 assert( db->mallocFailed==0 );
1134 sqlite3VdbeEndCoroutine(v, regYield);
1135 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
1136 assert( pSelect->pEList );
1137 nColumn = pSelect->pEList->nExpr;
1140 /* Set useTempTable to TRUE if the result of the SELECT statement
1141 ** should be written into a temporary table (template 4). Set to
1142 ** FALSE if each output row of the SELECT can be written directly into
1143 ** the destination table (template 3).
1145 ** A temp table must be used if the table being updated is also one
1146 ** of the tables being read by the SELECT statement. Also use a
1147 ** temp table in the case of row triggers.
1149 if( pTrigger || readsTable(pParse, iDb, pTab) ){
1150 useTempTable = 1;
1153 if( useTempTable ){
1154 /* Invoke the coroutine to extract information from the SELECT
1155 ** and add it to a transient table srcTab. The code generated
1156 ** here is from the 4th template:
1158 ** B: open temp table
1159 ** L: yield X, goto M at EOF
1160 ** insert row from R..R+n into temp table
1161 ** goto L
1162 ** M: ...
1164 int regRec; /* Register to hold packed record */
1165 int regTempRowid; /* Register to hold temp table ROWID */
1166 int addrL; /* Label "L" */
1168 srcTab = pParse->nTab++;
1169 regRec = sqlite3GetTempReg(pParse);
1170 regTempRowid = sqlite3GetTempReg(pParse);
1171 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
1172 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
1173 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
1174 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
1175 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
1176 sqlite3VdbeGoto(v, addrL);
1177 sqlite3VdbeJumpHere(v, addrL);
1178 sqlite3ReleaseTempReg(pParse, regRec);
1179 sqlite3ReleaseTempReg(pParse, regTempRowid);
1181 }else{
1182 /* This is the case if the data for the INSERT is coming from a
1183 ** single-row VALUES clause
1185 NameContext sNC;
1186 memset(&sNC, 0, sizeof(sNC));
1187 sNC.pParse = pParse;
1188 srcTab = -1;
1189 assert( useTempTable==0 );
1190 if( pList ){
1191 nColumn = pList->nExpr;
1192 if( sqlite3ResolveExprListNames(&sNC, pList) ){
1193 goto insert_cleanup;
1195 }else{
1196 nColumn = 0;
1200 /* If there is no IDLIST term but the table has an integer primary
1201 ** key, the set the ipkColumn variable to the integer primary key
1202 ** column index in the original table definition.
1204 if( pColumn==0 && nColumn>0 ){
1205 ipkColumn = pTab->iPKey;
1206 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1207 if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
1208 testcase( pTab->tabFlags & TF_HasVirtual );
1209 testcase( pTab->tabFlags & TF_HasStored );
1210 for(i=ipkColumn-1; i>=0; i--){
1211 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
1212 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
1213 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
1214 ipkColumn--;
1218 #endif
1220 /* Make sure the number of columns in the source data matches the number
1221 ** of columns to be inserted into the table.
1223 assert( TF_HasHidden==COLFLAG_HIDDEN );
1224 assert( TF_HasGenerated==COLFLAG_GENERATED );
1225 assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) );
1226 if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
1227 for(i=0; i<pTab->nCol; i++){
1228 if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
1231 if( nColumn!=(pTab->nCol-nHidden) ){
1232 sqlite3ErrorMsg(pParse,
1233 "table %S has %d columns but %d values were supplied",
1234 pTabList->a, pTab->nCol-nHidden, nColumn);
1235 goto insert_cleanup;
1238 if( pColumn!=0 && nColumn!=pColumn->nId ){
1239 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
1240 goto insert_cleanup;
1243 /* Initialize the count of rows to be inserted
1245 if( (db->flags & SQLITE_CountRows)!=0
1246 && !pParse->nested
1247 && !pParse->pTriggerTab
1248 && !pParse->bReturning
1250 regRowCount = ++pParse->nMem;
1251 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
1254 /* If this is not a view, open the table and and all indices */
1255 if( !isView ){
1256 int nIdx;
1257 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
1258 &iDataCur, &iIdxCur);
1259 aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
1260 if( aRegIdx==0 ){
1261 goto insert_cleanup;
1263 for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
1264 assert( pIdx );
1265 aRegIdx[i] = ++pParse->nMem;
1266 pParse->nMem += pIdx->nColumn;
1268 aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */
1270 #ifndef SQLITE_OMIT_UPSERT
1271 if( pUpsert ){
1272 Upsert *pNx;
1273 if( IsVirtual(pTab) ){
1274 sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
1275 pTab->zName);
1276 goto insert_cleanup;
1278 if( IsView(pTab) ){
1279 sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
1280 goto insert_cleanup;
1282 if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
1283 goto insert_cleanup;
1285 pTabList->a[0].iCursor = iDataCur;
1286 pNx = pUpsert;
1288 pNx->pUpsertSrc = pTabList;
1289 pNx->regData = regData;
1290 pNx->iDataCur = iDataCur;
1291 pNx->iIdxCur = iIdxCur;
1292 if( pNx->pUpsertTarget ){
1293 if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx, pUpsert) ){
1294 goto insert_cleanup;
1297 pNx = pNx->pNextUpsert;
1298 }while( pNx!=0 );
1300 #endif
1303 /* This is the top of the main insertion loop */
1304 if( useTempTable ){
1305 /* This block codes the top of loop only. The complete loop is the
1306 ** following pseudocode (template 4):
1308 ** rewind temp table, if empty goto D
1309 ** C: loop over rows of intermediate table
1310 ** transfer values form intermediate table into <table>
1311 ** end loop
1312 ** D: ...
1314 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
1315 addrCont = sqlite3VdbeCurrentAddr(v);
1316 }else if( pSelect ){
1317 /* This block codes the top of loop only. The complete loop is the
1318 ** following pseudocode (template 3):
1320 ** C: yield X, at EOF goto D
1321 ** insert the select result into <table> from R..R+n
1322 ** goto C
1323 ** D: ...
1325 sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
1326 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
1327 VdbeCoverage(v);
1328 if( ipkColumn>=0 ){
1329 /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
1330 ** SELECT, go ahead and copy the value into the rowid slot now, so that
1331 ** the value does not get overwritten by a NULL at tag-20191021-002. */
1332 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
1336 /* Compute data for ordinary columns of the new entry. Values
1337 ** are written in storage order into registers starting with regData.
1338 ** Only ordinary columns are computed in this loop. The rowid
1339 ** (if there is one) is computed later and generated columns are
1340 ** computed after the rowid since they might depend on the value
1341 ** of the rowid.
1343 nHidden = 0;
1344 iRegStore = regData; assert( regData==regRowid+1 );
1345 for(i=0; i<pTab->nCol; i++, iRegStore++){
1346 int k;
1347 u32 colFlags;
1348 assert( i>=nHidden );
1349 if( i==pTab->iPKey ){
1350 /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
1351 ** using the rowid. So put a NULL in the IPK slot of the record to avoid
1352 ** using excess space. The file format definition requires this extra
1353 ** NULL - we cannot optimize further by skipping the column completely */
1354 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1355 continue;
1357 if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
1358 nHidden++;
1359 if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
1360 /* Virtual columns do not participate in OP_MakeRecord. So back up
1361 ** iRegStore by one slot to compensate for the iRegStore++ in the
1362 ** outer for() loop */
1363 iRegStore--;
1364 continue;
1365 }else if( (colFlags & COLFLAG_STORED)!=0 ){
1366 /* Stored columns are computed later. But if there are BEFORE
1367 ** triggers, the slots used for stored columns will be OP_Copy-ed
1368 ** to a second block of registers, so the register needs to be
1369 ** initialized to NULL to avoid an uninitialized register read */
1370 if( tmask & TRIGGER_BEFORE ){
1371 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1373 continue;
1374 }else if( pColumn==0 ){
1375 /* Hidden columns that are not explicitly named in the INSERT
1376 ** get there default value */
1377 sqlite3ExprCodeFactorable(pParse,
1378 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1379 iRegStore);
1380 continue;
1383 if( pColumn ){
1384 assert( pColumn->eU4==EU4_IDX );
1385 for(j=0; j<pColumn->nId && pColumn->a[j].u4.idx!=i; j++){}
1386 if( j>=pColumn->nId ){
1387 /* A column not named in the insert column list gets its
1388 ** default value */
1389 sqlite3ExprCodeFactorable(pParse,
1390 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1391 iRegStore);
1392 continue;
1394 k = j;
1395 }else if( nColumn==0 ){
1396 /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */
1397 sqlite3ExprCodeFactorable(pParse,
1398 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1399 iRegStore);
1400 continue;
1401 }else{
1402 k = i - nHidden;
1405 if( useTempTable ){
1406 sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
1407 }else if( pSelect ){
1408 if( regFromSelect!=regData ){
1409 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
1411 }else{
1412 Expr *pX = pList->a[k].pExpr;
1413 int y = sqlite3ExprCodeTarget(pParse, pX, iRegStore);
1414 if( y!=iRegStore ){
1415 sqlite3VdbeAddOp2(v,
1416 ExprHasProperty(pX, EP_Subquery) ? OP_Copy : OP_SCopy, y, iRegStore);
1422 /* Run the BEFORE and INSTEAD OF triggers, if there are any
1424 endOfLoop = sqlite3VdbeMakeLabel(pParse);
1425 if( tmask & TRIGGER_BEFORE ){
1426 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
1428 /* build the NEW.* reference row. Note that if there is an INTEGER
1429 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
1430 ** translated into a unique ID for the row. But on a BEFORE trigger,
1431 ** we do not know what the unique ID will be (because the insert has
1432 ** not happened yet) so we substitute a rowid of -1
1434 if( ipkColumn<0 ){
1435 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1436 }else{
1437 int addr1;
1438 assert( !withoutRowid );
1439 if( useTempTable ){
1440 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
1441 }else{
1442 assert( pSelect==0 ); /* Otherwise useTempTable is true */
1443 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
1445 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
1446 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1447 sqlite3VdbeJumpHere(v, addr1);
1448 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
1451 /* Copy the new data already generated. */
1452 assert( pTab->nNVCol>0 || pParse->nErr>0 );
1453 sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
1455 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1456 /* Compute the new value for generated columns after all other
1457 ** columns have already been computed. This must be done after
1458 ** computing the ROWID in case one of the generated columns
1459 ** refers to the ROWID. */
1460 if( pTab->tabFlags & TF_HasGenerated ){
1461 testcase( pTab->tabFlags & TF_HasVirtual );
1462 testcase( pTab->tabFlags & TF_HasStored );
1463 sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
1465 #endif
1467 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
1468 ** do not attempt any conversions before assembling the record.
1469 ** If this is a real table, attempt conversions as required by the
1470 ** table column affinities.
1472 if( !isView ){
1473 sqlite3TableAffinity(v, pTab, regCols+1);
1476 /* Fire BEFORE or INSTEAD OF triggers */
1477 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
1478 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
1480 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
1483 if( !isView ){
1484 if( IsVirtual(pTab) ){
1485 /* The row that the VUpdate opcode will delete: none */
1486 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
1488 if( ipkColumn>=0 ){
1489 /* Compute the new rowid */
1490 if( useTempTable ){
1491 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
1492 }else if( pSelect ){
1493 /* Rowid already initialized at tag-20191021-001 */
1494 }else{
1495 Expr *pIpk = pList->a[ipkColumn].pExpr;
1496 if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
1497 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1498 appendFlag = 1;
1499 }else{
1500 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
1503 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
1504 ** to generate a unique primary key value.
1506 if( !appendFlag ){
1507 int addr1;
1508 if( !IsVirtual(pTab) ){
1509 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
1510 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1511 sqlite3VdbeJumpHere(v, addr1);
1512 }else{
1513 addr1 = sqlite3VdbeCurrentAddr(v);
1514 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
1516 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
1518 }else if( IsVirtual(pTab) || withoutRowid ){
1519 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
1520 }else{
1521 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1522 appendFlag = 1;
1524 autoIncStep(pParse, regAutoinc, regRowid);
1526 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1527 /* Compute the new value for generated columns after all other
1528 ** columns have already been computed. This must be done after
1529 ** computing the ROWID in case one of the generated columns
1530 ** is derived from the INTEGER PRIMARY KEY. */
1531 if( pTab->tabFlags & TF_HasGenerated ){
1532 sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
1534 #endif
1536 /* Generate code to check constraints and generate index keys and
1537 ** do the insertion.
1539 #ifndef SQLITE_OMIT_VIRTUALTABLE
1540 if( IsVirtual(pTab) ){
1541 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
1542 sqlite3VtabMakeWritable(pParse, pTab);
1543 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1544 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1545 sqlite3MayAbort(pParse);
1546 }else
1547 #endif
1549 int isReplace = 0;/* Set to true if constraints may cause a replace */
1550 int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
1551 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1552 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
1554 if( db->flags & SQLITE_ForeignKeys ){
1555 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
1558 /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
1559 ** constraints or (b) there are no triggers and this table is not a
1560 ** parent table in a foreign key constraint. It is safe to set the
1561 ** flag in the second case as if any REPLACE constraint is hit, an
1562 ** OP_Delete or OP_IdxDelete instruction will be executed on each
1563 ** cursor that is disturbed. And these instructions both clear the
1564 ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
1565 ** functionality. */
1566 bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
1567 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
1568 regIns, aRegIdx, 0, appendFlag, bUseSeek
1571 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
1572 }else if( pParse->bReturning ){
1573 /* If there is a RETURNING clause, populate the rowid register with
1574 ** constant value -1, in case one or more of the returned expressions
1575 ** refer to the "rowid" of the view. */
1576 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
1577 #endif
1580 /* Update the count of rows that are inserted
1582 if( regRowCount ){
1583 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
1586 if( pTrigger ){
1587 /* Code AFTER triggers */
1588 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
1589 pTab, regData-2-pTab->nCol, onError, endOfLoop);
1592 /* The bottom of the main insertion loop, if the data source
1593 ** is a SELECT statement.
1595 sqlite3VdbeResolveLabel(v, endOfLoop);
1596 if( useTempTable ){
1597 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1598 sqlite3VdbeJumpHere(v, addrInsTop);
1599 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1600 }else if( pSelect ){
1601 sqlite3VdbeGoto(v, addrCont);
1602 #ifdef SQLITE_DEBUG
1603 /* If we are jumping back to an OP_Yield that is preceded by an
1604 ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
1605 ** OP_ReleaseReg will be included in the loop. */
1606 if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
1607 assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
1608 sqlite3VdbeChangeP5(v, 1);
1610 #endif
1611 sqlite3VdbeJumpHere(v, addrInsTop);
1614 #ifndef SQLITE_OMIT_XFER_OPT
1615 insert_end:
1616 #endif /* SQLITE_OMIT_XFER_OPT */
1617 /* Update the sqlite_sequence table by storing the content of the
1618 ** maximum rowid counter values recorded while inserting into
1619 ** autoincrement tables.
1621 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
1622 sqlite3AutoincrementEnd(pParse);
1626 ** Return the number of rows inserted. If this routine is
1627 ** generating code because of a call to sqlite3NestedParse(), do not
1628 ** invoke the callback function.
1630 if( regRowCount ){
1631 sqlite3CodeChangeCount(v, regRowCount, "rows inserted");
1634 insert_cleanup:
1635 sqlite3SrcListDelete(db, pTabList);
1636 sqlite3ExprListDelete(db, pList);
1637 sqlite3UpsertDelete(db, pUpsert);
1638 sqlite3SelectDelete(db, pSelect);
1639 sqlite3IdListDelete(db, pColumn);
1640 if( aRegIdx ) sqlite3DbNNFreeNN(db, aRegIdx);
1643 /* Make sure "isView" and other macros defined above are undefined. Otherwise
1644 ** they may interfere with compilation of other functions in this file
1645 ** (or in another file, if this file becomes part of the amalgamation). */
1646 #ifdef isView
1647 #undef isView
1648 #endif
1649 #ifdef pTrigger
1650 #undef pTrigger
1651 #endif
1652 #ifdef tmask
1653 #undef tmask
1654 #endif
1657 ** Meanings of bits in of pWalker->eCode for
1658 ** sqlite3ExprReferencesUpdatedColumn()
1660 #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
1661 #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
1663 /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
1664 * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
1665 ** expression node references any of the
1666 ** columns that are being modified by an UPDATE statement.
1668 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
1669 if( pExpr->op==TK_COLUMN ){
1670 assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
1671 if( pExpr->iColumn>=0 ){
1672 if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
1673 pWalker->eCode |= CKCNSTRNT_COLUMN;
1675 }else{
1676 pWalker->eCode |= CKCNSTRNT_ROWID;
1679 return WRC_Continue;
1683 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
1684 ** only columns that are modified by the UPDATE are those for which
1685 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
1687 ** Return true if CHECK constraint pExpr uses any of the
1688 ** changing columns (or the rowid if it is changing). In other words,
1689 ** return true if this CHECK constraint must be validated for
1690 ** the new row in the UPDATE statement.
1692 ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
1693 ** The operation of this routine is the same - return true if an only if
1694 ** the expression uses one or more of columns identified by the second and
1695 ** third arguments.
1697 int sqlite3ExprReferencesUpdatedColumn(
1698 Expr *pExpr, /* The expression to be checked */
1699 int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */
1700 int chngRowid /* True if UPDATE changes the rowid */
1702 Walker w;
1703 memset(&w, 0, sizeof(w));
1704 w.eCode = 0;
1705 w.xExprCallback = checkConstraintExprNode;
1706 w.u.aiCol = aiChng;
1707 sqlite3WalkExpr(&w, pExpr);
1708 if( !chngRowid ){
1709 testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
1710 w.eCode &= ~CKCNSTRNT_ROWID;
1712 testcase( w.eCode==0 );
1713 testcase( w.eCode==CKCNSTRNT_COLUMN );
1714 testcase( w.eCode==CKCNSTRNT_ROWID );
1715 testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
1716 return w.eCode!=0;
1720 ** The sqlite3GenerateConstraintChecks() routine usually wants to visit
1721 ** the indexes of a table in the order provided in the Table->pIndex list.
1722 ** However, sometimes (rarely - when there is an upsert) it wants to visit
1723 ** the indexes in a different order. The following data structures accomplish
1724 ** this.
1726 ** The IndexIterator object is used to walk through all of the indexes
1727 ** of a table in either Index.pNext order, or in some other order established
1728 ** by an array of IndexListTerm objects.
1730 typedef struct IndexListTerm IndexListTerm;
1731 typedef struct IndexIterator IndexIterator;
1732 struct IndexIterator {
1733 int eType; /* 0 for Index.pNext list. 1 for an array of IndexListTerm */
1734 int i; /* Index of the current item from the list */
1735 union {
1736 struct { /* Use this object for eType==0: A Index.pNext list */
1737 Index *pIdx; /* The current Index */
1738 } lx;
1739 struct { /* Use this object for eType==1; Array of IndexListTerm */
1740 int nIdx; /* Size of the array */
1741 IndexListTerm *aIdx; /* Array of IndexListTerms */
1742 } ax;
1743 } u;
1746 /* When IndexIterator.eType==1, then each index is an array of instances
1747 ** of the following object
1749 struct IndexListTerm {
1750 Index *p; /* The index */
1751 int ix; /* Which entry in the original Table.pIndex list is this index*/
1754 /* Return the first index on the list */
1755 static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){
1756 assert( pIter->i==0 );
1757 if( pIter->eType ){
1758 *pIx = pIter->u.ax.aIdx[0].ix;
1759 return pIter->u.ax.aIdx[0].p;
1760 }else{
1761 *pIx = 0;
1762 return pIter->u.lx.pIdx;
1766 /* Return the next index from the list. Return NULL when out of indexes */
1767 static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){
1768 if( pIter->eType ){
1769 int i = ++pIter->i;
1770 if( i>=pIter->u.ax.nIdx ){
1771 *pIx = i;
1772 return 0;
1774 *pIx = pIter->u.ax.aIdx[i].ix;
1775 return pIter->u.ax.aIdx[i].p;
1776 }else{
1777 ++(*pIx);
1778 pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
1779 return pIter->u.lx.pIdx;
1784 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
1785 ** on table pTab.
1787 ** The regNewData parameter is the first register in a range that contains
1788 ** the data to be inserted or the data after the update. There will be
1789 ** pTab->nCol+1 registers in this range. The first register (the one
1790 ** that regNewData points to) will contain the new rowid, or NULL in the
1791 ** case of a WITHOUT ROWID table. The second register in the range will
1792 ** contain the content of the first table column. The third register will
1793 ** contain the content of the second table column. And so forth.
1795 ** The regOldData parameter is similar to regNewData except that it contains
1796 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
1797 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
1798 ** checking regOldData for zero.
1800 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1801 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1802 ** might be modified by the UPDATE. If pkChng is false, then the key of
1803 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1805 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1806 ** was explicitly specified as part of the INSERT statement. If pkChng
1807 ** is zero, it means that the either rowid is computed automatically or
1808 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
1809 ** pkChng will only be true if the INSERT statement provides an integer
1810 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
1812 ** The code generated by this routine will store new index entries into
1813 ** registers identified by aRegIdx[]. No index entry is created for
1814 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1815 ** the same as the order of indices on the linked list of indices
1816 ** at pTab->pIndex.
1818 ** (2019-05-07) The generated code also creates a new record for the
1819 ** main table, if pTab is a rowid table, and stores that record in the
1820 ** register identified by aRegIdx[nIdx] - in other words in the first
1821 ** entry of aRegIdx[] past the last index. It is important that the
1822 ** record be generated during constraint checks to avoid affinity changes
1823 ** to the register content that occur after constraint checks but before
1824 ** the new record is inserted.
1826 ** The caller must have already opened writeable cursors on the main
1827 ** table and all applicable indices (that is to say, all indices for which
1828 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
1829 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
1830 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
1831 ** for the first index in the pTab->pIndex list. Cursors for other indices
1832 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
1834 ** This routine also generates code to check constraints. NOT NULL,
1835 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
1836 ** then the appropriate action is performed. There are five possible
1837 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
1839 ** Constraint type Action What Happens
1840 ** --------------- ---------- ----------------------------------------
1841 ** any ROLLBACK The current transaction is rolled back and
1842 ** sqlite3_step() returns immediately with a
1843 ** return code of SQLITE_CONSTRAINT.
1845 ** any ABORT Back out changes from the current command
1846 ** only (do not do a complete rollback) then
1847 ** cause sqlite3_step() to return immediately
1848 ** with SQLITE_CONSTRAINT.
1850 ** any FAIL Sqlite3_step() returns immediately with a
1851 ** return code of SQLITE_CONSTRAINT. The
1852 ** transaction is not rolled back and any
1853 ** changes to prior rows are retained.
1855 ** any IGNORE The attempt in insert or update the current
1856 ** row is skipped, without throwing an error.
1857 ** Processing continues with the next row.
1858 ** (There is an immediate jump to ignoreDest.)
1860 ** NOT NULL REPLACE The NULL value is replace by the default
1861 ** value for that column. If the default value
1862 ** is NULL, the action is the same as ABORT.
1864 ** UNIQUE REPLACE The other row that conflicts with the row
1865 ** being inserted is removed.
1867 ** CHECK REPLACE Illegal. The results in an exception.
1869 ** Which action to take is determined by the overrideError parameter.
1870 ** Or if overrideError==OE_Default, then the pParse->onError parameter
1871 ** is used. Or if pParse->onError==OE_Default then the onError value
1872 ** for the constraint is used.
1874 void sqlite3GenerateConstraintChecks(
1875 Parse *pParse, /* The parser context */
1876 Table *pTab, /* The table being inserted or updated */
1877 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
1878 int iDataCur, /* Canonical data cursor (main table or PK index) */
1879 int iIdxCur, /* First index cursor */
1880 int regNewData, /* First register in a range holding values to insert */
1881 int regOldData, /* Previous content. 0 for INSERTs */
1882 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
1883 u8 overrideError, /* Override onError to this if not OE_Default */
1884 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
1885 int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
1886 int *aiChng, /* column i is unchanged if aiChng[i]<0 */
1887 Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
1889 Vdbe *v; /* VDBE under construction */
1890 Index *pIdx; /* Pointer to one of the indices */
1891 Index *pPk = 0; /* The PRIMARY KEY index for WITHOUT ROWID tables */
1892 sqlite3 *db; /* Database connection */
1893 int i; /* loop counter */
1894 int ix; /* Index loop counter */
1895 int nCol; /* Number of columns */
1896 int onError; /* Conflict resolution strategy */
1897 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
1898 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
1899 Upsert *pUpsertClause = 0; /* The specific ON CONFLICT clause for pIdx */
1900 u8 isUpdate; /* True if this is an UPDATE operation */
1901 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
1902 int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */
1903 int upsertIpkDelay = 0; /* Address of Goto to bypass initial IPK check */
1904 int ipkTop = 0; /* Top of the IPK uniqueness check */
1905 int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */
1906 /* Variables associated with retesting uniqueness constraints after
1907 ** replace triggers fire have run */
1908 int regTrigCnt; /* Register used to count replace trigger invocations */
1909 int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */
1910 int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
1911 Trigger *pTrigger; /* List of DELETE triggers on the table pTab */
1912 int nReplaceTrig = 0; /* Number of replace triggers coded */
1913 IndexIterator sIdxIter; /* Index iterator */
1915 isUpdate = regOldData!=0;
1916 db = pParse->db;
1917 v = pParse->pVdbe;
1918 assert( v!=0 );
1919 assert( !IsView(pTab) ); /* This table is not a VIEW */
1920 nCol = pTab->nCol;
1922 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
1923 ** normal rowid tables. nPkField is the number of key fields in the
1924 ** pPk index or 1 for a rowid table. In other words, nPkField is the
1925 ** number of fields in the true primary key of the table. */
1926 if( HasRowid(pTab) ){
1927 pPk = 0;
1928 nPkField = 1;
1929 }else{
1930 pPk = sqlite3PrimaryKeyIndex(pTab);
1931 nPkField = pPk->nKeyCol;
1934 /* Record that this module has started */
1935 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
1936 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
1938 /* Test all NOT NULL constraints.
1940 if( pTab->tabFlags & TF_HasNotNull ){
1941 int b2ndPass = 0; /* True if currently running 2nd pass */
1942 int nSeenReplace = 0; /* Number of ON CONFLICT REPLACE operations */
1943 int nGenerated = 0; /* Number of generated columns with NOT NULL */
1944 while(1){ /* Make 2 passes over columns. Exit loop via "break" */
1945 for(i=0; i<nCol; i++){
1946 int iReg; /* Register holding column value */
1947 Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */
1948 int isGenerated; /* non-zero if column is generated */
1949 onError = pCol->notNull;
1950 if( onError==OE_None ) continue; /* No NOT NULL on this column */
1951 if( i==pTab->iPKey ){
1952 continue; /* ROWID is never NULL */
1954 isGenerated = pCol->colFlags & COLFLAG_GENERATED;
1955 if( isGenerated && !b2ndPass ){
1956 nGenerated++;
1957 continue; /* Generated columns processed on 2nd pass */
1959 if( aiChng && aiChng[i]<0 && !isGenerated ){
1960 /* Do not check NOT NULL on columns that do not change */
1961 continue;
1963 if( overrideError!=OE_Default ){
1964 onError = overrideError;
1965 }else if( onError==OE_Default ){
1966 onError = OE_Abort;
1968 if( onError==OE_Replace ){
1969 if( b2ndPass /* REPLACE becomes ABORT on the 2nd pass */
1970 || pCol->iDflt==0 /* REPLACE is ABORT if no DEFAULT value */
1972 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1973 testcase( pCol->colFlags & COLFLAG_STORED );
1974 testcase( pCol->colFlags & COLFLAG_GENERATED );
1975 onError = OE_Abort;
1976 }else{
1977 assert( !isGenerated );
1979 }else if( b2ndPass && !isGenerated ){
1980 continue;
1982 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1983 || onError==OE_Ignore || onError==OE_Replace );
1984 testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
1985 iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
1986 switch( onError ){
1987 case OE_Replace: {
1988 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
1989 VdbeCoverage(v);
1990 assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
1991 nSeenReplace++;
1992 sqlite3ExprCodeCopy(pParse,
1993 sqlite3ColumnExpr(pTab, pCol), iReg);
1994 sqlite3VdbeJumpHere(v, addr1);
1995 break;
1997 case OE_Abort:
1998 sqlite3MayAbort(pParse);
1999 /* no break */ deliberate_fall_through
2000 case OE_Rollback:
2001 case OE_Fail: {
2002 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
2003 pCol->zCnName);
2004 testcase( zMsg==0 && db->mallocFailed==0 );
2005 sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
2006 onError, iReg);
2007 sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
2008 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
2009 VdbeCoverage(v);
2010 break;
2012 default: {
2013 assert( onError==OE_Ignore );
2014 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
2015 VdbeCoverage(v);
2016 break;
2018 } /* end switch(onError) */
2019 } /* end loop i over columns */
2020 if( nGenerated==0 && nSeenReplace==0 ){
2021 /* If there are no generated columns with NOT NULL constraints
2022 ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
2023 ** pass is sufficient */
2024 break;
2026 if( b2ndPass ) break; /* Never need more than 2 passes */
2027 b2ndPass = 1;
2028 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2029 if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
2030 /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
2031 ** first pass, recomputed values for all generated columns, as
2032 ** those values might depend on columns affected by the REPLACE.
2034 sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
2036 #endif
2037 } /* end of 2-pass loop */
2038 } /* end if( has-not-null-constraints ) */
2040 /* Test all CHECK constraints
2042 #ifndef SQLITE_OMIT_CHECK
2043 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
2044 ExprList *pCheck = pTab->pCheck;
2045 pParse->iSelfTab = -(regNewData+1);
2046 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
2047 for(i=0; i<pCheck->nExpr; i++){
2048 int allOk;
2049 Expr *pCopy;
2050 Expr *pExpr = pCheck->a[i].pExpr;
2051 if( aiChng
2052 && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
2054 /* The check constraints do not reference any of the columns being
2055 ** updated so there is no point it verifying the check constraint */
2056 continue;
2058 if( bAffinityDone==0 ){
2059 sqlite3TableAffinity(v, pTab, regNewData+1);
2060 bAffinityDone = 1;
2062 allOk = sqlite3VdbeMakeLabel(pParse);
2063 sqlite3VdbeVerifyAbortable(v, onError);
2064 pCopy = sqlite3ExprDup(db, pExpr, 0);
2065 if( !db->mallocFailed ){
2066 sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
2068 sqlite3ExprDelete(db, pCopy);
2069 if( onError==OE_Ignore ){
2070 sqlite3VdbeGoto(v, ignoreDest);
2071 }else{
2072 char *zName = pCheck->a[i].zEName;
2073 assert( zName!=0 || pParse->db->mallocFailed );
2074 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
2075 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
2076 onError, zName, P4_TRANSIENT,
2077 P5_ConstraintCheck);
2079 sqlite3VdbeResolveLabel(v, allOk);
2081 pParse->iSelfTab = 0;
2083 #endif /* !defined(SQLITE_OMIT_CHECK) */
2085 /* UNIQUE and PRIMARY KEY constraints should be handled in the following
2086 ** order:
2088 ** (1) OE_Update
2089 ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
2090 ** (3) OE_Replace
2092 ** OE_Fail and OE_Ignore must happen before any changes are made.
2093 ** OE_Update guarantees that only a single row will change, so it
2094 ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
2095 ** could happen in any order, but they are grouped up front for
2096 ** convenience.
2098 ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
2099 ** The order of constraints used to have OE_Update as (2) and OE_Abort
2100 ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
2101 ** constraint before any others, so it had to be moved.
2103 ** Constraint checking code is generated in this order:
2104 ** (A) The rowid constraint
2105 ** (B) Unique index constraints that do not have OE_Replace as their
2106 ** default conflict resolution strategy
2107 ** (C) Unique index that do use OE_Replace by default.
2109 ** The ordering of (2) and (3) is accomplished by making sure the linked
2110 ** list of indexes attached to a table puts all OE_Replace indexes last
2111 ** in the list. See sqlite3CreateIndex() for where that happens.
2113 sIdxIter.eType = 0;
2114 sIdxIter.i = 0;
2115 sIdxIter.u.ax.aIdx = 0; /* Silence harmless compiler warning */
2116 sIdxIter.u.lx.pIdx = pTab->pIndex;
2117 if( pUpsert ){
2118 if( pUpsert->pUpsertTarget==0 ){
2119 /* There is just on ON CONFLICT clause and it has no constraint-target */
2120 assert( pUpsert->pNextUpsert==0 );
2121 if( pUpsert->isDoUpdate==0 ){
2122 /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
2123 ** Make all unique constraint resolution be OE_Ignore */
2124 overrideError = OE_Ignore;
2125 pUpsert = 0;
2126 }else{
2127 /* A single ON CONFLICT DO UPDATE. Make all resolutions OE_Update */
2128 overrideError = OE_Update;
2130 }else if( pTab->pIndex!=0 ){
2131 /* Otherwise, we'll need to run the IndexListTerm array version of the
2132 ** iterator to ensure that all of the ON CONFLICT conditions are
2133 ** checked first and in order. */
2134 int nIdx, jj;
2135 u64 nByte;
2136 Upsert *pTerm;
2137 u8 *bUsed;
2138 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
2139 assert( aRegIdx[nIdx]>0 );
2141 sIdxIter.eType = 1;
2142 sIdxIter.u.ax.nIdx = nIdx;
2143 nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx;
2144 sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte);
2145 if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */
2146 bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx];
2147 pUpsert->pToFree = sIdxIter.u.ax.aIdx;
2148 for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
2149 if( pTerm->pUpsertTarget==0 ) break;
2150 if( pTerm->pUpsertIdx==0 ) continue; /* Skip ON CONFLICT for the IPK */
2151 jj = 0;
2152 pIdx = pTab->pIndex;
2153 while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
2154 pIdx = pIdx->pNext;
2155 jj++;
2157 if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */
2158 bUsed[jj] = 1;
2159 sIdxIter.u.ax.aIdx[i].p = pIdx;
2160 sIdxIter.u.ax.aIdx[i].ix = jj;
2161 i++;
2163 for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
2164 if( bUsed[jj] ) continue;
2165 sIdxIter.u.ax.aIdx[i].p = pIdx;
2166 sIdxIter.u.ax.aIdx[i].ix = jj;
2167 i++;
2169 assert( i==nIdx );
2173 /* Determine if it is possible that triggers (either explicitly coded
2174 ** triggers or FK resolution actions) might run as a result of deletes
2175 ** that happen when OE_Replace conflict resolution occurs. (Call these
2176 ** "replace triggers".) If any replace triggers run, we will need to
2177 ** recheck all of the uniqueness constraints after they have all run.
2178 ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
2180 ** If replace triggers are a possibility, then
2182 ** (1) Allocate register regTrigCnt and initialize it to zero.
2183 ** That register will count the number of replace triggers that
2184 ** fire. Constraint recheck only occurs if the number is positive.
2185 ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
2186 ** (3) Initialize addrRecheck and lblRecheckOk
2188 ** The uniqueness rechecking code will create a series of tests to run
2189 ** in a second pass. The addrRecheck and lblRecheckOk variables are
2190 ** used to link together these tests which are separated from each other
2191 ** in the generate bytecode.
2193 if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
2194 /* There are not DELETE triggers nor FK constraints. No constraint
2195 ** rechecks are needed. */
2196 pTrigger = 0;
2197 regTrigCnt = 0;
2198 }else{
2199 if( db->flags&SQLITE_RecTriggers ){
2200 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
2201 regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
2202 }else{
2203 pTrigger = 0;
2204 regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
2206 if( regTrigCnt ){
2207 /* Replace triggers might exist. Allocate the counter and
2208 ** initialize it to zero. */
2209 regTrigCnt = ++pParse->nMem;
2210 sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
2211 VdbeComment((v, "trigger count"));
2212 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2213 addrRecheck = lblRecheckOk;
2217 /* If rowid is changing, make sure the new rowid does not previously
2218 ** exist in the table.
2220 if( pkChng && pPk==0 ){
2221 int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
2223 /* Figure out what action to take in case of a rowid collision */
2224 onError = pTab->keyConf;
2225 if( overrideError!=OE_Default ){
2226 onError = overrideError;
2227 }else if( onError==OE_Default ){
2228 onError = OE_Abort;
2231 /* figure out whether or not upsert applies in this case */
2232 if( pUpsert ){
2233 pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0);
2234 if( pUpsertClause!=0 ){
2235 if( pUpsertClause->isDoUpdate==0 ){
2236 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
2237 }else{
2238 onError = OE_Update; /* DO UPDATE */
2241 if( pUpsertClause!=pUpsert ){
2242 /* The first ON CONFLICT clause has a conflict target other than
2243 ** the IPK. We have to jump ahead to that first ON CONFLICT clause
2244 ** and then come back here and deal with the IPK afterwards */
2245 upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto);
2249 /* If the response to a rowid conflict is REPLACE but the response
2250 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
2251 ** to defer the running of the rowid conflict checking until after
2252 ** the UNIQUE constraints have run.
2254 if( onError==OE_Replace /* IPK rule is REPLACE */
2255 && onError!=overrideError /* Rules for other constraints are different */
2256 && pTab->pIndex /* There exist other constraints */
2257 && !upsertIpkDelay /* IPK check already deferred by UPSERT */
2259 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
2260 VdbeComment((v, "defer IPK REPLACE until last"));
2263 if( isUpdate ){
2264 /* pkChng!=0 does not mean that the rowid has changed, only that
2265 ** it might have changed. Skip the conflict logic below if the rowid
2266 ** is unchanged. */
2267 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
2268 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2269 VdbeCoverage(v);
2272 /* Check to see if the new rowid already exists in the table. Skip
2273 ** the following conflict logic if it does not. */
2274 VdbeNoopComment((v, "uniqueness check for ROWID"));
2275 sqlite3VdbeVerifyAbortable(v, onError);
2276 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
2277 VdbeCoverage(v);
2279 switch( onError ){
2280 default: {
2281 onError = OE_Abort;
2282 /* no break */ deliberate_fall_through
2284 case OE_Rollback:
2285 case OE_Abort:
2286 case OE_Fail: {
2287 testcase( onError==OE_Rollback );
2288 testcase( onError==OE_Abort );
2289 testcase( onError==OE_Fail );
2290 sqlite3RowidConstraint(pParse, onError, pTab);
2291 break;
2293 case OE_Replace: {
2294 /* If there are DELETE triggers on this table and the
2295 ** recursive-triggers flag is set, call GenerateRowDelete() to
2296 ** remove the conflicting row from the table. This will fire
2297 ** the triggers and remove both the table and index b-tree entries.
2299 ** Otherwise, if there are no triggers or the recursive-triggers
2300 ** flag is not set, but the table has one or more indexes, call
2301 ** GenerateRowIndexDelete(). This removes the index b-tree entries
2302 ** only. The table b-tree entry will be replaced by the new entry
2303 ** when it is inserted.
2305 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
2306 ** also invoke MultiWrite() to indicate that this VDBE may require
2307 ** statement rollback (if the statement is aborted after the delete
2308 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
2309 ** but being more selective here allows statements like:
2311 ** REPLACE INTO t(rowid) VALUES($newrowid)
2313 ** to run without a statement journal if there are no indexes on the
2314 ** table.
2316 if( regTrigCnt ){
2317 sqlite3MultiWrite(pParse);
2318 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2319 regNewData, 1, 0, OE_Replace, 1, -1);
2320 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2321 nReplaceTrig++;
2322 }else{
2323 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2324 assert( HasRowid(pTab) );
2325 /* This OP_Delete opcode fires the pre-update-hook only. It does
2326 ** not modify the b-tree. It is more efficient to let the coming
2327 ** OP_Insert replace the existing entry than it is to delete the
2328 ** existing entry and then insert a new one. */
2329 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
2330 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
2331 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2332 if( pTab->pIndex ){
2333 sqlite3MultiWrite(pParse);
2334 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
2337 seenReplace = 1;
2338 break;
2340 #ifndef SQLITE_OMIT_UPSERT
2341 case OE_Update: {
2342 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
2343 /* no break */ deliberate_fall_through
2345 #endif
2346 case OE_Ignore: {
2347 testcase( onError==OE_Ignore );
2348 sqlite3VdbeGoto(v, ignoreDest);
2349 break;
2352 sqlite3VdbeResolveLabel(v, addrRowidOk);
2353 if( pUpsert && pUpsertClause!=pUpsert ){
2354 upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
2355 }else if( ipkTop ){
2356 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
2357 sqlite3VdbeJumpHere(v, ipkTop-1);
2361 /* Test all UNIQUE constraints by creating entries for each UNIQUE
2362 ** index and making sure that duplicate entries do not already exist.
2363 ** Compute the revised record entries for indices as we go.
2365 ** This loop also handles the case of the PRIMARY KEY index for a
2366 ** WITHOUT ROWID table.
2368 for(pIdx = indexIteratorFirst(&sIdxIter, &ix);
2369 pIdx;
2370 pIdx = indexIteratorNext(&sIdxIter, &ix)
2372 int regIdx; /* Range of registers holding content for pIdx */
2373 int regR; /* Range of registers holding conflicting PK */
2374 int iThisCur; /* Cursor for this UNIQUE index */
2375 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
2376 int addrConflictCk; /* First opcode in the conflict check logic */
2378 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
2379 if( pUpsert ){
2380 pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
2381 if( upsertIpkDelay && pUpsertClause==pUpsert ){
2382 sqlite3VdbeJumpHere(v, upsertIpkDelay);
2385 addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
2386 if( bAffinityDone==0 ){
2387 sqlite3TableAffinity(v, pTab, regNewData+1);
2388 bAffinityDone = 1;
2390 VdbeNoopComment((v, "prep index %s", pIdx->zName));
2391 iThisCur = iIdxCur+ix;
2394 /* Skip partial indices for which the WHERE clause is not true */
2395 if( pIdx->pPartIdxWhere ){
2396 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
2397 pParse->iSelfTab = -(regNewData+1);
2398 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
2399 SQLITE_JUMPIFNULL);
2400 pParse->iSelfTab = 0;
2403 /* Create a record for this index entry as it should appear after
2404 ** the insert or update. Store that record in the aRegIdx[ix] register
2406 regIdx = aRegIdx[ix]+1;
2407 for(i=0; i<pIdx->nColumn; i++){
2408 int iField = pIdx->aiColumn[i];
2409 int x;
2410 if( iField==XN_EXPR ){
2411 pParse->iSelfTab = -(regNewData+1);
2412 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
2413 pParse->iSelfTab = 0;
2414 VdbeComment((v, "%s column %d", pIdx->zName, i));
2415 }else if( iField==XN_ROWID || iField==pTab->iPKey ){
2416 x = regNewData;
2417 sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
2418 VdbeComment((v, "rowid"));
2419 }else{
2420 testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
2421 x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
2422 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
2423 VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
2426 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
2427 VdbeComment((v, "for %s", pIdx->zName));
2428 #ifdef SQLITE_ENABLE_NULL_TRIM
2429 if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
2430 sqlite3SetMakeRecordP5(v, pIdx->pTable);
2432 #endif
2433 sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
2435 /* In an UPDATE operation, if this index is the PRIMARY KEY index
2436 ** of a WITHOUT ROWID table and there has been no change the
2437 ** primary key, then no collision is possible. The collision detection
2438 ** logic below can all be skipped. */
2439 if( isUpdate && pPk==pIdx && pkChng==0 ){
2440 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2441 continue;
2444 /* Find out what action to take in case there is a uniqueness conflict */
2445 onError = pIdx->onError;
2446 if( onError==OE_None ){
2447 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2448 continue; /* pIdx is not a UNIQUE index */
2450 if( overrideError!=OE_Default ){
2451 onError = overrideError;
2452 }else if( onError==OE_Default ){
2453 onError = OE_Abort;
2456 /* Figure out if the upsert clause applies to this index */
2457 if( pUpsertClause ){
2458 if( pUpsertClause->isDoUpdate==0 ){
2459 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
2460 }else{
2461 onError = OE_Update; /* DO UPDATE */
2465 /* Collision detection may be omitted if all of the following are true:
2466 ** (1) The conflict resolution algorithm is REPLACE
2467 ** (2) The table is a WITHOUT ROWID table
2468 ** (3) There are no secondary indexes on the table
2469 ** (4) No delete triggers need to be fired if there is a conflict
2470 ** (5) No FK constraint counters need to be updated if a conflict occurs.
2472 ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
2473 ** must be explicitly deleted in order to ensure any pre-update hook
2474 ** is invoked. */
2475 assert( IsOrdinaryTable(pTab) );
2476 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
2477 if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
2478 && pPk==pIdx /* Condition 2 */
2479 && onError==OE_Replace /* Condition 1 */
2480 && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
2481 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
2482 && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
2483 (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
2485 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2486 continue;
2488 #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
2490 /* Check to see if the new index entry will be unique */
2491 sqlite3VdbeVerifyAbortable(v, onError);
2492 addrConflictCk =
2493 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
2494 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
2496 /* Generate code to handle collisions */
2497 regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField);
2498 if( isUpdate || onError==OE_Replace ){
2499 if( HasRowid(pTab) ){
2500 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
2501 /* Conflict only if the rowid of the existing index entry
2502 ** is different from old-rowid */
2503 if( isUpdate ){
2504 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
2505 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2506 VdbeCoverage(v);
2508 }else{
2509 int x;
2510 /* Extract the PRIMARY KEY from the end of the index entry and
2511 ** store it in registers regR..regR+nPk-1 */
2512 if( pIdx!=pPk ){
2513 for(i=0; i<pPk->nKeyCol; i++){
2514 assert( pPk->aiColumn[i]>=0 );
2515 x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
2516 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
2517 VdbeComment((v, "%s.%s", pTab->zName,
2518 pTab->aCol[pPk->aiColumn[i]].zCnName));
2521 if( isUpdate ){
2522 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
2523 ** table, only conflict if the new PRIMARY KEY values are actually
2524 ** different from the old. See TH3 withoutrowid04.test.
2526 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
2527 ** of the matched index row are different from the original PRIMARY
2528 ** KEY values of this row before the update. */
2529 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
2530 int op = OP_Ne;
2531 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
2533 for(i=0; i<pPk->nKeyCol; i++){
2534 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
2535 x = pPk->aiColumn[i];
2536 assert( x>=0 );
2537 if( i==(pPk->nKeyCol-1) ){
2538 addrJump = addrUniqueOk;
2539 op = OP_Eq;
2541 x = sqlite3TableColumnToStorage(pTab, x);
2542 sqlite3VdbeAddOp4(v, op,
2543 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
2545 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2546 VdbeCoverageIf(v, op==OP_Eq);
2547 VdbeCoverageIf(v, op==OP_Ne);
2553 /* Generate code that executes if the new index entry is not unique */
2554 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
2555 || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
2556 switch( onError ){
2557 case OE_Rollback:
2558 case OE_Abort:
2559 case OE_Fail: {
2560 testcase( onError==OE_Rollback );
2561 testcase( onError==OE_Abort );
2562 testcase( onError==OE_Fail );
2563 sqlite3UniqueConstraint(pParse, onError, pIdx);
2564 break;
2566 #ifndef SQLITE_OMIT_UPSERT
2567 case OE_Update: {
2568 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
2569 /* no break */ deliberate_fall_through
2571 #endif
2572 case OE_Ignore: {
2573 testcase( onError==OE_Ignore );
2574 sqlite3VdbeGoto(v, ignoreDest);
2575 break;
2577 default: {
2578 int nConflictCk; /* Number of opcodes in conflict check logic */
2580 assert( onError==OE_Replace );
2581 nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
2582 assert( nConflictCk>0 || db->mallocFailed );
2583 testcase( nConflictCk<=0 );
2584 testcase( nConflictCk>1 );
2585 if( regTrigCnt ){
2586 sqlite3MultiWrite(pParse);
2587 nReplaceTrig++;
2589 if( pTrigger && isUpdate ){
2590 sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
2592 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2593 regR, nPkField, 0, OE_Replace,
2594 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
2595 if( pTrigger && isUpdate ){
2596 sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
2598 if( regTrigCnt ){
2599 int addrBypass; /* Jump destination to bypass recheck logic */
2601 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2602 addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
2603 VdbeComment((v, "bypass recheck"));
2605 /* Here we insert code that will be invoked after all constraint
2606 ** checks have run, if and only if one or more replace triggers
2607 ** fired. */
2608 sqlite3VdbeResolveLabel(v, lblRecheckOk);
2609 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2610 if( pIdx->pPartIdxWhere ){
2611 /* Bypass the recheck if this partial index is not defined
2612 ** for the current row */
2613 sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
2614 VdbeCoverage(v);
2616 /* Copy the constraint check code from above, except change
2617 ** the constraint-ok jump destination to be the address of
2618 ** the next retest block */
2619 while( nConflictCk>0 ){
2620 VdbeOp x; /* Conflict check opcode to copy */
2621 /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
2622 ** Hence, make a complete copy of the opcode, rather than using
2623 ** a pointer to the opcode. */
2624 x = *sqlite3VdbeGetOp(v, addrConflictCk);
2625 if( x.opcode!=OP_IdxRowid ){
2626 int p2; /* New P2 value for copied conflict check opcode */
2627 const char *zP4;
2628 if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
2629 p2 = lblRecheckOk;
2630 }else{
2631 p2 = x.p2;
2633 zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
2634 sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
2635 sqlite3VdbeChangeP5(v, x.p5);
2636 VdbeCoverageIf(v, p2!=x.p2);
2638 nConflictCk--;
2639 addrConflictCk++;
2641 /* If the retest fails, issue an abort */
2642 sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
2644 sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
2646 seenReplace = 1;
2647 break;
2650 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2651 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
2652 if( pUpsertClause
2653 && upsertIpkReturn
2654 && sqlite3UpsertNextIsIPK(pUpsertClause)
2656 sqlite3VdbeGoto(v, upsertIpkDelay+1);
2657 sqlite3VdbeJumpHere(v, upsertIpkReturn);
2658 upsertIpkReturn = 0;
2662 /* If the IPK constraint is a REPLACE, run it last */
2663 if( ipkTop ){
2664 sqlite3VdbeGoto(v, ipkTop);
2665 VdbeComment((v, "Do IPK REPLACE"));
2666 assert( ipkBottom>0 );
2667 sqlite3VdbeJumpHere(v, ipkBottom);
2670 /* Recheck all uniqueness constraints after replace triggers have run */
2671 testcase( regTrigCnt!=0 && nReplaceTrig==0 );
2672 assert( regTrigCnt!=0 || nReplaceTrig==0 );
2673 if( nReplaceTrig ){
2674 sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
2675 if( !pPk ){
2676 if( isUpdate ){
2677 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
2678 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2679 VdbeCoverage(v);
2681 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
2682 VdbeCoverage(v);
2683 sqlite3RowidConstraint(pParse, OE_Abort, pTab);
2684 }else{
2685 sqlite3VdbeGoto(v, addrRecheck);
2687 sqlite3VdbeResolveLabel(v, lblRecheckOk);
2690 /* Generate the table record */
2691 if( HasRowid(pTab) ){
2692 int regRec = aRegIdx[ix];
2693 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
2694 sqlite3SetMakeRecordP5(v, pTab);
2695 if( !bAffinityDone ){
2696 sqlite3TableAffinity(v, pTab, 0);
2700 *pbMayReplace = seenReplace;
2701 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
2704 #ifdef SQLITE_ENABLE_NULL_TRIM
2706 ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
2707 ** to be the number of columns in table pTab that must not be NULL-trimmed.
2709 ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
2711 void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
2712 u16 i;
2714 /* Records with omitted columns are only allowed for schema format
2715 ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
2716 if( pTab->pSchema->file_format<2 ) return;
2718 for(i=pTab->nCol-1; i>0; i--){
2719 if( pTab->aCol[i].iDflt!=0 ) break;
2720 if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
2722 sqlite3VdbeChangeP5(v, i+1);
2724 #endif
2727 ** Table pTab is a WITHOUT ROWID table that is being written to. The cursor
2728 ** number is iCur, and register regData contains the new record for the
2729 ** PK index. This function adds code to invoke the pre-update hook,
2730 ** if one is registered.
2732 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2733 static void codeWithoutRowidPreupdate(
2734 Parse *pParse, /* Parse context */
2735 Table *pTab, /* Table being updated */
2736 int iCur, /* Cursor number for table */
2737 int regData /* Data containing new record */
2739 Vdbe *v = pParse->pVdbe;
2740 int r = sqlite3GetTempReg(pParse);
2741 assert( !HasRowid(pTab) );
2742 assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
2743 sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
2744 sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE);
2745 sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
2746 sqlite3ReleaseTempReg(pParse, r);
2748 #else
2749 # define codeWithoutRowidPreupdate(a,b,c,d)
2750 #endif
2753 ** This routine generates code to finish the INSERT or UPDATE operation
2754 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
2755 ** A consecutive range of registers starting at regNewData contains the
2756 ** rowid and the content to be inserted.
2758 ** The arguments to this routine should be the same as the first six
2759 ** arguments to sqlite3GenerateConstraintChecks.
2761 void sqlite3CompleteInsertion(
2762 Parse *pParse, /* The parser context */
2763 Table *pTab, /* the table into which we are inserting */
2764 int iDataCur, /* Cursor of the canonical data source */
2765 int iIdxCur, /* First index cursor */
2766 int regNewData, /* Range of content */
2767 int *aRegIdx, /* Register used by each index. 0 for unused indices */
2768 int update_flags, /* True for UPDATE, False for INSERT */
2769 int appendBias, /* True if this is likely to be an append */
2770 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
2772 Vdbe *v; /* Prepared statements under construction */
2773 Index *pIdx; /* An index being inserted or updated */
2774 u8 pik_flags; /* flag values passed to the btree insert */
2775 int i; /* Loop counter */
2777 assert( update_flags==0
2778 || update_flags==OPFLAG_ISUPDATE
2779 || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
2782 v = pParse->pVdbe;
2783 assert( v!=0 );
2784 assert( !IsView(pTab) ); /* This table is not a VIEW */
2785 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2786 /* All REPLACE indexes are at the end of the list */
2787 assert( pIdx->onError!=OE_Replace
2788 || pIdx->pNext==0
2789 || pIdx->pNext->onError==OE_Replace );
2790 if( aRegIdx[i]==0 ) continue;
2791 if( pIdx->pPartIdxWhere ){
2792 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
2793 VdbeCoverage(v);
2795 pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
2796 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2797 pik_flags |= OPFLAG_NCHANGE;
2798 pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
2799 if( update_flags==0 ){
2800 codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]);
2803 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
2804 aRegIdx[i]+1,
2805 pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
2806 sqlite3VdbeChangeP5(v, pik_flags);
2808 if( !HasRowid(pTab) ) return;
2809 if( pParse->nested ){
2810 pik_flags = 0;
2811 }else{
2812 pik_flags = OPFLAG_NCHANGE;
2813 pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
2815 if( appendBias ){
2816 pik_flags |= OPFLAG_APPEND;
2818 if( useSeekResult ){
2819 pik_flags |= OPFLAG_USESEEKRESULT;
2821 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
2822 if( !pParse->nested ){
2823 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
2825 sqlite3VdbeChangeP5(v, pik_flags);
2829 ** Allocate cursors for the pTab table and all its indices and generate
2830 ** code to open and initialized those cursors.
2832 ** The cursor for the object that contains the complete data (normally
2833 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
2834 ** ROWID table) is returned in *piDataCur. The first index cursor is
2835 ** returned in *piIdxCur. The number of indices is returned.
2837 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
2838 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
2839 ** If iBase is negative, then allocate the next available cursor.
2841 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
2842 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
2843 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
2844 ** pTab->pIndex list.
2846 ** If pTab is a virtual table, then this routine is a no-op and the
2847 ** *piDataCur and *piIdxCur values are left uninitialized.
2849 int sqlite3OpenTableAndIndices(
2850 Parse *pParse, /* Parsing context */
2851 Table *pTab, /* Table to be opened */
2852 int op, /* OP_OpenRead or OP_OpenWrite */
2853 u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
2854 int iBase, /* Use this for the table cursor, if there is one */
2855 u8 *aToOpen, /* If not NULL: boolean for each table and index */
2856 int *piDataCur, /* Write the database source cursor number here */
2857 int *piIdxCur /* Write the first index cursor number here */
2859 int i;
2860 int iDb;
2861 int iDataCur;
2862 Index *pIdx;
2863 Vdbe *v;
2865 assert( op==OP_OpenRead || op==OP_OpenWrite );
2866 assert( op==OP_OpenWrite || p5==0 );
2867 assert( piDataCur!=0 );
2868 assert( piIdxCur!=0 );
2869 if( IsVirtual(pTab) ){
2870 /* This routine is a no-op for virtual tables. Leave the output
2871 ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
2872 ** for improved error detection. */
2873 *piDataCur = *piIdxCur = -999;
2874 return 0;
2876 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2877 v = pParse->pVdbe;
2878 assert( v!=0 );
2879 if( iBase<0 ) iBase = pParse->nTab;
2880 iDataCur = iBase++;
2881 *piDataCur = iDataCur;
2882 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
2883 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
2884 }else if( pParse->db->noSharedCache==0 ){
2885 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
2887 *piIdxCur = iBase;
2888 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2889 int iIdxCur = iBase++;
2890 assert( pIdx->pSchema==pTab->pSchema );
2891 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2892 *piDataCur = iIdxCur;
2893 p5 = 0;
2895 if( aToOpen==0 || aToOpen[i+1] ){
2896 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
2897 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2898 sqlite3VdbeChangeP5(v, p5);
2899 VdbeComment((v, "%s", pIdx->zName));
2902 if( iBase>pParse->nTab ) pParse->nTab = iBase;
2903 return i;
2907 #ifdef SQLITE_TEST
2909 ** The following global variable is incremented whenever the
2910 ** transfer optimization is used. This is used for testing
2911 ** purposes only - to make sure the transfer optimization really
2912 ** is happening when it is supposed to.
2914 int sqlite3_xferopt_count;
2915 #endif /* SQLITE_TEST */
2918 #ifndef SQLITE_OMIT_XFER_OPT
2920 ** Check to see if index pSrc is compatible as a source of data
2921 ** for index pDest in an insert transfer optimization. The rules
2922 ** for a compatible index:
2924 ** * The index is over the same set of columns
2925 ** * The same DESC and ASC markings occurs on all columns
2926 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
2927 ** * The same collating sequence on each column
2928 ** * The index has the exact same WHERE clause
2930 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
2931 int i;
2932 assert( pDest && pSrc );
2933 assert( pDest->pTable!=pSrc->pTable );
2934 if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
2935 return 0; /* Different number of columns */
2937 if( pDest->onError!=pSrc->onError ){
2938 return 0; /* Different conflict resolution strategies */
2940 for(i=0; i<pSrc->nKeyCol; i++){
2941 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
2942 return 0; /* Different columns indexed */
2944 if( pSrc->aiColumn[i]==XN_EXPR ){
2945 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
2946 if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
2947 pDest->aColExpr->a[i].pExpr, -1)!=0 ){
2948 return 0; /* Different expressions in the index */
2951 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
2952 return 0; /* Different sort orders */
2954 if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
2955 return 0; /* Different collating sequences */
2958 if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
2959 return 0; /* Different WHERE clauses */
2962 /* If no test above fails then the indices must be compatible */
2963 return 1;
2967 ** Attempt the transfer optimization on INSERTs of the form
2969 ** INSERT INTO tab1 SELECT * FROM tab2;
2971 ** The xfer optimization transfers raw records from tab2 over to tab1.
2972 ** Columns are not decoded and reassembled, which greatly improves
2973 ** performance. Raw index records are transferred in the same way.
2975 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
2976 ** There are lots of rules for determining compatibility - see comments
2977 ** embedded in the code for details.
2979 ** This routine returns TRUE if the optimization is guaranteed to be used.
2980 ** Sometimes the xfer optimization will only work if the destination table
2981 ** is empty - a factor that can only be determined at run-time. In that
2982 ** case, this routine generates code for the xfer optimization but also
2983 ** does a test to see if the destination table is empty and jumps over the
2984 ** xfer optimization code if the test fails. In that case, this routine
2985 ** returns FALSE so that the caller will know to go ahead and generate
2986 ** an unoptimized transfer. This routine also returns FALSE if there
2987 ** is no chance that the xfer optimization can be applied.
2989 ** This optimization is particularly useful at making VACUUM run faster.
2991 static int xferOptimization(
2992 Parse *pParse, /* Parser context */
2993 Table *pDest, /* The table we are inserting into */
2994 Select *pSelect, /* A SELECT statement to use as the data source */
2995 int onError, /* How to handle constraint errors */
2996 int iDbDest /* The database of pDest */
2998 sqlite3 *db = pParse->db;
2999 ExprList *pEList; /* The result set of the SELECT */
3000 Table *pSrc; /* The table in the FROM clause of SELECT */
3001 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
3002 SrcItem *pItem; /* An element of pSelect->pSrc */
3003 int i; /* Loop counter */
3004 int iDbSrc; /* The database of pSrc */
3005 int iSrc, iDest; /* Cursors from source and destination */
3006 int addr1, addr2; /* Loop addresses */
3007 int emptyDestTest = 0; /* Address of test for empty pDest */
3008 int emptySrcTest = 0; /* Address of test for empty pSrc */
3009 Vdbe *v; /* The VDBE we are building */
3010 int regAutoinc; /* Memory register used by AUTOINC */
3011 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
3012 int regData, regRowid; /* Registers holding data and rowid */
3014 assert( pSelect!=0 );
3015 if( pParse->pWith || pSelect->pWith ){
3016 /* Do not attempt to process this query if there are an WITH clauses
3017 ** attached to it. Proceeding may generate a false "no such table: xxx"
3018 ** error if pSelect reads from a CTE named "xxx". */
3019 return 0;
3021 #ifndef SQLITE_OMIT_VIRTUALTABLE
3022 if( IsVirtual(pDest) ){
3023 return 0; /* tab1 must not be a virtual table */
3025 #endif
3026 if( onError==OE_Default ){
3027 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
3028 if( onError==OE_Default ) onError = OE_Abort;
3030 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
3031 if( pSelect->pSrc->nSrc!=1 ){
3032 return 0; /* FROM clause must have exactly one term */
3034 if( pSelect->pSrc->a[0].pSelect ){
3035 return 0; /* FROM clause cannot contain a subquery */
3037 if( pSelect->pWhere ){
3038 return 0; /* SELECT may not have a WHERE clause */
3040 if( pSelect->pOrderBy ){
3041 return 0; /* SELECT may not have an ORDER BY clause */
3043 /* Do not need to test for a HAVING clause. If HAVING is present but
3044 ** there is no ORDER BY, we will get an error. */
3045 if( pSelect->pGroupBy ){
3046 return 0; /* SELECT may not have a GROUP BY clause */
3048 if( pSelect->pLimit ){
3049 return 0; /* SELECT may not have a LIMIT clause */
3051 if( pSelect->pPrior ){
3052 return 0; /* SELECT may not be a compound query */
3054 if( pSelect->selFlags & SF_Distinct ){
3055 return 0; /* SELECT may not be DISTINCT */
3057 pEList = pSelect->pEList;
3058 assert( pEList!=0 );
3059 if( pEList->nExpr!=1 ){
3060 return 0; /* The result set must have exactly one column */
3062 assert( pEList->a[0].pExpr );
3063 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
3064 return 0; /* The result set must be the special operator "*" */
3067 /* At this point we have established that the statement is of the
3068 ** correct syntactic form to participate in this optimization. Now
3069 ** we have to check the semantics.
3071 pItem = pSelect->pSrc->a;
3072 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
3073 if( pSrc==0 ){
3074 return 0; /* FROM clause does not contain a real table */
3076 if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
3077 testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
3078 return 0; /* tab1 and tab2 may not be the same table */
3080 if( HasRowid(pDest)!=HasRowid(pSrc) ){
3081 return 0; /* source and destination must both be WITHOUT ROWID or not */
3083 if( !IsOrdinaryTable(pSrc) ){
3084 return 0; /* tab2 may not be a view or virtual table */
3086 if( pDest->nCol!=pSrc->nCol ){
3087 return 0; /* Number of columns must be the same in tab1 and tab2 */
3089 if( pDest->iPKey!=pSrc->iPKey ){
3090 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
3092 if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
3093 return 0; /* Cannot feed from a non-strict into a strict table */
3095 for(i=0; i<pDest->nCol; i++){
3096 Column *pDestCol = &pDest->aCol[i];
3097 Column *pSrcCol = &pSrc->aCol[i];
3098 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
3099 if( (db->mDbFlags & DBFLAG_Vacuum)==0
3100 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
3102 return 0; /* Neither table may have __hidden__ columns */
3104 #endif
3105 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3106 /* Even if tables t1 and t2 have identical schemas, if they contain
3107 ** generated columns, then this statement is semantically incorrect:
3109 ** INSERT INTO t2 SELECT * FROM t1;
3111 ** The reason is that generated column values are returned by the
3112 ** the SELECT statement on the right but the INSERT statement on the
3113 ** left wants them to be omitted.
3115 ** Nevertheless, this is a useful notational shorthand to tell SQLite
3116 ** to do a bulk transfer all of the content from t1 over to t2.
3118 ** We could, in theory, disable this (except for internal use by the
3119 ** VACUUM command where it is actually needed). But why do that? It
3120 ** seems harmless enough, and provides a useful service.
3122 if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
3123 (pSrcCol->colFlags & COLFLAG_GENERATED) ){
3124 return 0; /* Both columns have the same generated-column type */
3126 /* But the transfer is only allowed if both the source and destination
3127 ** tables have the exact same expressions for generated columns.
3128 ** This requirement could be relaxed for VIRTUAL columns, I suppose.
3130 if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
3131 if( sqlite3ExprCompare(0,
3132 sqlite3ColumnExpr(pSrc, pSrcCol),
3133 sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
3134 testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
3135 testcase( pDestCol->colFlags & COLFLAG_STORED );
3136 return 0; /* Different generator expressions */
3139 #endif
3140 if( pDestCol->affinity!=pSrcCol->affinity ){
3141 return 0; /* Affinity must be the same on all columns */
3143 if( sqlite3_stricmp(sqlite3ColumnColl(pDestCol),
3144 sqlite3ColumnColl(pSrcCol))!=0 ){
3145 return 0; /* Collating sequence must be the same on all columns */
3147 if( pDestCol->notNull && !pSrcCol->notNull ){
3148 return 0; /* tab2 must be NOT NULL if tab1 is */
3150 /* Default values for second and subsequent columns need to match. */
3151 if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
3152 Expr *pDestExpr = sqlite3ColumnExpr(pDest, pDestCol);
3153 Expr *pSrcExpr = sqlite3ColumnExpr(pSrc, pSrcCol);
3154 assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
3155 assert( pDestExpr==0 || !ExprHasProperty(pDestExpr, EP_IntValue) );
3156 assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
3157 assert( pSrcExpr==0 || !ExprHasProperty(pSrcExpr, EP_IntValue) );
3158 if( (pDestExpr==0)!=(pSrcExpr==0)
3159 || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
3160 pSrcExpr->u.zToken)!=0)
3162 return 0; /* Default values must be the same for all columns */
3166 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
3167 if( IsUniqueIndex(pDestIdx) ){
3168 destHasUniqueIdx = 1;
3170 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
3171 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
3173 if( pSrcIdx==0 ){
3174 return 0; /* pDestIdx has no corresponding index in pSrc */
3176 if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
3177 && sqlite3FaultSim(411)==SQLITE_OK ){
3178 /* The sqlite3FaultSim() call allows this corruption test to be
3179 ** bypassed during testing, in order to exercise other corruption tests
3180 ** further downstream. */
3181 return 0; /* Corrupt schema - two indexes on the same btree */
3184 #ifndef SQLITE_OMIT_CHECK
3185 if( pDest->pCheck
3186 && (db->mDbFlags & DBFLAG_Vacuum)==0
3187 && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1)
3189 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
3191 #endif
3192 #ifndef SQLITE_OMIT_FOREIGN_KEY
3193 /* Disallow the transfer optimization if the destination table contains
3194 ** any foreign key constraints. This is more restrictive than necessary.
3195 ** But the main beneficiary of the transfer optimization is the VACUUM
3196 ** command, and the VACUUM command disables foreign key constraints. So
3197 ** the extra complication to make this rule less restrictive is probably
3198 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
3200 assert( IsOrdinaryTable(pDest) );
3201 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
3202 return 0;
3204 #endif
3205 if( (db->flags & SQLITE_CountRows)!=0 ){
3206 return 0; /* xfer opt does not play well with PRAGMA count_changes */
3209 /* If we get this far, it means that the xfer optimization is at
3210 ** least a possibility, though it might only work if the destination
3211 ** table (tab1) is initially empty.
3213 #ifdef SQLITE_TEST
3214 sqlite3_xferopt_count++;
3215 #endif
3216 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
3217 v = sqlite3GetVdbe(pParse);
3218 sqlite3CodeVerifySchema(pParse, iDbSrc);
3219 iSrc = pParse->nTab++;
3220 iDest = pParse->nTab++;
3221 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
3222 regData = sqlite3GetTempReg(pParse);
3223 sqlite3VdbeAddOp2(v, OP_Null, 0, regData);
3224 regRowid = sqlite3GetTempReg(pParse);
3225 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
3226 assert( HasRowid(pDest) || destHasUniqueIdx );
3227 if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
3228 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
3229 || destHasUniqueIdx /* (2) */
3230 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
3232 /* In some circumstances, we are able to run the xfer optimization
3233 ** only if the destination table is initially empty. Unless the
3234 ** DBFLAG_Vacuum flag is set, this block generates code to make
3235 ** that determination. If DBFLAG_Vacuum is set, then the destination
3236 ** table is always empty.
3238 ** Conditions under which the destination must be empty:
3240 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
3241 ** (If the destination is not initially empty, the rowid fields
3242 ** of index entries might need to change.)
3244 ** (2) The destination has a unique index. (The xfer optimization
3245 ** is unable to test uniqueness.)
3247 ** (3) onError is something other than OE_Abort and OE_Rollback.
3249 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
3250 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
3251 sqlite3VdbeJumpHere(v, addr1);
3253 if( HasRowid(pSrc) ){
3254 u8 insFlags;
3255 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
3256 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
3257 if( pDest->iPKey>=0 ){
3258 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3259 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3260 sqlite3VdbeVerifyAbortable(v, onError);
3261 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
3262 VdbeCoverage(v);
3263 sqlite3RowidConstraint(pParse, onError, pDest);
3264 sqlite3VdbeJumpHere(v, addr2);
3266 autoIncStep(pParse, regAutoinc, regRowid);
3267 }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
3268 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
3269 }else{
3270 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3271 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
3274 if( db->mDbFlags & DBFLAG_Vacuum ){
3275 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3276 insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3277 }else{
3278 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT;
3280 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
3281 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3282 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3283 insFlags &= ~OPFLAG_PREFORMAT;
3284 }else
3285 #endif
3287 sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid);
3289 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
3290 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3291 sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
3293 sqlite3VdbeChangeP5(v, insFlags);
3295 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
3296 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
3297 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3298 }else{
3299 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
3300 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
3302 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
3303 u8 idxInsFlags = 0;
3304 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
3305 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
3307 assert( pSrcIdx );
3308 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
3309 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
3310 VdbeComment((v, "%s", pSrcIdx->zName));
3311 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
3312 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
3313 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
3314 VdbeComment((v, "%s", pDestIdx->zName));
3315 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
3316 if( db->mDbFlags & DBFLAG_Vacuum ){
3317 /* This INSERT command is part of a VACUUM operation, which guarantees
3318 ** that the destination table is empty. If all indexed columns use
3319 ** collation sequence BINARY, then it can also be assumed that the
3320 ** index will be populated by inserting keys in strictly sorted
3321 ** order. In this case, instead of seeking within the b-tree as part
3322 ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
3323 ** OP_IdxInsert to seek to the point within the b-tree where each key
3324 ** should be inserted. This is faster.
3326 ** If any of the indexed columns use a collation sequence other than
3327 ** BINARY, this optimization is disabled. This is because the user
3328 ** might change the definition of a collation sequence and then run
3329 ** a VACUUM command. In that case keys may not be written in strictly
3330 ** sorted order. */
3331 for(i=0; i<pSrcIdx->nColumn; i++){
3332 const char *zColl = pSrcIdx->azColl[i];
3333 if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
3335 if( i==pSrcIdx->nColumn ){
3336 idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3337 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3338 sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc);
3340 }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
3341 idxInsFlags |= OPFLAG_NCHANGE;
3343 if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){
3344 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3345 if( (db->mDbFlags & DBFLAG_Vacuum)==0
3346 && !HasRowid(pDest)
3347 && IsPrimaryKeyIndex(pDestIdx)
3349 codeWithoutRowidPreupdate(pParse, pDest, iDest, regData);
3352 sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
3353 sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
3354 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
3355 sqlite3VdbeJumpHere(v, addr1);
3356 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
3357 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3359 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
3360 sqlite3ReleaseTempReg(pParse, regRowid);
3361 sqlite3ReleaseTempReg(pParse, regData);
3362 if( emptyDestTest ){
3363 sqlite3AutoincrementEnd(pParse);
3364 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
3365 sqlite3VdbeJumpHere(v, emptyDestTest);
3366 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3367 return 0;
3368 }else{
3369 return 1;
3372 #endif /* SQLITE_OMIT_XFER_OPT */