Allow a session object to generate a changeset, even if columns were added to one...
[sqlite.git] / src / insert.c
blob1c31ca2338e619441c3a00ac2f22e17cc56b494b
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 /* Forward declaration */
582 static int xferOptimization(
583 Parse *pParse, /* Parser context */
584 Table *pDest, /* The table we are inserting into */
585 Select *pSelect, /* A SELECT statement to use as the data source */
586 int onError, /* How to handle constraint errors */
587 int iDbDest /* The database of pDest */
591 ** This routine is called to handle SQL of the following forms:
593 ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
594 ** insert into TABLE (IDLIST) select
595 ** insert into TABLE (IDLIST) default values
597 ** The IDLIST following the table name is always optional. If omitted,
598 ** then a list of all (non-hidden) columns for the table is substituted.
599 ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
600 ** is omitted.
602 ** For the pSelect parameter holds the values to be inserted for the
603 ** first two forms shown above. A VALUES clause is really just short-hand
604 ** for a SELECT statement that omits the FROM clause and everything else
605 ** that follows. If the pSelect parameter is NULL, that means that the
606 ** DEFAULT VALUES form of the INSERT statement is intended.
608 ** The code generated follows one of four templates. For a simple
609 ** insert with data coming from a single-row VALUES clause, the code executes
610 ** once straight down through. Pseudo-code follows (we call this
611 ** the "1st template"):
613 ** open write cursor to <table> and its indices
614 ** put VALUES clause expressions into registers
615 ** write the resulting record into <table>
616 ** cleanup
618 ** The three remaining templates assume the statement is of the form
620 ** INSERT INTO <table> SELECT ...
622 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
623 ** in other words if the SELECT pulls all columns from a single table
624 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
625 ** if <table2> and <table1> are distinct tables but have identical
626 ** schemas, including all the same indices, then a special optimization
627 ** is invoked that copies raw records from <table2> over to <table1>.
628 ** See the xferOptimization() function for the implementation of this
629 ** template. This is the 2nd template.
631 ** open a write cursor to <table>
632 ** open read cursor on <table2>
633 ** transfer all records in <table2> over to <table>
634 ** close cursors
635 ** foreach index on <table>
636 ** open a write cursor on the <table> index
637 ** open a read cursor on the corresponding <table2> index
638 ** transfer all records from the read to the write cursors
639 ** close cursors
640 ** end foreach
642 ** The 3rd template is for when the second template does not apply
643 ** and the SELECT clause does not read from <table> at any time.
644 ** The generated code follows this template:
646 ** X <- A
647 ** goto B
648 ** A: setup for the SELECT
649 ** loop over the rows in the SELECT
650 ** load values into registers R..R+n
651 ** yield X
652 ** end loop
653 ** cleanup after the SELECT
654 ** end-coroutine X
655 ** B: open write cursor to <table> and its indices
656 ** C: yield X, at EOF goto D
657 ** insert the select result into <table> from R..R+n
658 ** goto C
659 ** D: cleanup
661 ** The 4th template is used if the insert statement takes its
662 ** values from a SELECT but the data is being inserted into a table
663 ** that is also read as part of the SELECT. In the third form,
664 ** we have to use an intermediate table to store the results of
665 ** the select. The template is like this:
667 ** X <- A
668 ** goto B
669 ** A: setup for the SELECT
670 ** loop over the tables in the SELECT
671 ** load value into register R..R+n
672 ** yield X
673 ** end loop
674 ** cleanup after the SELECT
675 ** end co-routine R
676 ** B: open temp table
677 ** L: yield X, at EOF goto M
678 ** insert row from R..R+n into temp table
679 ** goto L
680 ** M: open write cursor to <table> and its indices
681 ** rewind temp table
682 ** C: loop over rows of intermediate table
683 ** transfer values form intermediate table into <table>
684 ** end loop
685 ** D: cleanup
687 void sqlite3Insert(
688 Parse *pParse, /* Parser context */
689 SrcList *pTabList, /* Name of table into which we are inserting */
690 Select *pSelect, /* A SELECT statement to use as the data source */
691 IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */
692 int onError, /* How to handle constraint errors */
693 Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
695 sqlite3 *db; /* The main database structure */
696 Table *pTab; /* The table to insert into. aka TABLE */
697 int i, j; /* Loop counters */
698 Vdbe *v; /* Generate code into this virtual machine */
699 Index *pIdx; /* For looping over indices of the table */
700 int nColumn; /* Number of columns in the data */
701 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
702 int iDataCur = 0; /* VDBE cursor that is the main data repository */
703 int iIdxCur = 0; /* First index cursor */
704 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
705 int endOfLoop; /* Label for the end of the insertion loop */
706 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
707 int addrInsTop = 0; /* Jump to label "D" */
708 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
709 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
710 int iDb; /* Index of database holding TABLE */
711 u8 useTempTable = 0; /* Store SELECT results in intermediate table */
712 u8 appendFlag = 0; /* True if the insert is likely to be an append */
713 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
714 u8 bIdListInOrder; /* True if IDLIST is in table order */
715 ExprList *pList = 0; /* List of VALUES() to be inserted */
716 int iRegStore; /* Register in which to store next column */
718 /* Register allocations */
719 int regFromSelect = 0;/* Base register for data coming from SELECT */
720 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
721 int regRowCount = 0; /* Memory cell used for the row counter */
722 int regIns; /* Block of regs holding rowid+data being inserted */
723 int regRowid; /* registers holding insert rowid */
724 int regData; /* register holding first column to insert */
725 int *aRegIdx = 0; /* One register allocated to each index */
727 #ifndef SQLITE_OMIT_TRIGGER
728 int isView; /* True if attempting to insert into a view */
729 Trigger *pTrigger; /* List of triggers on pTab, if required */
730 int tmask; /* Mask of trigger times */
731 #endif
733 db = pParse->db;
734 assert( db->pParse==pParse );
735 if( pParse->nErr ){
736 goto insert_cleanup;
738 assert( db->mallocFailed==0 );
739 dest.iSDParm = 0; /* Suppress a harmless compiler warning */
741 /* If the Select object is really just a simple VALUES() list with a
742 ** single row (the common case) then keep that one row of values
743 ** and discard the other (unused) parts of the pSelect object
745 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
746 pList = pSelect->pEList;
747 pSelect->pEList = 0;
748 sqlite3SelectDelete(db, pSelect);
749 pSelect = 0;
752 /* Locate the table into which we will be inserting new information.
754 assert( pTabList->nSrc==1 );
755 pTab = sqlite3SrcListLookup(pParse, pTabList);
756 if( pTab==0 ){
757 goto insert_cleanup;
759 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
760 assert( iDb<db->nDb );
761 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
762 db->aDb[iDb].zDbSName) ){
763 goto insert_cleanup;
765 withoutRowid = !HasRowid(pTab);
767 /* Figure out if we have any triggers and if the table being
768 ** inserted into is a view
770 #ifndef SQLITE_OMIT_TRIGGER
771 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
772 isView = IsView(pTab);
773 #else
774 # define pTrigger 0
775 # define tmask 0
776 # define isView 0
777 #endif
778 #ifdef SQLITE_OMIT_VIEW
779 # undef isView
780 # define isView 0
781 #endif
782 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
784 #if TREETRACE_ENABLED
785 if( sqlite3TreeTrace & 0x10000 ){
786 sqlite3TreeViewLine(0, "In sqlite3Insert() at %s:%d", __FILE__, __LINE__);
787 sqlite3TreeViewInsert(pParse->pWith, pTabList, pColumn, pSelect, pList,
788 onError, pUpsert, pTrigger);
790 #endif
792 /* If pTab is really a view, make sure it has been initialized.
793 ** ViewGetColumnNames() is a no-op if pTab is not a view.
795 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
796 goto insert_cleanup;
799 /* Cannot insert into a read-only table.
801 if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
802 goto insert_cleanup;
805 /* Allocate a VDBE
807 v = sqlite3GetVdbe(pParse);
808 if( v==0 ) goto insert_cleanup;
809 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
810 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
812 #ifndef SQLITE_OMIT_XFER_OPT
813 /* If the statement is of the form
815 ** INSERT INTO <table1> SELECT * FROM <table2>;
817 ** Then special optimizations can be applied that make the transfer
818 ** very fast and which reduce fragmentation of indices.
820 ** This is the 2nd template.
822 if( pColumn==0
823 && pSelect!=0
824 && pTrigger==0
825 && xferOptimization(pParse, pTab, pSelect, onError, iDb)
827 assert( !pTrigger );
828 assert( pList==0 );
829 goto insert_end;
831 #endif /* SQLITE_OMIT_XFER_OPT */
833 /* If this is an AUTOINCREMENT table, look up the sequence number in the
834 ** sqlite_sequence table and store it in memory cell regAutoinc.
836 regAutoinc = autoIncBegin(pParse, iDb, pTab);
838 /* Allocate a block registers to hold the rowid and the values
839 ** for all columns of the new row.
841 regRowid = regIns = pParse->nMem+1;
842 pParse->nMem += pTab->nCol + 1;
843 if( IsVirtual(pTab) ){
844 regRowid++;
845 pParse->nMem++;
847 regData = regRowid+1;
849 /* If the INSERT statement included an IDLIST term, then make sure
850 ** all elements of the IDLIST really are columns of the table and
851 ** remember the column indices.
853 ** If the table has an INTEGER PRIMARY KEY column and that column
854 ** is named in the IDLIST, then record in the ipkColumn variable
855 ** the index into IDLIST of the primary key column. ipkColumn is
856 ** the index of the primary key as it appears in IDLIST, not as
857 ** is appears in the original table. (The index of the INTEGER
858 ** PRIMARY KEY in the original table is pTab->iPKey.) After this
859 ** loop, if ipkColumn==(-1), that means that integer primary key
860 ** is unspecified, and hence the table is either WITHOUT ROWID or
861 ** it will automatically generated an integer primary key.
863 ** bIdListInOrder is true if the columns in IDLIST are in storage
864 ** order. This enables an optimization that avoids shuffling the
865 ** columns into storage order. False negatives are harmless,
866 ** but false positives will cause database corruption.
868 bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
869 if( pColumn ){
870 assert( pColumn->eU4!=EU4_EXPR );
871 pColumn->eU4 = EU4_IDX;
872 for(i=0; i<pColumn->nId; i++){
873 pColumn->a[i].u4.idx = -1;
875 for(i=0; i<pColumn->nId; i++){
876 for(j=0; j<pTab->nCol; j++){
877 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zCnName)==0 ){
878 pColumn->a[i].u4.idx = j;
879 if( i!=j ) bIdListInOrder = 0;
880 if( j==pTab->iPKey ){
881 ipkColumn = i; assert( !withoutRowid );
883 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
884 if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
885 sqlite3ErrorMsg(pParse,
886 "cannot INSERT into generated column \"%s\"",
887 pTab->aCol[j].zCnName);
888 goto insert_cleanup;
890 #endif
891 break;
894 if( j>=pTab->nCol ){
895 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
896 ipkColumn = i;
897 bIdListInOrder = 0;
898 }else{
899 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
900 pTabList->a, pColumn->a[i].zName);
901 pParse->checkSchema = 1;
902 goto insert_cleanup;
908 /* Figure out how many columns of data are supplied. If the data
909 ** is coming from a SELECT statement, then generate a co-routine that
910 ** produces a single row of the SELECT on each invocation. The
911 ** co-routine is the common header to the 3rd and 4th templates.
913 if( pSelect ){
914 /* Data is coming from a SELECT or from a multi-row VALUES clause.
915 ** Generate a co-routine to run the SELECT. */
916 int regYield; /* Register holding co-routine entry-point */
917 int addrTop; /* Top of the co-routine */
918 int rc; /* Result code */
920 regYield = ++pParse->nMem;
921 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
922 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
923 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
924 dest.iSdst = bIdListInOrder ? regData : 0;
925 dest.nSdst = pTab->nCol;
926 rc = sqlite3Select(pParse, pSelect, &dest);
927 regFromSelect = dest.iSdst;
928 assert( db->pParse==pParse );
929 if( rc || pParse->nErr ) goto insert_cleanup;
930 assert( db->mallocFailed==0 );
931 sqlite3VdbeEndCoroutine(v, regYield);
932 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
933 assert( pSelect->pEList );
934 nColumn = pSelect->pEList->nExpr;
936 /* Set useTempTable to TRUE if the result of the SELECT statement
937 ** should be written into a temporary table (template 4). Set to
938 ** FALSE if each output row of the SELECT can be written directly into
939 ** the destination table (template 3).
941 ** A temp table must be used if the table being updated is also one
942 ** of the tables being read by the SELECT statement. Also use a
943 ** temp table in the case of row triggers.
945 if( pTrigger || readsTable(pParse, iDb, pTab) ){
946 useTempTable = 1;
949 if( useTempTable ){
950 /* Invoke the coroutine to extract information from the SELECT
951 ** and add it to a transient table srcTab. The code generated
952 ** here is from the 4th template:
954 ** B: open temp table
955 ** L: yield X, goto M at EOF
956 ** insert row from R..R+n into temp table
957 ** goto L
958 ** M: ...
960 int regRec; /* Register to hold packed record */
961 int regTempRowid; /* Register to hold temp table ROWID */
962 int addrL; /* Label "L" */
964 srcTab = pParse->nTab++;
965 regRec = sqlite3GetTempReg(pParse);
966 regTempRowid = sqlite3GetTempReg(pParse);
967 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
968 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
969 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
970 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
971 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
972 sqlite3VdbeGoto(v, addrL);
973 sqlite3VdbeJumpHere(v, addrL);
974 sqlite3ReleaseTempReg(pParse, regRec);
975 sqlite3ReleaseTempReg(pParse, regTempRowid);
977 }else{
978 /* This is the case if the data for the INSERT is coming from a
979 ** single-row VALUES clause
981 NameContext sNC;
982 memset(&sNC, 0, sizeof(sNC));
983 sNC.pParse = pParse;
984 srcTab = -1;
985 assert( useTempTable==0 );
986 if( pList ){
987 nColumn = pList->nExpr;
988 if( sqlite3ResolveExprListNames(&sNC, pList) ){
989 goto insert_cleanup;
991 }else{
992 nColumn = 0;
996 /* If there is no IDLIST term but the table has an integer primary
997 ** key, the set the ipkColumn variable to the integer primary key
998 ** column index in the original table definition.
1000 if( pColumn==0 && nColumn>0 ){
1001 ipkColumn = pTab->iPKey;
1002 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1003 if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
1004 testcase( pTab->tabFlags & TF_HasVirtual );
1005 testcase( pTab->tabFlags & TF_HasStored );
1006 for(i=ipkColumn-1; i>=0; i--){
1007 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
1008 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
1009 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
1010 ipkColumn--;
1014 #endif
1016 /* Make sure the number of columns in the source data matches the number
1017 ** of columns to be inserted into the table.
1019 assert( TF_HasHidden==COLFLAG_HIDDEN );
1020 assert( TF_HasGenerated==COLFLAG_GENERATED );
1021 assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) );
1022 if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
1023 for(i=0; i<pTab->nCol; i++){
1024 if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
1027 if( nColumn!=(pTab->nCol-nHidden) ){
1028 sqlite3ErrorMsg(pParse,
1029 "table %S has %d columns but %d values were supplied",
1030 pTabList->a, pTab->nCol-nHidden, nColumn);
1031 goto insert_cleanup;
1034 if( pColumn!=0 && nColumn!=pColumn->nId ){
1035 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
1036 goto insert_cleanup;
1039 /* Initialize the count of rows to be inserted
1041 if( (db->flags & SQLITE_CountRows)!=0
1042 && !pParse->nested
1043 && !pParse->pTriggerTab
1044 && !pParse->bReturning
1046 regRowCount = ++pParse->nMem;
1047 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
1050 /* If this is not a view, open the table and and all indices */
1051 if( !isView ){
1052 int nIdx;
1053 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
1054 &iDataCur, &iIdxCur);
1055 aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
1056 if( aRegIdx==0 ){
1057 goto insert_cleanup;
1059 for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
1060 assert( pIdx );
1061 aRegIdx[i] = ++pParse->nMem;
1062 pParse->nMem += pIdx->nColumn;
1064 aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */
1066 #ifndef SQLITE_OMIT_UPSERT
1067 if( pUpsert ){
1068 Upsert *pNx;
1069 if( IsVirtual(pTab) ){
1070 sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
1071 pTab->zName);
1072 goto insert_cleanup;
1074 if( IsView(pTab) ){
1075 sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
1076 goto insert_cleanup;
1078 if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
1079 goto insert_cleanup;
1081 pTabList->a[0].iCursor = iDataCur;
1082 pNx = pUpsert;
1084 pNx->pUpsertSrc = pTabList;
1085 pNx->regData = regData;
1086 pNx->iDataCur = iDataCur;
1087 pNx->iIdxCur = iIdxCur;
1088 if( pNx->pUpsertTarget ){
1089 if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx) ){
1090 goto insert_cleanup;
1093 pNx = pNx->pNextUpsert;
1094 }while( pNx!=0 );
1096 #endif
1099 /* This is the top of the main insertion loop */
1100 if( useTempTable ){
1101 /* This block codes the top of loop only. The complete loop is the
1102 ** following pseudocode (template 4):
1104 ** rewind temp table, if empty goto D
1105 ** C: loop over rows of intermediate table
1106 ** transfer values form intermediate table into <table>
1107 ** end loop
1108 ** D: ...
1110 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
1111 addrCont = sqlite3VdbeCurrentAddr(v);
1112 }else if( pSelect ){
1113 /* This block codes the top of loop only. The complete loop is the
1114 ** following pseudocode (template 3):
1116 ** C: yield X, at EOF goto D
1117 ** insert the select result into <table> from R..R+n
1118 ** goto C
1119 ** D: ...
1121 sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
1122 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
1123 VdbeCoverage(v);
1124 if( ipkColumn>=0 ){
1125 /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
1126 ** SELECT, go ahead and copy the value into the rowid slot now, so that
1127 ** the value does not get overwritten by a NULL at tag-20191021-002. */
1128 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
1132 /* Compute data for ordinary columns of the new entry. Values
1133 ** are written in storage order into registers starting with regData.
1134 ** Only ordinary columns are computed in this loop. The rowid
1135 ** (if there is one) is computed later and generated columns are
1136 ** computed after the rowid since they might depend on the value
1137 ** of the rowid.
1139 nHidden = 0;
1140 iRegStore = regData; assert( regData==regRowid+1 );
1141 for(i=0; i<pTab->nCol; i++, iRegStore++){
1142 int k;
1143 u32 colFlags;
1144 assert( i>=nHidden );
1145 if( i==pTab->iPKey ){
1146 /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
1147 ** using the rowid. So put a NULL in the IPK slot of the record to avoid
1148 ** using excess space. The file format definition requires this extra
1149 ** NULL - we cannot optimize further by skipping the column completely */
1150 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1151 continue;
1153 if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
1154 nHidden++;
1155 if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
1156 /* Virtual columns do not participate in OP_MakeRecord. So back up
1157 ** iRegStore by one slot to compensate for the iRegStore++ in the
1158 ** outer for() loop */
1159 iRegStore--;
1160 continue;
1161 }else if( (colFlags & COLFLAG_STORED)!=0 ){
1162 /* Stored columns are computed later. But if there are BEFORE
1163 ** triggers, the slots used for stored columns will be OP_Copy-ed
1164 ** to a second block of registers, so the register needs to be
1165 ** initialized to NULL to avoid an uninitialized register read */
1166 if( tmask & TRIGGER_BEFORE ){
1167 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1169 continue;
1170 }else if( pColumn==0 ){
1171 /* Hidden columns that are not explicitly named in the INSERT
1172 ** get there default value */
1173 sqlite3ExprCodeFactorable(pParse,
1174 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1175 iRegStore);
1176 continue;
1179 if( pColumn ){
1180 assert( pColumn->eU4==EU4_IDX );
1181 for(j=0; j<pColumn->nId && pColumn->a[j].u4.idx!=i; j++){}
1182 if( j>=pColumn->nId ){
1183 /* A column not named in the insert column list gets its
1184 ** default value */
1185 sqlite3ExprCodeFactorable(pParse,
1186 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1187 iRegStore);
1188 continue;
1190 k = j;
1191 }else if( nColumn==0 ){
1192 /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */
1193 sqlite3ExprCodeFactorable(pParse,
1194 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1195 iRegStore);
1196 continue;
1197 }else{
1198 k = i - nHidden;
1201 if( useTempTable ){
1202 sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
1203 }else if( pSelect ){
1204 if( regFromSelect!=regData ){
1205 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
1207 }else{
1208 Expr *pX = pList->a[k].pExpr;
1209 int y = sqlite3ExprCodeTarget(pParse, pX, iRegStore);
1210 if( y!=iRegStore ){
1211 sqlite3VdbeAddOp2(v,
1212 ExprHasProperty(pX, EP_Subquery) ? OP_Copy : OP_SCopy, y, iRegStore);
1218 /* Run the BEFORE and INSTEAD OF triggers, if there are any
1220 endOfLoop = sqlite3VdbeMakeLabel(pParse);
1221 if( tmask & TRIGGER_BEFORE ){
1222 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
1224 /* build the NEW.* reference row. Note that if there is an INTEGER
1225 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
1226 ** translated into a unique ID for the row. But on a BEFORE trigger,
1227 ** we do not know what the unique ID will be (because the insert has
1228 ** not happened yet) so we substitute a rowid of -1
1230 if( ipkColumn<0 ){
1231 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1232 }else{
1233 int addr1;
1234 assert( !withoutRowid );
1235 if( useTempTable ){
1236 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
1237 }else{
1238 assert( pSelect==0 ); /* Otherwise useTempTable is true */
1239 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
1241 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
1242 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1243 sqlite3VdbeJumpHere(v, addr1);
1244 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
1247 /* Copy the new data already generated. */
1248 assert( pTab->nNVCol>0 || pParse->nErr>0 );
1249 sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
1251 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1252 /* Compute the new value for generated columns after all other
1253 ** columns have already been computed. This must be done after
1254 ** computing the ROWID in case one of the generated columns
1255 ** refers to the ROWID. */
1256 if( pTab->tabFlags & TF_HasGenerated ){
1257 testcase( pTab->tabFlags & TF_HasVirtual );
1258 testcase( pTab->tabFlags & TF_HasStored );
1259 sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
1261 #endif
1263 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
1264 ** do not attempt any conversions before assembling the record.
1265 ** If this is a real table, attempt conversions as required by the
1266 ** table column affinities.
1268 if( !isView ){
1269 sqlite3TableAffinity(v, pTab, regCols+1);
1272 /* Fire BEFORE or INSTEAD OF triggers */
1273 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
1274 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
1276 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
1279 if( !isView ){
1280 if( IsVirtual(pTab) ){
1281 /* The row that the VUpdate opcode will delete: none */
1282 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
1284 if( ipkColumn>=0 ){
1285 /* Compute the new rowid */
1286 if( useTempTable ){
1287 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
1288 }else if( pSelect ){
1289 /* Rowid already initialized at tag-20191021-001 */
1290 }else{
1291 Expr *pIpk = pList->a[ipkColumn].pExpr;
1292 if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
1293 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1294 appendFlag = 1;
1295 }else{
1296 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
1299 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
1300 ** to generate a unique primary key value.
1302 if( !appendFlag ){
1303 int addr1;
1304 if( !IsVirtual(pTab) ){
1305 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
1306 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1307 sqlite3VdbeJumpHere(v, addr1);
1308 }else{
1309 addr1 = sqlite3VdbeCurrentAddr(v);
1310 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
1312 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
1314 }else if( IsVirtual(pTab) || withoutRowid ){
1315 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
1316 }else{
1317 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1318 appendFlag = 1;
1320 autoIncStep(pParse, regAutoinc, regRowid);
1322 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1323 /* Compute the new value for generated columns after all other
1324 ** columns have already been computed. This must be done after
1325 ** computing the ROWID in case one of the generated columns
1326 ** is derived from the INTEGER PRIMARY KEY. */
1327 if( pTab->tabFlags & TF_HasGenerated ){
1328 sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
1330 #endif
1332 /* Generate code to check constraints and generate index keys and
1333 ** do the insertion.
1335 #ifndef SQLITE_OMIT_VIRTUALTABLE
1336 if( IsVirtual(pTab) ){
1337 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
1338 sqlite3VtabMakeWritable(pParse, pTab);
1339 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1340 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1341 sqlite3MayAbort(pParse);
1342 }else
1343 #endif
1345 int isReplace = 0;/* Set to true if constraints may cause a replace */
1346 int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
1347 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1348 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
1350 if( db->flags & SQLITE_ForeignKeys ){
1351 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
1354 /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
1355 ** constraints or (b) there are no triggers and this table is not a
1356 ** parent table in a foreign key constraint. It is safe to set the
1357 ** flag in the second case as if any REPLACE constraint is hit, an
1358 ** OP_Delete or OP_IdxDelete instruction will be executed on each
1359 ** cursor that is disturbed. And these instructions both clear the
1360 ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
1361 ** functionality. */
1362 bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
1363 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
1364 regIns, aRegIdx, 0, appendFlag, bUseSeek
1367 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
1368 }else if( pParse->bReturning ){
1369 /* If there is a RETURNING clause, populate the rowid register with
1370 ** constant value -1, in case one or more of the returned expressions
1371 ** refer to the "rowid" of the view. */
1372 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
1373 #endif
1376 /* Update the count of rows that are inserted
1378 if( regRowCount ){
1379 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
1382 if( pTrigger ){
1383 /* Code AFTER triggers */
1384 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
1385 pTab, regData-2-pTab->nCol, onError, endOfLoop);
1388 /* The bottom of the main insertion loop, if the data source
1389 ** is a SELECT statement.
1391 sqlite3VdbeResolveLabel(v, endOfLoop);
1392 if( useTempTable ){
1393 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1394 sqlite3VdbeJumpHere(v, addrInsTop);
1395 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1396 }else if( pSelect ){
1397 sqlite3VdbeGoto(v, addrCont);
1398 #ifdef SQLITE_DEBUG
1399 /* If we are jumping back to an OP_Yield that is preceded by an
1400 ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
1401 ** OP_ReleaseReg will be included in the loop. */
1402 if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
1403 assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
1404 sqlite3VdbeChangeP5(v, 1);
1406 #endif
1407 sqlite3VdbeJumpHere(v, addrInsTop);
1410 #ifndef SQLITE_OMIT_XFER_OPT
1411 insert_end:
1412 #endif /* SQLITE_OMIT_XFER_OPT */
1413 /* Update the sqlite_sequence table by storing the content of the
1414 ** maximum rowid counter values recorded while inserting into
1415 ** autoincrement tables.
1417 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
1418 sqlite3AutoincrementEnd(pParse);
1422 ** Return the number of rows inserted. If this routine is
1423 ** generating code because of a call to sqlite3NestedParse(), do not
1424 ** invoke the callback function.
1426 if( regRowCount ){
1427 sqlite3CodeChangeCount(v, regRowCount, "rows inserted");
1430 insert_cleanup:
1431 sqlite3SrcListDelete(db, pTabList);
1432 sqlite3ExprListDelete(db, pList);
1433 sqlite3UpsertDelete(db, pUpsert);
1434 sqlite3SelectDelete(db, pSelect);
1435 sqlite3IdListDelete(db, pColumn);
1436 if( aRegIdx ) sqlite3DbNNFreeNN(db, aRegIdx);
1439 /* Make sure "isView" and other macros defined above are undefined. Otherwise
1440 ** they may interfere with compilation of other functions in this file
1441 ** (or in another file, if this file becomes part of the amalgamation). */
1442 #ifdef isView
1443 #undef isView
1444 #endif
1445 #ifdef pTrigger
1446 #undef pTrigger
1447 #endif
1448 #ifdef tmask
1449 #undef tmask
1450 #endif
1453 ** Meanings of bits in of pWalker->eCode for
1454 ** sqlite3ExprReferencesUpdatedColumn()
1456 #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
1457 #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
1459 /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
1460 * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
1461 ** expression node references any of the
1462 ** columns that are being modified by an UPDATE statement.
1464 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
1465 if( pExpr->op==TK_COLUMN ){
1466 assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
1467 if( pExpr->iColumn>=0 ){
1468 if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
1469 pWalker->eCode |= CKCNSTRNT_COLUMN;
1471 }else{
1472 pWalker->eCode |= CKCNSTRNT_ROWID;
1475 return WRC_Continue;
1479 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
1480 ** only columns that are modified by the UPDATE are those for which
1481 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
1483 ** Return true if CHECK constraint pExpr uses any of the
1484 ** changing columns (or the rowid if it is changing). In other words,
1485 ** return true if this CHECK constraint must be validated for
1486 ** the new row in the UPDATE statement.
1488 ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
1489 ** The operation of this routine is the same - return true if an only if
1490 ** the expression uses one or more of columns identified by the second and
1491 ** third arguments.
1493 int sqlite3ExprReferencesUpdatedColumn(
1494 Expr *pExpr, /* The expression to be checked */
1495 int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */
1496 int chngRowid /* True if UPDATE changes the rowid */
1498 Walker w;
1499 memset(&w, 0, sizeof(w));
1500 w.eCode = 0;
1501 w.xExprCallback = checkConstraintExprNode;
1502 w.u.aiCol = aiChng;
1503 sqlite3WalkExpr(&w, pExpr);
1504 if( !chngRowid ){
1505 testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
1506 w.eCode &= ~CKCNSTRNT_ROWID;
1508 testcase( w.eCode==0 );
1509 testcase( w.eCode==CKCNSTRNT_COLUMN );
1510 testcase( w.eCode==CKCNSTRNT_ROWID );
1511 testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
1512 return w.eCode!=0;
1516 ** The sqlite3GenerateConstraintChecks() routine usually wants to visit
1517 ** the indexes of a table in the order provided in the Table->pIndex list.
1518 ** However, sometimes (rarely - when there is an upsert) it wants to visit
1519 ** the indexes in a different order. The following data structures accomplish
1520 ** this.
1522 ** The IndexIterator object is used to walk through all of the indexes
1523 ** of a table in either Index.pNext order, or in some other order established
1524 ** by an array of IndexListTerm objects.
1526 typedef struct IndexListTerm IndexListTerm;
1527 typedef struct IndexIterator IndexIterator;
1528 struct IndexIterator {
1529 int eType; /* 0 for Index.pNext list. 1 for an array of IndexListTerm */
1530 int i; /* Index of the current item from the list */
1531 union {
1532 struct { /* Use this object for eType==0: A Index.pNext list */
1533 Index *pIdx; /* The current Index */
1534 } lx;
1535 struct { /* Use this object for eType==1; Array of IndexListTerm */
1536 int nIdx; /* Size of the array */
1537 IndexListTerm *aIdx; /* Array of IndexListTerms */
1538 } ax;
1539 } u;
1542 /* When IndexIterator.eType==1, then each index is an array of instances
1543 ** of the following object
1545 struct IndexListTerm {
1546 Index *p; /* The index */
1547 int ix; /* Which entry in the original Table.pIndex list is this index*/
1550 /* Return the first index on the list */
1551 static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){
1552 assert( pIter->i==0 );
1553 if( pIter->eType ){
1554 *pIx = pIter->u.ax.aIdx[0].ix;
1555 return pIter->u.ax.aIdx[0].p;
1556 }else{
1557 *pIx = 0;
1558 return pIter->u.lx.pIdx;
1562 /* Return the next index from the list. Return NULL when out of indexes */
1563 static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){
1564 if( pIter->eType ){
1565 int i = ++pIter->i;
1566 if( i>=pIter->u.ax.nIdx ){
1567 *pIx = i;
1568 return 0;
1570 *pIx = pIter->u.ax.aIdx[i].ix;
1571 return pIter->u.ax.aIdx[i].p;
1572 }else{
1573 ++(*pIx);
1574 pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
1575 return pIter->u.lx.pIdx;
1580 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
1581 ** on table pTab.
1583 ** The regNewData parameter is the first register in a range that contains
1584 ** the data to be inserted or the data after the update. There will be
1585 ** pTab->nCol+1 registers in this range. The first register (the one
1586 ** that regNewData points to) will contain the new rowid, or NULL in the
1587 ** case of a WITHOUT ROWID table. The second register in the range will
1588 ** contain the content of the first table column. The third register will
1589 ** contain the content of the second table column. And so forth.
1591 ** The regOldData parameter is similar to regNewData except that it contains
1592 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
1593 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
1594 ** checking regOldData for zero.
1596 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1597 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1598 ** might be modified by the UPDATE. If pkChng is false, then the key of
1599 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1601 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1602 ** was explicitly specified as part of the INSERT statement. If pkChng
1603 ** is zero, it means that the either rowid is computed automatically or
1604 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
1605 ** pkChng will only be true if the INSERT statement provides an integer
1606 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
1608 ** The code generated by this routine will store new index entries into
1609 ** registers identified by aRegIdx[]. No index entry is created for
1610 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1611 ** the same as the order of indices on the linked list of indices
1612 ** at pTab->pIndex.
1614 ** (2019-05-07) The generated code also creates a new record for the
1615 ** main table, if pTab is a rowid table, and stores that record in the
1616 ** register identified by aRegIdx[nIdx] - in other words in the first
1617 ** entry of aRegIdx[] past the last index. It is important that the
1618 ** record be generated during constraint checks to avoid affinity changes
1619 ** to the register content that occur after constraint checks but before
1620 ** the new record is inserted.
1622 ** The caller must have already opened writeable cursors on the main
1623 ** table and all applicable indices (that is to say, all indices for which
1624 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
1625 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
1626 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
1627 ** for the first index in the pTab->pIndex list. Cursors for other indices
1628 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
1630 ** This routine also generates code to check constraints. NOT NULL,
1631 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
1632 ** then the appropriate action is performed. There are five possible
1633 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
1635 ** Constraint type Action What Happens
1636 ** --------------- ---------- ----------------------------------------
1637 ** any ROLLBACK The current transaction is rolled back and
1638 ** sqlite3_step() returns immediately with a
1639 ** return code of SQLITE_CONSTRAINT.
1641 ** any ABORT Back out changes from the current command
1642 ** only (do not do a complete rollback) then
1643 ** cause sqlite3_step() to return immediately
1644 ** with SQLITE_CONSTRAINT.
1646 ** any FAIL Sqlite3_step() returns immediately with a
1647 ** return code of SQLITE_CONSTRAINT. The
1648 ** transaction is not rolled back and any
1649 ** changes to prior rows are retained.
1651 ** any IGNORE The attempt in insert or update the current
1652 ** row is skipped, without throwing an error.
1653 ** Processing continues with the next row.
1654 ** (There is an immediate jump to ignoreDest.)
1656 ** NOT NULL REPLACE The NULL value is replace by the default
1657 ** value for that column. If the default value
1658 ** is NULL, the action is the same as ABORT.
1660 ** UNIQUE REPLACE The other row that conflicts with the row
1661 ** being inserted is removed.
1663 ** CHECK REPLACE Illegal. The results in an exception.
1665 ** Which action to take is determined by the overrideError parameter.
1666 ** Or if overrideError==OE_Default, then the pParse->onError parameter
1667 ** is used. Or if pParse->onError==OE_Default then the onError value
1668 ** for the constraint is used.
1670 void sqlite3GenerateConstraintChecks(
1671 Parse *pParse, /* The parser context */
1672 Table *pTab, /* The table being inserted or updated */
1673 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
1674 int iDataCur, /* Canonical data cursor (main table or PK index) */
1675 int iIdxCur, /* First index cursor */
1676 int regNewData, /* First register in a range holding values to insert */
1677 int regOldData, /* Previous content. 0 for INSERTs */
1678 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
1679 u8 overrideError, /* Override onError to this if not OE_Default */
1680 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
1681 int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
1682 int *aiChng, /* column i is unchanged if aiChng[i]<0 */
1683 Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
1685 Vdbe *v; /* VDBE under construction */
1686 Index *pIdx; /* Pointer to one of the indices */
1687 Index *pPk = 0; /* The PRIMARY KEY index for WITHOUT ROWID tables */
1688 sqlite3 *db; /* Database connection */
1689 int i; /* loop counter */
1690 int ix; /* Index loop counter */
1691 int nCol; /* Number of columns */
1692 int onError; /* Conflict resolution strategy */
1693 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
1694 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
1695 Upsert *pUpsertClause = 0; /* The specific ON CONFLICT clause for pIdx */
1696 u8 isUpdate; /* True if this is an UPDATE operation */
1697 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
1698 int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */
1699 int upsertIpkDelay = 0; /* Address of Goto to bypass initial IPK check */
1700 int ipkTop = 0; /* Top of the IPK uniqueness check */
1701 int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */
1702 /* Variables associated with retesting uniqueness constraints after
1703 ** replace triggers fire have run */
1704 int regTrigCnt; /* Register used to count replace trigger invocations */
1705 int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */
1706 int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
1707 Trigger *pTrigger; /* List of DELETE triggers on the table pTab */
1708 int nReplaceTrig = 0; /* Number of replace triggers coded */
1709 IndexIterator sIdxIter; /* Index iterator */
1711 isUpdate = regOldData!=0;
1712 db = pParse->db;
1713 v = pParse->pVdbe;
1714 assert( v!=0 );
1715 assert( !IsView(pTab) ); /* This table is not a VIEW */
1716 nCol = pTab->nCol;
1718 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
1719 ** normal rowid tables. nPkField is the number of key fields in the
1720 ** pPk index or 1 for a rowid table. In other words, nPkField is the
1721 ** number of fields in the true primary key of the table. */
1722 if( HasRowid(pTab) ){
1723 pPk = 0;
1724 nPkField = 1;
1725 }else{
1726 pPk = sqlite3PrimaryKeyIndex(pTab);
1727 nPkField = pPk->nKeyCol;
1730 /* Record that this module has started */
1731 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
1732 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
1734 /* Test all NOT NULL constraints.
1736 if( pTab->tabFlags & TF_HasNotNull ){
1737 int b2ndPass = 0; /* True if currently running 2nd pass */
1738 int nSeenReplace = 0; /* Number of ON CONFLICT REPLACE operations */
1739 int nGenerated = 0; /* Number of generated columns with NOT NULL */
1740 while(1){ /* Make 2 passes over columns. Exit loop via "break" */
1741 for(i=0; i<nCol; i++){
1742 int iReg; /* Register holding column value */
1743 Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */
1744 int isGenerated; /* non-zero if column is generated */
1745 onError = pCol->notNull;
1746 if( onError==OE_None ) continue; /* No NOT NULL on this column */
1747 if( i==pTab->iPKey ){
1748 continue; /* ROWID is never NULL */
1750 isGenerated = pCol->colFlags & COLFLAG_GENERATED;
1751 if( isGenerated && !b2ndPass ){
1752 nGenerated++;
1753 continue; /* Generated columns processed on 2nd pass */
1755 if( aiChng && aiChng[i]<0 && !isGenerated ){
1756 /* Do not check NOT NULL on columns that do not change */
1757 continue;
1759 if( overrideError!=OE_Default ){
1760 onError = overrideError;
1761 }else if( onError==OE_Default ){
1762 onError = OE_Abort;
1764 if( onError==OE_Replace ){
1765 if( b2ndPass /* REPLACE becomes ABORT on the 2nd pass */
1766 || pCol->iDflt==0 /* REPLACE is ABORT if no DEFAULT value */
1768 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1769 testcase( pCol->colFlags & COLFLAG_STORED );
1770 testcase( pCol->colFlags & COLFLAG_GENERATED );
1771 onError = OE_Abort;
1772 }else{
1773 assert( !isGenerated );
1775 }else if( b2ndPass && !isGenerated ){
1776 continue;
1778 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1779 || onError==OE_Ignore || onError==OE_Replace );
1780 testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
1781 iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
1782 switch( onError ){
1783 case OE_Replace: {
1784 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
1785 VdbeCoverage(v);
1786 assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
1787 nSeenReplace++;
1788 sqlite3ExprCodeCopy(pParse,
1789 sqlite3ColumnExpr(pTab, pCol), iReg);
1790 sqlite3VdbeJumpHere(v, addr1);
1791 break;
1793 case OE_Abort:
1794 sqlite3MayAbort(pParse);
1795 /* no break */ deliberate_fall_through
1796 case OE_Rollback:
1797 case OE_Fail: {
1798 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1799 pCol->zCnName);
1800 testcase( zMsg==0 && db->mallocFailed==0 );
1801 sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
1802 onError, iReg);
1803 sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
1804 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
1805 VdbeCoverage(v);
1806 break;
1808 default: {
1809 assert( onError==OE_Ignore );
1810 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
1811 VdbeCoverage(v);
1812 break;
1814 } /* end switch(onError) */
1815 } /* end loop i over columns */
1816 if( nGenerated==0 && nSeenReplace==0 ){
1817 /* If there are no generated columns with NOT NULL constraints
1818 ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
1819 ** pass is sufficient */
1820 break;
1822 if( b2ndPass ) break; /* Never need more than 2 passes */
1823 b2ndPass = 1;
1824 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1825 if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
1826 /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
1827 ** first pass, recomputed values for all generated columns, as
1828 ** those values might depend on columns affected by the REPLACE.
1830 sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
1832 #endif
1833 } /* end of 2-pass loop */
1834 } /* end if( has-not-null-constraints ) */
1836 /* Test all CHECK constraints
1838 #ifndef SQLITE_OMIT_CHECK
1839 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
1840 ExprList *pCheck = pTab->pCheck;
1841 pParse->iSelfTab = -(regNewData+1);
1842 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
1843 for(i=0; i<pCheck->nExpr; i++){
1844 int allOk;
1845 Expr *pCopy;
1846 Expr *pExpr = pCheck->a[i].pExpr;
1847 if( aiChng
1848 && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
1850 /* The check constraints do not reference any of the columns being
1851 ** updated so there is no point it verifying the check constraint */
1852 continue;
1854 if( bAffinityDone==0 ){
1855 sqlite3TableAffinity(v, pTab, regNewData+1);
1856 bAffinityDone = 1;
1858 allOk = sqlite3VdbeMakeLabel(pParse);
1859 sqlite3VdbeVerifyAbortable(v, onError);
1860 pCopy = sqlite3ExprDup(db, pExpr, 0);
1861 if( !db->mallocFailed ){
1862 sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
1864 sqlite3ExprDelete(db, pCopy);
1865 if( onError==OE_Ignore ){
1866 sqlite3VdbeGoto(v, ignoreDest);
1867 }else{
1868 char *zName = pCheck->a[i].zEName;
1869 assert( zName!=0 || pParse->db->mallocFailed );
1870 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
1871 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1872 onError, zName, P4_TRANSIENT,
1873 P5_ConstraintCheck);
1875 sqlite3VdbeResolveLabel(v, allOk);
1877 pParse->iSelfTab = 0;
1879 #endif /* !defined(SQLITE_OMIT_CHECK) */
1881 /* UNIQUE and PRIMARY KEY constraints should be handled in the following
1882 ** order:
1884 ** (1) OE_Update
1885 ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
1886 ** (3) OE_Replace
1888 ** OE_Fail and OE_Ignore must happen before any changes are made.
1889 ** OE_Update guarantees that only a single row will change, so it
1890 ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
1891 ** could happen in any order, but they are grouped up front for
1892 ** convenience.
1894 ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
1895 ** The order of constraints used to have OE_Update as (2) and OE_Abort
1896 ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
1897 ** constraint before any others, so it had to be moved.
1899 ** Constraint checking code is generated in this order:
1900 ** (A) The rowid constraint
1901 ** (B) Unique index constraints that do not have OE_Replace as their
1902 ** default conflict resolution strategy
1903 ** (C) Unique index that do use OE_Replace by default.
1905 ** The ordering of (2) and (3) is accomplished by making sure the linked
1906 ** list of indexes attached to a table puts all OE_Replace indexes last
1907 ** in the list. See sqlite3CreateIndex() for where that happens.
1909 sIdxIter.eType = 0;
1910 sIdxIter.i = 0;
1911 sIdxIter.u.ax.aIdx = 0; /* Silence harmless compiler warning */
1912 sIdxIter.u.lx.pIdx = pTab->pIndex;
1913 if( pUpsert ){
1914 if( pUpsert->pUpsertTarget==0 ){
1915 /* There is just on ON CONFLICT clause and it has no constraint-target */
1916 assert( pUpsert->pNextUpsert==0 );
1917 if( pUpsert->isDoUpdate==0 ){
1918 /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
1919 ** Make all unique constraint resolution be OE_Ignore */
1920 overrideError = OE_Ignore;
1921 pUpsert = 0;
1922 }else{
1923 /* A single ON CONFLICT DO UPDATE. Make all resolutions OE_Update */
1924 overrideError = OE_Update;
1926 }else if( pTab->pIndex!=0 ){
1927 /* Otherwise, we'll need to run the IndexListTerm array version of the
1928 ** iterator to ensure that all of the ON CONFLICT conditions are
1929 ** checked first and in order. */
1930 int nIdx, jj;
1931 u64 nByte;
1932 Upsert *pTerm;
1933 u8 *bUsed;
1934 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
1935 assert( aRegIdx[nIdx]>0 );
1937 sIdxIter.eType = 1;
1938 sIdxIter.u.ax.nIdx = nIdx;
1939 nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx;
1940 sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte);
1941 if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */
1942 bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx];
1943 pUpsert->pToFree = sIdxIter.u.ax.aIdx;
1944 for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
1945 if( pTerm->pUpsertTarget==0 ) break;
1946 if( pTerm->pUpsertIdx==0 ) continue; /* Skip ON CONFLICT for the IPK */
1947 jj = 0;
1948 pIdx = pTab->pIndex;
1949 while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
1950 pIdx = pIdx->pNext;
1951 jj++;
1953 if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */
1954 bUsed[jj] = 1;
1955 sIdxIter.u.ax.aIdx[i].p = pIdx;
1956 sIdxIter.u.ax.aIdx[i].ix = jj;
1957 i++;
1959 for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
1960 if( bUsed[jj] ) continue;
1961 sIdxIter.u.ax.aIdx[i].p = pIdx;
1962 sIdxIter.u.ax.aIdx[i].ix = jj;
1963 i++;
1965 assert( i==nIdx );
1969 /* Determine if it is possible that triggers (either explicitly coded
1970 ** triggers or FK resolution actions) might run as a result of deletes
1971 ** that happen when OE_Replace conflict resolution occurs. (Call these
1972 ** "replace triggers".) If any replace triggers run, we will need to
1973 ** recheck all of the uniqueness constraints after they have all run.
1974 ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
1976 ** If replace triggers are a possibility, then
1978 ** (1) Allocate register regTrigCnt and initialize it to zero.
1979 ** That register will count the number of replace triggers that
1980 ** fire. Constraint recheck only occurs if the number is positive.
1981 ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
1982 ** (3) Initialize addrRecheck and lblRecheckOk
1984 ** The uniqueness rechecking code will create a series of tests to run
1985 ** in a second pass. The addrRecheck and lblRecheckOk variables are
1986 ** used to link together these tests which are separated from each other
1987 ** in the generate bytecode.
1989 if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
1990 /* There are not DELETE triggers nor FK constraints. No constraint
1991 ** rechecks are needed. */
1992 pTrigger = 0;
1993 regTrigCnt = 0;
1994 }else{
1995 if( db->flags&SQLITE_RecTriggers ){
1996 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1997 regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
1998 }else{
1999 pTrigger = 0;
2000 regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
2002 if( regTrigCnt ){
2003 /* Replace triggers might exist. Allocate the counter and
2004 ** initialize it to zero. */
2005 regTrigCnt = ++pParse->nMem;
2006 sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
2007 VdbeComment((v, "trigger count"));
2008 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2009 addrRecheck = lblRecheckOk;
2013 /* If rowid is changing, make sure the new rowid does not previously
2014 ** exist in the table.
2016 if( pkChng && pPk==0 ){
2017 int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
2019 /* Figure out what action to take in case of a rowid collision */
2020 onError = pTab->keyConf;
2021 if( overrideError!=OE_Default ){
2022 onError = overrideError;
2023 }else if( onError==OE_Default ){
2024 onError = OE_Abort;
2027 /* figure out whether or not upsert applies in this case */
2028 if( pUpsert ){
2029 pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0);
2030 if( pUpsertClause!=0 ){
2031 if( pUpsertClause->isDoUpdate==0 ){
2032 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
2033 }else{
2034 onError = OE_Update; /* DO UPDATE */
2037 if( pUpsertClause!=pUpsert ){
2038 /* The first ON CONFLICT clause has a conflict target other than
2039 ** the IPK. We have to jump ahead to that first ON CONFLICT clause
2040 ** and then come back here and deal with the IPK afterwards */
2041 upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto);
2045 /* If the response to a rowid conflict is REPLACE but the response
2046 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
2047 ** to defer the running of the rowid conflict checking until after
2048 ** the UNIQUE constraints have run.
2050 if( onError==OE_Replace /* IPK rule is REPLACE */
2051 && onError!=overrideError /* Rules for other constraints are different */
2052 && pTab->pIndex /* There exist other constraints */
2053 && !upsertIpkDelay /* IPK check already deferred by UPSERT */
2055 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
2056 VdbeComment((v, "defer IPK REPLACE until last"));
2059 if( isUpdate ){
2060 /* pkChng!=0 does not mean that the rowid has changed, only that
2061 ** it might have changed. Skip the conflict logic below if the rowid
2062 ** is unchanged. */
2063 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
2064 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2065 VdbeCoverage(v);
2068 /* Check to see if the new rowid already exists in the table. Skip
2069 ** the following conflict logic if it does not. */
2070 VdbeNoopComment((v, "uniqueness check for ROWID"));
2071 sqlite3VdbeVerifyAbortable(v, onError);
2072 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
2073 VdbeCoverage(v);
2075 switch( onError ){
2076 default: {
2077 onError = OE_Abort;
2078 /* no break */ deliberate_fall_through
2080 case OE_Rollback:
2081 case OE_Abort:
2082 case OE_Fail: {
2083 testcase( onError==OE_Rollback );
2084 testcase( onError==OE_Abort );
2085 testcase( onError==OE_Fail );
2086 sqlite3RowidConstraint(pParse, onError, pTab);
2087 break;
2089 case OE_Replace: {
2090 /* If there are DELETE triggers on this table and the
2091 ** recursive-triggers flag is set, call GenerateRowDelete() to
2092 ** remove the conflicting row from the table. This will fire
2093 ** the triggers and remove both the table and index b-tree entries.
2095 ** Otherwise, if there are no triggers or the recursive-triggers
2096 ** flag is not set, but the table has one or more indexes, call
2097 ** GenerateRowIndexDelete(). This removes the index b-tree entries
2098 ** only. The table b-tree entry will be replaced by the new entry
2099 ** when it is inserted.
2101 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
2102 ** also invoke MultiWrite() to indicate that this VDBE may require
2103 ** statement rollback (if the statement is aborted after the delete
2104 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
2105 ** but being more selective here allows statements like:
2107 ** REPLACE INTO t(rowid) VALUES($newrowid)
2109 ** to run without a statement journal if there are no indexes on the
2110 ** table.
2112 if( regTrigCnt ){
2113 sqlite3MultiWrite(pParse);
2114 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2115 regNewData, 1, 0, OE_Replace, 1, -1);
2116 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2117 nReplaceTrig++;
2118 }else{
2119 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2120 assert( HasRowid(pTab) );
2121 /* This OP_Delete opcode fires the pre-update-hook only. It does
2122 ** not modify the b-tree. It is more efficient to let the coming
2123 ** OP_Insert replace the existing entry than it is to delete the
2124 ** existing entry and then insert a new one. */
2125 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
2126 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
2127 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2128 if( pTab->pIndex ){
2129 sqlite3MultiWrite(pParse);
2130 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
2133 seenReplace = 1;
2134 break;
2136 #ifndef SQLITE_OMIT_UPSERT
2137 case OE_Update: {
2138 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
2139 /* no break */ deliberate_fall_through
2141 #endif
2142 case OE_Ignore: {
2143 testcase( onError==OE_Ignore );
2144 sqlite3VdbeGoto(v, ignoreDest);
2145 break;
2148 sqlite3VdbeResolveLabel(v, addrRowidOk);
2149 if( pUpsert && pUpsertClause!=pUpsert ){
2150 upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
2151 }else if( ipkTop ){
2152 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
2153 sqlite3VdbeJumpHere(v, ipkTop-1);
2157 /* Test all UNIQUE constraints by creating entries for each UNIQUE
2158 ** index and making sure that duplicate entries do not already exist.
2159 ** Compute the revised record entries for indices as we go.
2161 ** This loop also handles the case of the PRIMARY KEY index for a
2162 ** WITHOUT ROWID table.
2164 for(pIdx = indexIteratorFirst(&sIdxIter, &ix);
2165 pIdx;
2166 pIdx = indexIteratorNext(&sIdxIter, &ix)
2168 int regIdx; /* Range of registers holding content for pIdx */
2169 int regR; /* Range of registers holding conflicting PK */
2170 int iThisCur; /* Cursor for this UNIQUE index */
2171 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
2172 int addrConflictCk; /* First opcode in the conflict check logic */
2174 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
2175 if( pUpsert ){
2176 pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
2177 if( upsertIpkDelay && pUpsertClause==pUpsert ){
2178 sqlite3VdbeJumpHere(v, upsertIpkDelay);
2181 addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
2182 if( bAffinityDone==0 ){
2183 sqlite3TableAffinity(v, pTab, regNewData+1);
2184 bAffinityDone = 1;
2186 VdbeNoopComment((v, "prep index %s", pIdx->zName));
2187 iThisCur = iIdxCur+ix;
2190 /* Skip partial indices for which the WHERE clause is not true */
2191 if( pIdx->pPartIdxWhere ){
2192 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
2193 pParse->iSelfTab = -(regNewData+1);
2194 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
2195 SQLITE_JUMPIFNULL);
2196 pParse->iSelfTab = 0;
2199 /* Create a record for this index entry as it should appear after
2200 ** the insert or update. Store that record in the aRegIdx[ix] register
2202 regIdx = aRegIdx[ix]+1;
2203 for(i=0; i<pIdx->nColumn; i++){
2204 int iField = pIdx->aiColumn[i];
2205 int x;
2206 if( iField==XN_EXPR ){
2207 pParse->iSelfTab = -(regNewData+1);
2208 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
2209 pParse->iSelfTab = 0;
2210 VdbeComment((v, "%s column %d", pIdx->zName, i));
2211 }else if( iField==XN_ROWID || iField==pTab->iPKey ){
2212 x = regNewData;
2213 sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
2214 VdbeComment((v, "rowid"));
2215 }else{
2216 testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
2217 x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
2218 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
2219 VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
2222 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
2223 VdbeComment((v, "for %s", pIdx->zName));
2224 #ifdef SQLITE_ENABLE_NULL_TRIM
2225 if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
2226 sqlite3SetMakeRecordP5(v, pIdx->pTable);
2228 #endif
2229 sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
2231 /* In an UPDATE operation, if this index is the PRIMARY KEY index
2232 ** of a WITHOUT ROWID table and there has been no change the
2233 ** primary key, then no collision is possible. The collision detection
2234 ** logic below can all be skipped. */
2235 if( isUpdate && pPk==pIdx && pkChng==0 ){
2236 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2237 continue;
2240 /* Find out what action to take in case there is a uniqueness conflict */
2241 onError = pIdx->onError;
2242 if( onError==OE_None ){
2243 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2244 continue; /* pIdx is not a UNIQUE index */
2246 if( overrideError!=OE_Default ){
2247 onError = overrideError;
2248 }else if( onError==OE_Default ){
2249 onError = OE_Abort;
2252 /* Figure out if the upsert clause applies to this index */
2253 if( pUpsertClause ){
2254 if( pUpsertClause->isDoUpdate==0 ){
2255 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
2256 }else{
2257 onError = OE_Update; /* DO UPDATE */
2261 /* Collision detection may be omitted if all of the following are true:
2262 ** (1) The conflict resolution algorithm is REPLACE
2263 ** (2) The table is a WITHOUT ROWID table
2264 ** (3) There are no secondary indexes on the table
2265 ** (4) No delete triggers need to be fired if there is a conflict
2266 ** (5) No FK constraint counters need to be updated if a conflict occurs.
2268 ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
2269 ** must be explicitly deleted in order to ensure any pre-update hook
2270 ** is invoked. */
2271 assert( IsOrdinaryTable(pTab) );
2272 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
2273 if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
2274 && pPk==pIdx /* Condition 2 */
2275 && onError==OE_Replace /* Condition 1 */
2276 && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
2277 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
2278 && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
2279 (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
2281 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2282 continue;
2284 #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
2286 /* Check to see if the new index entry will be unique */
2287 sqlite3VdbeVerifyAbortable(v, onError);
2288 addrConflictCk =
2289 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
2290 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
2292 /* Generate code to handle collisions */
2293 regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField);
2294 if( isUpdate || onError==OE_Replace ){
2295 if( HasRowid(pTab) ){
2296 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
2297 /* Conflict only if the rowid of the existing index entry
2298 ** is different from old-rowid */
2299 if( isUpdate ){
2300 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
2301 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2302 VdbeCoverage(v);
2304 }else{
2305 int x;
2306 /* Extract the PRIMARY KEY from the end of the index entry and
2307 ** store it in registers regR..regR+nPk-1 */
2308 if( pIdx!=pPk ){
2309 for(i=0; i<pPk->nKeyCol; i++){
2310 assert( pPk->aiColumn[i]>=0 );
2311 x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
2312 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
2313 VdbeComment((v, "%s.%s", pTab->zName,
2314 pTab->aCol[pPk->aiColumn[i]].zCnName));
2317 if( isUpdate ){
2318 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
2319 ** table, only conflict if the new PRIMARY KEY values are actually
2320 ** different from the old. See TH3 withoutrowid04.test.
2322 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
2323 ** of the matched index row are different from the original PRIMARY
2324 ** KEY values of this row before the update. */
2325 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
2326 int op = OP_Ne;
2327 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
2329 for(i=0; i<pPk->nKeyCol; i++){
2330 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
2331 x = pPk->aiColumn[i];
2332 assert( x>=0 );
2333 if( i==(pPk->nKeyCol-1) ){
2334 addrJump = addrUniqueOk;
2335 op = OP_Eq;
2337 x = sqlite3TableColumnToStorage(pTab, x);
2338 sqlite3VdbeAddOp4(v, op,
2339 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
2341 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2342 VdbeCoverageIf(v, op==OP_Eq);
2343 VdbeCoverageIf(v, op==OP_Ne);
2349 /* Generate code that executes if the new index entry is not unique */
2350 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
2351 || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
2352 switch( onError ){
2353 case OE_Rollback:
2354 case OE_Abort:
2355 case OE_Fail: {
2356 testcase( onError==OE_Rollback );
2357 testcase( onError==OE_Abort );
2358 testcase( onError==OE_Fail );
2359 sqlite3UniqueConstraint(pParse, onError, pIdx);
2360 break;
2362 #ifndef SQLITE_OMIT_UPSERT
2363 case OE_Update: {
2364 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
2365 /* no break */ deliberate_fall_through
2367 #endif
2368 case OE_Ignore: {
2369 testcase( onError==OE_Ignore );
2370 sqlite3VdbeGoto(v, ignoreDest);
2371 break;
2373 default: {
2374 int nConflictCk; /* Number of opcodes in conflict check logic */
2376 assert( onError==OE_Replace );
2377 nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
2378 assert( nConflictCk>0 || db->mallocFailed );
2379 testcase( nConflictCk<=0 );
2380 testcase( nConflictCk>1 );
2381 if( regTrigCnt ){
2382 sqlite3MultiWrite(pParse);
2383 nReplaceTrig++;
2385 if( pTrigger && isUpdate ){
2386 sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
2388 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2389 regR, nPkField, 0, OE_Replace,
2390 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
2391 if( pTrigger && isUpdate ){
2392 sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
2394 if( regTrigCnt ){
2395 int addrBypass; /* Jump destination to bypass recheck logic */
2397 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2398 addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
2399 VdbeComment((v, "bypass recheck"));
2401 /* Here we insert code that will be invoked after all constraint
2402 ** checks have run, if and only if one or more replace triggers
2403 ** fired. */
2404 sqlite3VdbeResolveLabel(v, lblRecheckOk);
2405 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2406 if( pIdx->pPartIdxWhere ){
2407 /* Bypass the recheck if this partial index is not defined
2408 ** for the current row */
2409 sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
2410 VdbeCoverage(v);
2412 /* Copy the constraint check code from above, except change
2413 ** the constraint-ok jump destination to be the address of
2414 ** the next retest block */
2415 while( nConflictCk>0 ){
2416 VdbeOp x; /* Conflict check opcode to copy */
2417 /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
2418 ** Hence, make a complete copy of the opcode, rather than using
2419 ** a pointer to the opcode. */
2420 x = *sqlite3VdbeGetOp(v, addrConflictCk);
2421 if( x.opcode!=OP_IdxRowid ){
2422 int p2; /* New P2 value for copied conflict check opcode */
2423 const char *zP4;
2424 if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
2425 p2 = lblRecheckOk;
2426 }else{
2427 p2 = x.p2;
2429 zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
2430 sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
2431 sqlite3VdbeChangeP5(v, x.p5);
2432 VdbeCoverageIf(v, p2!=x.p2);
2434 nConflictCk--;
2435 addrConflictCk++;
2437 /* If the retest fails, issue an abort */
2438 sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
2440 sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
2442 seenReplace = 1;
2443 break;
2446 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2447 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
2448 if( pUpsertClause
2449 && upsertIpkReturn
2450 && sqlite3UpsertNextIsIPK(pUpsertClause)
2452 sqlite3VdbeGoto(v, upsertIpkDelay+1);
2453 sqlite3VdbeJumpHere(v, upsertIpkReturn);
2454 upsertIpkReturn = 0;
2458 /* If the IPK constraint is a REPLACE, run it last */
2459 if( ipkTop ){
2460 sqlite3VdbeGoto(v, ipkTop);
2461 VdbeComment((v, "Do IPK REPLACE"));
2462 assert( ipkBottom>0 );
2463 sqlite3VdbeJumpHere(v, ipkBottom);
2466 /* Recheck all uniqueness constraints after replace triggers have run */
2467 testcase( regTrigCnt!=0 && nReplaceTrig==0 );
2468 assert( regTrigCnt!=0 || nReplaceTrig==0 );
2469 if( nReplaceTrig ){
2470 sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
2471 if( !pPk ){
2472 if( isUpdate ){
2473 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
2474 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2475 VdbeCoverage(v);
2477 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
2478 VdbeCoverage(v);
2479 sqlite3RowidConstraint(pParse, OE_Abort, pTab);
2480 }else{
2481 sqlite3VdbeGoto(v, addrRecheck);
2483 sqlite3VdbeResolveLabel(v, lblRecheckOk);
2486 /* Generate the table record */
2487 if( HasRowid(pTab) ){
2488 int regRec = aRegIdx[ix];
2489 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
2490 sqlite3SetMakeRecordP5(v, pTab);
2491 if( !bAffinityDone ){
2492 sqlite3TableAffinity(v, pTab, 0);
2496 *pbMayReplace = seenReplace;
2497 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
2500 #ifdef SQLITE_ENABLE_NULL_TRIM
2502 ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
2503 ** to be the number of columns in table pTab that must not be NULL-trimmed.
2505 ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
2507 void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
2508 u16 i;
2510 /* Records with omitted columns are only allowed for schema format
2511 ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
2512 if( pTab->pSchema->file_format<2 ) return;
2514 for(i=pTab->nCol-1; i>0; i--){
2515 if( pTab->aCol[i].iDflt!=0 ) break;
2516 if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
2518 sqlite3VdbeChangeP5(v, i+1);
2520 #endif
2523 ** Table pTab is a WITHOUT ROWID table that is being written to. The cursor
2524 ** number is iCur, and register regData contains the new record for the
2525 ** PK index. This function adds code to invoke the pre-update hook,
2526 ** if one is registered.
2528 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2529 static void codeWithoutRowidPreupdate(
2530 Parse *pParse, /* Parse context */
2531 Table *pTab, /* Table being updated */
2532 int iCur, /* Cursor number for table */
2533 int regData /* Data containing new record */
2535 Vdbe *v = pParse->pVdbe;
2536 int r = sqlite3GetTempReg(pParse);
2537 assert( !HasRowid(pTab) );
2538 assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
2539 sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
2540 sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE);
2541 sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
2542 sqlite3ReleaseTempReg(pParse, r);
2544 #else
2545 # define codeWithoutRowidPreupdate(a,b,c,d)
2546 #endif
2549 ** This routine generates code to finish the INSERT or UPDATE operation
2550 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
2551 ** A consecutive range of registers starting at regNewData contains the
2552 ** rowid and the content to be inserted.
2554 ** The arguments to this routine should be the same as the first six
2555 ** arguments to sqlite3GenerateConstraintChecks.
2557 void sqlite3CompleteInsertion(
2558 Parse *pParse, /* The parser context */
2559 Table *pTab, /* the table into which we are inserting */
2560 int iDataCur, /* Cursor of the canonical data source */
2561 int iIdxCur, /* First index cursor */
2562 int regNewData, /* Range of content */
2563 int *aRegIdx, /* Register used by each index. 0 for unused indices */
2564 int update_flags, /* True for UPDATE, False for INSERT */
2565 int appendBias, /* True if this is likely to be an append */
2566 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
2568 Vdbe *v; /* Prepared statements under construction */
2569 Index *pIdx; /* An index being inserted or updated */
2570 u8 pik_flags; /* flag values passed to the btree insert */
2571 int i; /* Loop counter */
2573 assert( update_flags==0
2574 || update_flags==OPFLAG_ISUPDATE
2575 || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
2578 v = pParse->pVdbe;
2579 assert( v!=0 );
2580 assert( !IsView(pTab) ); /* This table is not a VIEW */
2581 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2582 /* All REPLACE indexes are at the end of the list */
2583 assert( pIdx->onError!=OE_Replace
2584 || pIdx->pNext==0
2585 || pIdx->pNext->onError==OE_Replace );
2586 if( aRegIdx[i]==0 ) continue;
2587 if( pIdx->pPartIdxWhere ){
2588 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
2589 VdbeCoverage(v);
2591 pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
2592 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2593 pik_flags |= OPFLAG_NCHANGE;
2594 pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
2595 if( update_flags==0 ){
2596 codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]);
2599 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
2600 aRegIdx[i]+1,
2601 pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
2602 sqlite3VdbeChangeP5(v, pik_flags);
2604 if( !HasRowid(pTab) ) return;
2605 if( pParse->nested ){
2606 pik_flags = 0;
2607 }else{
2608 pik_flags = OPFLAG_NCHANGE;
2609 pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
2611 if( appendBias ){
2612 pik_flags |= OPFLAG_APPEND;
2614 if( useSeekResult ){
2615 pik_flags |= OPFLAG_USESEEKRESULT;
2617 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
2618 if( !pParse->nested ){
2619 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
2621 sqlite3VdbeChangeP5(v, pik_flags);
2625 ** Allocate cursors for the pTab table and all its indices and generate
2626 ** code to open and initialized those cursors.
2628 ** The cursor for the object that contains the complete data (normally
2629 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
2630 ** ROWID table) is returned in *piDataCur. The first index cursor is
2631 ** returned in *piIdxCur. The number of indices is returned.
2633 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
2634 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
2635 ** If iBase is negative, then allocate the next available cursor.
2637 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
2638 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
2639 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
2640 ** pTab->pIndex list.
2642 ** If pTab is a virtual table, then this routine is a no-op and the
2643 ** *piDataCur and *piIdxCur values are left uninitialized.
2645 int sqlite3OpenTableAndIndices(
2646 Parse *pParse, /* Parsing context */
2647 Table *pTab, /* Table to be opened */
2648 int op, /* OP_OpenRead or OP_OpenWrite */
2649 u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
2650 int iBase, /* Use this for the table cursor, if there is one */
2651 u8 *aToOpen, /* If not NULL: boolean for each table and index */
2652 int *piDataCur, /* Write the database source cursor number here */
2653 int *piIdxCur /* Write the first index cursor number here */
2655 int i;
2656 int iDb;
2657 int iDataCur;
2658 Index *pIdx;
2659 Vdbe *v;
2661 assert( op==OP_OpenRead || op==OP_OpenWrite );
2662 assert( op==OP_OpenWrite || p5==0 );
2663 assert( piDataCur!=0 );
2664 assert( piIdxCur!=0 );
2665 if( IsVirtual(pTab) ){
2666 /* This routine is a no-op for virtual tables. Leave the output
2667 ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
2668 ** for improved error detection. */
2669 *piDataCur = *piIdxCur = -999;
2670 return 0;
2672 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2673 v = pParse->pVdbe;
2674 assert( v!=0 );
2675 if( iBase<0 ) iBase = pParse->nTab;
2676 iDataCur = iBase++;
2677 *piDataCur = iDataCur;
2678 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
2679 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
2680 }else if( pParse->db->noSharedCache==0 ){
2681 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
2683 *piIdxCur = iBase;
2684 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2685 int iIdxCur = iBase++;
2686 assert( pIdx->pSchema==pTab->pSchema );
2687 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2688 *piDataCur = iIdxCur;
2689 p5 = 0;
2691 if( aToOpen==0 || aToOpen[i+1] ){
2692 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
2693 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2694 sqlite3VdbeChangeP5(v, p5);
2695 VdbeComment((v, "%s", pIdx->zName));
2698 if( iBase>pParse->nTab ) pParse->nTab = iBase;
2699 return i;
2703 #ifdef SQLITE_TEST
2705 ** The following global variable is incremented whenever the
2706 ** transfer optimization is used. This is used for testing
2707 ** purposes only - to make sure the transfer optimization really
2708 ** is happening when it is supposed to.
2710 int sqlite3_xferopt_count;
2711 #endif /* SQLITE_TEST */
2714 #ifndef SQLITE_OMIT_XFER_OPT
2716 ** Check to see if index pSrc is compatible as a source of data
2717 ** for index pDest in an insert transfer optimization. The rules
2718 ** for a compatible index:
2720 ** * The index is over the same set of columns
2721 ** * The same DESC and ASC markings occurs on all columns
2722 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
2723 ** * The same collating sequence on each column
2724 ** * The index has the exact same WHERE clause
2726 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
2727 int i;
2728 assert( pDest && pSrc );
2729 assert( pDest->pTable!=pSrc->pTable );
2730 if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
2731 return 0; /* Different number of columns */
2733 if( pDest->onError!=pSrc->onError ){
2734 return 0; /* Different conflict resolution strategies */
2736 for(i=0; i<pSrc->nKeyCol; i++){
2737 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
2738 return 0; /* Different columns indexed */
2740 if( pSrc->aiColumn[i]==XN_EXPR ){
2741 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
2742 if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
2743 pDest->aColExpr->a[i].pExpr, -1)!=0 ){
2744 return 0; /* Different expressions in the index */
2747 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
2748 return 0; /* Different sort orders */
2750 if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
2751 return 0; /* Different collating sequences */
2754 if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
2755 return 0; /* Different WHERE clauses */
2758 /* If no test above fails then the indices must be compatible */
2759 return 1;
2763 ** Attempt the transfer optimization on INSERTs of the form
2765 ** INSERT INTO tab1 SELECT * FROM tab2;
2767 ** The xfer optimization transfers raw records from tab2 over to tab1.
2768 ** Columns are not decoded and reassembled, which greatly improves
2769 ** performance. Raw index records are transferred in the same way.
2771 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
2772 ** There are lots of rules for determining compatibility - see comments
2773 ** embedded in the code for details.
2775 ** This routine returns TRUE if the optimization is guaranteed to be used.
2776 ** Sometimes the xfer optimization will only work if the destination table
2777 ** is empty - a factor that can only be determined at run-time. In that
2778 ** case, this routine generates code for the xfer optimization but also
2779 ** does a test to see if the destination table is empty and jumps over the
2780 ** xfer optimization code if the test fails. In that case, this routine
2781 ** returns FALSE so that the caller will know to go ahead and generate
2782 ** an unoptimized transfer. This routine also returns FALSE if there
2783 ** is no chance that the xfer optimization can be applied.
2785 ** This optimization is particularly useful at making VACUUM run faster.
2787 static int xferOptimization(
2788 Parse *pParse, /* Parser context */
2789 Table *pDest, /* The table we are inserting into */
2790 Select *pSelect, /* A SELECT statement to use as the data source */
2791 int onError, /* How to handle constraint errors */
2792 int iDbDest /* The database of pDest */
2794 sqlite3 *db = pParse->db;
2795 ExprList *pEList; /* The result set of the SELECT */
2796 Table *pSrc; /* The table in the FROM clause of SELECT */
2797 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
2798 SrcItem *pItem; /* An element of pSelect->pSrc */
2799 int i; /* Loop counter */
2800 int iDbSrc; /* The database of pSrc */
2801 int iSrc, iDest; /* Cursors from source and destination */
2802 int addr1, addr2; /* Loop addresses */
2803 int emptyDestTest = 0; /* Address of test for empty pDest */
2804 int emptySrcTest = 0; /* Address of test for empty pSrc */
2805 Vdbe *v; /* The VDBE we are building */
2806 int regAutoinc; /* Memory register used by AUTOINC */
2807 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
2808 int regData, regRowid; /* Registers holding data and rowid */
2810 assert( pSelect!=0 );
2811 if( pParse->pWith || pSelect->pWith ){
2812 /* Do not attempt to process this query if there are an WITH clauses
2813 ** attached to it. Proceeding may generate a false "no such table: xxx"
2814 ** error if pSelect reads from a CTE named "xxx". */
2815 return 0;
2817 #ifndef SQLITE_OMIT_VIRTUALTABLE
2818 if( IsVirtual(pDest) ){
2819 return 0; /* tab1 must not be a virtual table */
2821 #endif
2822 if( onError==OE_Default ){
2823 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
2824 if( onError==OE_Default ) onError = OE_Abort;
2826 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
2827 if( pSelect->pSrc->nSrc!=1 ){
2828 return 0; /* FROM clause must have exactly one term */
2830 if( pSelect->pSrc->a[0].pSelect ){
2831 return 0; /* FROM clause cannot contain a subquery */
2833 if( pSelect->pWhere ){
2834 return 0; /* SELECT may not have a WHERE clause */
2836 if( pSelect->pOrderBy ){
2837 return 0; /* SELECT may not have an ORDER BY clause */
2839 /* Do not need to test for a HAVING clause. If HAVING is present but
2840 ** there is no ORDER BY, we will get an error. */
2841 if( pSelect->pGroupBy ){
2842 return 0; /* SELECT may not have a GROUP BY clause */
2844 if( pSelect->pLimit ){
2845 return 0; /* SELECT may not have a LIMIT clause */
2847 if( pSelect->pPrior ){
2848 return 0; /* SELECT may not be a compound query */
2850 if( pSelect->selFlags & SF_Distinct ){
2851 return 0; /* SELECT may not be DISTINCT */
2853 pEList = pSelect->pEList;
2854 assert( pEList!=0 );
2855 if( pEList->nExpr!=1 ){
2856 return 0; /* The result set must have exactly one column */
2858 assert( pEList->a[0].pExpr );
2859 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
2860 return 0; /* The result set must be the special operator "*" */
2863 /* At this point we have established that the statement is of the
2864 ** correct syntactic form to participate in this optimization. Now
2865 ** we have to check the semantics.
2867 pItem = pSelect->pSrc->a;
2868 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
2869 if( pSrc==0 ){
2870 return 0; /* FROM clause does not contain a real table */
2872 if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
2873 testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
2874 return 0; /* tab1 and tab2 may not be the same table */
2876 if( HasRowid(pDest)!=HasRowid(pSrc) ){
2877 return 0; /* source and destination must both be WITHOUT ROWID or not */
2879 if( !IsOrdinaryTable(pSrc) ){
2880 return 0; /* tab2 may not be a view or virtual table */
2882 if( pDest->nCol!=pSrc->nCol ){
2883 return 0; /* Number of columns must be the same in tab1 and tab2 */
2885 if( pDest->iPKey!=pSrc->iPKey ){
2886 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
2888 if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
2889 return 0; /* Cannot feed from a non-strict into a strict table */
2891 for(i=0; i<pDest->nCol; i++){
2892 Column *pDestCol = &pDest->aCol[i];
2893 Column *pSrcCol = &pSrc->aCol[i];
2894 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
2895 if( (db->mDbFlags & DBFLAG_Vacuum)==0
2896 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
2898 return 0; /* Neither table may have __hidden__ columns */
2900 #endif
2901 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2902 /* Even if tables t1 and t2 have identical schemas, if they contain
2903 ** generated columns, then this statement is semantically incorrect:
2905 ** INSERT INTO t2 SELECT * FROM t1;
2907 ** The reason is that generated column values are returned by the
2908 ** the SELECT statement on the right but the INSERT statement on the
2909 ** left wants them to be omitted.
2911 ** Nevertheless, this is a useful notational shorthand to tell SQLite
2912 ** to do a bulk transfer all of the content from t1 over to t2.
2914 ** We could, in theory, disable this (except for internal use by the
2915 ** VACUUM command where it is actually needed). But why do that? It
2916 ** seems harmless enough, and provides a useful service.
2918 if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
2919 (pSrcCol->colFlags & COLFLAG_GENERATED) ){
2920 return 0; /* Both columns have the same generated-column type */
2922 /* But the transfer is only allowed if both the source and destination
2923 ** tables have the exact same expressions for generated columns.
2924 ** This requirement could be relaxed for VIRTUAL columns, I suppose.
2926 if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
2927 if( sqlite3ExprCompare(0,
2928 sqlite3ColumnExpr(pSrc, pSrcCol),
2929 sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
2930 testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
2931 testcase( pDestCol->colFlags & COLFLAG_STORED );
2932 return 0; /* Different generator expressions */
2935 #endif
2936 if( pDestCol->affinity!=pSrcCol->affinity ){
2937 return 0; /* Affinity must be the same on all columns */
2939 if( sqlite3_stricmp(sqlite3ColumnColl(pDestCol),
2940 sqlite3ColumnColl(pSrcCol))!=0 ){
2941 return 0; /* Collating sequence must be the same on all columns */
2943 if( pDestCol->notNull && !pSrcCol->notNull ){
2944 return 0; /* tab2 must be NOT NULL if tab1 is */
2946 /* Default values for second and subsequent columns need to match. */
2947 if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
2948 Expr *pDestExpr = sqlite3ColumnExpr(pDest, pDestCol);
2949 Expr *pSrcExpr = sqlite3ColumnExpr(pSrc, pSrcCol);
2950 assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
2951 assert( pDestExpr==0 || !ExprHasProperty(pDestExpr, EP_IntValue) );
2952 assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
2953 assert( pSrcExpr==0 || !ExprHasProperty(pSrcExpr, EP_IntValue) );
2954 if( (pDestExpr==0)!=(pSrcExpr==0)
2955 || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
2956 pSrcExpr->u.zToken)!=0)
2958 return 0; /* Default values must be the same for all columns */
2962 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
2963 if( IsUniqueIndex(pDestIdx) ){
2964 destHasUniqueIdx = 1;
2966 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
2967 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
2969 if( pSrcIdx==0 ){
2970 return 0; /* pDestIdx has no corresponding index in pSrc */
2972 if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
2973 && sqlite3FaultSim(411)==SQLITE_OK ){
2974 /* The sqlite3FaultSim() call allows this corruption test to be
2975 ** bypassed during testing, in order to exercise other corruption tests
2976 ** further downstream. */
2977 return 0; /* Corrupt schema - two indexes on the same btree */
2980 #ifndef SQLITE_OMIT_CHECK
2981 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
2982 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
2984 #endif
2985 #ifndef SQLITE_OMIT_FOREIGN_KEY
2986 /* Disallow the transfer optimization if the destination table contains
2987 ** any foreign key constraints. This is more restrictive than necessary.
2988 ** But the main beneficiary of the transfer optimization is the VACUUM
2989 ** command, and the VACUUM command disables foreign key constraints. So
2990 ** the extra complication to make this rule less restrictive is probably
2991 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
2993 assert( IsOrdinaryTable(pDest) );
2994 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
2995 return 0;
2997 #endif
2998 if( (db->flags & SQLITE_CountRows)!=0 ){
2999 return 0; /* xfer opt does not play well with PRAGMA count_changes */
3002 /* If we get this far, it means that the xfer optimization is at
3003 ** least a possibility, though it might only work if the destination
3004 ** table (tab1) is initially empty.
3006 #ifdef SQLITE_TEST
3007 sqlite3_xferopt_count++;
3008 #endif
3009 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
3010 v = sqlite3GetVdbe(pParse);
3011 sqlite3CodeVerifySchema(pParse, iDbSrc);
3012 iSrc = pParse->nTab++;
3013 iDest = pParse->nTab++;
3014 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
3015 regData = sqlite3GetTempReg(pParse);
3016 sqlite3VdbeAddOp2(v, OP_Null, 0, regData);
3017 regRowid = sqlite3GetTempReg(pParse);
3018 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
3019 assert( HasRowid(pDest) || destHasUniqueIdx );
3020 if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
3021 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
3022 || destHasUniqueIdx /* (2) */
3023 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
3025 /* In some circumstances, we are able to run the xfer optimization
3026 ** only if the destination table is initially empty. Unless the
3027 ** DBFLAG_Vacuum flag is set, this block generates code to make
3028 ** that determination. If DBFLAG_Vacuum is set, then the destination
3029 ** table is always empty.
3031 ** Conditions under which the destination must be empty:
3033 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
3034 ** (If the destination is not initially empty, the rowid fields
3035 ** of index entries might need to change.)
3037 ** (2) The destination has a unique index. (The xfer optimization
3038 ** is unable to test uniqueness.)
3040 ** (3) onError is something other than OE_Abort and OE_Rollback.
3042 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
3043 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
3044 sqlite3VdbeJumpHere(v, addr1);
3046 if( HasRowid(pSrc) ){
3047 u8 insFlags;
3048 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
3049 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
3050 if( pDest->iPKey>=0 ){
3051 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3052 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3053 sqlite3VdbeVerifyAbortable(v, onError);
3054 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
3055 VdbeCoverage(v);
3056 sqlite3RowidConstraint(pParse, onError, pDest);
3057 sqlite3VdbeJumpHere(v, addr2);
3059 autoIncStep(pParse, regAutoinc, regRowid);
3060 }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
3061 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
3062 }else{
3063 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3064 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
3067 if( db->mDbFlags & DBFLAG_Vacuum ){
3068 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3069 insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3070 }else{
3071 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT;
3073 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
3074 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3075 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3076 insFlags &= ~OPFLAG_PREFORMAT;
3077 }else
3078 #endif
3080 sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid);
3082 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
3083 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3084 sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
3086 sqlite3VdbeChangeP5(v, insFlags);
3088 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
3089 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
3090 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3091 }else{
3092 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
3093 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
3095 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
3096 u8 idxInsFlags = 0;
3097 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
3098 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
3100 assert( pSrcIdx );
3101 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
3102 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
3103 VdbeComment((v, "%s", pSrcIdx->zName));
3104 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
3105 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
3106 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
3107 VdbeComment((v, "%s", pDestIdx->zName));
3108 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
3109 if( db->mDbFlags & DBFLAG_Vacuum ){
3110 /* This INSERT command is part of a VACUUM operation, which guarantees
3111 ** that the destination table is empty. If all indexed columns use
3112 ** collation sequence BINARY, then it can also be assumed that the
3113 ** index will be populated by inserting keys in strictly sorted
3114 ** order. In this case, instead of seeking within the b-tree as part
3115 ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
3116 ** OP_IdxInsert to seek to the point within the b-tree where each key
3117 ** should be inserted. This is faster.
3119 ** If any of the indexed columns use a collation sequence other than
3120 ** BINARY, this optimization is disabled. This is because the user
3121 ** might change the definition of a collation sequence and then run
3122 ** a VACUUM command. In that case keys may not be written in strictly
3123 ** sorted order. */
3124 for(i=0; i<pSrcIdx->nColumn; i++){
3125 const char *zColl = pSrcIdx->azColl[i];
3126 if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
3128 if( i==pSrcIdx->nColumn ){
3129 idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3130 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3131 sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc);
3133 }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
3134 idxInsFlags |= OPFLAG_NCHANGE;
3136 if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){
3137 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3138 if( (db->mDbFlags & DBFLAG_Vacuum)==0
3139 && !HasRowid(pDest)
3140 && IsPrimaryKeyIndex(pDestIdx)
3142 codeWithoutRowidPreupdate(pParse, pDest, iDest, regData);
3145 sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
3146 sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
3147 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
3148 sqlite3VdbeJumpHere(v, addr1);
3149 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
3150 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3152 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
3153 sqlite3ReleaseTempReg(pParse, regRowid);
3154 sqlite3ReleaseTempReg(pParse, regData);
3155 if( emptyDestTest ){
3156 sqlite3AutoincrementEnd(pParse);
3157 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
3158 sqlite3VdbeJumpHere(v, emptyDestTest);
3159 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3160 return 0;
3161 }else{
3162 return 1;
3165 #endif /* SQLITE_OMIT_XFER_OPT */