adjustments for constant time function volatile variables
[sqlcipher.git] / src / insert.c
blob423af772348fa4ccdfdb0ff1653b83373b105d62
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 sqlite3TableLock(pParse, iDb, pTab->tnum,
39 (opcode==OP_OpenWrite)?1:0, pTab->zName);
40 if( HasRowid(pTab) ){
41 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
42 VdbeComment((v, "%s", pTab->zName));
43 }else{
44 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
45 assert( pPk!=0 );
46 assert( pPk->tnum==pTab->tnum || CORRUPT_DB );
47 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
48 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
49 VdbeComment((v, "%s", pTab->zName));
54 ** Return a pointer to the column affinity string associated with index
55 ** pIdx. A column affinity string has one character for each column in
56 ** the table, according to the affinity of the column:
58 ** Character Column affinity
59 ** ------------------------------
60 ** 'A' BLOB
61 ** 'B' TEXT
62 ** 'C' NUMERIC
63 ** 'D' INTEGER
64 ** 'F' REAL
66 ** An extra 'D' is appended to the end of the string to cover the
67 ** rowid that appears as the last column in every index.
69 ** Memory for the buffer containing the column index affinity string
70 ** is managed along with the rest of the Index structure. It will be
71 ** released when sqlite3DeleteIndex() is called.
73 static SQLITE_NOINLINE const char *computeIndexAffStr(sqlite3 *db, Index *pIdx){
74 /* The first time a column affinity string for a particular index is
75 ** required, it is allocated and populated here. It is then stored as
76 ** a member of the Index structure for subsequent use.
78 ** The column affinity string will eventually be deleted by
79 ** sqliteDeleteIndex() when the Index structure itself is cleaned
80 ** up.
82 int n;
83 Table *pTab = pIdx->pTable;
84 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
85 if( !pIdx->zColAff ){
86 sqlite3OomFault(db);
87 return 0;
89 for(n=0; n<pIdx->nColumn; n++){
90 i16 x = pIdx->aiColumn[n];
91 char aff;
92 if( x>=0 ){
93 aff = pTab->aCol[x].affinity;
94 }else if( x==XN_ROWID ){
95 aff = SQLITE_AFF_INTEGER;
96 }else{
97 assert( x==XN_EXPR );
98 assert( pIdx->bHasExpr );
99 assert( pIdx->aColExpr!=0 );
100 aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
102 if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
103 if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
104 pIdx->zColAff[n] = aff;
106 pIdx->zColAff[n] = 0;
107 return pIdx->zColAff;
109 const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
110 if( !pIdx->zColAff ) return computeIndexAffStr(db, pIdx);
111 return pIdx->zColAff;
116 ** Compute an affinity string for a table. Space is obtained
117 ** from sqlite3DbMalloc(). The caller is responsible for freeing
118 ** the space when done.
120 char *sqlite3TableAffinityStr(sqlite3 *db, const Table *pTab){
121 char *zColAff;
122 zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1);
123 if( zColAff ){
124 int i, j;
125 for(i=j=0; i<pTab->nCol; i++){
126 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
127 zColAff[j++] = pTab->aCol[i].affinity;
131 zColAff[j--] = 0;
132 }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );
134 return zColAff;
138 ** Make changes to the evolving bytecode to do affinity transformations
139 ** of values that are about to be gathered into a row for table pTab.
141 ** For ordinary (legacy, non-strict) tables:
142 ** -----------------------------------------
144 ** Compute the affinity string for table pTab, if it has not already been
145 ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
147 ** If the affinity string is empty (because it was all SQLITE_AFF_BLOB entries
148 ** which were then optimized out) then this routine becomes a no-op.
150 ** Otherwise if iReg>0 then code an OP_Affinity opcode that will set the
151 ** affinities for register iReg and following. Or if iReg==0,
152 ** then just set the P4 operand of the previous opcode (which should be
153 ** an OP_MakeRecord) to the affinity string.
155 ** A column affinity string has one character per column:
157 ** Character Column affinity
158 ** --------- ---------------
159 ** 'A' BLOB
160 ** 'B' TEXT
161 ** 'C' NUMERIC
162 ** 'D' INTEGER
163 ** 'E' REAL
165 ** For STRICT tables:
166 ** ------------------
168 ** Generate an appropropriate OP_TypeCheck opcode that will verify the
169 ** datatypes against the column definitions in pTab. If iReg==0, that
170 ** means an OP_MakeRecord opcode has already been generated and should be
171 ** the last opcode generated. The new OP_TypeCheck needs to be inserted
172 ** before the OP_MakeRecord. The new OP_TypeCheck should use the same
173 ** register set as the OP_MakeRecord. If iReg>0 then register iReg is
174 ** the first of a series of registers that will form the new record.
175 ** Apply the type checking to that array of registers.
177 void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
178 int i;
179 char *zColAff;
180 if( pTab->tabFlags & TF_Strict ){
181 if( iReg==0 ){
182 /* Move the previous opcode (which should be OP_MakeRecord) forward
183 ** by one slot and insert a new OP_TypeCheck where the current
184 ** OP_MakeRecord is found */
185 VdbeOp *pPrev;
186 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
187 pPrev = sqlite3VdbeGetLastOp(v);
188 assert( pPrev!=0 );
189 assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );
190 pPrev->opcode = OP_TypeCheck;
191 sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, pPrev->p3);
192 }else{
193 /* Insert an isolated OP_Typecheck */
194 sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol);
195 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
197 return;
199 zColAff = pTab->zColAff;
200 if( zColAff==0 ){
201 zColAff = sqlite3TableAffinityStr(0, pTab);
202 if( !zColAff ){
203 sqlite3OomFault(sqlite3VdbeDb(v));
204 return;
206 pTab->zColAff = zColAff;
208 assert( zColAff!=0 );
209 i = sqlite3Strlen30NN(zColAff);
210 if( i ){
211 if( iReg ){
212 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
213 }else{
214 assert( sqlite3VdbeGetLastOp(v)->opcode==OP_MakeRecord
215 || sqlite3VdbeDb(v)->mallocFailed );
216 sqlite3VdbeChangeP4(v, -1, zColAff, i);
222 ** Return non-zero if the table pTab in database iDb or any of its indices
223 ** have been opened at any point in the VDBE program. This is used to see if
224 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
225 ** run without using a temporary table for the results of the SELECT.
227 static int readsTable(Parse *p, int iDb, Table *pTab){
228 Vdbe *v = sqlite3GetVdbe(p);
229 int i;
230 int iEnd = sqlite3VdbeCurrentAddr(v);
231 #ifndef SQLITE_OMIT_VIRTUALTABLE
232 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
233 #endif
235 for(i=1; i<iEnd; i++){
236 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
237 assert( pOp!=0 );
238 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
239 Index *pIndex;
240 Pgno tnum = pOp->p2;
241 if( tnum==pTab->tnum ){
242 return 1;
244 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
245 if( tnum==pIndex->tnum ){
246 return 1;
250 #ifndef SQLITE_OMIT_VIRTUALTABLE
251 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
252 assert( pOp->p4.pVtab!=0 );
253 assert( pOp->p4type==P4_VTAB );
254 return 1;
256 #endif
258 return 0;
261 /* This walker callback will compute the union of colFlags flags for all
262 ** referenced columns in a CHECK constraint or generated column expression.
264 static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
265 if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
266 assert( pExpr->iColumn < pWalker->u.pTab->nCol );
267 pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
269 return WRC_Continue;
272 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
274 ** All regular columns for table pTab have been puts into registers
275 ** starting with iRegStore. The registers that correspond to STORED
276 ** or VIRTUAL columns have not yet been initialized. This routine goes
277 ** back and computes the values for those columns based on the previously
278 ** computed normal columns.
280 void sqlite3ComputeGeneratedColumns(
281 Parse *pParse, /* Parsing context */
282 int iRegStore, /* Register holding the first column */
283 Table *pTab /* The table */
285 int i;
286 Walker w;
287 Column *pRedo;
288 int eProgress;
289 VdbeOp *pOp;
291 assert( pTab->tabFlags & TF_HasGenerated );
292 testcase( pTab->tabFlags & TF_HasVirtual );
293 testcase( pTab->tabFlags & TF_HasStored );
295 /* Before computing generated columns, first go through and make sure
296 ** that appropriate affinity has been applied to the regular columns
298 sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
299 if( (pTab->tabFlags & TF_HasStored)!=0 ){
300 pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
301 if( pOp->opcode==OP_Affinity ){
302 /* Change the OP_Affinity argument to '@' (NONE) for all stored
303 ** columns. '@' is the no-op affinity and those columns have not
304 ** yet been computed. */
305 int ii, jj;
306 char *zP4 = pOp->p4.z;
307 assert( zP4!=0 );
308 assert( pOp->p4type==P4_DYNAMIC );
309 for(ii=jj=0; zP4[jj]; ii++){
310 if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
311 continue;
313 if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
314 zP4[jj] = SQLITE_AFF_NONE;
316 jj++;
318 }else if( pOp->opcode==OP_TypeCheck ){
319 /* If an OP_TypeCheck was generated because the table is STRICT,
320 ** then set the P3 operand to indicate that generated columns should
321 ** not be checked */
322 pOp->p3 = 1;
326 /* Because there can be multiple generated columns that refer to one another,
327 ** this is a two-pass algorithm. On the first pass, mark all generated
328 ** columns as "not available".
330 for(i=0; i<pTab->nCol; i++){
331 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
332 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
333 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
334 pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
338 w.u.pTab = pTab;
339 w.xExprCallback = exprColumnFlagUnion;
340 w.xSelectCallback = 0;
341 w.xSelectCallback2 = 0;
343 /* On the second pass, compute the value of each NOT-AVAILABLE column.
344 ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will
345 ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as
346 ** they are needed.
348 pParse->iSelfTab = -iRegStore;
350 eProgress = 0;
351 pRedo = 0;
352 for(i=0; i<pTab->nCol; i++){
353 Column *pCol = pTab->aCol + i;
354 if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
355 int x;
356 pCol->colFlags |= COLFLAG_BUSY;
357 w.eCode = 0;
358 sqlite3WalkExpr(&w, sqlite3ColumnExpr(pTab, pCol));
359 pCol->colFlags &= ~COLFLAG_BUSY;
360 if( w.eCode & COLFLAG_NOTAVAIL ){
361 pRedo = pCol;
362 continue;
364 eProgress = 1;
365 assert( pCol->colFlags & COLFLAG_GENERATED );
366 x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
367 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, x);
368 pCol->colFlags &= ~COLFLAG_NOTAVAIL;
371 }while( pRedo && eProgress );
372 if( pRedo ){
373 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zCnName);
375 pParse->iSelfTab = 0;
377 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
380 #ifndef SQLITE_OMIT_AUTOINCREMENT
382 ** Locate or create an AutoincInfo structure associated with table pTab
383 ** which is in database iDb. Return the register number for the register
384 ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
385 ** table. (Also return zero when doing a VACUUM since we do not want to
386 ** update the AUTOINCREMENT counters during a VACUUM.)
388 ** There is at most one AutoincInfo structure per table even if the
389 ** same table is autoincremented multiple times due to inserts within
390 ** triggers. A new AutoincInfo structure is created if this is the
391 ** first use of table pTab. On 2nd and subsequent uses, the original
392 ** AutoincInfo structure is used.
394 ** Four consecutive registers are allocated:
396 ** (1) The name of the pTab table.
397 ** (2) The maximum ROWID of pTab.
398 ** (3) The rowid in sqlite_sequence of pTab
399 ** (4) The original value of the max ROWID in pTab, or NULL if none
401 ** The 2nd register is the one that is returned. That is all the
402 ** insert routine needs to know about.
404 static int autoIncBegin(
405 Parse *pParse, /* Parsing context */
406 int iDb, /* Index of the database holding pTab */
407 Table *pTab /* The table we are writing to */
409 int memId = 0; /* Register holding maximum rowid */
410 assert( pParse->db->aDb[iDb].pSchema!=0 );
411 if( (pTab->tabFlags & TF_Autoincrement)!=0
412 && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
414 Parse *pToplevel = sqlite3ParseToplevel(pParse);
415 AutoincInfo *pInfo;
416 Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
418 /* Verify that the sqlite_sequence table exists and is an ordinary
419 ** rowid table with exactly two columns.
420 ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
421 if( pSeqTab==0
422 || !HasRowid(pSeqTab)
423 || NEVER(IsVirtual(pSeqTab))
424 || pSeqTab->nCol!=2
426 pParse->nErr++;
427 pParse->rc = SQLITE_CORRUPT_SEQUENCE;
428 return 0;
431 pInfo = pToplevel->pAinc;
432 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
433 if( pInfo==0 ){
434 pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
435 sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
436 testcase( pParse->earlyCleanup );
437 if( pParse->db->mallocFailed ) return 0;
438 pInfo->pNext = pToplevel->pAinc;
439 pToplevel->pAinc = pInfo;
440 pInfo->pTab = pTab;
441 pInfo->iDb = iDb;
442 pToplevel->nMem++; /* Register to hold name of table */
443 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
444 pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
446 memId = pInfo->regCtr;
448 return memId;
452 ** This routine generates code that will initialize all of the
453 ** register used by the autoincrement tracker.
455 void sqlite3AutoincrementBegin(Parse *pParse){
456 AutoincInfo *p; /* Information about an AUTOINCREMENT */
457 sqlite3 *db = pParse->db; /* The database connection */
458 Db *pDb; /* Database only autoinc table */
459 int memId; /* Register holding max rowid */
460 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
462 /* This routine is never called during trigger-generation. It is
463 ** only called from the top-level */
464 assert( pParse->pTriggerTab==0 );
465 assert( sqlite3IsToplevel(pParse) );
467 assert( v ); /* We failed long ago if this is not so */
468 for(p = pParse->pAinc; p; p = p->pNext){
469 static const int iLn = VDBE_OFFSET_LINENO(2);
470 static const VdbeOpList autoInc[] = {
471 /* 0 */ {OP_Null, 0, 0, 0},
472 /* 1 */ {OP_Rewind, 0, 10, 0},
473 /* 2 */ {OP_Column, 0, 0, 0},
474 /* 3 */ {OP_Ne, 0, 9, 0},
475 /* 4 */ {OP_Rowid, 0, 0, 0},
476 /* 5 */ {OP_Column, 0, 1, 0},
477 /* 6 */ {OP_AddImm, 0, 0, 0},
478 /* 7 */ {OP_Copy, 0, 0, 0},
479 /* 8 */ {OP_Goto, 0, 11, 0},
480 /* 9 */ {OP_Next, 0, 2, 0},
481 /* 10 */ {OP_Integer, 0, 0, 0},
482 /* 11 */ {OP_Close, 0, 0, 0}
484 VdbeOp *aOp;
485 pDb = &db->aDb[p->iDb];
486 memId = p->regCtr;
487 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
488 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
489 sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
490 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
491 if( aOp==0 ) break;
492 aOp[0].p2 = memId;
493 aOp[0].p3 = memId+2;
494 aOp[2].p3 = memId;
495 aOp[3].p1 = memId-1;
496 aOp[3].p3 = memId;
497 aOp[3].p5 = SQLITE_JUMPIFNULL;
498 aOp[4].p2 = memId+1;
499 aOp[5].p3 = memId;
500 aOp[6].p1 = memId;
501 aOp[7].p2 = memId+2;
502 aOp[7].p1 = memId;
503 aOp[10].p2 = memId;
504 if( pParse->nTab==0 ) pParse->nTab = 1;
509 ** Update the maximum rowid for an autoincrement calculation.
511 ** This routine should be called when the regRowid register holds a
512 ** new rowid that is about to be inserted. If that new rowid is
513 ** larger than the maximum rowid in the memId memory cell, then the
514 ** memory cell is updated.
516 static void autoIncStep(Parse *pParse, int memId, int regRowid){
517 if( memId>0 ){
518 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
523 ** This routine generates the code needed to write autoincrement
524 ** maximum rowid values back into the sqlite_sequence register.
525 ** Every statement that might do an INSERT into an autoincrement
526 ** table (either directly or through triggers) needs to call this
527 ** routine just before the "exit" code.
529 static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
530 AutoincInfo *p;
531 Vdbe *v = pParse->pVdbe;
532 sqlite3 *db = pParse->db;
534 assert( v );
535 for(p = pParse->pAinc; p; p = p->pNext){
536 static const int iLn = VDBE_OFFSET_LINENO(2);
537 static const VdbeOpList autoIncEnd[] = {
538 /* 0 */ {OP_NotNull, 0, 2, 0},
539 /* 1 */ {OP_NewRowid, 0, 0, 0},
540 /* 2 */ {OP_MakeRecord, 0, 2, 0},
541 /* 3 */ {OP_Insert, 0, 0, 0},
542 /* 4 */ {OP_Close, 0, 0, 0}
544 VdbeOp *aOp;
545 Db *pDb = &db->aDb[p->iDb];
546 int iRec;
547 int memId = p->regCtr;
549 iRec = sqlite3GetTempReg(pParse);
550 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
551 sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
552 VdbeCoverage(v);
553 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
554 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
555 if( aOp==0 ) break;
556 aOp[0].p1 = memId+1;
557 aOp[1].p2 = memId+1;
558 aOp[2].p1 = memId-1;
559 aOp[2].p3 = iRec;
560 aOp[3].p2 = iRec;
561 aOp[3].p3 = memId+1;
562 aOp[3].p5 = OPFLAG_APPEND;
563 sqlite3ReleaseTempReg(pParse, iRec);
566 void sqlite3AutoincrementEnd(Parse *pParse){
567 if( pParse->pAinc ) autoIncrementEnd(pParse);
569 #else
571 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
572 ** above are all no-ops
574 # define autoIncBegin(A,B,C) (0)
575 # define autoIncStep(A,B,C)
576 #endif /* SQLITE_OMIT_AUTOINCREMENT */
579 /* Forward declaration */
580 static int xferOptimization(
581 Parse *pParse, /* Parser context */
582 Table *pDest, /* The table we are inserting into */
583 Select *pSelect, /* A SELECT statement to use as the data source */
584 int onError, /* How to handle constraint errors */
585 int iDbDest /* The database of pDest */
589 ** This routine is called to handle SQL of the following forms:
591 ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
592 ** insert into TABLE (IDLIST) select
593 ** insert into TABLE (IDLIST) default values
595 ** The IDLIST following the table name is always optional. If omitted,
596 ** then a list of all (non-hidden) columns for the table is substituted.
597 ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
598 ** is omitted.
600 ** For the pSelect parameter holds the values to be inserted for the
601 ** first two forms shown above. A VALUES clause is really just short-hand
602 ** for a SELECT statement that omits the FROM clause and everything else
603 ** that follows. If the pSelect parameter is NULL, that means that the
604 ** DEFAULT VALUES form of the INSERT statement is intended.
606 ** The code generated follows one of four templates. For a simple
607 ** insert with data coming from a single-row VALUES clause, the code executes
608 ** once straight down through. Pseudo-code follows (we call this
609 ** the "1st template"):
611 ** open write cursor to <table> and its indices
612 ** put VALUES clause expressions into registers
613 ** write the resulting record into <table>
614 ** cleanup
616 ** The three remaining templates assume the statement is of the form
618 ** INSERT INTO <table> SELECT ...
620 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
621 ** in other words if the SELECT pulls all columns from a single table
622 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
623 ** if <table2> and <table1> are distinct tables but have identical
624 ** schemas, including all the same indices, then a special optimization
625 ** is invoked that copies raw records from <table2> over to <table1>.
626 ** See the xferOptimization() function for the implementation of this
627 ** template. This is the 2nd template.
629 ** open a write cursor to <table>
630 ** open read cursor on <table2>
631 ** transfer all records in <table2> over to <table>
632 ** close cursors
633 ** foreach index on <table>
634 ** open a write cursor on the <table> index
635 ** open a read cursor on the corresponding <table2> index
636 ** transfer all records from the read to the write cursors
637 ** close cursors
638 ** end foreach
640 ** The 3rd template is for when the second template does not apply
641 ** and the SELECT clause does not read from <table> at any time.
642 ** The generated code follows this template:
644 ** X <- A
645 ** goto B
646 ** A: setup for the SELECT
647 ** loop over the rows in the SELECT
648 ** load values into registers R..R+n
649 ** yield X
650 ** end loop
651 ** cleanup after the SELECT
652 ** end-coroutine X
653 ** B: open write cursor to <table> and its indices
654 ** C: yield X, at EOF goto D
655 ** insert the select result into <table> from R..R+n
656 ** goto C
657 ** D: cleanup
659 ** The 4th template is used if the insert statement takes its
660 ** values from a SELECT but the data is being inserted into a table
661 ** that is also read as part of the SELECT. In the third form,
662 ** we have to use an intermediate table to store the results of
663 ** the select. The template is like this:
665 ** X <- A
666 ** goto B
667 ** A: setup for the SELECT
668 ** loop over the tables in the SELECT
669 ** load value into register R..R+n
670 ** yield X
671 ** end loop
672 ** cleanup after the SELECT
673 ** end co-routine R
674 ** B: open temp table
675 ** L: yield X, at EOF goto M
676 ** insert row from R..R+n into temp table
677 ** goto L
678 ** M: open write cursor to <table> and its indices
679 ** rewind temp table
680 ** C: loop over rows of intermediate table
681 ** transfer values form intermediate table into <table>
682 ** end loop
683 ** D: cleanup
685 void sqlite3Insert(
686 Parse *pParse, /* Parser context */
687 SrcList *pTabList, /* Name of table into which we are inserting */
688 Select *pSelect, /* A SELECT statement to use as the data source */
689 IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */
690 int onError, /* How to handle constraint errors */
691 Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
693 sqlite3 *db; /* The main database structure */
694 Table *pTab; /* The table to insert into. aka TABLE */
695 int i, j; /* Loop counters */
696 Vdbe *v; /* Generate code into this virtual machine */
697 Index *pIdx; /* For looping over indices of the table */
698 int nColumn; /* Number of columns in the data */
699 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
700 int iDataCur = 0; /* VDBE cursor that is the main data repository */
701 int iIdxCur = 0; /* First index cursor */
702 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
703 int endOfLoop; /* Label for the end of the insertion loop */
704 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
705 int addrInsTop = 0; /* Jump to label "D" */
706 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
707 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
708 int iDb; /* Index of database holding TABLE */
709 u8 useTempTable = 0; /* Store SELECT results in intermediate table */
710 u8 appendFlag = 0; /* True if the insert is likely to be an append */
711 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
712 u8 bIdListInOrder; /* True if IDLIST is in table order */
713 ExprList *pList = 0; /* List of VALUES() to be inserted */
714 int iRegStore; /* Register in which to store next column */
716 /* Register allocations */
717 int regFromSelect = 0;/* Base register for data coming from SELECT */
718 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
719 int regRowCount = 0; /* Memory cell used for the row counter */
720 int regIns; /* Block of regs holding rowid+data being inserted */
721 int regRowid; /* registers holding insert rowid */
722 int regData; /* register holding first column to insert */
723 int *aRegIdx = 0; /* One register allocated to each index */
725 #ifndef SQLITE_OMIT_TRIGGER
726 int isView; /* True if attempting to insert into a view */
727 Trigger *pTrigger; /* List of triggers on pTab, if required */
728 int tmask; /* Mask of trigger times */
729 #endif
731 db = pParse->db;
732 assert( db->pParse==pParse );
733 if( pParse->nErr ){
734 goto insert_cleanup;
736 assert( db->mallocFailed==0 );
737 dest.iSDParm = 0; /* Suppress a harmless compiler warning */
739 /* If the Select object is really just a simple VALUES() list with a
740 ** single row (the common case) then keep that one row of values
741 ** and discard the other (unused) parts of the pSelect object
743 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
744 pList = pSelect->pEList;
745 pSelect->pEList = 0;
746 sqlite3SelectDelete(db, pSelect);
747 pSelect = 0;
750 /* Locate the table into which we will be inserting new information.
752 assert( pTabList->nSrc==1 );
753 pTab = sqlite3SrcListLookup(pParse, pTabList);
754 if( pTab==0 ){
755 goto insert_cleanup;
757 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
758 assert( iDb<db->nDb );
759 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
760 db->aDb[iDb].zDbSName) ){
761 goto insert_cleanup;
763 withoutRowid = !HasRowid(pTab);
765 /* Figure out if we have any triggers and if the table being
766 ** inserted into is a view
768 #ifndef SQLITE_OMIT_TRIGGER
769 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
770 isView = IsView(pTab);
771 #else
772 # define pTrigger 0
773 # define tmask 0
774 # define isView 0
775 #endif
776 #ifdef SQLITE_OMIT_VIEW
777 # undef isView
778 # define isView 0
779 #endif
780 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
782 #if TREETRACE_ENABLED
783 if( sqlite3TreeTrace & 0x10000 ){
784 sqlite3TreeViewLine(0, "In sqlite3Insert() at %s:%d", __FILE__, __LINE__);
785 sqlite3TreeViewInsert(pParse->pWith, pTabList, pColumn, pSelect, pList,
786 onError, pUpsert, pTrigger);
788 #endif
790 /* If pTab is really a view, make sure it has been initialized.
791 ** ViewGetColumnNames() is a no-op if pTab is not a view.
793 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
794 goto insert_cleanup;
797 /* Cannot insert into a read-only table.
799 if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
800 goto insert_cleanup;
803 /* Allocate a VDBE
805 v = sqlite3GetVdbe(pParse);
806 if( v==0 ) goto insert_cleanup;
807 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
808 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
810 #ifndef SQLITE_OMIT_XFER_OPT
811 /* If the statement is of the form
813 ** INSERT INTO <table1> SELECT * FROM <table2>;
815 ** Then special optimizations can be applied that make the transfer
816 ** very fast and which reduce fragmentation of indices.
818 ** This is the 2nd template.
820 if( pColumn==0
821 && pSelect!=0
822 && pTrigger==0
823 && xferOptimization(pParse, pTab, pSelect, onError, iDb)
825 assert( !pTrigger );
826 assert( pList==0 );
827 goto insert_end;
829 #endif /* SQLITE_OMIT_XFER_OPT */
831 /* If this is an AUTOINCREMENT table, look up the sequence number in the
832 ** sqlite_sequence table and store it in memory cell regAutoinc.
834 regAutoinc = autoIncBegin(pParse, iDb, pTab);
836 /* Allocate a block registers to hold the rowid and the values
837 ** for all columns of the new row.
839 regRowid = regIns = pParse->nMem+1;
840 pParse->nMem += pTab->nCol + 1;
841 if( IsVirtual(pTab) ){
842 regRowid++;
843 pParse->nMem++;
845 regData = regRowid+1;
847 /* If the INSERT statement included an IDLIST term, then make sure
848 ** all elements of the IDLIST really are columns of the table and
849 ** remember the column indices.
851 ** If the table has an INTEGER PRIMARY KEY column and that column
852 ** is named in the IDLIST, then record in the ipkColumn variable
853 ** the index into IDLIST of the primary key column. ipkColumn is
854 ** the index of the primary key as it appears in IDLIST, not as
855 ** is appears in the original table. (The index of the INTEGER
856 ** PRIMARY KEY in the original table is pTab->iPKey.) After this
857 ** loop, if ipkColumn==(-1), that means that integer primary key
858 ** is unspecified, and hence the table is either WITHOUT ROWID or
859 ** it will automatically generated an integer primary key.
861 ** bIdListInOrder is true if the columns in IDLIST are in storage
862 ** order. This enables an optimization that avoids shuffling the
863 ** columns into storage order. False negatives are harmless,
864 ** but false positives will cause database corruption.
866 bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
867 if( pColumn ){
868 assert( pColumn->eU4!=EU4_EXPR );
869 pColumn->eU4 = EU4_IDX;
870 for(i=0; i<pColumn->nId; i++){
871 pColumn->a[i].u4.idx = -1;
873 for(i=0; i<pColumn->nId; i++){
874 for(j=0; j<pTab->nCol; j++){
875 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zCnName)==0 ){
876 pColumn->a[i].u4.idx = j;
877 if( i!=j ) bIdListInOrder = 0;
878 if( j==pTab->iPKey ){
879 ipkColumn = i; assert( !withoutRowid );
881 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
882 if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
883 sqlite3ErrorMsg(pParse,
884 "cannot INSERT into generated column \"%s\"",
885 pTab->aCol[j].zCnName);
886 goto insert_cleanup;
888 #endif
889 break;
892 if( j>=pTab->nCol ){
893 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
894 ipkColumn = i;
895 bIdListInOrder = 0;
896 }else{
897 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
898 pTabList->a, pColumn->a[i].zName);
899 pParse->checkSchema = 1;
900 goto insert_cleanup;
906 /* Figure out how many columns of data are supplied. If the data
907 ** is coming from a SELECT statement, then generate a co-routine that
908 ** produces a single row of the SELECT on each invocation. The
909 ** co-routine is the common header to the 3rd and 4th templates.
911 if( pSelect ){
912 /* Data is coming from a SELECT or from a multi-row VALUES clause.
913 ** Generate a co-routine to run the SELECT. */
914 int regYield; /* Register holding co-routine entry-point */
915 int addrTop; /* Top of the co-routine */
916 int rc; /* Result code */
918 regYield = ++pParse->nMem;
919 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
920 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
921 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
922 dest.iSdst = bIdListInOrder ? regData : 0;
923 dest.nSdst = pTab->nCol;
924 rc = sqlite3Select(pParse, pSelect, &dest);
925 regFromSelect = dest.iSdst;
926 assert( db->pParse==pParse );
927 if( rc || pParse->nErr ) goto insert_cleanup;
928 assert( db->mallocFailed==0 );
929 sqlite3VdbeEndCoroutine(v, regYield);
930 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
931 assert( pSelect->pEList );
932 nColumn = pSelect->pEList->nExpr;
934 /* Set useTempTable to TRUE if the result of the SELECT statement
935 ** should be written into a temporary table (template 4). Set to
936 ** FALSE if each output row of the SELECT can be written directly into
937 ** the destination table (template 3).
939 ** A temp table must be used if the table being updated is also one
940 ** of the tables being read by the SELECT statement. Also use a
941 ** temp table in the case of row triggers.
943 if( pTrigger || readsTable(pParse, iDb, pTab) ){
944 useTempTable = 1;
947 if( useTempTable ){
948 /* Invoke the coroutine to extract information from the SELECT
949 ** and add it to a transient table srcTab. The code generated
950 ** here is from the 4th template:
952 ** B: open temp table
953 ** L: yield X, goto M at EOF
954 ** insert row from R..R+n into temp table
955 ** goto L
956 ** M: ...
958 int regRec; /* Register to hold packed record */
959 int regTempRowid; /* Register to hold temp table ROWID */
960 int addrL; /* Label "L" */
962 srcTab = pParse->nTab++;
963 regRec = sqlite3GetTempReg(pParse);
964 regTempRowid = sqlite3GetTempReg(pParse);
965 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
966 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
967 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
968 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
969 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
970 sqlite3VdbeGoto(v, addrL);
971 sqlite3VdbeJumpHere(v, addrL);
972 sqlite3ReleaseTempReg(pParse, regRec);
973 sqlite3ReleaseTempReg(pParse, regTempRowid);
975 }else{
976 /* This is the case if the data for the INSERT is coming from a
977 ** single-row VALUES clause
979 NameContext sNC;
980 memset(&sNC, 0, sizeof(sNC));
981 sNC.pParse = pParse;
982 srcTab = -1;
983 assert( useTempTable==0 );
984 if( pList ){
985 nColumn = pList->nExpr;
986 if( sqlite3ResolveExprListNames(&sNC, pList) ){
987 goto insert_cleanup;
989 }else{
990 nColumn = 0;
994 /* If there is no IDLIST term but the table has an integer primary
995 ** key, the set the ipkColumn variable to the integer primary key
996 ** column index in the original table definition.
998 if( pColumn==0 && nColumn>0 ){
999 ipkColumn = pTab->iPKey;
1000 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1001 if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
1002 testcase( pTab->tabFlags & TF_HasVirtual );
1003 testcase( pTab->tabFlags & TF_HasStored );
1004 for(i=ipkColumn-1; i>=0; i--){
1005 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
1006 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
1007 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
1008 ipkColumn--;
1012 #endif
1014 /* Make sure the number of columns in the source data matches the number
1015 ** of columns to be inserted into the table.
1017 assert( TF_HasHidden==COLFLAG_HIDDEN );
1018 assert( TF_HasGenerated==COLFLAG_GENERATED );
1019 assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) );
1020 if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
1021 for(i=0; i<pTab->nCol; i++){
1022 if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
1025 if( nColumn!=(pTab->nCol-nHidden) ){
1026 sqlite3ErrorMsg(pParse,
1027 "table %S has %d columns but %d values were supplied",
1028 pTabList->a, pTab->nCol-nHidden, nColumn);
1029 goto insert_cleanup;
1032 if( pColumn!=0 && nColumn!=pColumn->nId ){
1033 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
1034 goto insert_cleanup;
1037 /* Initialize the count of rows to be inserted
1039 if( (db->flags & SQLITE_CountRows)!=0
1040 && !pParse->nested
1041 && !pParse->pTriggerTab
1042 && !pParse->bReturning
1044 regRowCount = ++pParse->nMem;
1045 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
1048 /* If this is not a view, open the table and and all indices */
1049 if( !isView ){
1050 int nIdx;
1051 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
1052 &iDataCur, &iIdxCur);
1053 aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
1054 if( aRegIdx==0 ){
1055 goto insert_cleanup;
1057 for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
1058 assert( pIdx );
1059 aRegIdx[i] = ++pParse->nMem;
1060 pParse->nMem += pIdx->nColumn;
1062 aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */
1064 #ifndef SQLITE_OMIT_UPSERT
1065 if( pUpsert ){
1066 Upsert *pNx;
1067 if( IsVirtual(pTab) ){
1068 sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
1069 pTab->zName);
1070 goto insert_cleanup;
1072 if( IsView(pTab) ){
1073 sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
1074 goto insert_cleanup;
1076 if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
1077 goto insert_cleanup;
1079 pTabList->a[0].iCursor = iDataCur;
1080 pNx = pUpsert;
1082 pNx->pUpsertSrc = pTabList;
1083 pNx->regData = regData;
1084 pNx->iDataCur = iDataCur;
1085 pNx->iIdxCur = iIdxCur;
1086 if( pNx->pUpsertTarget ){
1087 if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx) ){
1088 goto insert_cleanup;
1091 pNx = pNx->pNextUpsert;
1092 }while( pNx!=0 );
1094 #endif
1097 /* This is the top of the main insertion loop */
1098 if( useTempTable ){
1099 /* This block codes the top of loop only. The complete loop is the
1100 ** following pseudocode (template 4):
1102 ** rewind temp table, if empty goto D
1103 ** C: loop over rows of intermediate table
1104 ** transfer values form intermediate table into <table>
1105 ** end loop
1106 ** D: ...
1108 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
1109 addrCont = sqlite3VdbeCurrentAddr(v);
1110 }else if( pSelect ){
1111 /* This block codes the top of loop only. The complete loop is the
1112 ** following pseudocode (template 3):
1114 ** C: yield X, at EOF goto D
1115 ** insert the select result into <table> from R..R+n
1116 ** goto C
1117 ** D: ...
1119 sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
1120 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
1121 VdbeCoverage(v);
1122 if( ipkColumn>=0 ){
1123 /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
1124 ** SELECT, go ahead and copy the value into the rowid slot now, so that
1125 ** the value does not get overwritten by a NULL at tag-20191021-002. */
1126 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
1130 /* Compute data for ordinary columns of the new entry. Values
1131 ** are written in storage order into registers starting with regData.
1132 ** Only ordinary columns are computed in this loop. The rowid
1133 ** (if there is one) is computed later and generated columns are
1134 ** computed after the rowid since they might depend on the value
1135 ** of the rowid.
1137 nHidden = 0;
1138 iRegStore = regData; assert( regData==regRowid+1 );
1139 for(i=0; i<pTab->nCol; i++, iRegStore++){
1140 int k;
1141 u32 colFlags;
1142 assert( i>=nHidden );
1143 if( i==pTab->iPKey ){
1144 /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
1145 ** using the rowid. So put a NULL in the IPK slot of the record to avoid
1146 ** using excess space. The file format definition requires this extra
1147 ** NULL - we cannot optimize further by skipping the column completely */
1148 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1149 continue;
1151 if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
1152 nHidden++;
1153 if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
1154 /* Virtual columns do not participate in OP_MakeRecord. So back up
1155 ** iRegStore by one slot to compensate for the iRegStore++ in the
1156 ** outer for() loop */
1157 iRegStore--;
1158 continue;
1159 }else if( (colFlags & COLFLAG_STORED)!=0 ){
1160 /* Stored columns are computed later. But if there are BEFORE
1161 ** triggers, the slots used for stored columns will be OP_Copy-ed
1162 ** to a second block of registers, so the register needs to be
1163 ** initialized to NULL to avoid an uninitialized register read */
1164 if( tmask & TRIGGER_BEFORE ){
1165 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1167 continue;
1168 }else if( pColumn==0 ){
1169 /* Hidden columns that are not explicitly named in the INSERT
1170 ** get there default value */
1171 sqlite3ExprCodeFactorable(pParse,
1172 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1173 iRegStore);
1174 continue;
1177 if( pColumn ){
1178 assert( pColumn->eU4==EU4_IDX );
1179 for(j=0; j<pColumn->nId && pColumn->a[j].u4.idx!=i; j++){}
1180 if( j>=pColumn->nId ){
1181 /* A column not named in the insert column list gets its
1182 ** default value */
1183 sqlite3ExprCodeFactorable(pParse,
1184 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1185 iRegStore);
1186 continue;
1188 k = j;
1189 }else if( nColumn==0 ){
1190 /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */
1191 sqlite3ExprCodeFactorable(pParse,
1192 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1193 iRegStore);
1194 continue;
1195 }else{
1196 k = i - nHidden;
1199 if( useTempTable ){
1200 sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
1201 }else if( pSelect ){
1202 if( regFromSelect!=regData ){
1203 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
1205 }else{
1206 Expr *pX = pList->a[k].pExpr;
1207 int y = sqlite3ExprCodeTarget(pParse, pX, iRegStore);
1208 if( y!=iRegStore ){
1209 sqlite3VdbeAddOp2(v,
1210 ExprHasProperty(pX, EP_Subquery) ? OP_Copy : OP_SCopy, y, iRegStore);
1216 /* Run the BEFORE and INSTEAD OF triggers, if there are any
1218 endOfLoop = sqlite3VdbeMakeLabel(pParse);
1219 if( tmask & TRIGGER_BEFORE ){
1220 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
1222 /* build the NEW.* reference row. Note that if there is an INTEGER
1223 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
1224 ** translated into a unique ID for the row. But on a BEFORE trigger,
1225 ** we do not know what the unique ID will be (because the insert has
1226 ** not happened yet) so we substitute a rowid of -1
1228 if( ipkColumn<0 ){
1229 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1230 }else{
1231 int addr1;
1232 assert( !withoutRowid );
1233 if( useTempTable ){
1234 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
1235 }else{
1236 assert( pSelect==0 ); /* Otherwise useTempTable is true */
1237 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
1239 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
1240 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1241 sqlite3VdbeJumpHere(v, addr1);
1242 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
1245 /* Copy the new data already generated. */
1246 assert( pTab->nNVCol>0 || pParse->nErr>0 );
1247 sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
1249 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1250 /* Compute the new value for generated columns after all other
1251 ** columns have already been computed. This must be done after
1252 ** computing the ROWID in case one of the generated columns
1253 ** refers to the ROWID. */
1254 if( pTab->tabFlags & TF_HasGenerated ){
1255 testcase( pTab->tabFlags & TF_HasVirtual );
1256 testcase( pTab->tabFlags & TF_HasStored );
1257 sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
1259 #endif
1261 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
1262 ** do not attempt any conversions before assembling the record.
1263 ** If this is a real table, attempt conversions as required by the
1264 ** table column affinities.
1266 if( !isView ){
1267 sqlite3TableAffinity(v, pTab, regCols+1);
1270 /* Fire BEFORE or INSTEAD OF triggers */
1271 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
1272 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
1274 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
1277 if( !isView ){
1278 if( IsVirtual(pTab) ){
1279 /* The row that the VUpdate opcode will delete: none */
1280 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
1282 if( ipkColumn>=0 ){
1283 /* Compute the new rowid */
1284 if( useTempTable ){
1285 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
1286 }else if( pSelect ){
1287 /* Rowid already initialized at tag-20191021-001 */
1288 }else{
1289 Expr *pIpk = pList->a[ipkColumn].pExpr;
1290 if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
1291 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1292 appendFlag = 1;
1293 }else{
1294 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
1297 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
1298 ** to generate a unique primary key value.
1300 if( !appendFlag ){
1301 int addr1;
1302 if( !IsVirtual(pTab) ){
1303 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
1304 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1305 sqlite3VdbeJumpHere(v, addr1);
1306 }else{
1307 addr1 = sqlite3VdbeCurrentAddr(v);
1308 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
1310 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
1312 }else if( IsVirtual(pTab) || withoutRowid ){
1313 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
1314 }else{
1315 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1316 appendFlag = 1;
1318 autoIncStep(pParse, regAutoinc, regRowid);
1320 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1321 /* Compute the new value for generated columns after all other
1322 ** columns have already been computed. This must be done after
1323 ** computing the ROWID in case one of the generated columns
1324 ** is derived from the INTEGER PRIMARY KEY. */
1325 if( pTab->tabFlags & TF_HasGenerated ){
1326 sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
1328 #endif
1330 /* Generate code to check constraints and generate index keys and
1331 ** do the insertion.
1333 #ifndef SQLITE_OMIT_VIRTUALTABLE
1334 if( IsVirtual(pTab) ){
1335 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
1336 sqlite3VtabMakeWritable(pParse, pTab);
1337 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1338 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1339 sqlite3MayAbort(pParse);
1340 }else
1341 #endif
1343 int isReplace = 0;/* Set to true if constraints may cause a replace */
1344 int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
1345 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1346 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
1348 if( db->flags & SQLITE_ForeignKeys ){
1349 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
1352 /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
1353 ** constraints or (b) there are no triggers and this table is not a
1354 ** parent table in a foreign key constraint. It is safe to set the
1355 ** flag in the second case as if any REPLACE constraint is hit, an
1356 ** OP_Delete or OP_IdxDelete instruction will be executed on each
1357 ** cursor that is disturbed. And these instructions both clear the
1358 ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
1359 ** functionality. */
1360 bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
1361 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
1362 regIns, aRegIdx, 0, appendFlag, bUseSeek
1365 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
1366 }else if( pParse->bReturning ){
1367 /* If there is a RETURNING clause, populate the rowid register with
1368 ** constant value -1, in case one or more of the returned expressions
1369 ** refer to the "rowid" of the view. */
1370 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
1371 #endif
1374 /* Update the count of rows that are inserted
1376 if( regRowCount ){
1377 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
1380 if( pTrigger ){
1381 /* Code AFTER triggers */
1382 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
1383 pTab, regData-2-pTab->nCol, onError, endOfLoop);
1386 /* The bottom of the main insertion loop, if the data source
1387 ** is a SELECT statement.
1389 sqlite3VdbeResolveLabel(v, endOfLoop);
1390 if( useTempTable ){
1391 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1392 sqlite3VdbeJumpHere(v, addrInsTop);
1393 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1394 }else if( pSelect ){
1395 sqlite3VdbeGoto(v, addrCont);
1396 #ifdef SQLITE_DEBUG
1397 /* If we are jumping back to an OP_Yield that is preceded by an
1398 ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
1399 ** OP_ReleaseReg will be included in the loop. */
1400 if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
1401 assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
1402 sqlite3VdbeChangeP5(v, 1);
1404 #endif
1405 sqlite3VdbeJumpHere(v, addrInsTop);
1408 #ifndef SQLITE_OMIT_XFER_OPT
1409 insert_end:
1410 #endif /* SQLITE_OMIT_XFER_OPT */
1411 /* Update the sqlite_sequence table by storing the content of the
1412 ** maximum rowid counter values recorded while inserting into
1413 ** autoincrement tables.
1415 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
1416 sqlite3AutoincrementEnd(pParse);
1420 ** Return the number of rows inserted. If this routine is
1421 ** generating code because of a call to sqlite3NestedParse(), do not
1422 ** invoke the callback function.
1424 if( regRowCount ){
1425 sqlite3CodeChangeCount(v, regRowCount, "rows inserted");
1428 insert_cleanup:
1429 sqlite3SrcListDelete(db, pTabList);
1430 sqlite3ExprListDelete(db, pList);
1431 sqlite3UpsertDelete(db, pUpsert);
1432 sqlite3SelectDelete(db, pSelect);
1433 sqlite3IdListDelete(db, pColumn);
1434 if( aRegIdx ) sqlite3DbNNFreeNN(db, aRegIdx);
1437 /* Make sure "isView" and other macros defined above are undefined. Otherwise
1438 ** they may interfere with compilation of other functions in this file
1439 ** (or in another file, if this file becomes part of the amalgamation). */
1440 #ifdef isView
1441 #undef isView
1442 #endif
1443 #ifdef pTrigger
1444 #undef pTrigger
1445 #endif
1446 #ifdef tmask
1447 #undef tmask
1448 #endif
1451 ** Meanings of bits in of pWalker->eCode for
1452 ** sqlite3ExprReferencesUpdatedColumn()
1454 #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
1455 #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
1457 /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
1458 * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
1459 ** expression node references any of the
1460 ** columns that are being modifed by an UPDATE statement.
1462 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
1463 if( pExpr->op==TK_COLUMN ){
1464 assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
1465 if( pExpr->iColumn>=0 ){
1466 if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
1467 pWalker->eCode |= CKCNSTRNT_COLUMN;
1469 }else{
1470 pWalker->eCode |= CKCNSTRNT_ROWID;
1473 return WRC_Continue;
1477 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
1478 ** only columns that are modified by the UPDATE are those for which
1479 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
1481 ** Return true if CHECK constraint pExpr uses any of the
1482 ** changing columns (or the rowid if it is changing). In other words,
1483 ** return true if this CHECK constraint must be validated for
1484 ** the new row in the UPDATE statement.
1486 ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
1487 ** The operation of this routine is the same - return true if an only if
1488 ** the expression uses one or more of columns identified by the second and
1489 ** third arguments.
1491 int sqlite3ExprReferencesUpdatedColumn(
1492 Expr *pExpr, /* The expression to be checked */
1493 int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */
1494 int chngRowid /* True if UPDATE changes the rowid */
1496 Walker w;
1497 memset(&w, 0, sizeof(w));
1498 w.eCode = 0;
1499 w.xExprCallback = checkConstraintExprNode;
1500 w.u.aiCol = aiChng;
1501 sqlite3WalkExpr(&w, pExpr);
1502 if( !chngRowid ){
1503 testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
1504 w.eCode &= ~CKCNSTRNT_ROWID;
1506 testcase( w.eCode==0 );
1507 testcase( w.eCode==CKCNSTRNT_COLUMN );
1508 testcase( w.eCode==CKCNSTRNT_ROWID );
1509 testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
1510 return w.eCode!=0;
1514 ** The sqlite3GenerateConstraintChecks() routine usually wants to visit
1515 ** the indexes of a table in the order provided in the Table->pIndex list.
1516 ** However, sometimes (rarely - when there is an upsert) it wants to visit
1517 ** the indexes in a different order. The following data structures accomplish
1518 ** this.
1520 ** The IndexIterator object is used to walk through all of the indexes
1521 ** of a table in either Index.pNext order, or in some other order established
1522 ** by an array of IndexListTerm objects.
1524 typedef struct IndexListTerm IndexListTerm;
1525 typedef struct IndexIterator IndexIterator;
1526 struct IndexIterator {
1527 int eType; /* 0 for Index.pNext list. 1 for an array of IndexListTerm */
1528 int i; /* Index of the current item from the list */
1529 union {
1530 struct { /* Use this object for eType==0: A Index.pNext list */
1531 Index *pIdx; /* The current Index */
1532 } lx;
1533 struct { /* Use this object for eType==1; Array of IndexListTerm */
1534 int nIdx; /* Size of the array */
1535 IndexListTerm *aIdx; /* Array of IndexListTerms */
1536 } ax;
1537 } u;
1540 /* When IndexIterator.eType==1, then each index is an array of instances
1541 ** of the following object
1543 struct IndexListTerm {
1544 Index *p; /* The index */
1545 int ix; /* Which entry in the original Table.pIndex list is this index*/
1548 /* Return the first index on the list */
1549 static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){
1550 assert( pIter->i==0 );
1551 if( pIter->eType ){
1552 *pIx = pIter->u.ax.aIdx[0].ix;
1553 return pIter->u.ax.aIdx[0].p;
1554 }else{
1555 *pIx = 0;
1556 return pIter->u.lx.pIdx;
1560 /* Return the next index from the list. Return NULL when out of indexes */
1561 static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){
1562 if( pIter->eType ){
1563 int i = ++pIter->i;
1564 if( i>=pIter->u.ax.nIdx ){
1565 *pIx = i;
1566 return 0;
1568 *pIx = pIter->u.ax.aIdx[i].ix;
1569 return pIter->u.ax.aIdx[i].p;
1570 }else{
1571 ++(*pIx);
1572 pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
1573 return pIter->u.lx.pIdx;
1578 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
1579 ** on table pTab.
1581 ** The regNewData parameter is the first register in a range that contains
1582 ** the data to be inserted or the data after the update. There will be
1583 ** pTab->nCol+1 registers in this range. The first register (the one
1584 ** that regNewData points to) will contain the new rowid, or NULL in the
1585 ** case of a WITHOUT ROWID table. The second register in the range will
1586 ** contain the content of the first table column. The third register will
1587 ** contain the content of the second table column. And so forth.
1589 ** The regOldData parameter is similar to regNewData except that it contains
1590 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
1591 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
1592 ** checking regOldData for zero.
1594 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
1595 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1596 ** might be modified by the UPDATE. If pkChng is false, then the key of
1597 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1599 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
1600 ** was explicitly specified as part of the INSERT statement. If pkChng
1601 ** is zero, it means that the either rowid is computed automatically or
1602 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
1603 ** pkChng will only be true if the INSERT statement provides an integer
1604 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
1606 ** The code generated by this routine will store new index entries into
1607 ** registers identified by aRegIdx[]. No index entry is created for
1608 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1609 ** the same as the order of indices on the linked list of indices
1610 ** at pTab->pIndex.
1612 ** (2019-05-07) The generated code also creates a new record for the
1613 ** main table, if pTab is a rowid table, and stores that record in the
1614 ** register identified by aRegIdx[nIdx] - in other words in the first
1615 ** entry of aRegIdx[] past the last index. It is important that the
1616 ** record be generated during constraint checks to avoid affinity changes
1617 ** to the register content that occur after constraint checks but before
1618 ** the new record is inserted.
1620 ** The caller must have already opened writeable cursors on the main
1621 ** table and all applicable indices (that is to say, all indices for which
1622 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
1623 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
1624 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
1625 ** for the first index in the pTab->pIndex list. Cursors for other indices
1626 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
1628 ** This routine also generates code to check constraints. NOT NULL,
1629 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
1630 ** then the appropriate action is performed. There are five possible
1631 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
1633 ** Constraint type Action What Happens
1634 ** --------------- ---------- ----------------------------------------
1635 ** any ROLLBACK The current transaction is rolled back and
1636 ** sqlite3_step() returns immediately with a
1637 ** return code of SQLITE_CONSTRAINT.
1639 ** any ABORT Back out changes from the current command
1640 ** only (do not do a complete rollback) then
1641 ** cause sqlite3_step() to return immediately
1642 ** with SQLITE_CONSTRAINT.
1644 ** any FAIL Sqlite3_step() returns immediately with a
1645 ** return code of SQLITE_CONSTRAINT. The
1646 ** transaction is not rolled back and any
1647 ** changes to prior rows are retained.
1649 ** any IGNORE The attempt in insert or update the current
1650 ** row is skipped, without throwing an error.
1651 ** Processing continues with the next row.
1652 ** (There is an immediate jump to ignoreDest.)
1654 ** NOT NULL REPLACE The NULL value is replace by the default
1655 ** value for that column. If the default value
1656 ** is NULL, the action is the same as ABORT.
1658 ** UNIQUE REPLACE The other row that conflicts with the row
1659 ** being inserted is removed.
1661 ** CHECK REPLACE Illegal. The results in an exception.
1663 ** Which action to take is determined by the overrideError parameter.
1664 ** Or if overrideError==OE_Default, then the pParse->onError parameter
1665 ** is used. Or if pParse->onError==OE_Default then the onError value
1666 ** for the constraint is used.
1668 void sqlite3GenerateConstraintChecks(
1669 Parse *pParse, /* The parser context */
1670 Table *pTab, /* The table being inserted or updated */
1671 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
1672 int iDataCur, /* Canonical data cursor (main table or PK index) */
1673 int iIdxCur, /* First index cursor */
1674 int regNewData, /* First register in a range holding values to insert */
1675 int regOldData, /* Previous content. 0 for INSERTs */
1676 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
1677 u8 overrideError, /* Override onError to this if not OE_Default */
1678 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
1679 int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
1680 int *aiChng, /* column i is unchanged if aiChng[i]<0 */
1681 Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
1683 Vdbe *v; /* VDBE under constrution */
1684 Index *pIdx; /* Pointer to one of the indices */
1685 Index *pPk = 0; /* The PRIMARY KEY index for WITHOUT ROWID tables */
1686 sqlite3 *db; /* Database connection */
1687 int i; /* loop counter */
1688 int ix; /* Index loop counter */
1689 int nCol; /* Number of columns */
1690 int onError; /* Conflict resolution strategy */
1691 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
1692 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
1693 Upsert *pUpsertClause = 0; /* The specific ON CONFLICT clause for pIdx */
1694 u8 isUpdate; /* True if this is an UPDATE operation */
1695 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
1696 int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */
1697 int upsertIpkDelay = 0; /* Address of Goto to bypass initial IPK check */
1698 int ipkTop = 0; /* Top of the IPK uniqueness check */
1699 int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */
1700 /* Variables associated with retesting uniqueness constraints after
1701 ** replace triggers fire have run */
1702 int regTrigCnt; /* Register used to count replace trigger invocations */
1703 int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */
1704 int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
1705 Trigger *pTrigger; /* List of DELETE triggers on the table pTab */
1706 int nReplaceTrig = 0; /* Number of replace triggers coded */
1707 IndexIterator sIdxIter; /* Index iterator */
1709 isUpdate = regOldData!=0;
1710 db = pParse->db;
1711 v = pParse->pVdbe;
1712 assert( v!=0 );
1713 assert( !IsView(pTab) ); /* This table is not a VIEW */
1714 nCol = pTab->nCol;
1716 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
1717 ** normal rowid tables. nPkField is the number of key fields in the
1718 ** pPk index or 1 for a rowid table. In other words, nPkField is the
1719 ** number of fields in the true primary key of the table. */
1720 if( HasRowid(pTab) ){
1721 pPk = 0;
1722 nPkField = 1;
1723 }else{
1724 pPk = sqlite3PrimaryKeyIndex(pTab);
1725 nPkField = pPk->nKeyCol;
1728 /* Record that this module has started */
1729 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
1730 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
1732 /* Test all NOT NULL constraints.
1734 if( pTab->tabFlags & TF_HasNotNull ){
1735 int b2ndPass = 0; /* True if currently running 2nd pass */
1736 int nSeenReplace = 0; /* Number of ON CONFLICT REPLACE operations */
1737 int nGenerated = 0; /* Number of generated columns with NOT NULL */
1738 while(1){ /* Make 2 passes over columns. Exit loop via "break" */
1739 for(i=0; i<nCol; i++){
1740 int iReg; /* Register holding column value */
1741 Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */
1742 int isGenerated; /* non-zero if column is generated */
1743 onError = pCol->notNull;
1744 if( onError==OE_None ) continue; /* No NOT NULL on this column */
1745 if( i==pTab->iPKey ){
1746 continue; /* ROWID is never NULL */
1748 isGenerated = pCol->colFlags & COLFLAG_GENERATED;
1749 if( isGenerated && !b2ndPass ){
1750 nGenerated++;
1751 continue; /* Generated columns processed on 2nd pass */
1753 if( aiChng && aiChng[i]<0 && !isGenerated ){
1754 /* Do not check NOT NULL on columns that do not change */
1755 continue;
1757 if( overrideError!=OE_Default ){
1758 onError = overrideError;
1759 }else if( onError==OE_Default ){
1760 onError = OE_Abort;
1762 if( onError==OE_Replace ){
1763 if( b2ndPass /* REPLACE becomes ABORT on the 2nd pass */
1764 || pCol->iDflt==0 /* REPLACE is ABORT if no DEFAULT value */
1766 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1767 testcase( pCol->colFlags & COLFLAG_STORED );
1768 testcase( pCol->colFlags & COLFLAG_GENERATED );
1769 onError = OE_Abort;
1770 }else{
1771 assert( !isGenerated );
1773 }else if( b2ndPass && !isGenerated ){
1774 continue;
1776 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1777 || onError==OE_Ignore || onError==OE_Replace );
1778 testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
1779 iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
1780 switch( onError ){
1781 case OE_Replace: {
1782 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
1783 VdbeCoverage(v);
1784 assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
1785 nSeenReplace++;
1786 sqlite3ExprCodeCopy(pParse,
1787 sqlite3ColumnExpr(pTab, pCol), iReg);
1788 sqlite3VdbeJumpHere(v, addr1);
1789 break;
1791 case OE_Abort:
1792 sqlite3MayAbort(pParse);
1793 /* no break */ deliberate_fall_through
1794 case OE_Rollback:
1795 case OE_Fail: {
1796 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
1797 pCol->zCnName);
1798 testcase( zMsg==0 && db->mallocFailed==0 );
1799 sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
1800 onError, iReg);
1801 sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
1802 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
1803 VdbeCoverage(v);
1804 break;
1806 default: {
1807 assert( onError==OE_Ignore );
1808 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
1809 VdbeCoverage(v);
1810 break;
1812 } /* end switch(onError) */
1813 } /* end loop i over columns */
1814 if( nGenerated==0 && nSeenReplace==0 ){
1815 /* If there are no generated columns with NOT NULL constraints
1816 ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
1817 ** pass is sufficient */
1818 break;
1820 if( b2ndPass ) break; /* Never need more than 2 passes */
1821 b2ndPass = 1;
1822 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1823 if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
1824 /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
1825 ** first pass, recomputed values for all generated columns, as
1826 ** those values might depend on columns affected by the REPLACE.
1828 sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
1830 #endif
1831 } /* end of 2-pass loop */
1832 } /* end if( has-not-null-constraints ) */
1834 /* Test all CHECK constraints
1836 #ifndef SQLITE_OMIT_CHECK
1837 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
1838 ExprList *pCheck = pTab->pCheck;
1839 pParse->iSelfTab = -(regNewData+1);
1840 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
1841 for(i=0; i<pCheck->nExpr; i++){
1842 int allOk;
1843 Expr *pCopy;
1844 Expr *pExpr = pCheck->a[i].pExpr;
1845 if( aiChng
1846 && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
1848 /* The check constraints do not reference any of the columns being
1849 ** updated so there is no point it verifying the check constraint */
1850 continue;
1852 if( bAffinityDone==0 ){
1853 sqlite3TableAffinity(v, pTab, regNewData+1);
1854 bAffinityDone = 1;
1856 allOk = sqlite3VdbeMakeLabel(pParse);
1857 sqlite3VdbeVerifyAbortable(v, onError);
1858 pCopy = sqlite3ExprDup(db, pExpr, 0);
1859 if( !db->mallocFailed ){
1860 sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
1862 sqlite3ExprDelete(db, pCopy);
1863 if( onError==OE_Ignore ){
1864 sqlite3VdbeGoto(v, ignoreDest);
1865 }else{
1866 char *zName = pCheck->a[i].zEName;
1867 assert( zName!=0 || pParse->db->mallocFailed );
1868 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
1869 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
1870 onError, zName, P4_TRANSIENT,
1871 P5_ConstraintCheck);
1873 sqlite3VdbeResolveLabel(v, allOk);
1875 pParse->iSelfTab = 0;
1877 #endif /* !defined(SQLITE_OMIT_CHECK) */
1879 /* UNIQUE and PRIMARY KEY constraints should be handled in the following
1880 ** order:
1882 ** (1) OE_Update
1883 ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
1884 ** (3) OE_Replace
1886 ** OE_Fail and OE_Ignore must happen before any changes are made.
1887 ** OE_Update guarantees that only a single row will change, so it
1888 ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
1889 ** could happen in any order, but they are grouped up front for
1890 ** convenience.
1892 ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
1893 ** The order of constraints used to have OE_Update as (2) and OE_Abort
1894 ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
1895 ** constraint before any others, so it had to be moved.
1897 ** Constraint checking code is generated in this order:
1898 ** (A) The rowid constraint
1899 ** (B) Unique index constraints that do not have OE_Replace as their
1900 ** default conflict resolution strategy
1901 ** (C) Unique index that do use OE_Replace by default.
1903 ** The ordering of (2) and (3) is accomplished by making sure the linked
1904 ** list of indexes attached to a table puts all OE_Replace indexes last
1905 ** in the list. See sqlite3CreateIndex() for where that happens.
1907 sIdxIter.eType = 0;
1908 sIdxIter.i = 0;
1909 sIdxIter.u.ax.aIdx = 0; /* Silence harmless compiler warning */
1910 sIdxIter.u.lx.pIdx = pTab->pIndex;
1911 if( pUpsert ){
1912 if( pUpsert->pUpsertTarget==0 ){
1913 /* There is just on ON CONFLICT clause and it has no constraint-target */
1914 assert( pUpsert->pNextUpsert==0 );
1915 if( pUpsert->isDoUpdate==0 ){
1916 /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
1917 ** Make all unique constraint resolution be OE_Ignore */
1918 overrideError = OE_Ignore;
1919 pUpsert = 0;
1920 }else{
1921 /* A single ON CONFLICT DO UPDATE. Make all resolutions OE_Update */
1922 overrideError = OE_Update;
1924 }else if( pTab->pIndex!=0 ){
1925 /* Otherwise, we'll need to run the IndexListTerm array version of the
1926 ** iterator to ensure that all of the ON CONFLICT conditions are
1927 ** checked first and in order. */
1928 int nIdx, jj;
1929 u64 nByte;
1930 Upsert *pTerm;
1931 u8 *bUsed;
1932 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
1933 assert( aRegIdx[nIdx]>0 );
1935 sIdxIter.eType = 1;
1936 sIdxIter.u.ax.nIdx = nIdx;
1937 nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx;
1938 sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte);
1939 if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */
1940 bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx];
1941 pUpsert->pToFree = sIdxIter.u.ax.aIdx;
1942 for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
1943 if( pTerm->pUpsertTarget==0 ) break;
1944 if( pTerm->pUpsertIdx==0 ) continue; /* Skip ON CONFLICT for the IPK */
1945 jj = 0;
1946 pIdx = pTab->pIndex;
1947 while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
1948 pIdx = pIdx->pNext;
1949 jj++;
1951 if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */
1952 bUsed[jj] = 1;
1953 sIdxIter.u.ax.aIdx[i].p = pIdx;
1954 sIdxIter.u.ax.aIdx[i].ix = jj;
1955 i++;
1957 for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
1958 if( bUsed[jj] ) continue;
1959 sIdxIter.u.ax.aIdx[i].p = pIdx;
1960 sIdxIter.u.ax.aIdx[i].ix = jj;
1961 i++;
1963 assert( i==nIdx );
1967 /* Determine if it is possible that triggers (either explicitly coded
1968 ** triggers or FK resolution actions) might run as a result of deletes
1969 ** that happen when OE_Replace conflict resolution occurs. (Call these
1970 ** "replace triggers".) If any replace triggers run, we will need to
1971 ** recheck all of the uniqueness constraints after they have all run.
1972 ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
1974 ** If replace triggers are a possibility, then
1976 ** (1) Allocate register regTrigCnt and initialize it to zero.
1977 ** That register will count the number of replace triggers that
1978 ** fire. Constraint recheck only occurs if the number is positive.
1979 ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
1980 ** (3) Initialize addrRecheck and lblRecheckOk
1982 ** The uniqueness rechecking code will create a series of tests to run
1983 ** in a second pass. The addrRecheck and lblRecheckOk variables are
1984 ** used to link together these tests which are separated from each other
1985 ** in the generate bytecode.
1987 if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
1988 /* There are not DELETE triggers nor FK constraints. No constraint
1989 ** rechecks are needed. */
1990 pTrigger = 0;
1991 regTrigCnt = 0;
1992 }else{
1993 if( db->flags&SQLITE_RecTriggers ){
1994 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1995 regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
1996 }else{
1997 pTrigger = 0;
1998 regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
2000 if( regTrigCnt ){
2001 /* Replace triggers might exist. Allocate the counter and
2002 ** initialize it to zero. */
2003 regTrigCnt = ++pParse->nMem;
2004 sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
2005 VdbeComment((v, "trigger count"));
2006 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2007 addrRecheck = lblRecheckOk;
2011 /* If rowid is changing, make sure the new rowid does not previously
2012 ** exist in the table.
2014 if( pkChng && pPk==0 ){
2015 int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
2017 /* Figure out what action to take in case of a rowid collision */
2018 onError = pTab->keyConf;
2019 if( overrideError!=OE_Default ){
2020 onError = overrideError;
2021 }else if( onError==OE_Default ){
2022 onError = OE_Abort;
2025 /* figure out whether or not upsert applies in this case */
2026 if( pUpsert ){
2027 pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0);
2028 if( pUpsertClause!=0 ){
2029 if( pUpsertClause->isDoUpdate==0 ){
2030 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
2031 }else{
2032 onError = OE_Update; /* DO UPDATE */
2035 if( pUpsertClause!=pUpsert ){
2036 /* The first ON CONFLICT clause has a conflict target other than
2037 ** the IPK. We have to jump ahead to that first ON CONFLICT clause
2038 ** and then come back here and deal with the IPK afterwards */
2039 upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto);
2043 /* If the response to a rowid conflict is REPLACE but the response
2044 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
2045 ** to defer the running of the rowid conflict checking until after
2046 ** the UNIQUE constraints have run.
2048 if( onError==OE_Replace /* IPK rule is REPLACE */
2049 && onError!=overrideError /* Rules for other constraints are different */
2050 && pTab->pIndex /* There exist other constraints */
2051 && !upsertIpkDelay /* IPK check already deferred by UPSERT */
2053 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
2054 VdbeComment((v, "defer IPK REPLACE until last"));
2057 if( isUpdate ){
2058 /* pkChng!=0 does not mean that the rowid has changed, only that
2059 ** it might have changed. Skip the conflict logic below if the rowid
2060 ** is unchanged. */
2061 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
2062 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2063 VdbeCoverage(v);
2066 /* Check to see if the new rowid already exists in the table. Skip
2067 ** the following conflict logic if it does not. */
2068 VdbeNoopComment((v, "uniqueness check for ROWID"));
2069 sqlite3VdbeVerifyAbortable(v, onError);
2070 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
2071 VdbeCoverage(v);
2073 switch( onError ){
2074 default: {
2075 onError = OE_Abort;
2076 /* no break */ deliberate_fall_through
2078 case OE_Rollback:
2079 case OE_Abort:
2080 case OE_Fail: {
2081 testcase( onError==OE_Rollback );
2082 testcase( onError==OE_Abort );
2083 testcase( onError==OE_Fail );
2084 sqlite3RowidConstraint(pParse, onError, pTab);
2085 break;
2087 case OE_Replace: {
2088 /* If there are DELETE triggers on this table and the
2089 ** recursive-triggers flag is set, call GenerateRowDelete() to
2090 ** remove the conflicting row from the table. This will fire
2091 ** the triggers and remove both the table and index b-tree entries.
2093 ** Otherwise, if there are no triggers or the recursive-triggers
2094 ** flag is not set, but the table has one or more indexes, call
2095 ** GenerateRowIndexDelete(). This removes the index b-tree entries
2096 ** only. The table b-tree entry will be replaced by the new entry
2097 ** when it is inserted.
2099 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
2100 ** also invoke MultiWrite() to indicate that this VDBE may require
2101 ** statement rollback (if the statement is aborted after the delete
2102 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
2103 ** but being more selective here allows statements like:
2105 ** REPLACE INTO t(rowid) VALUES($newrowid)
2107 ** to run without a statement journal if there are no indexes on the
2108 ** table.
2110 if( regTrigCnt ){
2111 sqlite3MultiWrite(pParse);
2112 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2113 regNewData, 1, 0, OE_Replace, 1, -1);
2114 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2115 nReplaceTrig++;
2116 }else{
2117 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2118 assert( HasRowid(pTab) );
2119 /* This OP_Delete opcode fires the pre-update-hook only. It does
2120 ** not modify the b-tree. It is more efficient to let the coming
2121 ** OP_Insert replace the existing entry than it is to delete the
2122 ** existing entry and then insert a new one. */
2123 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
2124 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
2125 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2126 if( pTab->pIndex ){
2127 sqlite3MultiWrite(pParse);
2128 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
2131 seenReplace = 1;
2132 break;
2134 #ifndef SQLITE_OMIT_UPSERT
2135 case OE_Update: {
2136 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
2137 /* no break */ deliberate_fall_through
2139 #endif
2140 case OE_Ignore: {
2141 testcase( onError==OE_Ignore );
2142 sqlite3VdbeGoto(v, ignoreDest);
2143 break;
2146 sqlite3VdbeResolveLabel(v, addrRowidOk);
2147 if( pUpsert && pUpsertClause!=pUpsert ){
2148 upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
2149 }else if( ipkTop ){
2150 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
2151 sqlite3VdbeJumpHere(v, ipkTop-1);
2155 /* Test all UNIQUE constraints by creating entries for each UNIQUE
2156 ** index and making sure that duplicate entries do not already exist.
2157 ** Compute the revised record entries for indices as we go.
2159 ** This loop also handles the case of the PRIMARY KEY index for a
2160 ** WITHOUT ROWID table.
2162 for(pIdx = indexIteratorFirst(&sIdxIter, &ix);
2163 pIdx;
2164 pIdx = indexIteratorNext(&sIdxIter, &ix)
2166 int regIdx; /* Range of registers hold conent for pIdx */
2167 int regR; /* Range of registers holding conflicting PK */
2168 int iThisCur; /* Cursor for this UNIQUE index */
2169 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
2170 int addrConflictCk; /* First opcode in the conflict check logic */
2172 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
2173 if( pUpsert ){
2174 pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
2175 if( upsertIpkDelay && pUpsertClause==pUpsert ){
2176 sqlite3VdbeJumpHere(v, upsertIpkDelay);
2179 addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
2180 if( bAffinityDone==0 ){
2181 sqlite3TableAffinity(v, pTab, regNewData+1);
2182 bAffinityDone = 1;
2184 VdbeNoopComment((v, "prep index %s", pIdx->zName));
2185 iThisCur = iIdxCur+ix;
2188 /* Skip partial indices for which the WHERE clause is not true */
2189 if( pIdx->pPartIdxWhere ){
2190 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
2191 pParse->iSelfTab = -(regNewData+1);
2192 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
2193 SQLITE_JUMPIFNULL);
2194 pParse->iSelfTab = 0;
2197 /* Create a record for this index entry as it should appear after
2198 ** the insert or update. Store that record in the aRegIdx[ix] register
2200 regIdx = aRegIdx[ix]+1;
2201 for(i=0; i<pIdx->nColumn; i++){
2202 int iField = pIdx->aiColumn[i];
2203 int x;
2204 if( iField==XN_EXPR ){
2205 pParse->iSelfTab = -(regNewData+1);
2206 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
2207 pParse->iSelfTab = 0;
2208 VdbeComment((v, "%s column %d", pIdx->zName, i));
2209 }else if( iField==XN_ROWID || iField==pTab->iPKey ){
2210 x = regNewData;
2211 sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
2212 VdbeComment((v, "rowid"));
2213 }else{
2214 testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
2215 x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
2216 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
2217 VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
2220 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
2221 VdbeComment((v, "for %s", pIdx->zName));
2222 #ifdef SQLITE_ENABLE_NULL_TRIM
2223 if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
2224 sqlite3SetMakeRecordP5(v, pIdx->pTable);
2226 #endif
2227 sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
2229 /* In an UPDATE operation, if this index is the PRIMARY KEY index
2230 ** of a WITHOUT ROWID table and there has been no change the
2231 ** primary key, then no collision is possible. The collision detection
2232 ** logic below can all be skipped. */
2233 if( isUpdate && pPk==pIdx && pkChng==0 ){
2234 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2235 continue;
2238 /* Find out what action to take in case there is a uniqueness conflict */
2239 onError = pIdx->onError;
2240 if( onError==OE_None ){
2241 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2242 continue; /* pIdx is not a UNIQUE index */
2244 if( overrideError!=OE_Default ){
2245 onError = overrideError;
2246 }else if( onError==OE_Default ){
2247 onError = OE_Abort;
2250 /* Figure out if the upsert clause applies to this index */
2251 if( pUpsertClause ){
2252 if( pUpsertClause->isDoUpdate==0 ){
2253 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
2254 }else{
2255 onError = OE_Update; /* DO UPDATE */
2259 /* Collision detection may be omitted if all of the following are true:
2260 ** (1) The conflict resolution algorithm is REPLACE
2261 ** (2) The table is a WITHOUT ROWID table
2262 ** (3) There are no secondary indexes on the table
2263 ** (4) No delete triggers need to be fired if there is a conflict
2264 ** (5) No FK constraint counters need to be updated if a conflict occurs.
2266 ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
2267 ** must be explicitly deleted in order to ensure any pre-update hook
2268 ** is invoked. */
2269 assert( IsOrdinaryTable(pTab) );
2270 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
2271 if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
2272 && pPk==pIdx /* Condition 2 */
2273 && onError==OE_Replace /* Condition 1 */
2274 && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
2275 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
2276 && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
2277 (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
2279 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2280 continue;
2282 #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
2284 /* Check to see if the new index entry will be unique */
2285 sqlite3VdbeVerifyAbortable(v, onError);
2286 addrConflictCk =
2287 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
2288 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
2290 /* Generate code to handle collisions */
2291 regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField);
2292 if( isUpdate || onError==OE_Replace ){
2293 if( HasRowid(pTab) ){
2294 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
2295 /* Conflict only if the rowid of the existing index entry
2296 ** is different from old-rowid */
2297 if( isUpdate ){
2298 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
2299 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2300 VdbeCoverage(v);
2302 }else{
2303 int x;
2304 /* Extract the PRIMARY KEY from the end of the index entry and
2305 ** store it in registers regR..regR+nPk-1 */
2306 if( pIdx!=pPk ){
2307 for(i=0; i<pPk->nKeyCol; i++){
2308 assert( pPk->aiColumn[i]>=0 );
2309 x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
2310 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
2311 VdbeComment((v, "%s.%s", pTab->zName,
2312 pTab->aCol[pPk->aiColumn[i]].zCnName));
2315 if( isUpdate ){
2316 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
2317 ** table, only conflict if the new PRIMARY KEY values are actually
2318 ** different from the old. See TH3 withoutrowid04.test.
2320 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
2321 ** of the matched index row are different from the original PRIMARY
2322 ** KEY values of this row before the update. */
2323 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
2324 int op = OP_Ne;
2325 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
2327 for(i=0; i<pPk->nKeyCol; i++){
2328 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
2329 x = pPk->aiColumn[i];
2330 assert( x>=0 );
2331 if( i==(pPk->nKeyCol-1) ){
2332 addrJump = addrUniqueOk;
2333 op = OP_Eq;
2335 x = sqlite3TableColumnToStorage(pTab, x);
2336 sqlite3VdbeAddOp4(v, op,
2337 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
2339 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2340 VdbeCoverageIf(v, op==OP_Eq);
2341 VdbeCoverageIf(v, op==OP_Ne);
2347 /* Generate code that executes if the new index entry is not unique */
2348 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
2349 || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
2350 switch( onError ){
2351 case OE_Rollback:
2352 case OE_Abort:
2353 case OE_Fail: {
2354 testcase( onError==OE_Rollback );
2355 testcase( onError==OE_Abort );
2356 testcase( onError==OE_Fail );
2357 sqlite3UniqueConstraint(pParse, onError, pIdx);
2358 break;
2360 #ifndef SQLITE_OMIT_UPSERT
2361 case OE_Update: {
2362 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
2363 /* no break */ deliberate_fall_through
2365 #endif
2366 case OE_Ignore: {
2367 testcase( onError==OE_Ignore );
2368 sqlite3VdbeGoto(v, ignoreDest);
2369 break;
2371 default: {
2372 int nConflictCk; /* Number of opcodes in conflict check logic */
2374 assert( onError==OE_Replace );
2375 nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
2376 assert( nConflictCk>0 || db->mallocFailed );
2377 testcase( nConflictCk<=0 );
2378 testcase( nConflictCk>1 );
2379 if( regTrigCnt ){
2380 sqlite3MultiWrite(pParse);
2381 nReplaceTrig++;
2383 if( pTrigger && isUpdate ){
2384 sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
2386 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2387 regR, nPkField, 0, OE_Replace,
2388 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
2389 if( pTrigger && isUpdate ){
2390 sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
2392 if( regTrigCnt ){
2393 int addrBypass; /* Jump destination to bypass recheck logic */
2395 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2396 addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
2397 VdbeComment((v, "bypass recheck"));
2399 /* Here we insert code that will be invoked after all constraint
2400 ** checks have run, if and only if one or more replace triggers
2401 ** fired. */
2402 sqlite3VdbeResolveLabel(v, lblRecheckOk);
2403 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2404 if( pIdx->pPartIdxWhere ){
2405 /* Bypass the recheck if this partial index is not defined
2406 ** for the current row */
2407 sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
2408 VdbeCoverage(v);
2410 /* Copy the constraint check code from above, except change
2411 ** the constraint-ok jump destination to be the address of
2412 ** the next retest block */
2413 while( nConflictCk>0 ){
2414 VdbeOp x; /* Conflict check opcode to copy */
2415 /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
2416 ** Hence, make a complete copy of the opcode, rather than using
2417 ** a pointer to the opcode. */
2418 x = *sqlite3VdbeGetOp(v, addrConflictCk);
2419 if( x.opcode!=OP_IdxRowid ){
2420 int p2; /* New P2 value for copied conflict check opcode */
2421 const char *zP4;
2422 if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
2423 p2 = lblRecheckOk;
2424 }else{
2425 p2 = x.p2;
2427 zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
2428 sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
2429 sqlite3VdbeChangeP5(v, x.p5);
2430 VdbeCoverageIf(v, p2!=x.p2);
2432 nConflictCk--;
2433 addrConflictCk++;
2435 /* If the retest fails, issue an abort */
2436 sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
2438 sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
2440 seenReplace = 1;
2441 break;
2444 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2445 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
2446 if( pUpsertClause
2447 && upsertIpkReturn
2448 && sqlite3UpsertNextIsIPK(pUpsertClause)
2450 sqlite3VdbeGoto(v, upsertIpkDelay+1);
2451 sqlite3VdbeJumpHere(v, upsertIpkReturn);
2452 upsertIpkReturn = 0;
2456 /* If the IPK constraint is a REPLACE, run it last */
2457 if( ipkTop ){
2458 sqlite3VdbeGoto(v, ipkTop);
2459 VdbeComment((v, "Do IPK REPLACE"));
2460 assert( ipkBottom>0 );
2461 sqlite3VdbeJumpHere(v, ipkBottom);
2464 /* Recheck all uniqueness constraints after replace triggers have run */
2465 testcase( regTrigCnt!=0 && nReplaceTrig==0 );
2466 assert( regTrigCnt!=0 || nReplaceTrig==0 );
2467 if( nReplaceTrig ){
2468 sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
2469 if( !pPk ){
2470 if( isUpdate ){
2471 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
2472 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2473 VdbeCoverage(v);
2475 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
2476 VdbeCoverage(v);
2477 sqlite3RowidConstraint(pParse, OE_Abort, pTab);
2478 }else{
2479 sqlite3VdbeGoto(v, addrRecheck);
2481 sqlite3VdbeResolveLabel(v, lblRecheckOk);
2484 /* Generate the table record */
2485 if( HasRowid(pTab) ){
2486 int regRec = aRegIdx[ix];
2487 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
2488 sqlite3SetMakeRecordP5(v, pTab);
2489 if( !bAffinityDone ){
2490 sqlite3TableAffinity(v, pTab, 0);
2494 *pbMayReplace = seenReplace;
2495 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
2498 #ifdef SQLITE_ENABLE_NULL_TRIM
2500 ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
2501 ** to be the number of columns in table pTab that must not be NULL-trimmed.
2503 ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
2505 void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
2506 u16 i;
2508 /* Records with omitted columns are only allowed for schema format
2509 ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
2510 if( pTab->pSchema->file_format<2 ) return;
2512 for(i=pTab->nCol-1; i>0; i--){
2513 if( pTab->aCol[i].iDflt!=0 ) break;
2514 if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
2516 sqlite3VdbeChangeP5(v, i+1);
2518 #endif
2521 ** Table pTab is a WITHOUT ROWID table that is being written to. The cursor
2522 ** number is iCur, and register regData contains the new record for the
2523 ** PK index. This function adds code to invoke the pre-update hook,
2524 ** if one is registered.
2526 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2527 static void codeWithoutRowidPreupdate(
2528 Parse *pParse, /* Parse context */
2529 Table *pTab, /* Table being updated */
2530 int iCur, /* Cursor number for table */
2531 int regData /* Data containing new record */
2533 Vdbe *v = pParse->pVdbe;
2534 int r = sqlite3GetTempReg(pParse);
2535 assert( !HasRowid(pTab) );
2536 assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
2537 sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
2538 sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE);
2539 sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
2540 sqlite3ReleaseTempReg(pParse, r);
2542 #else
2543 # define codeWithoutRowidPreupdate(a,b,c,d)
2544 #endif
2547 ** This routine generates code to finish the INSERT or UPDATE operation
2548 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
2549 ** A consecutive range of registers starting at regNewData contains the
2550 ** rowid and the content to be inserted.
2552 ** The arguments to this routine should be the same as the first six
2553 ** arguments to sqlite3GenerateConstraintChecks.
2555 void sqlite3CompleteInsertion(
2556 Parse *pParse, /* The parser context */
2557 Table *pTab, /* the table into which we are inserting */
2558 int iDataCur, /* Cursor of the canonical data source */
2559 int iIdxCur, /* First index cursor */
2560 int regNewData, /* Range of content */
2561 int *aRegIdx, /* Register used by each index. 0 for unused indices */
2562 int update_flags, /* True for UPDATE, False for INSERT */
2563 int appendBias, /* True if this is likely to be an append */
2564 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
2566 Vdbe *v; /* Prepared statements under construction */
2567 Index *pIdx; /* An index being inserted or updated */
2568 u8 pik_flags; /* flag values passed to the btree insert */
2569 int i; /* Loop counter */
2571 assert( update_flags==0
2572 || update_flags==OPFLAG_ISUPDATE
2573 || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
2576 v = pParse->pVdbe;
2577 assert( v!=0 );
2578 assert( !IsView(pTab) ); /* This table is not a VIEW */
2579 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2580 /* All REPLACE indexes are at the end of the list */
2581 assert( pIdx->onError!=OE_Replace
2582 || pIdx->pNext==0
2583 || pIdx->pNext->onError==OE_Replace );
2584 if( aRegIdx[i]==0 ) continue;
2585 if( pIdx->pPartIdxWhere ){
2586 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
2587 VdbeCoverage(v);
2589 pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
2590 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2591 pik_flags |= OPFLAG_NCHANGE;
2592 pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
2593 if( update_flags==0 ){
2594 codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]);
2597 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
2598 aRegIdx[i]+1,
2599 pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
2600 sqlite3VdbeChangeP5(v, pik_flags);
2602 if( !HasRowid(pTab) ) return;
2603 if( pParse->nested ){
2604 pik_flags = 0;
2605 }else{
2606 pik_flags = OPFLAG_NCHANGE;
2607 pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
2609 if( appendBias ){
2610 pik_flags |= OPFLAG_APPEND;
2612 if( useSeekResult ){
2613 pik_flags |= OPFLAG_USESEEKRESULT;
2615 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
2616 if( !pParse->nested ){
2617 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
2619 sqlite3VdbeChangeP5(v, pik_flags);
2623 ** Allocate cursors for the pTab table and all its indices and generate
2624 ** code to open and initialized those cursors.
2626 ** The cursor for the object that contains the complete data (normally
2627 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
2628 ** ROWID table) is returned in *piDataCur. The first index cursor is
2629 ** returned in *piIdxCur. The number of indices is returned.
2631 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
2632 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
2633 ** If iBase is negative, then allocate the next available cursor.
2635 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
2636 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
2637 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
2638 ** pTab->pIndex list.
2640 ** If pTab is a virtual table, then this routine is a no-op and the
2641 ** *piDataCur and *piIdxCur values are left uninitialized.
2643 int sqlite3OpenTableAndIndices(
2644 Parse *pParse, /* Parsing context */
2645 Table *pTab, /* Table to be opened */
2646 int op, /* OP_OpenRead or OP_OpenWrite */
2647 u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
2648 int iBase, /* Use this for the table cursor, if there is one */
2649 u8 *aToOpen, /* If not NULL: boolean for each table and index */
2650 int *piDataCur, /* Write the database source cursor number here */
2651 int *piIdxCur /* Write the first index cursor number here */
2653 int i;
2654 int iDb;
2655 int iDataCur;
2656 Index *pIdx;
2657 Vdbe *v;
2659 assert( op==OP_OpenRead || op==OP_OpenWrite );
2660 assert( op==OP_OpenWrite || p5==0 );
2661 if( IsVirtual(pTab) ){
2662 /* This routine is a no-op for virtual tables. Leave the output
2663 ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
2664 ** for improved error detection. */
2665 *piDataCur = *piIdxCur = -999;
2666 return 0;
2668 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2669 v = pParse->pVdbe;
2670 assert( v!=0 );
2671 if( iBase<0 ) iBase = pParse->nTab;
2672 iDataCur = iBase++;
2673 if( piDataCur ) *piDataCur = iDataCur;
2674 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
2675 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
2676 }else{
2677 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
2679 if( piIdxCur ) *piIdxCur = iBase;
2680 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2681 int iIdxCur = iBase++;
2682 assert( pIdx->pSchema==pTab->pSchema );
2683 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2684 if( piDataCur ) *piDataCur = iIdxCur;
2685 p5 = 0;
2687 if( aToOpen==0 || aToOpen[i+1] ){
2688 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
2689 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2690 sqlite3VdbeChangeP5(v, p5);
2691 VdbeComment((v, "%s", pIdx->zName));
2694 if( iBase>pParse->nTab ) pParse->nTab = iBase;
2695 return i;
2699 #ifdef SQLITE_TEST
2701 ** The following global variable is incremented whenever the
2702 ** transfer optimization is used. This is used for testing
2703 ** purposes only - to make sure the transfer optimization really
2704 ** is happening when it is supposed to.
2706 int sqlite3_xferopt_count;
2707 #endif /* SQLITE_TEST */
2710 #ifndef SQLITE_OMIT_XFER_OPT
2712 ** Check to see if index pSrc is compatible as a source of data
2713 ** for index pDest in an insert transfer optimization. The rules
2714 ** for a compatible index:
2716 ** * The index is over the same set of columns
2717 ** * The same DESC and ASC markings occurs on all columns
2718 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
2719 ** * The same collating sequence on each column
2720 ** * The index has the exact same WHERE clause
2722 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
2723 int i;
2724 assert( pDest && pSrc );
2725 assert( pDest->pTable!=pSrc->pTable );
2726 if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
2727 return 0; /* Different number of columns */
2729 if( pDest->onError!=pSrc->onError ){
2730 return 0; /* Different conflict resolution strategies */
2732 for(i=0; i<pSrc->nKeyCol; i++){
2733 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
2734 return 0; /* Different columns indexed */
2736 if( pSrc->aiColumn[i]==XN_EXPR ){
2737 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
2738 if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
2739 pDest->aColExpr->a[i].pExpr, -1)!=0 ){
2740 return 0; /* Different expressions in the index */
2743 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
2744 return 0; /* Different sort orders */
2746 if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
2747 return 0; /* Different collating sequences */
2750 if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
2751 return 0; /* Different WHERE clauses */
2754 /* If no test above fails then the indices must be compatible */
2755 return 1;
2759 ** Attempt the transfer optimization on INSERTs of the form
2761 ** INSERT INTO tab1 SELECT * FROM tab2;
2763 ** The xfer optimization transfers raw records from tab2 over to tab1.
2764 ** Columns are not decoded and reassembled, which greatly improves
2765 ** performance. Raw index records are transferred in the same way.
2767 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
2768 ** There are lots of rules for determining compatibility - see comments
2769 ** embedded in the code for details.
2771 ** This routine returns TRUE if the optimization is guaranteed to be used.
2772 ** Sometimes the xfer optimization will only work if the destination table
2773 ** is empty - a factor that can only be determined at run-time. In that
2774 ** case, this routine generates code for the xfer optimization but also
2775 ** does a test to see if the destination table is empty and jumps over the
2776 ** xfer optimization code if the test fails. In that case, this routine
2777 ** returns FALSE so that the caller will know to go ahead and generate
2778 ** an unoptimized transfer. This routine also returns FALSE if there
2779 ** is no chance that the xfer optimization can be applied.
2781 ** This optimization is particularly useful at making VACUUM run faster.
2783 static int xferOptimization(
2784 Parse *pParse, /* Parser context */
2785 Table *pDest, /* The table we are inserting into */
2786 Select *pSelect, /* A SELECT statement to use as the data source */
2787 int onError, /* How to handle constraint errors */
2788 int iDbDest /* The database of pDest */
2790 sqlite3 *db = pParse->db;
2791 ExprList *pEList; /* The result set of the SELECT */
2792 Table *pSrc; /* The table in the FROM clause of SELECT */
2793 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
2794 SrcItem *pItem; /* An element of pSelect->pSrc */
2795 int i; /* Loop counter */
2796 int iDbSrc; /* The database of pSrc */
2797 int iSrc, iDest; /* Cursors from source and destination */
2798 int addr1, addr2; /* Loop addresses */
2799 int emptyDestTest = 0; /* Address of test for empty pDest */
2800 int emptySrcTest = 0; /* Address of test for empty pSrc */
2801 Vdbe *v; /* The VDBE we are building */
2802 int regAutoinc; /* Memory register used by AUTOINC */
2803 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
2804 int regData, regRowid; /* Registers holding data and rowid */
2806 assert( pSelect!=0 );
2807 if( pParse->pWith || pSelect->pWith ){
2808 /* Do not attempt to process this query if there are an WITH clauses
2809 ** attached to it. Proceeding may generate a false "no such table: xxx"
2810 ** error if pSelect reads from a CTE named "xxx". */
2811 return 0;
2813 #ifndef SQLITE_OMIT_VIRTUALTABLE
2814 if( IsVirtual(pDest) ){
2815 return 0; /* tab1 must not be a virtual table */
2817 #endif
2818 if( onError==OE_Default ){
2819 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
2820 if( onError==OE_Default ) onError = OE_Abort;
2822 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
2823 if( pSelect->pSrc->nSrc!=1 ){
2824 return 0; /* FROM clause must have exactly one term */
2826 if( pSelect->pSrc->a[0].pSelect ){
2827 return 0; /* FROM clause cannot contain a subquery */
2829 if( pSelect->pWhere ){
2830 return 0; /* SELECT may not have a WHERE clause */
2832 if( pSelect->pOrderBy ){
2833 return 0; /* SELECT may not have an ORDER BY clause */
2835 /* Do not need to test for a HAVING clause. If HAVING is present but
2836 ** there is no ORDER BY, we will get an error. */
2837 if( pSelect->pGroupBy ){
2838 return 0; /* SELECT may not have a GROUP BY clause */
2840 if( pSelect->pLimit ){
2841 return 0; /* SELECT may not have a LIMIT clause */
2843 if( pSelect->pPrior ){
2844 return 0; /* SELECT may not be a compound query */
2846 if( pSelect->selFlags & SF_Distinct ){
2847 return 0; /* SELECT may not be DISTINCT */
2849 pEList = pSelect->pEList;
2850 assert( pEList!=0 );
2851 if( pEList->nExpr!=1 ){
2852 return 0; /* The result set must have exactly one column */
2854 assert( pEList->a[0].pExpr );
2855 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
2856 return 0; /* The result set must be the special operator "*" */
2859 /* At this point we have established that the statement is of the
2860 ** correct syntactic form to participate in this optimization. Now
2861 ** we have to check the semantics.
2863 pItem = pSelect->pSrc->a;
2864 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
2865 if( pSrc==0 ){
2866 return 0; /* FROM clause does not contain a real table */
2868 if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
2869 testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
2870 return 0; /* tab1 and tab2 may not be the same table */
2872 if( HasRowid(pDest)!=HasRowid(pSrc) ){
2873 return 0; /* source and destination must both be WITHOUT ROWID or not */
2875 if( !IsOrdinaryTable(pSrc) ){
2876 return 0; /* tab2 may not be a view or virtual table */
2878 if( pDest->nCol!=pSrc->nCol ){
2879 return 0; /* Number of columns must be the same in tab1 and tab2 */
2881 if( pDest->iPKey!=pSrc->iPKey ){
2882 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
2884 if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
2885 return 0; /* Cannot feed from a non-strict into a strict table */
2887 for(i=0; i<pDest->nCol; i++){
2888 Column *pDestCol = &pDest->aCol[i];
2889 Column *pSrcCol = &pSrc->aCol[i];
2890 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
2891 if( (db->mDbFlags & DBFLAG_Vacuum)==0
2892 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
2894 return 0; /* Neither table may have __hidden__ columns */
2896 #endif
2897 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2898 /* Even if tables t1 and t2 have identical schemas, if they contain
2899 ** generated columns, then this statement is semantically incorrect:
2901 ** INSERT INTO t2 SELECT * FROM t1;
2903 ** The reason is that generated column values are returned by the
2904 ** the SELECT statement on the right but the INSERT statement on the
2905 ** left wants them to be omitted.
2907 ** Nevertheless, this is a useful notational shorthand to tell SQLite
2908 ** to do a bulk transfer all of the content from t1 over to t2.
2910 ** We could, in theory, disable this (except for internal use by the
2911 ** VACUUM command where it is actually needed). But why do that? It
2912 ** seems harmless enough, and provides a useful service.
2914 if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
2915 (pSrcCol->colFlags & COLFLAG_GENERATED) ){
2916 return 0; /* Both columns have the same generated-column type */
2918 /* But the transfer is only allowed if both the source and destination
2919 ** tables have the exact same expressions for generated columns.
2920 ** This requirement could be relaxed for VIRTUAL columns, I suppose.
2922 if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
2923 if( sqlite3ExprCompare(0,
2924 sqlite3ColumnExpr(pSrc, pSrcCol),
2925 sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
2926 testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
2927 testcase( pDestCol->colFlags & COLFLAG_STORED );
2928 return 0; /* Different generator expressions */
2931 #endif
2932 if( pDestCol->affinity!=pSrcCol->affinity ){
2933 return 0; /* Affinity must be the same on all columns */
2935 if( sqlite3_stricmp(sqlite3ColumnColl(pDestCol),
2936 sqlite3ColumnColl(pSrcCol))!=0 ){
2937 return 0; /* Collating sequence must be the same on all columns */
2939 if( pDestCol->notNull && !pSrcCol->notNull ){
2940 return 0; /* tab2 must be NOT NULL if tab1 is */
2942 /* Default values for second and subsequent columns need to match. */
2943 if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
2944 Expr *pDestExpr = sqlite3ColumnExpr(pDest, pDestCol);
2945 Expr *pSrcExpr = sqlite3ColumnExpr(pSrc, pSrcCol);
2946 assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
2947 assert( pDestExpr==0 || !ExprHasProperty(pDestExpr, EP_IntValue) );
2948 assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
2949 assert( pSrcExpr==0 || !ExprHasProperty(pSrcExpr, EP_IntValue) );
2950 if( (pDestExpr==0)!=(pSrcExpr==0)
2951 || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
2952 pSrcExpr->u.zToken)!=0)
2954 return 0; /* Default values must be the same for all columns */
2958 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
2959 if( IsUniqueIndex(pDestIdx) ){
2960 destHasUniqueIdx = 1;
2962 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
2963 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
2965 if( pSrcIdx==0 ){
2966 return 0; /* pDestIdx has no corresponding index in pSrc */
2968 if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
2969 && sqlite3FaultSim(411)==SQLITE_OK ){
2970 /* The sqlite3FaultSim() call allows this corruption test to be
2971 ** bypassed during testing, in order to exercise other corruption tests
2972 ** further downstream. */
2973 return 0; /* Corrupt schema - two indexes on the same btree */
2976 #ifndef SQLITE_OMIT_CHECK
2977 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
2978 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
2980 #endif
2981 #ifndef SQLITE_OMIT_FOREIGN_KEY
2982 /* Disallow the transfer optimization if the destination table constains
2983 ** any foreign key constraints. This is more restrictive than necessary.
2984 ** But the main beneficiary of the transfer optimization is the VACUUM
2985 ** command, and the VACUUM command disables foreign key constraints. So
2986 ** the extra complication to make this rule less restrictive is probably
2987 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
2989 assert( IsOrdinaryTable(pDest) );
2990 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
2991 return 0;
2993 #endif
2994 if( (db->flags & SQLITE_CountRows)!=0 ){
2995 return 0; /* xfer opt does not play well with PRAGMA count_changes */
2998 /* If we get this far, it means that the xfer optimization is at
2999 ** least a possibility, though it might only work if the destination
3000 ** table (tab1) is initially empty.
3002 #ifdef SQLITE_TEST
3003 sqlite3_xferopt_count++;
3004 #endif
3005 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
3006 v = sqlite3GetVdbe(pParse);
3007 sqlite3CodeVerifySchema(pParse, iDbSrc);
3008 iSrc = pParse->nTab++;
3009 iDest = pParse->nTab++;
3010 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
3011 regData = sqlite3GetTempReg(pParse);
3012 sqlite3VdbeAddOp2(v, OP_Null, 0, regData);
3013 regRowid = sqlite3GetTempReg(pParse);
3014 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
3015 assert( HasRowid(pDest) || destHasUniqueIdx );
3016 if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
3017 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
3018 || destHasUniqueIdx /* (2) */
3019 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
3021 /* In some circumstances, we are able to run the xfer optimization
3022 ** only if the destination table is initially empty. Unless the
3023 ** DBFLAG_Vacuum flag is set, this block generates code to make
3024 ** that determination. If DBFLAG_Vacuum is set, then the destination
3025 ** table is always empty.
3027 ** Conditions under which the destination must be empty:
3029 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
3030 ** (If the destination is not initially empty, the rowid fields
3031 ** of index entries might need to change.)
3033 ** (2) The destination has a unique index. (The xfer optimization
3034 ** is unable to test uniqueness.)
3036 ** (3) onError is something other than OE_Abort and OE_Rollback.
3038 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
3039 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
3040 sqlite3VdbeJumpHere(v, addr1);
3042 if( HasRowid(pSrc) ){
3043 u8 insFlags;
3044 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
3045 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
3046 if( pDest->iPKey>=0 ){
3047 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3048 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3049 sqlite3VdbeVerifyAbortable(v, onError);
3050 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
3051 VdbeCoverage(v);
3052 sqlite3RowidConstraint(pParse, onError, pDest);
3053 sqlite3VdbeJumpHere(v, addr2);
3055 autoIncStep(pParse, regAutoinc, regRowid);
3056 }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
3057 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
3058 }else{
3059 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3060 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
3063 if( db->mDbFlags & DBFLAG_Vacuum ){
3064 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3065 insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3066 }else{
3067 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT;
3069 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
3070 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3071 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3072 insFlags &= ~OPFLAG_PREFORMAT;
3073 }else
3074 #endif
3076 sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid);
3078 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
3079 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3080 sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
3082 sqlite3VdbeChangeP5(v, insFlags);
3084 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
3085 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
3086 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3087 }else{
3088 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
3089 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
3091 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
3092 u8 idxInsFlags = 0;
3093 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
3094 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
3096 assert( pSrcIdx );
3097 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
3098 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
3099 VdbeComment((v, "%s", pSrcIdx->zName));
3100 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
3101 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
3102 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
3103 VdbeComment((v, "%s", pDestIdx->zName));
3104 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
3105 if( db->mDbFlags & DBFLAG_Vacuum ){
3106 /* This INSERT command is part of a VACUUM operation, which guarantees
3107 ** that the destination table is empty. If all indexed columns use
3108 ** collation sequence BINARY, then it can also be assumed that the
3109 ** index will be populated by inserting keys in strictly sorted
3110 ** order. In this case, instead of seeking within the b-tree as part
3111 ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
3112 ** OP_IdxInsert to seek to the point within the b-tree where each key
3113 ** should be inserted. This is faster.
3115 ** If any of the indexed columns use a collation sequence other than
3116 ** BINARY, this optimization is disabled. This is because the user
3117 ** might change the definition of a collation sequence and then run
3118 ** a VACUUM command. In that case keys may not be written in strictly
3119 ** sorted order. */
3120 for(i=0; i<pSrcIdx->nColumn; i++){
3121 const char *zColl = pSrcIdx->azColl[i];
3122 if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
3124 if( i==pSrcIdx->nColumn ){
3125 idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3126 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3127 sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc);
3129 }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
3130 idxInsFlags |= OPFLAG_NCHANGE;
3132 if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){
3133 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3134 if( (db->mDbFlags & DBFLAG_Vacuum)==0
3135 && !HasRowid(pDest)
3136 && IsPrimaryKeyIndex(pDestIdx)
3138 codeWithoutRowidPreupdate(pParse, pDest, iDest, regData);
3141 sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
3142 sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
3143 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
3144 sqlite3VdbeJumpHere(v, addr1);
3145 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
3146 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3148 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
3149 sqlite3ReleaseTempReg(pParse, regRowid);
3150 sqlite3ReleaseTempReg(pParse, regData);
3151 if( emptyDestTest ){
3152 sqlite3AutoincrementEnd(pParse);
3153 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
3154 sqlite3VdbeJumpHere(v, emptyDestTest);
3155 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3156 return 0;
3157 }else{
3158 return 1;
3161 #endif /* SQLITE_OMIT_XFER_OPT */