Fixes default log output to console for macOS
[sqlcipher.git] / src / insert.c
bloba7e94420bfd6220b405be0935e5ba0cdc3f754f8
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 if( pRet->pPrior ) pRet->selFlags |= SF_Values;
721 pLeft->pPrior = 0;
722 pLeft->op = TK_SELECT;
723 assert( pLeft->pNext==0 );
724 assert( pRet->pNext==0 );
725 p = &pRet->pSrc->a[0];
726 p->pSelect = pLeft;
727 p->fg.viaCoroutine = 1;
728 p->addrFillSub = sqlite3VdbeCurrentAddr(v) + 1;
729 p->regReturn = ++pParse->nMem;
730 p->iCursor = -1;
731 p->u1.nRow = 2;
732 sqlite3VdbeAddOp3(v,OP_InitCoroutine,p->regReturn,0,p->addrFillSub);
733 sqlite3SelectDestInit(&dest, SRT_Coroutine, p->regReturn);
735 /* Allocate registers for the output of the co-routine. Do so so
736 ** that there are two unused registers immediately before those
737 ** used by the co-routine. This allows the code in sqlite3Insert()
738 ** to use these registers directly, instead of copying the output
739 ** of the co-routine to a separate array for processing. */
740 dest.iSdst = pParse->nMem + 3;
741 dest.nSdst = pLeft->pEList->nExpr;
742 pParse->nMem += 2 + dest.nSdst;
744 pLeft->selFlags |= SF_MultiValue;
745 sqlite3Select(pParse, pLeft, &dest);
746 p->regResult = dest.iSdst;
747 assert( pParse->nErr || dest.iSdst>0 );
748 pLeft = pRet;
750 }else{
751 p = &pLeft->pSrc->a[0];
752 assert( !p->fg.isTabFunc && !p->fg.isIndexedBy );
753 p->u1.nRow++;
756 if( pParse->nErr==0 ){
757 assert( p!=0 );
758 if( p->pSelect->pEList->nExpr!=pRow->nExpr ){
759 sqlite3SelectWrongNumTermsError(pParse, p->pSelect);
760 }else{
761 sqlite3ExprCodeExprList(pParse, pRow, p->regResult, 0, 0);
762 sqlite3VdbeAddOp1(pParse->pVdbe, OP_Yield, p->regReturn);
765 sqlite3ExprListDelete(pParse->db, pRow);
768 return pLeft;
771 /* Forward declaration */
772 static int xferOptimization(
773 Parse *pParse, /* Parser context */
774 Table *pDest, /* The table we are inserting into */
775 Select *pSelect, /* A SELECT statement to use as the data source */
776 int onError, /* How to handle constraint errors */
777 int iDbDest /* The database of pDest */
781 ** This routine is called to handle SQL of the following forms:
783 ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
784 ** insert into TABLE (IDLIST) select
785 ** insert into TABLE (IDLIST) default values
787 ** The IDLIST following the table name is always optional. If omitted,
788 ** then a list of all (non-hidden) columns for the table is substituted.
789 ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
790 ** is omitted.
792 ** For the pSelect parameter holds the values to be inserted for the
793 ** first two forms shown above. A VALUES clause is really just short-hand
794 ** for a SELECT statement that omits the FROM clause and everything else
795 ** that follows. If the pSelect parameter is NULL, that means that the
796 ** DEFAULT VALUES form of the INSERT statement is intended.
798 ** The code generated follows one of four templates. For a simple
799 ** insert with data coming from a single-row VALUES clause, the code executes
800 ** once straight down through. Pseudo-code follows (we call this
801 ** the "1st template"):
803 ** open write cursor to <table> and its indices
804 ** put VALUES clause expressions into registers
805 ** write the resulting record into <table>
806 ** cleanup
808 ** The three remaining templates assume the statement is of the form
810 ** INSERT INTO <table> SELECT ...
812 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
813 ** in other words if the SELECT pulls all columns from a single table
814 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
815 ** if <table2> and <table1> are distinct tables but have identical
816 ** schemas, including all the same indices, then a special optimization
817 ** is invoked that copies raw records from <table2> over to <table1>.
818 ** See the xferOptimization() function for the implementation of this
819 ** template. This is the 2nd template.
821 ** open a write cursor to <table>
822 ** open read cursor on <table2>
823 ** transfer all records in <table2> over to <table>
824 ** close cursors
825 ** foreach index on <table>
826 ** open a write cursor on the <table> index
827 ** open a read cursor on the corresponding <table2> index
828 ** transfer all records from the read to the write cursors
829 ** close cursors
830 ** end foreach
832 ** The 3rd template is for when the second template does not apply
833 ** and the SELECT clause does not read from <table> at any time.
834 ** The generated code follows this template:
836 ** X <- A
837 ** goto B
838 ** A: setup for the SELECT
839 ** loop over the rows in the SELECT
840 ** load values into registers R..R+n
841 ** yield X
842 ** end loop
843 ** cleanup after the SELECT
844 ** end-coroutine X
845 ** B: open write cursor to <table> and its indices
846 ** C: yield X, at EOF goto D
847 ** insert the select result into <table> from R..R+n
848 ** goto C
849 ** D: cleanup
851 ** The 4th template is used if the insert statement takes its
852 ** values from a SELECT but the data is being inserted into a table
853 ** that is also read as part of the SELECT. In the third form,
854 ** we have to use an intermediate table to store the results of
855 ** the select. The template is like this:
857 ** X <- A
858 ** goto B
859 ** A: setup for the SELECT
860 ** loop over the tables in the SELECT
861 ** load value into register R..R+n
862 ** yield X
863 ** end loop
864 ** cleanup after the SELECT
865 ** end co-routine R
866 ** B: open temp table
867 ** L: yield X, at EOF goto M
868 ** insert row from R..R+n into temp table
869 ** goto L
870 ** M: open write cursor to <table> and its indices
871 ** rewind temp table
872 ** C: loop over rows of intermediate table
873 ** transfer values form intermediate table into <table>
874 ** end loop
875 ** D: cleanup
877 void sqlite3Insert(
878 Parse *pParse, /* Parser context */
879 SrcList *pTabList, /* Name of table into which we are inserting */
880 Select *pSelect, /* A SELECT statement to use as the data source */
881 IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */
882 int onError, /* How to handle constraint errors */
883 Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
885 sqlite3 *db; /* The main database structure */
886 Table *pTab; /* The table to insert into. aka TABLE */
887 int i, j; /* Loop counters */
888 Vdbe *v; /* Generate code into this virtual machine */
889 Index *pIdx; /* For looping over indices of the table */
890 int nColumn; /* Number of columns in the data */
891 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
892 int iDataCur = 0; /* VDBE cursor that is the main data repository */
893 int iIdxCur = 0; /* First index cursor */
894 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
895 int endOfLoop; /* Label for the end of the insertion loop */
896 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
897 int addrInsTop = 0; /* Jump to label "D" */
898 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
899 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
900 int iDb; /* Index of database holding TABLE */
901 u8 useTempTable = 0; /* Store SELECT results in intermediate table */
902 u8 appendFlag = 0; /* True if the insert is likely to be an append */
903 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
904 u8 bIdListInOrder; /* True if IDLIST is in table order */
905 ExprList *pList = 0; /* List of VALUES() to be inserted */
906 int iRegStore; /* Register in which to store next column */
908 /* Register allocations */
909 int regFromSelect = 0;/* Base register for data coming from SELECT */
910 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
911 int regRowCount = 0; /* Memory cell used for the row counter */
912 int regIns; /* Block of regs holding rowid+data being inserted */
913 int regRowid; /* registers holding insert rowid */
914 int regData; /* register holding first column to insert */
915 int *aRegIdx = 0; /* One register allocated to each index */
917 #ifndef SQLITE_OMIT_TRIGGER
918 int isView; /* True if attempting to insert into a view */
919 Trigger *pTrigger; /* List of triggers on pTab, if required */
920 int tmask; /* Mask of trigger times */
921 #endif
923 db = pParse->db;
924 assert( db->pParse==pParse );
925 if( pParse->nErr ){
926 goto insert_cleanup;
928 assert( db->mallocFailed==0 );
929 dest.iSDParm = 0; /* Suppress a harmless compiler warning */
931 /* If the Select object is really just a simple VALUES() list with a
932 ** single row (the common case) then keep that one row of values
933 ** and discard the other (unused) parts of the pSelect object
935 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
936 pList = pSelect->pEList;
937 pSelect->pEList = 0;
938 sqlite3SelectDelete(db, pSelect);
939 pSelect = 0;
942 /* Locate the table into which we will be inserting new information.
944 assert( pTabList->nSrc==1 );
945 pTab = sqlite3SrcListLookup(pParse, pTabList);
946 if( pTab==0 ){
947 goto insert_cleanup;
949 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
950 assert( iDb<db->nDb );
951 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
952 db->aDb[iDb].zDbSName) ){
953 goto insert_cleanup;
955 withoutRowid = !HasRowid(pTab);
957 /* Figure out if we have any triggers and if the table being
958 ** inserted into is a view
960 #ifndef SQLITE_OMIT_TRIGGER
961 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
962 isView = IsView(pTab);
963 #else
964 # define pTrigger 0
965 # define tmask 0
966 # define isView 0
967 #endif
968 #ifdef SQLITE_OMIT_VIEW
969 # undef isView
970 # define isView 0
971 #endif
972 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
974 #if TREETRACE_ENABLED
975 if( sqlite3TreeTrace & 0x10000 ){
976 sqlite3TreeViewLine(0, "In sqlite3Insert() at %s:%d", __FILE__, __LINE__);
977 sqlite3TreeViewInsert(pParse->pWith, pTabList, pColumn, pSelect, pList,
978 onError, pUpsert, pTrigger);
980 #endif
982 /* If pTab is really a view, make sure it has been initialized.
983 ** ViewGetColumnNames() is a no-op if pTab is not a view.
985 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
986 goto insert_cleanup;
989 /* Cannot insert into a read-only table.
991 if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
992 goto insert_cleanup;
995 /* Allocate a VDBE
997 v = sqlite3GetVdbe(pParse);
998 if( v==0 ) goto insert_cleanup;
999 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
1000 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
1002 #ifndef SQLITE_OMIT_XFER_OPT
1003 /* If the statement is of the form
1005 ** INSERT INTO <table1> SELECT * FROM <table2>;
1007 ** Then special optimizations can be applied that make the transfer
1008 ** very fast and which reduce fragmentation of indices.
1010 ** This is the 2nd template.
1012 if( pColumn==0
1013 && pSelect!=0
1014 && pTrigger==0
1015 && xferOptimization(pParse, pTab, pSelect, onError, iDb)
1017 assert( !pTrigger );
1018 assert( pList==0 );
1019 goto insert_end;
1021 #endif /* SQLITE_OMIT_XFER_OPT */
1023 /* If this is an AUTOINCREMENT table, look up the sequence number in the
1024 ** sqlite_sequence table and store it in memory cell regAutoinc.
1026 regAutoinc = autoIncBegin(pParse, iDb, pTab);
1028 /* Allocate a block registers to hold the rowid and the values
1029 ** for all columns of the new row.
1031 regRowid = regIns = pParse->nMem+1;
1032 pParse->nMem += pTab->nCol + 1;
1033 if( IsVirtual(pTab) ){
1034 regRowid++;
1035 pParse->nMem++;
1037 regData = regRowid+1;
1039 /* If the INSERT statement included an IDLIST term, then make sure
1040 ** all elements of the IDLIST really are columns of the table and
1041 ** remember the column indices.
1043 ** If the table has an INTEGER PRIMARY KEY column and that column
1044 ** is named in the IDLIST, then record in the ipkColumn variable
1045 ** the index into IDLIST of the primary key column. ipkColumn is
1046 ** the index of the primary key as it appears in IDLIST, not as
1047 ** is appears in the original table. (The index of the INTEGER
1048 ** PRIMARY KEY in the original table is pTab->iPKey.) After this
1049 ** loop, if ipkColumn==(-1), that means that integer primary key
1050 ** is unspecified, and hence the table is either WITHOUT ROWID or
1051 ** it will automatically generated an integer primary key.
1053 ** bIdListInOrder is true if the columns in IDLIST are in storage
1054 ** order. This enables an optimization that avoids shuffling the
1055 ** columns into storage order. False negatives are harmless,
1056 ** but false positives will cause database corruption.
1058 bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
1059 if( pColumn ){
1060 assert( pColumn->eU4!=EU4_EXPR );
1061 pColumn->eU4 = EU4_IDX;
1062 for(i=0; i<pColumn->nId; i++){
1063 pColumn->a[i].u4.idx = -1;
1065 for(i=0; i<pColumn->nId; i++){
1066 for(j=0; j<pTab->nCol; j++){
1067 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zCnName)==0 ){
1068 pColumn->a[i].u4.idx = j;
1069 if( i!=j ) bIdListInOrder = 0;
1070 if( j==pTab->iPKey ){
1071 ipkColumn = i; assert( !withoutRowid );
1073 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1074 if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
1075 sqlite3ErrorMsg(pParse,
1076 "cannot INSERT into generated column \"%s\"",
1077 pTab->aCol[j].zCnName);
1078 goto insert_cleanup;
1080 #endif
1081 break;
1084 if( j>=pTab->nCol ){
1085 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
1086 ipkColumn = i;
1087 bIdListInOrder = 0;
1088 }else{
1089 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
1090 pTabList->a, pColumn->a[i].zName);
1091 pParse->checkSchema = 1;
1092 goto insert_cleanup;
1098 /* Figure out how many columns of data are supplied. If the data
1099 ** is coming from a SELECT statement, then generate a co-routine that
1100 ** produces a single row of the SELECT on each invocation. The
1101 ** co-routine is the common header to the 3rd and 4th templates.
1103 if( pSelect ){
1104 /* Data is coming from a SELECT or from a multi-row VALUES clause.
1105 ** Generate a co-routine to run the SELECT. */
1106 int rc; /* Result code */
1108 if( pSelect->pSrc->nSrc==1
1109 && pSelect->pSrc->a[0].fg.viaCoroutine
1110 && pSelect->pPrior==0
1112 SrcItem *pItem = &pSelect->pSrc->a[0];
1113 dest.iSDParm = pItem->regReturn;
1114 regFromSelect = pItem->regResult;
1115 nColumn = pItem->pSelect->pEList->nExpr;
1116 ExplainQueryPlan((pParse, 0, "SCAN %S", pItem));
1117 if( bIdListInOrder && nColumn==pTab->nCol ){
1118 regData = regFromSelect;
1119 regRowid = regData - 1;
1120 regIns = regRowid - (IsVirtual(pTab) ? 1 : 0);
1122 }else{
1123 int addrTop; /* Top of the co-routine */
1124 int regYield = ++pParse->nMem;
1125 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
1126 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
1127 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
1128 dest.iSdst = bIdListInOrder ? regData : 0;
1129 dest.nSdst = pTab->nCol;
1130 rc = sqlite3Select(pParse, pSelect, &dest);
1131 regFromSelect = dest.iSdst;
1132 assert( db->pParse==pParse );
1133 if( rc || pParse->nErr ) goto insert_cleanup;
1134 assert( db->mallocFailed==0 );
1135 sqlite3VdbeEndCoroutine(v, regYield);
1136 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
1137 assert( pSelect->pEList );
1138 nColumn = pSelect->pEList->nExpr;
1141 /* Set useTempTable to TRUE if the result of the SELECT statement
1142 ** should be written into a temporary table (template 4). Set to
1143 ** FALSE if each output row of the SELECT can be written directly into
1144 ** the destination table (template 3).
1146 ** A temp table must be used if the table being updated is also one
1147 ** of the tables being read by the SELECT statement. Also use a
1148 ** temp table in the case of row triggers.
1150 if( pTrigger || readsTable(pParse, iDb, pTab) ){
1151 useTempTable = 1;
1154 if( useTempTable ){
1155 /* Invoke the coroutine to extract information from the SELECT
1156 ** and add it to a transient table srcTab. The code generated
1157 ** here is from the 4th template:
1159 ** B: open temp table
1160 ** L: yield X, goto M at EOF
1161 ** insert row from R..R+n into temp table
1162 ** goto L
1163 ** M: ...
1165 int regRec; /* Register to hold packed record */
1166 int regTempRowid; /* Register to hold temp table ROWID */
1167 int addrL; /* Label "L" */
1169 srcTab = pParse->nTab++;
1170 regRec = sqlite3GetTempReg(pParse);
1171 regTempRowid = sqlite3GetTempReg(pParse);
1172 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
1173 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
1174 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
1175 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
1176 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
1177 sqlite3VdbeGoto(v, addrL);
1178 sqlite3VdbeJumpHere(v, addrL);
1179 sqlite3ReleaseTempReg(pParse, regRec);
1180 sqlite3ReleaseTempReg(pParse, regTempRowid);
1182 }else{
1183 /* This is the case if the data for the INSERT is coming from a
1184 ** single-row VALUES clause
1186 NameContext sNC;
1187 memset(&sNC, 0, sizeof(sNC));
1188 sNC.pParse = pParse;
1189 srcTab = -1;
1190 assert( useTempTable==0 );
1191 if( pList ){
1192 nColumn = pList->nExpr;
1193 if( sqlite3ResolveExprListNames(&sNC, pList) ){
1194 goto insert_cleanup;
1196 }else{
1197 nColumn = 0;
1201 /* If there is no IDLIST term but the table has an integer primary
1202 ** key, the set the ipkColumn variable to the integer primary key
1203 ** column index in the original table definition.
1205 if( pColumn==0 && nColumn>0 ){
1206 ipkColumn = pTab->iPKey;
1207 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1208 if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
1209 testcase( pTab->tabFlags & TF_HasVirtual );
1210 testcase( pTab->tabFlags & TF_HasStored );
1211 for(i=ipkColumn-1; i>=0; i--){
1212 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
1213 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
1214 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
1215 ipkColumn--;
1219 #endif
1221 /* Make sure the number of columns in the source data matches the number
1222 ** of columns to be inserted into the table.
1224 assert( TF_HasHidden==COLFLAG_HIDDEN );
1225 assert( TF_HasGenerated==COLFLAG_GENERATED );
1226 assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) );
1227 if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
1228 for(i=0; i<pTab->nCol; i++){
1229 if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
1232 if( nColumn!=(pTab->nCol-nHidden) ){
1233 sqlite3ErrorMsg(pParse,
1234 "table %S has %d columns but %d values were supplied",
1235 pTabList->a, pTab->nCol-nHidden, nColumn);
1236 goto insert_cleanup;
1239 if( pColumn!=0 && nColumn!=pColumn->nId ){
1240 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
1241 goto insert_cleanup;
1244 /* Initialize the count of rows to be inserted
1246 if( (db->flags & SQLITE_CountRows)!=0
1247 && !pParse->nested
1248 && !pParse->pTriggerTab
1249 && !pParse->bReturning
1251 regRowCount = ++pParse->nMem;
1252 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
1255 /* If this is not a view, open the table and and all indices */
1256 if( !isView ){
1257 int nIdx;
1258 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
1259 &iDataCur, &iIdxCur);
1260 aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
1261 if( aRegIdx==0 ){
1262 goto insert_cleanup;
1264 for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
1265 assert( pIdx );
1266 aRegIdx[i] = ++pParse->nMem;
1267 pParse->nMem += pIdx->nColumn;
1269 aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */
1271 #ifndef SQLITE_OMIT_UPSERT
1272 if( pUpsert ){
1273 Upsert *pNx;
1274 if( IsVirtual(pTab) ){
1275 sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
1276 pTab->zName);
1277 goto insert_cleanup;
1279 if( IsView(pTab) ){
1280 sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
1281 goto insert_cleanup;
1283 if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
1284 goto insert_cleanup;
1286 pTabList->a[0].iCursor = iDataCur;
1287 pNx = pUpsert;
1289 pNx->pUpsertSrc = pTabList;
1290 pNx->regData = regData;
1291 pNx->iDataCur = iDataCur;
1292 pNx->iIdxCur = iIdxCur;
1293 if( pNx->pUpsertTarget ){
1294 if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx, pUpsert) ){
1295 goto insert_cleanup;
1298 pNx = pNx->pNextUpsert;
1299 }while( pNx!=0 );
1301 #endif
1304 /* This is the top of the main insertion loop */
1305 if( useTempTable ){
1306 /* This block codes the top of loop only. The complete loop is the
1307 ** following pseudocode (template 4):
1309 ** rewind temp table, if empty goto D
1310 ** C: loop over rows of intermediate table
1311 ** transfer values form intermediate table into <table>
1312 ** end loop
1313 ** D: ...
1315 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
1316 addrCont = sqlite3VdbeCurrentAddr(v);
1317 }else if( pSelect ){
1318 /* This block codes the top of loop only. The complete loop is the
1319 ** following pseudocode (template 3):
1321 ** C: yield X, at EOF goto D
1322 ** insert the select result into <table> from R..R+n
1323 ** goto C
1324 ** D: ...
1326 sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
1327 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
1328 VdbeCoverage(v);
1329 if( ipkColumn>=0 ){
1330 /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
1331 ** SELECT, go ahead and copy the value into the rowid slot now, so that
1332 ** the value does not get overwritten by a NULL at tag-20191021-002. */
1333 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
1337 /* Compute data for ordinary columns of the new entry. Values
1338 ** are written in storage order into registers starting with regData.
1339 ** Only ordinary columns are computed in this loop. The rowid
1340 ** (if there is one) is computed later and generated columns are
1341 ** computed after the rowid since they might depend on the value
1342 ** of the rowid.
1344 nHidden = 0;
1345 iRegStore = regData; assert( regData==regRowid+1 );
1346 for(i=0; i<pTab->nCol; i++, iRegStore++){
1347 int k;
1348 u32 colFlags;
1349 assert( i>=nHidden );
1350 if( i==pTab->iPKey ){
1351 /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
1352 ** using the rowid. So put a NULL in the IPK slot of the record to avoid
1353 ** using excess space. The file format definition requires this extra
1354 ** NULL - we cannot optimize further by skipping the column completely */
1355 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1356 continue;
1358 if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
1359 nHidden++;
1360 if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
1361 /* Virtual columns do not participate in OP_MakeRecord. So back up
1362 ** iRegStore by one slot to compensate for the iRegStore++ in the
1363 ** outer for() loop */
1364 iRegStore--;
1365 continue;
1366 }else if( (colFlags & COLFLAG_STORED)!=0 ){
1367 /* Stored columns are computed later. But if there are BEFORE
1368 ** triggers, the slots used for stored columns will be OP_Copy-ed
1369 ** to a second block of registers, so the register needs to be
1370 ** initialized to NULL to avoid an uninitialized register read */
1371 if( tmask & TRIGGER_BEFORE ){
1372 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1374 continue;
1375 }else if( pColumn==0 ){
1376 /* Hidden columns that are not explicitly named in the INSERT
1377 ** get there default value */
1378 sqlite3ExprCodeFactorable(pParse,
1379 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1380 iRegStore);
1381 continue;
1384 if( pColumn ){
1385 assert( pColumn->eU4==EU4_IDX );
1386 for(j=0; j<pColumn->nId && pColumn->a[j].u4.idx!=i; j++){}
1387 if( j>=pColumn->nId ){
1388 /* A column not named in the insert column list gets its
1389 ** default value */
1390 sqlite3ExprCodeFactorable(pParse,
1391 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1392 iRegStore);
1393 continue;
1395 k = j;
1396 }else if( nColumn==0 ){
1397 /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */
1398 sqlite3ExprCodeFactorable(pParse,
1399 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1400 iRegStore);
1401 continue;
1402 }else{
1403 k = i - nHidden;
1406 if( useTempTable ){
1407 sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
1408 }else if( pSelect ){
1409 if( regFromSelect!=regData ){
1410 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
1412 }else{
1413 Expr *pX = pList->a[k].pExpr;
1414 int y = sqlite3ExprCodeTarget(pParse, pX, iRegStore);
1415 if( y!=iRegStore ){
1416 sqlite3VdbeAddOp2(v,
1417 ExprHasProperty(pX, EP_Subquery) ? OP_Copy : OP_SCopy, y, iRegStore);
1423 /* Run the BEFORE and INSTEAD OF triggers, if there are any
1425 endOfLoop = sqlite3VdbeMakeLabel(pParse);
1426 if( tmask & TRIGGER_BEFORE ){
1427 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
1429 /* build the NEW.* reference row. Note that if there is an INTEGER
1430 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
1431 ** translated into a unique ID for the row. But on a BEFORE trigger,
1432 ** we do not know what the unique ID will be (because the insert has
1433 ** not happened yet) so we substitute a rowid of -1
1435 if( ipkColumn<0 ){
1436 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1437 }else{
1438 int addr1;
1439 assert( !withoutRowid );
1440 if( useTempTable ){
1441 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
1442 }else{
1443 assert( pSelect==0 ); /* Otherwise useTempTable is true */
1444 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
1446 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
1447 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1448 sqlite3VdbeJumpHere(v, addr1);
1449 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
1452 /* Copy the new data already generated. */
1453 assert( pTab->nNVCol>0 || pParse->nErr>0 );
1454 sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
1456 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1457 /* Compute the new value for generated columns after all other
1458 ** columns have already been computed. This must be done after
1459 ** computing the ROWID in case one of the generated columns
1460 ** refers to the ROWID. */
1461 if( pTab->tabFlags & TF_HasGenerated ){
1462 testcase( pTab->tabFlags & TF_HasVirtual );
1463 testcase( pTab->tabFlags & TF_HasStored );
1464 sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
1466 #endif
1468 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
1469 ** do not attempt any conversions before assembling the record.
1470 ** If this is a real table, attempt conversions as required by the
1471 ** table column affinities.
1473 if( !isView ){
1474 sqlite3TableAffinity(v, pTab, regCols+1);
1477 /* Fire BEFORE or INSTEAD OF triggers */
1478 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
1479 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
1481 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
1484 if( !isView ){
1485 if( IsVirtual(pTab) ){
1486 /* The row that the VUpdate opcode will delete: none */
1487 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
1489 if( ipkColumn>=0 ){
1490 /* Compute the new rowid */
1491 if( useTempTable ){
1492 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
1493 }else if( pSelect ){
1494 /* Rowid already initialized at tag-20191021-001 */
1495 }else{
1496 Expr *pIpk = pList->a[ipkColumn].pExpr;
1497 if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
1498 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1499 appendFlag = 1;
1500 }else{
1501 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
1504 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
1505 ** to generate a unique primary key value.
1507 if( !appendFlag ){
1508 int addr1;
1509 if( !IsVirtual(pTab) ){
1510 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
1511 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1512 sqlite3VdbeJumpHere(v, addr1);
1513 }else{
1514 addr1 = sqlite3VdbeCurrentAddr(v);
1515 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
1517 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
1519 }else if( IsVirtual(pTab) || withoutRowid ){
1520 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
1521 }else{
1522 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1523 appendFlag = 1;
1525 autoIncStep(pParse, regAutoinc, regRowid);
1527 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1528 /* Compute the new value for generated columns after all other
1529 ** columns have already been computed. This must be done after
1530 ** computing the ROWID in case one of the generated columns
1531 ** is derived from the INTEGER PRIMARY KEY. */
1532 if( pTab->tabFlags & TF_HasGenerated ){
1533 sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
1535 #endif
1537 /* Generate code to check constraints and generate index keys and
1538 ** do the insertion.
1540 #ifndef SQLITE_OMIT_VIRTUALTABLE
1541 if( IsVirtual(pTab) ){
1542 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
1543 sqlite3VtabMakeWritable(pParse, pTab);
1544 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1545 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1546 sqlite3MayAbort(pParse);
1547 }else
1548 #endif
1550 int isReplace = 0;/* Set to true if constraints may cause a replace */
1551 int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
1552 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1553 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
1555 if( db->flags & SQLITE_ForeignKeys ){
1556 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
1559 /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
1560 ** constraints or (b) there are no triggers and this table is not a
1561 ** parent table in a foreign key constraint. It is safe to set the
1562 ** flag in the second case as if any REPLACE constraint is hit, an
1563 ** OP_Delete or OP_IdxDelete instruction will be executed on each
1564 ** cursor that is disturbed. And these instructions both clear the
1565 ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
1566 ** functionality. */
1567 bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
1568 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
1569 regIns, aRegIdx, 0, appendFlag, bUseSeek
1572 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
1573 }else if( pParse->bReturning ){
1574 /* If there is a RETURNING clause, populate the rowid register with
1575 ** constant value -1, in case one or more of the returned expressions
1576 ** refer to the "rowid" of the view. */
1577 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
1578 #endif
1581 /* Update the count of rows that are inserted
1583 if( regRowCount ){
1584 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
1587 if( pTrigger ){
1588 /* Code AFTER triggers */
1589 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
1590 pTab, regData-2-pTab->nCol, onError, endOfLoop);
1593 /* The bottom of the main insertion loop, if the data source
1594 ** is a SELECT statement.
1596 sqlite3VdbeResolveLabel(v, endOfLoop);
1597 if( useTempTable ){
1598 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1599 sqlite3VdbeJumpHere(v, addrInsTop);
1600 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1601 }else if( pSelect ){
1602 sqlite3VdbeGoto(v, addrCont);
1603 #ifdef SQLITE_DEBUG
1604 /* If we are jumping back to an OP_Yield that is preceded by an
1605 ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
1606 ** OP_ReleaseReg will be included in the loop. */
1607 if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
1608 assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
1609 sqlite3VdbeChangeP5(v, 1);
1611 #endif
1612 sqlite3VdbeJumpHere(v, addrInsTop);
1615 #ifndef SQLITE_OMIT_XFER_OPT
1616 insert_end:
1617 #endif /* SQLITE_OMIT_XFER_OPT */
1618 /* Update the sqlite_sequence table by storing the content of the
1619 ** maximum rowid counter values recorded while inserting into
1620 ** autoincrement tables.
1622 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
1623 sqlite3AutoincrementEnd(pParse);
1627 ** Return the number of rows inserted. If this routine is
1628 ** generating code because of a call to sqlite3NestedParse(), do not
1629 ** invoke the callback function.
1631 if( regRowCount ){
1632 sqlite3CodeChangeCount(v, regRowCount, "rows inserted");
1635 insert_cleanup:
1636 sqlite3SrcListDelete(db, pTabList);
1637 sqlite3ExprListDelete(db, pList);
1638 sqlite3UpsertDelete(db, pUpsert);
1639 sqlite3SelectDelete(db, pSelect);
1640 sqlite3IdListDelete(db, pColumn);
1641 if( aRegIdx ) sqlite3DbNNFreeNN(db, aRegIdx);
1644 /* Make sure "isView" and other macros defined above are undefined. Otherwise
1645 ** they may interfere with compilation of other functions in this file
1646 ** (or in another file, if this file becomes part of the amalgamation). */
1647 #ifdef isView
1648 #undef isView
1649 #endif
1650 #ifdef pTrigger
1651 #undef pTrigger
1652 #endif
1653 #ifdef tmask
1654 #undef tmask
1655 #endif
1658 ** Meanings of bits in of pWalker->eCode for
1659 ** sqlite3ExprReferencesUpdatedColumn()
1661 #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
1662 #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
1664 /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
1665 * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
1666 ** expression node references any of the
1667 ** columns that are being modified by an UPDATE statement.
1669 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
1670 if( pExpr->op==TK_COLUMN ){
1671 assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
1672 if( pExpr->iColumn>=0 ){
1673 if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
1674 pWalker->eCode |= CKCNSTRNT_COLUMN;
1676 }else{
1677 pWalker->eCode |= CKCNSTRNT_ROWID;
1680 return WRC_Continue;
1684 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
1685 ** only columns that are modified by the UPDATE are those for which
1686 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
1688 ** Return true if CHECK constraint pExpr uses any of the
1689 ** changing columns (or the rowid if it is changing). In other words,
1690 ** return true if this CHECK constraint must be validated for
1691 ** the new row in the UPDATE statement.
1693 ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
1694 ** The operation of this routine is the same - return true if an only if
1695 ** the expression uses one or more of columns identified by the second and
1696 ** third arguments.
1698 int sqlite3ExprReferencesUpdatedColumn(
1699 Expr *pExpr, /* The expression to be checked */
1700 int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */
1701 int chngRowid /* True if UPDATE changes the rowid */
1703 Walker w;
1704 memset(&w, 0, sizeof(w));
1705 w.eCode = 0;
1706 w.xExprCallback = checkConstraintExprNode;
1707 w.u.aiCol = aiChng;
1708 sqlite3WalkExpr(&w, pExpr);
1709 if( !chngRowid ){
1710 testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
1711 w.eCode &= ~CKCNSTRNT_ROWID;
1713 testcase( w.eCode==0 );
1714 testcase( w.eCode==CKCNSTRNT_COLUMN );
1715 testcase( w.eCode==CKCNSTRNT_ROWID );
1716 testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
1717 return w.eCode!=0;
1721 ** The sqlite3GenerateConstraintChecks() routine usually wants to visit
1722 ** the indexes of a table in the order provided in the Table->pIndex list.
1723 ** However, sometimes (rarely - when there is an upsert) it wants to visit
1724 ** the indexes in a different order. The following data structures accomplish
1725 ** this.
1727 ** The IndexIterator object is used to walk through all of the indexes
1728 ** of a table in either Index.pNext order, or in some other order established
1729 ** by an array of IndexListTerm objects.
1731 typedef struct IndexListTerm IndexListTerm;
1732 typedef struct IndexIterator IndexIterator;
1733 struct IndexIterator {
1734 int eType; /* 0 for Index.pNext list. 1 for an array of IndexListTerm */
1735 int i; /* Index of the current item from the list */
1736 union {
1737 struct { /* Use this object for eType==0: A Index.pNext list */
1738 Index *pIdx; /* The current Index */
1739 } lx;
1740 struct { /* Use this object for eType==1; Array of IndexListTerm */
1741 int nIdx; /* Size of the array */
1742 IndexListTerm *aIdx; /* Array of IndexListTerms */
1743 } ax;
1744 } u;
1747 /* When IndexIterator.eType==1, then each index is an array of instances
1748 ** of the following object
1750 struct IndexListTerm {
1751 Index *p; /* The index */
1752 int ix; /* Which entry in the original Table.pIndex list is this index*/
1755 /* Return the first index on the list */
1756 static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){
1757 assert( pIter->i==0 );
1758 if( pIter->eType ){
1759 *pIx = pIter->u.ax.aIdx[0].ix;
1760 return pIter->u.ax.aIdx[0].p;
1761 }else{
1762 *pIx = 0;
1763 return pIter->u.lx.pIdx;
1767 /* Return the next index from the list. Return NULL when out of indexes */
1768 static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){
1769 if( pIter->eType ){
1770 int i = ++pIter->i;
1771 if( i>=pIter->u.ax.nIdx ){
1772 *pIx = i;
1773 return 0;
1775 *pIx = pIter->u.ax.aIdx[i].ix;
1776 return pIter->u.ax.aIdx[i].p;
1777 }else{
1778 ++(*pIx);
1779 pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
1780 return pIter->u.lx.pIdx;
1785 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
1786 ** on table pTab.
1788 ** The regNewData parameter is the first register in a range that contains
1789 ** the data to be inserted or the data after the update. There will be
1790 ** pTab->nCol+1 registers in this range. The first register (the one
1791 ** that regNewData points to) will contain the new rowid, or NULL in the
1792 ** case of a WITHOUT ROWID table. The second register in the range will
1793 ** contain the content of the first table column. The third register will
1794 ** contain the content of the second table column. And so forth.
1796 ** The regOldData parameter is similar to regNewData except that it contains
1797 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
1798 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
1799 ** checking regOldData for zero.
1801 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1802 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1803 ** might be modified by the UPDATE. If pkChng is false, then the key of
1804 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1806 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1807 ** was explicitly specified as part of the INSERT statement. If pkChng
1808 ** is zero, it means that the either rowid is computed automatically or
1809 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
1810 ** pkChng will only be true if the INSERT statement provides an integer
1811 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
1813 ** The code generated by this routine will store new index entries into
1814 ** registers identified by aRegIdx[]. No index entry is created for
1815 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1816 ** the same as the order of indices on the linked list of indices
1817 ** at pTab->pIndex.
1819 ** (2019-05-07) The generated code also creates a new record for the
1820 ** main table, if pTab is a rowid table, and stores that record in the
1821 ** register identified by aRegIdx[nIdx] - in other words in the first
1822 ** entry of aRegIdx[] past the last index. It is important that the
1823 ** record be generated during constraint checks to avoid affinity changes
1824 ** to the register content that occur after constraint checks but before
1825 ** the new record is inserted.
1827 ** The caller must have already opened writeable cursors on the main
1828 ** table and all applicable indices (that is to say, all indices for which
1829 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
1830 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
1831 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
1832 ** for the first index in the pTab->pIndex list. Cursors for other indices
1833 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
1835 ** This routine also generates code to check constraints. NOT NULL,
1836 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
1837 ** then the appropriate action is performed. There are five possible
1838 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
1840 ** Constraint type Action What Happens
1841 ** --------------- ---------- ----------------------------------------
1842 ** any ROLLBACK The current transaction is rolled back and
1843 ** sqlite3_step() returns immediately with a
1844 ** return code of SQLITE_CONSTRAINT.
1846 ** any ABORT Back out changes from the current command
1847 ** only (do not do a complete rollback) then
1848 ** cause sqlite3_step() to return immediately
1849 ** with SQLITE_CONSTRAINT.
1851 ** any FAIL Sqlite3_step() returns immediately with a
1852 ** return code of SQLITE_CONSTRAINT. The
1853 ** transaction is not rolled back and any
1854 ** changes to prior rows are retained.
1856 ** any IGNORE The attempt in insert or update the current
1857 ** row is skipped, without throwing an error.
1858 ** Processing continues with the next row.
1859 ** (There is an immediate jump to ignoreDest.)
1861 ** NOT NULL REPLACE The NULL value is replace by the default
1862 ** value for that column. If the default value
1863 ** is NULL, the action is the same as ABORT.
1865 ** UNIQUE REPLACE The other row that conflicts with the row
1866 ** being inserted is removed.
1868 ** CHECK REPLACE Illegal. The results in an exception.
1870 ** Which action to take is determined by the overrideError parameter.
1871 ** Or if overrideError==OE_Default, then the pParse->onError parameter
1872 ** is used. Or if pParse->onError==OE_Default then the onError value
1873 ** for the constraint is used.
1875 void sqlite3GenerateConstraintChecks(
1876 Parse *pParse, /* The parser context */
1877 Table *pTab, /* The table being inserted or updated */
1878 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
1879 int iDataCur, /* Canonical data cursor (main table or PK index) */
1880 int iIdxCur, /* First index cursor */
1881 int regNewData, /* First register in a range holding values to insert */
1882 int regOldData, /* Previous content. 0 for INSERTs */
1883 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
1884 u8 overrideError, /* Override onError to this if not OE_Default */
1885 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
1886 int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
1887 int *aiChng, /* column i is unchanged if aiChng[i]<0 */
1888 Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
1890 Vdbe *v; /* VDBE under construction */
1891 Index *pIdx; /* Pointer to one of the indices */
1892 Index *pPk = 0; /* The PRIMARY KEY index for WITHOUT ROWID tables */
1893 sqlite3 *db; /* Database connection */
1894 int i; /* loop counter */
1895 int ix; /* Index loop counter */
1896 int nCol; /* Number of columns */
1897 int onError; /* Conflict resolution strategy */
1898 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
1899 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
1900 Upsert *pUpsertClause = 0; /* The specific ON CONFLICT clause for pIdx */
1901 u8 isUpdate; /* True if this is an UPDATE operation */
1902 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
1903 int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */
1904 int upsertIpkDelay = 0; /* Address of Goto to bypass initial IPK check */
1905 int ipkTop = 0; /* Top of the IPK uniqueness check */
1906 int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */
1907 /* Variables associated with retesting uniqueness constraints after
1908 ** replace triggers fire have run */
1909 int regTrigCnt; /* Register used to count replace trigger invocations */
1910 int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */
1911 int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
1912 Trigger *pTrigger; /* List of DELETE triggers on the table pTab */
1913 int nReplaceTrig = 0; /* Number of replace triggers coded */
1914 IndexIterator sIdxIter; /* Index iterator */
1916 isUpdate = regOldData!=0;
1917 db = pParse->db;
1918 v = pParse->pVdbe;
1919 assert( v!=0 );
1920 assert( !IsView(pTab) ); /* This table is not a VIEW */
1921 nCol = pTab->nCol;
1923 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
1924 ** normal rowid tables. nPkField is the number of key fields in the
1925 ** pPk index or 1 for a rowid table. In other words, nPkField is the
1926 ** number of fields in the true primary key of the table. */
1927 if( HasRowid(pTab) ){
1928 pPk = 0;
1929 nPkField = 1;
1930 }else{
1931 pPk = sqlite3PrimaryKeyIndex(pTab);
1932 nPkField = pPk->nKeyCol;
1935 /* Record that this module has started */
1936 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
1937 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
1939 /* Test all NOT NULL constraints.
1941 if( pTab->tabFlags & TF_HasNotNull ){
1942 int b2ndPass = 0; /* True if currently running 2nd pass */
1943 int nSeenReplace = 0; /* Number of ON CONFLICT REPLACE operations */
1944 int nGenerated = 0; /* Number of generated columns with NOT NULL */
1945 while(1){ /* Make 2 passes over columns. Exit loop via "break" */
1946 for(i=0; i<nCol; i++){
1947 int iReg; /* Register holding column value */
1948 Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */
1949 int isGenerated; /* non-zero if column is generated */
1950 onError = pCol->notNull;
1951 if( onError==OE_None ) continue; /* No NOT NULL on this column */
1952 if( i==pTab->iPKey ){
1953 continue; /* ROWID is never NULL */
1955 isGenerated = pCol->colFlags & COLFLAG_GENERATED;
1956 if( isGenerated && !b2ndPass ){
1957 nGenerated++;
1958 continue; /* Generated columns processed on 2nd pass */
1960 if( aiChng && aiChng[i]<0 && !isGenerated ){
1961 /* Do not check NOT NULL on columns that do not change */
1962 continue;
1964 if( overrideError!=OE_Default ){
1965 onError = overrideError;
1966 }else if( onError==OE_Default ){
1967 onError = OE_Abort;
1969 if( onError==OE_Replace ){
1970 if( b2ndPass /* REPLACE becomes ABORT on the 2nd pass */
1971 || pCol->iDflt==0 /* REPLACE is ABORT if no DEFAULT value */
1973 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1974 testcase( pCol->colFlags & COLFLAG_STORED );
1975 testcase( pCol->colFlags & COLFLAG_GENERATED );
1976 onError = OE_Abort;
1977 }else{
1978 assert( !isGenerated );
1980 }else if( b2ndPass && !isGenerated ){
1981 continue;
1983 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1984 || onError==OE_Ignore || onError==OE_Replace );
1985 testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
1986 iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
1987 switch( onError ){
1988 case OE_Replace: {
1989 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
1990 VdbeCoverage(v);
1991 assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
1992 nSeenReplace++;
1993 sqlite3ExprCodeCopy(pParse,
1994 sqlite3ColumnExpr(pTab, pCol), iReg);
1995 sqlite3VdbeJumpHere(v, addr1);
1996 break;
1998 case OE_Abort:
1999 sqlite3MayAbort(pParse);
2000 /* no break */ deliberate_fall_through
2001 case OE_Rollback:
2002 case OE_Fail: {
2003 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
2004 pCol->zCnName);
2005 testcase( zMsg==0 && db->mallocFailed==0 );
2006 sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
2007 onError, iReg);
2008 sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
2009 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
2010 VdbeCoverage(v);
2011 break;
2013 default: {
2014 assert( onError==OE_Ignore );
2015 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
2016 VdbeCoverage(v);
2017 break;
2019 } /* end switch(onError) */
2020 } /* end loop i over columns */
2021 if( nGenerated==0 && nSeenReplace==0 ){
2022 /* If there are no generated columns with NOT NULL constraints
2023 ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
2024 ** pass is sufficient */
2025 break;
2027 if( b2ndPass ) break; /* Never need more than 2 passes */
2028 b2ndPass = 1;
2029 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2030 if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
2031 /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
2032 ** first pass, recomputed values for all generated columns, as
2033 ** those values might depend on columns affected by the REPLACE.
2035 sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
2037 #endif
2038 } /* end of 2-pass loop */
2039 } /* end if( has-not-null-constraints ) */
2041 /* Test all CHECK constraints
2043 #ifndef SQLITE_OMIT_CHECK
2044 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
2045 ExprList *pCheck = pTab->pCheck;
2046 pParse->iSelfTab = -(regNewData+1);
2047 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
2048 for(i=0; i<pCheck->nExpr; i++){
2049 int allOk;
2050 Expr *pCopy;
2051 Expr *pExpr = pCheck->a[i].pExpr;
2052 if( aiChng
2053 && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
2055 /* The check constraints do not reference any of the columns being
2056 ** updated so there is no point it verifying the check constraint */
2057 continue;
2059 if( bAffinityDone==0 ){
2060 sqlite3TableAffinity(v, pTab, regNewData+1);
2061 bAffinityDone = 1;
2063 allOk = sqlite3VdbeMakeLabel(pParse);
2064 sqlite3VdbeVerifyAbortable(v, onError);
2065 pCopy = sqlite3ExprDup(db, pExpr, 0);
2066 if( !db->mallocFailed ){
2067 sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
2069 sqlite3ExprDelete(db, pCopy);
2070 if( onError==OE_Ignore ){
2071 sqlite3VdbeGoto(v, ignoreDest);
2072 }else{
2073 char *zName = pCheck->a[i].zEName;
2074 assert( zName!=0 || pParse->db->mallocFailed );
2075 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
2076 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
2077 onError, zName, P4_TRANSIENT,
2078 P5_ConstraintCheck);
2080 sqlite3VdbeResolveLabel(v, allOk);
2082 pParse->iSelfTab = 0;
2084 #endif /* !defined(SQLITE_OMIT_CHECK) */
2086 /* UNIQUE and PRIMARY KEY constraints should be handled in the following
2087 ** order:
2089 ** (1) OE_Update
2090 ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
2091 ** (3) OE_Replace
2093 ** OE_Fail and OE_Ignore must happen before any changes are made.
2094 ** OE_Update guarantees that only a single row will change, so it
2095 ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
2096 ** could happen in any order, but they are grouped up front for
2097 ** convenience.
2099 ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
2100 ** The order of constraints used to have OE_Update as (2) and OE_Abort
2101 ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
2102 ** constraint before any others, so it had to be moved.
2104 ** Constraint checking code is generated in this order:
2105 ** (A) The rowid constraint
2106 ** (B) Unique index constraints that do not have OE_Replace as their
2107 ** default conflict resolution strategy
2108 ** (C) Unique index that do use OE_Replace by default.
2110 ** The ordering of (2) and (3) is accomplished by making sure the linked
2111 ** list of indexes attached to a table puts all OE_Replace indexes last
2112 ** in the list. See sqlite3CreateIndex() for where that happens.
2114 sIdxIter.eType = 0;
2115 sIdxIter.i = 0;
2116 sIdxIter.u.ax.aIdx = 0; /* Silence harmless compiler warning */
2117 sIdxIter.u.lx.pIdx = pTab->pIndex;
2118 if( pUpsert ){
2119 if( pUpsert->pUpsertTarget==0 ){
2120 /* There is just on ON CONFLICT clause and it has no constraint-target */
2121 assert( pUpsert->pNextUpsert==0 );
2122 if( pUpsert->isDoUpdate==0 ){
2123 /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
2124 ** Make all unique constraint resolution be OE_Ignore */
2125 overrideError = OE_Ignore;
2126 pUpsert = 0;
2127 }else{
2128 /* A single ON CONFLICT DO UPDATE. Make all resolutions OE_Update */
2129 overrideError = OE_Update;
2131 }else if( pTab->pIndex!=0 ){
2132 /* Otherwise, we'll need to run the IndexListTerm array version of the
2133 ** iterator to ensure that all of the ON CONFLICT conditions are
2134 ** checked first and in order. */
2135 int nIdx, jj;
2136 u64 nByte;
2137 Upsert *pTerm;
2138 u8 *bUsed;
2139 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
2140 assert( aRegIdx[nIdx]>0 );
2142 sIdxIter.eType = 1;
2143 sIdxIter.u.ax.nIdx = nIdx;
2144 nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx;
2145 sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte);
2146 if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */
2147 bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx];
2148 pUpsert->pToFree = sIdxIter.u.ax.aIdx;
2149 for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
2150 if( pTerm->pUpsertTarget==0 ) break;
2151 if( pTerm->pUpsertIdx==0 ) continue; /* Skip ON CONFLICT for the IPK */
2152 jj = 0;
2153 pIdx = pTab->pIndex;
2154 while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
2155 pIdx = pIdx->pNext;
2156 jj++;
2158 if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */
2159 bUsed[jj] = 1;
2160 sIdxIter.u.ax.aIdx[i].p = pIdx;
2161 sIdxIter.u.ax.aIdx[i].ix = jj;
2162 i++;
2164 for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
2165 if( bUsed[jj] ) continue;
2166 sIdxIter.u.ax.aIdx[i].p = pIdx;
2167 sIdxIter.u.ax.aIdx[i].ix = jj;
2168 i++;
2170 assert( i==nIdx );
2174 /* Determine if it is possible that triggers (either explicitly coded
2175 ** triggers or FK resolution actions) might run as a result of deletes
2176 ** that happen when OE_Replace conflict resolution occurs. (Call these
2177 ** "replace triggers".) If any replace triggers run, we will need to
2178 ** recheck all of the uniqueness constraints after they have all run.
2179 ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
2181 ** If replace triggers are a possibility, then
2183 ** (1) Allocate register regTrigCnt and initialize it to zero.
2184 ** That register will count the number of replace triggers that
2185 ** fire. Constraint recheck only occurs if the number is positive.
2186 ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
2187 ** (3) Initialize addrRecheck and lblRecheckOk
2189 ** The uniqueness rechecking code will create a series of tests to run
2190 ** in a second pass. The addrRecheck and lblRecheckOk variables are
2191 ** used to link together these tests which are separated from each other
2192 ** in the generate bytecode.
2194 if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
2195 /* There are not DELETE triggers nor FK constraints. No constraint
2196 ** rechecks are needed. */
2197 pTrigger = 0;
2198 regTrigCnt = 0;
2199 }else{
2200 if( db->flags&SQLITE_RecTriggers ){
2201 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
2202 regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
2203 }else{
2204 pTrigger = 0;
2205 regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
2207 if( regTrigCnt ){
2208 /* Replace triggers might exist. Allocate the counter and
2209 ** initialize it to zero. */
2210 regTrigCnt = ++pParse->nMem;
2211 sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
2212 VdbeComment((v, "trigger count"));
2213 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2214 addrRecheck = lblRecheckOk;
2218 /* If rowid is changing, make sure the new rowid does not previously
2219 ** exist in the table.
2221 if( pkChng && pPk==0 ){
2222 int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
2224 /* Figure out what action to take in case of a rowid collision */
2225 onError = pTab->keyConf;
2226 if( overrideError!=OE_Default ){
2227 onError = overrideError;
2228 }else if( onError==OE_Default ){
2229 onError = OE_Abort;
2232 /* figure out whether or not upsert applies in this case */
2233 if( pUpsert ){
2234 pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0);
2235 if( pUpsertClause!=0 ){
2236 if( pUpsertClause->isDoUpdate==0 ){
2237 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
2238 }else{
2239 onError = OE_Update; /* DO UPDATE */
2242 if( pUpsertClause!=pUpsert ){
2243 /* The first ON CONFLICT clause has a conflict target other than
2244 ** the IPK. We have to jump ahead to that first ON CONFLICT clause
2245 ** and then come back here and deal with the IPK afterwards */
2246 upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto);
2250 /* If the response to a rowid conflict is REPLACE but the response
2251 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
2252 ** to defer the running of the rowid conflict checking until after
2253 ** the UNIQUE constraints have run.
2255 if( onError==OE_Replace /* IPK rule is REPLACE */
2256 && onError!=overrideError /* Rules for other constraints are different */
2257 && pTab->pIndex /* There exist other constraints */
2258 && !upsertIpkDelay /* IPK check already deferred by UPSERT */
2260 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
2261 VdbeComment((v, "defer IPK REPLACE until last"));
2264 if( isUpdate ){
2265 /* pkChng!=0 does not mean that the rowid has changed, only that
2266 ** it might have changed. Skip the conflict logic below if the rowid
2267 ** is unchanged. */
2268 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
2269 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2270 VdbeCoverage(v);
2273 /* Check to see if the new rowid already exists in the table. Skip
2274 ** the following conflict logic if it does not. */
2275 VdbeNoopComment((v, "uniqueness check for ROWID"));
2276 sqlite3VdbeVerifyAbortable(v, onError);
2277 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
2278 VdbeCoverage(v);
2280 switch( onError ){
2281 default: {
2282 onError = OE_Abort;
2283 /* no break */ deliberate_fall_through
2285 case OE_Rollback:
2286 case OE_Abort:
2287 case OE_Fail: {
2288 testcase( onError==OE_Rollback );
2289 testcase( onError==OE_Abort );
2290 testcase( onError==OE_Fail );
2291 sqlite3RowidConstraint(pParse, onError, pTab);
2292 break;
2294 case OE_Replace: {
2295 /* If there are DELETE triggers on this table and the
2296 ** recursive-triggers flag is set, call GenerateRowDelete() to
2297 ** remove the conflicting row from the table. This will fire
2298 ** the triggers and remove both the table and index b-tree entries.
2300 ** Otherwise, if there are no triggers or the recursive-triggers
2301 ** flag is not set, but the table has one or more indexes, call
2302 ** GenerateRowIndexDelete(). This removes the index b-tree entries
2303 ** only. The table b-tree entry will be replaced by the new entry
2304 ** when it is inserted.
2306 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
2307 ** also invoke MultiWrite() to indicate that this VDBE may require
2308 ** statement rollback (if the statement is aborted after the delete
2309 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
2310 ** but being more selective here allows statements like:
2312 ** REPLACE INTO t(rowid) VALUES($newrowid)
2314 ** to run without a statement journal if there are no indexes on the
2315 ** table.
2317 if( regTrigCnt ){
2318 sqlite3MultiWrite(pParse);
2319 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2320 regNewData, 1, 0, OE_Replace, 1, -1);
2321 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2322 nReplaceTrig++;
2323 }else{
2324 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2325 assert( HasRowid(pTab) );
2326 /* This OP_Delete opcode fires the pre-update-hook only. It does
2327 ** not modify the b-tree. It is more efficient to let the coming
2328 ** OP_Insert replace the existing entry than it is to delete the
2329 ** existing entry and then insert a new one. */
2330 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
2331 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
2332 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2333 if( pTab->pIndex ){
2334 sqlite3MultiWrite(pParse);
2335 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
2338 seenReplace = 1;
2339 break;
2341 #ifndef SQLITE_OMIT_UPSERT
2342 case OE_Update: {
2343 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
2344 /* no break */ deliberate_fall_through
2346 #endif
2347 case OE_Ignore: {
2348 testcase( onError==OE_Ignore );
2349 sqlite3VdbeGoto(v, ignoreDest);
2350 break;
2353 sqlite3VdbeResolveLabel(v, addrRowidOk);
2354 if( pUpsert && pUpsertClause!=pUpsert ){
2355 upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
2356 }else if( ipkTop ){
2357 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
2358 sqlite3VdbeJumpHere(v, ipkTop-1);
2362 /* Test all UNIQUE constraints by creating entries for each UNIQUE
2363 ** index and making sure that duplicate entries do not already exist.
2364 ** Compute the revised record entries for indices as we go.
2366 ** This loop also handles the case of the PRIMARY KEY index for a
2367 ** WITHOUT ROWID table.
2369 for(pIdx = indexIteratorFirst(&sIdxIter, &ix);
2370 pIdx;
2371 pIdx = indexIteratorNext(&sIdxIter, &ix)
2373 int regIdx; /* Range of registers holding content for pIdx */
2374 int regR; /* Range of registers holding conflicting PK */
2375 int iThisCur; /* Cursor for this UNIQUE index */
2376 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
2377 int addrConflictCk; /* First opcode in the conflict check logic */
2379 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
2380 if( pUpsert ){
2381 pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
2382 if( upsertIpkDelay && pUpsertClause==pUpsert ){
2383 sqlite3VdbeJumpHere(v, upsertIpkDelay);
2386 addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
2387 if( bAffinityDone==0 ){
2388 sqlite3TableAffinity(v, pTab, regNewData+1);
2389 bAffinityDone = 1;
2391 VdbeNoopComment((v, "prep index %s", pIdx->zName));
2392 iThisCur = iIdxCur+ix;
2395 /* Skip partial indices for which the WHERE clause is not true */
2396 if( pIdx->pPartIdxWhere ){
2397 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
2398 pParse->iSelfTab = -(regNewData+1);
2399 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
2400 SQLITE_JUMPIFNULL);
2401 pParse->iSelfTab = 0;
2404 /* Create a record for this index entry as it should appear after
2405 ** the insert or update. Store that record in the aRegIdx[ix] register
2407 regIdx = aRegIdx[ix]+1;
2408 for(i=0; i<pIdx->nColumn; i++){
2409 int iField = pIdx->aiColumn[i];
2410 int x;
2411 if( iField==XN_EXPR ){
2412 pParse->iSelfTab = -(regNewData+1);
2413 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
2414 pParse->iSelfTab = 0;
2415 VdbeComment((v, "%s column %d", pIdx->zName, i));
2416 }else if( iField==XN_ROWID || iField==pTab->iPKey ){
2417 x = regNewData;
2418 sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
2419 VdbeComment((v, "rowid"));
2420 }else{
2421 testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
2422 x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
2423 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
2424 VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
2427 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
2428 VdbeComment((v, "for %s", pIdx->zName));
2429 #ifdef SQLITE_ENABLE_NULL_TRIM
2430 if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
2431 sqlite3SetMakeRecordP5(v, pIdx->pTable);
2433 #endif
2434 sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
2436 /* In an UPDATE operation, if this index is the PRIMARY KEY index
2437 ** of a WITHOUT ROWID table and there has been no change the
2438 ** primary key, then no collision is possible. The collision detection
2439 ** logic below can all be skipped. */
2440 if( isUpdate && pPk==pIdx && pkChng==0 ){
2441 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2442 continue;
2445 /* Find out what action to take in case there is a uniqueness conflict */
2446 onError = pIdx->onError;
2447 if( onError==OE_None ){
2448 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2449 continue; /* pIdx is not a UNIQUE index */
2451 if( overrideError!=OE_Default ){
2452 onError = overrideError;
2453 }else if( onError==OE_Default ){
2454 onError = OE_Abort;
2457 /* Figure out if the upsert clause applies to this index */
2458 if( pUpsertClause ){
2459 if( pUpsertClause->isDoUpdate==0 ){
2460 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
2461 }else{
2462 onError = OE_Update; /* DO UPDATE */
2466 /* Collision detection may be omitted if all of the following are true:
2467 ** (1) The conflict resolution algorithm is REPLACE
2468 ** (2) The table is a WITHOUT ROWID table
2469 ** (3) There are no secondary indexes on the table
2470 ** (4) No delete triggers need to be fired if there is a conflict
2471 ** (5) No FK constraint counters need to be updated if a conflict occurs.
2473 ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
2474 ** must be explicitly deleted in order to ensure any pre-update hook
2475 ** is invoked. */
2476 assert( IsOrdinaryTable(pTab) );
2477 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
2478 if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
2479 && pPk==pIdx /* Condition 2 */
2480 && onError==OE_Replace /* Condition 1 */
2481 && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
2482 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
2483 && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
2484 (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
2486 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2487 continue;
2489 #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
2491 /* Check to see if the new index entry will be unique */
2492 sqlite3VdbeVerifyAbortable(v, onError);
2493 addrConflictCk =
2494 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
2495 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
2497 /* Generate code to handle collisions */
2498 regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField);
2499 if( isUpdate || onError==OE_Replace ){
2500 if( HasRowid(pTab) ){
2501 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
2502 /* Conflict only if the rowid of the existing index entry
2503 ** is different from old-rowid */
2504 if( isUpdate ){
2505 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
2506 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2507 VdbeCoverage(v);
2509 }else{
2510 int x;
2511 /* Extract the PRIMARY KEY from the end of the index entry and
2512 ** store it in registers regR..regR+nPk-1 */
2513 if( pIdx!=pPk ){
2514 for(i=0; i<pPk->nKeyCol; i++){
2515 assert( pPk->aiColumn[i]>=0 );
2516 x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
2517 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
2518 VdbeComment((v, "%s.%s", pTab->zName,
2519 pTab->aCol[pPk->aiColumn[i]].zCnName));
2522 if( isUpdate ){
2523 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
2524 ** table, only conflict if the new PRIMARY KEY values are actually
2525 ** different from the old. See TH3 withoutrowid04.test.
2527 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
2528 ** of the matched index row are different from the original PRIMARY
2529 ** KEY values of this row before the update. */
2530 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
2531 int op = OP_Ne;
2532 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
2534 for(i=0; i<pPk->nKeyCol; i++){
2535 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
2536 x = pPk->aiColumn[i];
2537 assert( x>=0 );
2538 if( i==(pPk->nKeyCol-1) ){
2539 addrJump = addrUniqueOk;
2540 op = OP_Eq;
2542 x = sqlite3TableColumnToStorage(pTab, x);
2543 sqlite3VdbeAddOp4(v, op,
2544 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
2546 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2547 VdbeCoverageIf(v, op==OP_Eq);
2548 VdbeCoverageIf(v, op==OP_Ne);
2554 /* Generate code that executes if the new index entry is not unique */
2555 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
2556 || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
2557 switch( onError ){
2558 case OE_Rollback:
2559 case OE_Abort:
2560 case OE_Fail: {
2561 testcase( onError==OE_Rollback );
2562 testcase( onError==OE_Abort );
2563 testcase( onError==OE_Fail );
2564 sqlite3UniqueConstraint(pParse, onError, pIdx);
2565 break;
2567 #ifndef SQLITE_OMIT_UPSERT
2568 case OE_Update: {
2569 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
2570 /* no break */ deliberate_fall_through
2572 #endif
2573 case OE_Ignore: {
2574 testcase( onError==OE_Ignore );
2575 sqlite3VdbeGoto(v, ignoreDest);
2576 break;
2578 default: {
2579 int nConflictCk; /* Number of opcodes in conflict check logic */
2581 assert( onError==OE_Replace );
2582 nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
2583 assert( nConflictCk>0 || db->mallocFailed );
2584 testcase( nConflictCk<=0 );
2585 testcase( nConflictCk>1 );
2586 if( regTrigCnt ){
2587 sqlite3MultiWrite(pParse);
2588 nReplaceTrig++;
2590 if( pTrigger && isUpdate ){
2591 sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
2593 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2594 regR, nPkField, 0, OE_Replace,
2595 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
2596 if( pTrigger && isUpdate ){
2597 sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
2599 if( regTrigCnt ){
2600 int addrBypass; /* Jump destination to bypass recheck logic */
2602 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2603 addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
2604 VdbeComment((v, "bypass recheck"));
2606 /* Here we insert code that will be invoked after all constraint
2607 ** checks have run, if and only if one or more replace triggers
2608 ** fired. */
2609 sqlite3VdbeResolveLabel(v, lblRecheckOk);
2610 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2611 if( pIdx->pPartIdxWhere ){
2612 /* Bypass the recheck if this partial index is not defined
2613 ** for the current row */
2614 sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
2615 VdbeCoverage(v);
2617 /* Copy the constraint check code from above, except change
2618 ** the constraint-ok jump destination to be the address of
2619 ** the next retest block */
2620 while( nConflictCk>0 ){
2621 VdbeOp x; /* Conflict check opcode to copy */
2622 /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
2623 ** Hence, make a complete copy of the opcode, rather than using
2624 ** a pointer to the opcode. */
2625 x = *sqlite3VdbeGetOp(v, addrConflictCk);
2626 if( x.opcode!=OP_IdxRowid ){
2627 int p2; /* New P2 value for copied conflict check opcode */
2628 const char *zP4;
2629 if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
2630 p2 = lblRecheckOk;
2631 }else{
2632 p2 = x.p2;
2634 zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
2635 sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
2636 sqlite3VdbeChangeP5(v, x.p5);
2637 VdbeCoverageIf(v, p2!=x.p2);
2639 nConflictCk--;
2640 addrConflictCk++;
2642 /* If the retest fails, issue an abort */
2643 sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
2645 sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
2647 seenReplace = 1;
2648 break;
2651 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2652 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
2653 if( pUpsertClause
2654 && upsertIpkReturn
2655 && sqlite3UpsertNextIsIPK(pUpsertClause)
2657 sqlite3VdbeGoto(v, upsertIpkDelay+1);
2658 sqlite3VdbeJumpHere(v, upsertIpkReturn);
2659 upsertIpkReturn = 0;
2663 /* If the IPK constraint is a REPLACE, run it last */
2664 if( ipkTop ){
2665 sqlite3VdbeGoto(v, ipkTop);
2666 VdbeComment((v, "Do IPK REPLACE"));
2667 assert( ipkBottom>0 );
2668 sqlite3VdbeJumpHere(v, ipkBottom);
2671 /* Recheck all uniqueness constraints after replace triggers have run */
2672 testcase( regTrigCnt!=0 && nReplaceTrig==0 );
2673 assert( regTrigCnt!=0 || nReplaceTrig==0 );
2674 if( nReplaceTrig ){
2675 sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
2676 if( !pPk ){
2677 if( isUpdate ){
2678 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
2679 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2680 VdbeCoverage(v);
2682 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
2683 VdbeCoverage(v);
2684 sqlite3RowidConstraint(pParse, OE_Abort, pTab);
2685 }else{
2686 sqlite3VdbeGoto(v, addrRecheck);
2688 sqlite3VdbeResolveLabel(v, lblRecheckOk);
2691 /* Generate the table record */
2692 if( HasRowid(pTab) ){
2693 int regRec = aRegIdx[ix];
2694 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
2695 sqlite3SetMakeRecordP5(v, pTab);
2696 if( !bAffinityDone ){
2697 sqlite3TableAffinity(v, pTab, 0);
2701 *pbMayReplace = seenReplace;
2702 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
2705 #ifdef SQLITE_ENABLE_NULL_TRIM
2707 ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
2708 ** to be the number of columns in table pTab that must not be NULL-trimmed.
2710 ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
2712 void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
2713 u16 i;
2715 /* Records with omitted columns are only allowed for schema format
2716 ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
2717 if( pTab->pSchema->file_format<2 ) return;
2719 for(i=pTab->nCol-1; i>0; i--){
2720 if( pTab->aCol[i].iDflt!=0 ) break;
2721 if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
2723 sqlite3VdbeChangeP5(v, i+1);
2725 #endif
2728 ** Table pTab is a WITHOUT ROWID table that is being written to. The cursor
2729 ** number is iCur, and register regData contains the new record for the
2730 ** PK index. This function adds code to invoke the pre-update hook,
2731 ** if one is registered.
2733 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2734 static void codeWithoutRowidPreupdate(
2735 Parse *pParse, /* Parse context */
2736 Table *pTab, /* Table being updated */
2737 int iCur, /* Cursor number for table */
2738 int regData /* Data containing new record */
2740 Vdbe *v = pParse->pVdbe;
2741 int r = sqlite3GetTempReg(pParse);
2742 assert( !HasRowid(pTab) );
2743 assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
2744 sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
2745 sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE);
2746 sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
2747 sqlite3ReleaseTempReg(pParse, r);
2749 #else
2750 # define codeWithoutRowidPreupdate(a,b,c,d)
2751 #endif
2754 ** This routine generates code to finish the INSERT or UPDATE operation
2755 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
2756 ** A consecutive range of registers starting at regNewData contains the
2757 ** rowid and the content to be inserted.
2759 ** The arguments to this routine should be the same as the first six
2760 ** arguments to sqlite3GenerateConstraintChecks.
2762 void sqlite3CompleteInsertion(
2763 Parse *pParse, /* The parser context */
2764 Table *pTab, /* the table into which we are inserting */
2765 int iDataCur, /* Cursor of the canonical data source */
2766 int iIdxCur, /* First index cursor */
2767 int regNewData, /* Range of content */
2768 int *aRegIdx, /* Register used by each index. 0 for unused indices */
2769 int update_flags, /* True for UPDATE, False for INSERT */
2770 int appendBias, /* True if this is likely to be an append */
2771 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
2773 Vdbe *v; /* Prepared statements under construction */
2774 Index *pIdx; /* An index being inserted or updated */
2775 u8 pik_flags; /* flag values passed to the btree insert */
2776 int i; /* Loop counter */
2778 assert( update_flags==0
2779 || update_flags==OPFLAG_ISUPDATE
2780 || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
2783 v = pParse->pVdbe;
2784 assert( v!=0 );
2785 assert( !IsView(pTab) ); /* This table is not a VIEW */
2786 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2787 /* All REPLACE indexes are at the end of the list */
2788 assert( pIdx->onError!=OE_Replace
2789 || pIdx->pNext==0
2790 || pIdx->pNext->onError==OE_Replace );
2791 if( aRegIdx[i]==0 ) continue;
2792 if( pIdx->pPartIdxWhere ){
2793 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
2794 VdbeCoverage(v);
2796 pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
2797 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2798 pik_flags |= OPFLAG_NCHANGE;
2799 pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
2800 if( update_flags==0 ){
2801 codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]);
2804 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
2805 aRegIdx[i]+1,
2806 pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
2807 sqlite3VdbeChangeP5(v, pik_flags);
2809 if( !HasRowid(pTab) ) return;
2810 if( pParse->nested ){
2811 pik_flags = 0;
2812 }else{
2813 pik_flags = OPFLAG_NCHANGE;
2814 pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
2816 if( appendBias ){
2817 pik_flags |= OPFLAG_APPEND;
2819 if( useSeekResult ){
2820 pik_flags |= OPFLAG_USESEEKRESULT;
2822 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
2823 if( !pParse->nested ){
2824 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
2826 sqlite3VdbeChangeP5(v, pik_flags);
2830 ** Allocate cursors for the pTab table and all its indices and generate
2831 ** code to open and initialized those cursors.
2833 ** The cursor for the object that contains the complete data (normally
2834 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
2835 ** ROWID table) is returned in *piDataCur. The first index cursor is
2836 ** returned in *piIdxCur. The number of indices is returned.
2838 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
2839 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
2840 ** If iBase is negative, then allocate the next available cursor.
2842 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
2843 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
2844 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
2845 ** pTab->pIndex list.
2847 ** If pTab is a virtual table, then this routine is a no-op and the
2848 ** *piDataCur and *piIdxCur values are left uninitialized.
2850 int sqlite3OpenTableAndIndices(
2851 Parse *pParse, /* Parsing context */
2852 Table *pTab, /* Table to be opened */
2853 int op, /* OP_OpenRead or OP_OpenWrite */
2854 u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
2855 int iBase, /* Use this for the table cursor, if there is one */
2856 u8 *aToOpen, /* If not NULL: boolean for each table and index */
2857 int *piDataCur, /* Write the database source cursor number here */
2858 int *piIdxCur /* Write the first index cursor number here */
2860 int i;
2861 int iDb;
2862 int iDataCur;
2863 Index *pIdx;
2864 Vdbe *v;
2866 assert( op==OP_OpenRead || op==OP_OpenWrite );
2867 assert( op==OP_OpenWrite || p5==0 );
2868 assert( piDataCur!=0 );
2869 assert( piIdxCur!=0 );
2870 if( IsVirtual(pTab) ){
2871 /* This routine is a no-op for virtual tables. Leave the output
2872 ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
2873 ** for improved error detection. */
2874 *piDataCur = *piIdxCur = -999;
2875 return 0;
2877 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2878 v = pParse->pVdbe;
2879 assert( v!=0 );
2880 if( iBase<0 ) iBase = pParse->nTab;
2881 iDataCur = iBase++;
2882 *piDataCur = iDataCur;
2883 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
2884 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
2885 }else if( pParse->db->noSharedCache==0 ){
2886 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
2888 *piIdxCur = iBase;
2889 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2890 int iIdxCur = iBase++;
2891 assert( pIdx->pSchema==pTab->pSchema );
2892 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2893 *piDataCur = iIdxCur;
2894 p5 = 0;
2896 if( aToOpen==0 || aToOpen[i+1] ){
2897 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
2898 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2899 sqlite3VdbeChangeP5(v, p5);
2900 VdbeComment((v, "%s", pIdx->zName));
2903 if( iBase>pParse->nTab ) pParse->nTab = iBase;
2904 return i;
2908 #ifdef SQLITE_TEST
2910 ** The following global variable is incremented whenever the
2911 ** transfer optimization is used. This is used for testing
2912 ** purposes only - to make sure the transfer optimization really
2913 ** is happening when it is supposed to.
2915 int sqlite3_xferopt_count;
2916 #endif /* SQLITE_TEST */
2919 #ifndef SQLITE_OMIT_XFER_OPT
2921 ** Check to see if index pSrc is compatible as a source of data
2922 ** for index pDest in an insert transfer optimization. The rules
2923 ** for a compatible index:
2925 ** * The index is over the same set of columns
2926 ** * The same DESC and ASC markings occurs on all columns
2927 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
2928 ** * The same collating sequence on each column
2929 ** * The index has the exact same WHERE clause
2931 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
2932 int i;
2933 assert( pDest && pSrc );
2934 assert( pDest->pTable!=pSrc->pTable );
2935 if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
2936 return 0; /* Different number of columns */
2938 if( pDest->onError!=pSrc->onError ){
2939 return 0; /* Different conflict resolution strategies */
2941 for(i=0; i<pSrc->nKeyCol; i++){
2942 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
2943 return 0; /* Different columns indexed */
2945 if( pSrc->aiColumn[i]==XN_EXPR ){
2946 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
2947 if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
2948 pDest->aColExpr->a[i].pExpr, -1)!=0 ){
2949 return 0; /* Different expressions in the index */
2952 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
2953 return 0; /* Different sort orders */
2955 if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
2956 return 0; /* Different collating sequences */
2959 if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
2960 return 0; /* Different WHERE clauses */
2963 /* If no test above fails then the indices must be compatible */
2964 return 1;
2968 ** Attempt the transfer optimization on INSERTs of the form
2970 ** INSERT INTO tab1 SELECT * FROM tab2;
2972 ** The xfer optimization transfers raw records from tab2 over to tab1.
2973 ** Columns are not decoded and reassembled, which greatly improves
2974 ** performance. Raw index records are transferred in the same way.
2976 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
2977 ** There are lots of rules for determining compatibility - see comments
2978 ** embedded in the code for details.
2980 ** This routine returns TRUE if the optimization is guaranteed to be used.
2981 ** Sometimes the xfer optimization will only work if the destination table
2982 ** is empty - a factor that can only be determined at run-time. In that
2983 ** case, this routine generates code for the xfer optimization but also
2984 ** does a test to see if the destination table is empty and jumps over the
2985 ** xfer optimization code if the test fails. In that case, this routine
2986 ** returns FALSE so that the caller will know to go ahead and generate
2987 ** an unoptimized transfer. This routine also returns FALSE if there
2988 ** is no chance that the xfer optimization can be applied.
2990 ** This optimization is particularly useful at making VACUUM run faster.
2992 static int xferOptimization(
2993 Parse *pParse, /* Parser context */
2994 Table *pDest, /* The table we are inserting into */
2995 Select *pSelect, /* A SELECT statement to use as the data source */
2996 int onError, /* How to handle constraint errors */
2997 int iDbDest /* The database of pDest */
2999 sqlite3 *db = pParse->db;
3000 ExprList *pEList; /* The result set of the SELECT */
3001 Table *pSrc; /* The table in the FROM clause of SELECT */
3002 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
3003 SrcItem *pItem; /* An element of pSelect->pSrc */
3004 int i; /* Loop counter */
3005 int iDbSrc; /* The database of pSrc */
3006 int iSrc, iDest; /* Cursors from source and destination */
3007 int addr1, addr2; /* Loop addresses */
3008 int emptyDestTest = 0; /* Address of test for empty pDest */
3009 int emptySrcTest = 0; /* Address of test for empty pSrc */
3010 Vdbe *v; /* The VDBE we are building */
3011 int regAutoinc; /* Memory register used by AUTOINC */
3012 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
3013 int regData, regRowid; /* Registers holding data and rowid */
3015 assert( pSelect!=0 );
3016 if( pParse->pWith || pSelect->pWith ){
3017 /* Do not attempt to process this query if there are an WITH clauses
3018 ** attached to it. Proceeding may generate a false "no such table: xxx"
3019 ** error if pSelect reads from a CTE named "xxx". */
3020 return 0;
3022 #ifndef SQLITE_OMIT_VIRTUALTABLE
3023 if( IsVirtual(pDest) ){
3024 return 0; /* tab1 must not be a virtual table */
3026 #endif
3027 if( onError==OE_Default ){
3028 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
3029 if( onError==OE_Default ) onError = OE_Abort;
3031 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
3032 if( pSelect->pSrc->nSrc!=1 ){
3033 return 0; /* FROM clause must have exactly one term */
3035 if( pSelect->pSrc->a[0].pSelect ){
3036 return 0; /* FROM clause cannot contain a subquery */
3038 if( pSelect->pWhere ){
3039 return 0; /* SELECT may not have a WHERE clause */
3041 if( pSelect->pOrderBy ){
3042 return 0; /* SELECT may not have an ORDER BY clause */
3044 /* Do not need to test for a HAVING clause. If HAVING is present but
3045 ** there is no ORDER BY, we will get an error. */
3046 if( pSelect->pGroupBy ){
3047 return 0; /* SELECT may not have a GROUP BY clause */
3049 if( pSelect->pLimit ){
3050 return 0; /* SELECT may not have a LIMIT clause */
3052 if( pSelect->pPrior ){
3053 return 0; /* SELECT may not be a compound query */
3055 if( pSelect->selFlags & SF_Distinct ){
3056 return 0; /* SELECT may not be DISTINCT */
3058 pEList = pSelect->pEList;
3059 assert( pEList!=0 );
3060 if( pEList->nExpr!=1 ){
3061 return 0; /* The result set must have exactly one column */
3063 assert( pEList->a[0].pExpr );
3064 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
3065 return 0; /* The result set must be the special operator "*" */
3068 /* At this point we have established that the statement is of the
3069 ** correct syntactic form to participate in this optimization. Now
3070 ** we have to check the semantics.
3072 pItem = pSelect->pSrc->a;
3073 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
3074 if( pSrc==0 ){
3075 return 0; /* FROM clause does not contain a real table */
3077 if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
3078 testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
3079 return 0; /* tab1 and tab2 may not be the same table */
3081 if( HasRowid(pDest)!=HasRowid(pSrc) ){
3082 return 0; /* source and destination must both be WITHOUT ROWID or not */
3084 if( !IsOrdinaryTable(pSrc) ){
3085 return 0; /* tab2 may not be a view or virtual table */
3087 if( pDest->nCol!=pSrc->nCol ){
3088 return 0; /* Number of columns must be the same in tab1 and tab2 */
3090 if( pDest->iPKey!=pSrc->iPKey ){
3091 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
3093 if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
3094 return 0; /* Cannot feed from a non-strict into a strict table */
3096 for(i=0; i<pDest->nCol; i++){
3097 Column *pDestCol = &pDest->aCol[i];
3098 Column *pSrcCol = &pSrc->aCol[i];
3099 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
3100 if( (db->mDbFlags & DBFLAG_Vacuum)==0
3101 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
3103 return 0; /* Neither table may have __hidden__ columns */
3105 #endif
3106 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3107 /* Even if tables t1 and t2 have identical schemas, if they contain
3108 ** generated columns, then this statement is semantically incorrect:
3110 ** INSERT INTO t2 SELECT * FROM t1;
3112 ** The reason is that generated column values are returned by the
3113 ** the SELECT statement on the right but the INSERT statement on the
3114 ** left wants them to be omitted.
3116 ** Nevertheless, this is a useful notational shorthand to tell SQLite
3117 ** to do a bulk transfer all of the content from t1 over to t2.
3119 ** We could, in theory, disable this (except for internal use by the
3120 ** VACUUM command where it is actually needed). But why do that? It
3121 ** seems harmless enough, and provides a useful service.
3123 if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
3124 (pSrcCol->colFlags & COLFLAG_GENERATED) ){
3125 return 0; /* Both columns have the same generated-column type */
3127 /* But the transfer is only allowed if both the source and destination
3128 ** tables have the exact same expressions for generated columns.
3129 ** This requirement could be relaxed for VIRTUAL columns, I suppose.
3131 if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
3132 if( sqlite3ExprCompare(0,
3133 sqlite3ColumnExpr(pSrc, pSrcCol),
3134 sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
3135 testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
3136 testcase( pDestCol->colFlags & COLFLAG_STORED );
3137 return 0; /* Different generator expressions */
3140 #endif
3141 if( pDestCol->affinity!=pSrcCol->affinity ){
3142 return 0; /* Affinity must be the same on all columns */
3144 if( sqlite3_stricmp(sqlite3ColumnColl(pDestCol),
3145 sqlite3ColumnColl(pSrcCol))!=0 ){
3146 return 0; /* Collating sequence must be the same on all columns */
3148 if( pDestCol->notNull && !pSrcCol->notNull ){
3149 return 0; /* tab2 must be NOT NULL if tab1 is */
3151 /* Default values for second and subsequent columns need to match. */
3152 if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
3153 Expr *pDestExpr = sqlite3ColumnExpr(pDest, pDestCol);
3154 Expr *pSrcExpr = sqlite3ColumnExpr(pSrc, pSrcCol);
3155 assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
3156 assert( pDestExpr==0 || !ExprHasProperty(pDestExpr, EP_IntValue) );
3157 assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
3158 assert( pSrcExpr==0 || !ExprHasProperty(pSrcExpr, EP_IntValue) );
3159 if( (pDestExpr==0)!=(pSrcExpr==0)
3160 || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
3161 pSrcExpr->u.zToken)!=0)
3163 return 0; /* Default values must be the same for all columns */
3167 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
3168 if( IsUniqueIndex(pDestIdx) ){
3169 destHasUniqueIdx = 1;
3171 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
3172 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
3174 if( pSrcIdx==0 ){
3175 return 0; /* pDestIdx has no corresponding index in pSrc */
3177 if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
3178 && sqlite3FaultSim(411)==SQLITE_OK ){
3179 /* The sqlite3FaultSim() call allows this corruption test to be
3180 ** bypassed during testing, in order to exercise other corruption tests
3181 ** further downstream. */
3182 return 0; /* Corrupt schema - two indexes on the same btree */
3185 #ifndef SQLITE_OMIT_CHECK
3186 if( pDest->pCheck
3187 && (db->mDbFlags & DBFLAG_Vacuum)==0
3188 && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1)
3190 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
3192 #endif
3193 #ifndef SQLITE_OMIT_FOREIGN_KEY
3194 /* Disallow the transfer optimization if the destination table contains
3195 ** any foreign key constraints. This is more restrictive than necessary.
3196 ** But the main beneficiary of the transfer optimization is the VACUUM
3197 ** command, and the VACUUM command disables foreign key constraints. So
3198 ** the extra complication to make this rule less restrictive is probably
3199 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
3201 assert( IsOrdinaryTable(pDest) );
3202 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
3203 return 0;
3205 #endif
3206 if( (db->flags & SQLITE_CountRows)!=0 ){
3207 return 0; /* xfer opt does not play well with PRAGMA count_changes */
3210 /* If we get this far, it means that the xfer optimization is at
3211 ** least a possibility, though it might only work if the destination
3212 ** table (tab1) is initially empty.
3214 #ifdef SQLITE_TEST
3215 sqlite3_xferopt_count++;
3216 #endif
3217 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
3218 v = sqlite3GetVdbe(pParse);
3219 sqlite3CodeVerifySchema(pParse, iDbSrc);
3220 iSrc = pParse->nTab++;
3221 iDest = pParse->nTab++;
3222 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
3223 regData = sqlite3GetTempReg(pParse);
3224 sqlite3VdbeAddOp2(v, OP_Null, 0, regData);
3225 regRowid = sqlite3GetTempReg(pParse);
3226 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
3227 assert( HasRowid(pDest) || destHasUniqueIdx );
3228 if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
3229 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
3230 || destHasUniqueIdx /* (2) */
3231 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
3233 /* In some circumstances, we are able to run the xfer optimization
3234 ** only if the destination table is initially empty. Unless the
3235 ** DBFLAG_Vacuum flag is set, this block generates code to make
3236 ** that determination. If DBFLAG_Vacuum is set, then the destination
3237 ** table is always empty.
3239 ** Conditions under which the destination must be empty:
3241 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
3242 ** (If the destination is not initially empty, the rowid fields
3243 ** of index entries might need to change.)
3245 ** (2) The destination has a unique index. (The xfer optimization
3246 ** is unable to test uniqueness.)
3248 ** (3) onError is something other than OE_Abort and OE_Rollback.
3250 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
3251 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
3252 sqlite3VdbeJumpHere(v, addr1);
3254 if( HasRowid(pSrc) ){
3255 u8 insFlags;
3256 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
3257 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
3258 if( pDest->iPKey>=0 ){
3259 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3260 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3261 sqlite3VdbeVerifyAbortable(v, onError);
3262 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
3263 VdbeCoverage(v);
3264 sqlite3RowidConstraint(pParse, onError, pDest);
3265 sqlite3VdbeJumpHere(v, addr2);
3267 autoIncStep(pParse, regAutoinc, regRowid);
3268 }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
3269 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
3270 }else{
3271 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3272 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
3275 if( db->mDbFlags & DBFLAG_Vacuum ){
3276 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3277 insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3278 }else{
3279 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT;
3281 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
3282 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3283 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3284 insFlags &= ~OPFLAG_PREFORMAT;
3285 }else
3286 #endif
3288 sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid);
3290 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
3291 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3292 sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
3294 sqlite3VdbeChangeP5(v, insFlags);
3296 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
3297 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
3298 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3299 }else{
3300 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
3301 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
3303 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
3304 u8 idxInsFlags = 0;
3305 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
3306 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
3308 assert( pSrcIdx );
3309 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
3310 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
3311 VdbeComment((v, "%s", pSrcIdx->zName));
3312 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
3313 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
3314 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
3315 VdbeComment((v, "%s", pDestIdx->zName));
3316 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
3317 if( db->mDbFlags & DBFLAG_Vacuum ){
3318 /* This INSERT command is part of a VACUUM operation, which guarantees
3319 ** that the destination table is empty. If all indexed columns use
3320 ** collation sequence BINARY, then it can also be assumed that the
3321 ** index will be populated by inserting keys in strictly sorted
3322 ** order. In this case, instead of seeking within the b-tree as part
3323 ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
3324 ** OP_IdxInsert to seek to the point within the b-tree where each key
3325 ** should be inserted. This is faster.
3327 ** If any of the indexed columns use a collation sequence other than
3328 ** BINARY, this optimization is disabled. This is because the user
3329 ** might change the definition of a collation sequence and then run
3330 ** a VACUUM command. In that case keys may not be written in strictly
3331 ** sorted order. */
3332 for(i=0; i<pSrcIdx->nColumn; i++){
3333 const char *zColl = pSrcIdx->azColl[i];
3334 if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
3336 if( i==pSrcIdx->nColumn ){
3337 idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3338 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3339 sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc);
3341 }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
3342 idxInsFlags |= OPFLAG_NCHANGE;
3344 if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){
3345 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3346 if( (db->mDbFlags & DBFLAG_Vacuum)==0
3347 && !HasRowid(pDest)
3348 && IsPrimaryKeyIndex(pDestIdx)
3350 codeWithoutRowidPreupdate(pParse, pDest, iDest, regData);
3353 sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
3354 sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
3355 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
3356 sqlite3VdbeJumpHere(v, addr1);
3357 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
3358 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3360 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
3361 sqlite3ReleaseTempReg(pParse, regRowid);
3362 sqlite3ReleaseTempReg(pParse, regData);
3363 if( emptyDestTest ){
3364 sqlite3AutoincrementEnd(pParse);
3365 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
3366 sqlite3VdbeJumpHere(v, emptyDestTest);
3367 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3368 return 0;
3369 }else{
3370 return 1;
3373 #endif /* SQLITE_OMIT_XFER_OPT */