1cce7d176Sdrh /* 2b19a2bc6Sdrh ** 2001 September 15 3cce7d176Sdrh ** 4b19a2bc6Sdrh ** The author disclaims copyright to this source code. In place of 5b19a2bc6Sdrh ** a legal notice, here is a blessing: 6cce7d176Sdrh ** 7b19a2bc6Sdrh ** May you do good and not evil. 8b19a2bc6Sdrh ** May you find forgiveness for yourself and forgive others. 9b19a2bc6Sdrh ** May you share freely, never taking more than you give. 10cce7d176Sdrh ** 11cce7d176Sdrh ************************************************************************* 12cce7d176Sdrh ** This file contains C code routines that are called by the parser 13b19a2bc6Sdrh ** to handle INSERT statements in SQLite. 14cce7d176Sdrh */ 15cce7d176Sdrh #include "sqliteInt.h" 16cce7d176Sdrh 17cce7d176Sdrh /* 1826198bb4Sdrh ** Generate code that will 19dd9930efSdrh ** 2026198bb4Sdrh ** (1) acquire a lock for table pTab then 2126198bb4Sdrh ** (2) open pTab as cursor iCur. 2226198bb4Sdrh ** 2326198bb4Sdrh ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index 2426198bb4Sdrh ** for that table that is actually opened. 25bbb5e4e0Sdrh */ 26bbb5e4e0Sdrh void sqlite3OpenTable( 272ec2fb22Sdrh Parse *pParse, /* Generate code into this VDBE */ 28bbb5e4e0Sdrh int iCur, /* The cursor number of the table */ 29bbb5e4e0Sdrh int iDb, /* The database index in sqlite3.aDb[] */ 30bbb5e4e0Sdrh Table *pTab, /* The table to be opened */ 31bbb5e4e0Sdrh int opcode /* OP_OpenRead or OP_OpenWrite */ 32bbb5e4e0Sdrh ){ 33bbb5e4e0Sdrh Vdbe *v; 345f53aac2Sdrh assert( !IsVirtual(pTab) ); 35289a0c84Sdrh assert( pParse->pVdbe!=0 ); 36289a0c84Sdrh v = pParse->pVdbe; 37bbb5e4e0Sdrh assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); 382ec2fb22Sdrh sqlite3TableLock(pParse, iDb, pTab->tnum, 392ec2fb22Sdrh (opcode==OP_OpenWrite)?1:0, pTab->zName); 40ec95c441Sdrh if( HasRowid(pTab) ){ 410b0b3a95Sdrh sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol); 42bbb5e4e0Sdrh VdbeComment((v, "%s", pTab->zName)); 4326198bb4Sdrh }else{ 44dd9930efSdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab); 45dd9930efSdrh assert( pPk!=0 ); 46afe028a8Sdrh assert( pPk->tnum==pTab->tnum ); 472ec2fb22Sdrh sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb); 482ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pPk); 49bbb5e4e0Sdrh VdbeComment((v, "%s", pTab->zName)); 50bbb5e4e0Sdrh } 51bbb5e4e0Sdrh } 52bbb5e4e0Sdrh 53bbb5e4e0Sdrh /* 5469f8bb9cSdan ** Return a pointer to the column affinity string associated with index 5569f8bb9cSdan ** pIdx. A column affinity string has one character for each column in 5669f8bb9cSdan ** the table, according to the affinity of the column: 573d1bfeaaSdanielk1977 ** 583d1bfeaaSdanielk1977 ** Character Column affinity 593d1bfeaaSdanielk1977 ** ------------------------------ 6005883a34Sdrh ** 'A' BLOB 614583c37cSdrh ** 'B' TEXT 624583c37cSdrh ** 'C' NUMERIC 634583c37cSdrh ** 'D' INTEGER 644583c37cSdrh ** 'F' REAL 652d401ab8Sdrh ** 664583c37cSdrh ** An extra 'D' is appended to the end of the string to cover the 672d401ab8Sdrh ** rowid that appears as the last column in every index. 6869f8bb9cSdan ** 6969f8bb9cSdan ** Memory for the buffer containing the column index affinity string 7069f8bb9cSdan ** is managed along with the rest of the Index structure. It will be 7169f8bb9cSdan ** released when sqlite3DeleteIndex() is called. 723d1bfeaaSdanielk1977 */ 73e9107698Sdrh const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){ 74a37cdde0Sdanielk1977 if( !pIdx->zColAff ){ 75e014a838Sdanielk1977 /* The first time a column affinity string for a particular index is 76a37cdde0Sdanielk1977 ** required, it is allocated and populated here. It is then stored as 77e014a838Sdanielk1977 ** a member of the Index structure for subsequent use. 78a37cdde0Sdanielk1977 ** 79a37cdde0Sdanielk1977 ** The column affinity string will eventually be deleted by 80e014a838Sdanielk1977 ** sqliteDeleteIndex() when the Index structure itself is cleaned 81a37cdde0Sdanielk1977 ** up. 82a37cdde0Sdanielk1977 */ 83a37cdde0Sdanielk1977 int n; 84a37cdde0Sdanielk1977 Table *pTab = pIdx->pTable; 85ad124329Sdrh pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1); 86a37cdde0Sdanielk1977 if( !pIdx->zColAff ){ 874a642b60Sdrh sqlite3OomFault(db); 8869f8bb9cSdan return 0; 89a37cdde0Sdanielk1977 } 90a37cdde0Sdanielk1977 for(n=0; n<pIdx->nColumn; n++){ 91ad124329Sdrh i16 x = pIdx->aiColumn[n]; 926860e6faSdrh char aff; 9381506b88Sdrh if( x>=0 ){ 9481506b88Sdrh aff = pTab->aCol[x].affinity; 9581506b88Sdrh }else if( x==XN_ROWID ){ 9681506b88Sdrh aff = SQLITE_AFF_INTEGER; 9781506b88Sdrh }else{ 984b92f98cSdrh assert( x==XN_EXPR ); 991f9ca2c8Sdrh assert( pIdx->aColExpr!=0 ); 1006860e6faSdrh aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr); 10181506b88Sdrh } 10296fb16eeSdrh if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB; 1037314495fSdrh if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC; 1046860e6faSdrh pIdx->zColAff[n] = aff; 1051f9ca2c8Sdrh } 1062d401ab8Sdrh pIdx->zColAff[n] = 0; 107a37cdde0Sdanielk1977 } 1083d1bfeaaSdanielk1977 10969f8bb9cSdan return pIdx->zColAff; 110a37cdde0Sdanielk1977 } 111a37cdde0Sdanielk1977 112a37cdde0Sdanielk1977 /* 11357bf4a8eSdrh ** Compute the affinity string for table pTab, if it has not already been 11405883a34Sdrh ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities. 11557bf4a8eSdrh ** 116*24384d88Sdrh ** If the affinity exists (if it is not entirely SQLITE_AFF_BLOB values) and 11757bf4a8eSdrh ** if iReg>0 then code an OP_Affinity opcode that will set the affinities 11857bf4a8eSdrh ** for register iReg and following. Or if affinities exists and iReg==0, 11957bf4a8eSdrh ** then just set the P4 operand of the previous opcode (which should be 12057bf4a8eSdrh ** an OP_MakeRecord) to the affinity string. 12157bf4a8eSdrh ** 122b6e8fd10Sdrh ** A column affinity string has one character per column: 123a37cdde0Sdanielk1977 ** 124a37cdde0Sdanielk1977 ** Character Column affinity 125a37cdde0Sdanielk1977 ** ------------------------------ 12605883a34Sdrh ** 'A' BLOB 1274583c37cSdrh ** 'B' TEXT 1284583c37cSdrh ** 'C' NUMERIC 1294583c37cSdrh ** 'D' INTEGER 1304583c37cSdrh ** 'E' REAL 131a37cdde0Sdanielk1977 */ 13257bf4a8eSdrh void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ 133ab45fc04Sdrh int i, j; 13457bf4a8eSdrh char *zColAff = pTab->zColAff; 13557bf4a8eSdrh if( zColAff==0 ){ 136abb6fcabSdrh sqlite3 *db = sqlite3VdbeDb(v); 137b975598eSdrh zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); 1383d1bfeaaSdanielk1977 if( !zColAff ){ 1394a642b60Sdrh sqlite3OomFault(db); 140a37cdde0Sdanielk1977 return; 1413d1bfeaaSdanielk1977 } 1423d1bfeaaSdanielk1977 143ab45fc04Sdrh for(i=j=0; i<pTab->nCol; i++){ 14496fb16eeSdrh assert( pTab->aCol[i].affinity!=0 ); 145ab45fc04Sdrh if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){ 146ab45fc04Sdrh zColAff[j++] = pTab->aCol[i].affinity; 147ab45fc04Sdrh } 1483d1bfeaaSdanielk1977 } 14957bf4a8eSdrh do{ 150ab45fc04Sdrh zColAff[j--] = 0; 151ab45fc04Sdrh }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB ); 1523d1bfeaaSdanielk1977 pTab->zColAff = zColAff; 1533d1bfeaaSdanielk1977 } 1547301e774Sdrh assert( zColAff!=0 ); 1557301e774Sdrh i = sqlite3Strlen30NN(zColAff); 15657bf4a8eSdrh if( i ){ 15757bf4a8eSdrh if( iReg ){ 15857bf4a8eSdrh sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i); 15957bf4a8eSdrh }else{ 16057bf4a8eSdrh sqlite3VdbeChangeP4(v, -1, zColAff, i); 16157bf4a8eSdrh } 16257bf4a8eSdrh } 1633d1bfeaaSdanielk1977 } 1643d1bfeaaSdanielk1977 1654d88778bSdanielk1977 /* 16648d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices 167b6e8fd10Sdrh ** have been opened at any point in the VDBE program. This is used to see if 16848d1178aSdrh ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can 169b6e8fd10Sdrh ** run without using a temporary table for the results of the SELECT. 1704d88778bSdanielk1977 */ 17105a86c5cSdrh static int readsTable(Parse *p, int iDb, Table *pTab){ 172595a523aSdanielk1977 Vdbe *v = sqlite3GetVdbe(p); 1734d88778bSdanielk1977 int i; 17448d1178aSdrh int iEnd = sqlite3VdbeCurrentAddr(v); 175595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 176595a523aSdanielk1977 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; 177595a523aSdanielk1977 #endif 178595a523aSdanielk1977 17905a86c5cSdrh for(i=1; i<iEnd; i++){ 18048d1178aSdrh VdbeOp *pOp = sqlite3VdbeGetOp(v, i); 181ef0bea92Sdrh assert( pOp!=0 ); 182207872a4Sdanielk1977 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ 18348d1178aSdrh Index *pIndex; 1848deae5adSdrh Pgno tnum = pOp->p2; 18548d1178aSdrh if( tnum==pTab->tnum ){ 18648d1178aSdrh return 1; 18748d1178aSdrh } 18848d1178aSdrh for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 18948d1178aSdrh if( tnum==pIndex->tnum ){ 19048d1178aSdrh return 1; 19148d1178aSdrh } 19248d1178aSdrh } 19348d1178aSdrh } 194543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 195595a523aSdanielk1977 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){ 1962dca4ac1Sdanielk1977 assert( pOp->p4.pVtab!=0 ); 19766a5167bSdrh assert( pOp->p4type==P4_VTAB ); 19848d1178aSdrh return 1; 1994d88778bSdanielk1977 } 200543165efSdrh #endif 2014d88778bSdanielk1977 } 2024d88778bSdanielk1977 return 0; 2034d88778bSdanielk1977 } 2043d1bfeaaSdanielk1977 205dfa15270Sdrh /* This walker callback will compute the union of colFlags flags for all 2067dc76d8bSdrh ** referenced columns in a CHECK constraint or generated column expression. 207dfa15270Sdrh */ 208dfa15270Sdrh static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){ 2097dc76d8bSdrh if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){ 2107dc76d8bSdrh assert( pExpr->iColumn < pWalker->u.pTab->nCol ); 211dfa15270Sdrh pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags; 212dfa15270Sdrh } 213dfa15270Sdrh return WRC_Continue; 214dfa15270Sdrh } 215dfa15270Sdrh 216c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 217c1431144Sdrh /* 218c1431144Sdrh ** All regular columns for table pTab have been puts into registers 219c1431144Sdrh ** starting with iRegStore. The registers that correspond to STORED 220dd6cc9b5Sdrh ** or VIRTUAL columns have not yet been initialized. This routine goes 221dd6cc9b5Sdrh ** back and computes the values for those columns based on the previously 222dd6cc9b5Sdrh ** computed normal columns. 223c1431144Sdrh */ 224dd6cc9b5Sdrh void sqlite3ComputeGeneratedColumns( 225c1431144Sdrh Parse *pParse, /* Parsing context */ 226c1431144Sdrh int iRegStore, /* Register holding the first column */ 227c1431144Sdrh Table *pTab /* The table */ 228c1431144Sdrh ){ 229c1431144Sdrh int i; 230dfa15270Sdrh Walker w; 231dfa15270Sdrh Column *pRedo; 232dfa15270Sdrh int eProgress; 233b5f6243fSdrh VdbeOp *pOp; 234b5f6243fSdrh 235b5f6243fSdrh assert( pTab->tabFlags & TF_HasGenerated ); 236b5f6243fSdrh testcase( pTab->tabFlags & TF_HasVirtual ); 237b5f6243fSdrh testcase( pTab->tabFlags & TF_HasStored ); 238b5f6243fSdrh 239b5f6243fSdrh /* Before computing generated columns, first go through and make sure 240b5f6243fSdrh ** that appropriate affinity has been applied to the regular columns 241b5f6243fSdrh */ 242b5f6243fSdrh sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore); 243b5f6243fSdrh if( (pTab->tabFlags & TF_HasStored)!=0 244b5f6243fSdrh && (pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1))->opcode==OP_Affinity 245b5f6243fSdrh ){ 246b5f6243fSdrh /* Change the OP_Affinity argument to '@' (NONE) for all stored 247b5f6243fSdrh ** columns. '@' is the no-op affinity and those columns have not 248b5f6243fSdrh ** yet been computed. */ 249b5f6243fSdrh int ii, jj; 250b5f6243fSdrh char *zP4 = pOp->p4.z; 251b5f6243fSdrh assert( zP4!=0 ); 252b5f6243fSdrh assert( pOp->p4type==P4_DYNAMIC ); 253b5f6243fSdrh for(ii=jj=0; zP4[jj]; ii++){ 254b5f6243fSdrh if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){ 255b5f6243fSdrh continue; 256b5f6243fSdrh } 257b5f6243fSdrh if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){ 258b5f6243fSdrh zP4[jj] = SQLITE_AFF_NONE; 259b5f6243fSdrh } 260b5f6243fSdrh jj++; 261b5f6243fSdrh } 262b5f6243fSdrh } 263dfa15270Sdrh 264dd6cc9b5Sdrh /* Because there can be multiple generated columns that refer to one another, 265dd6cc9b5Sdrh ** this is a two-pass algorithm. On the first pass, mark all generated 266dd6cc9b5Sdrh ** columns as "not available". 2679942ef0dSdrh */ 2689942ef0dSdrh for(i=0; i<pTab->nCol; i++){ 269dd6cc9b5Sdrh if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ 270ab0992f0Sdrh testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ); 271ab0992f0Sdrh testcase( pTab->aCol[i].colFlags & COLFLAG_STORED ); 2729942ef0dSdrh pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL; 2739942ef0dSdrh } 2749942ef0dSdrh } 275dfa15270Sdrh 276dfa15270Sdrh w.u.pTab = pTab; 277dfa15270Sdrh w.xExprCallback = exprColumnFlagUnion; 278dfa15270Sdrh w.xSelectCallback = 0; 279dfa15270Sdrh w.xSelectCallback2 = 0; 280dfa15270Sdrh 2819942ef0dSdrh /* On the second pass, compute the value of each NOT-AVAILABLE column. 2829942ef0dSdrh ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will 2839942ef0dSdrh ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as 2849942ef0dSdrh ** they are needed. 2859942ef0dSdrh */ 286c1431144Sdrh pParse->iSelfTab = -iRegStore; 287dfa15270Sdrh do{ 288dfa15270Sdrh eProgress = 0; 289dfa15270Sdrh pRedo = 0; 290dfa15270Sdrh for(i=0; i<pTab->nCol; i++){ 291dfa15270Sdrh Column *pCol = pTab->aCol + i; 292dfa15270Sdrh if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){ 293dfa15270Sdrh int x; 294dfa15270Sdrh pCol->colFlags |= COLFLAG_BUSY; 295dfa15270Sdrh w.eCode = 0; 296dfa15270Sdrh sqlite3WalkExpr(&w, pCol->pDflt); 297dfa15270Sdrh pCol->colFlags &= ~COLFLAG_BUSY; 298dfa15270Sdrh if( w.eCode & COLFLAG_NOTAVAIL ){ 299dfa15270Sdrh pRedo = pCol; 300dfa15270Sdrh continue; 301dd6cc9b5Sdrh } 302dfa15270Sdrh eProgress = 1; 303dfa15270Sdrh assert( pCol->colFlags & COLFLAG_GENERATED ); 304dfa15270Sdrh x = sqlite3TableColumnToStorage(pTab, i) + iRegStore; 305dfa15270Sdrh sqlite3ExprCodeGeneratedColumn(pParse, pCol, x); 306dfa15270Sdrh pCol->colFlags &= ~COLFLAG_NOTAVAIL; 307c1431144Sdrh } 308dfa15270Sdrh } 309dfa15270Sdrh }while( pRedo && eProgress ); 310dfa15270Sdrh if( pRedo ){ 311dfa15270Sdrh sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zName); 312c1431144Sdrh } 313c1431144Sdrh pParse->iSelfTab = 0; 314c1431144Sdrh } 315c1431144Sdrh #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 316c1431144Sdrh 317c1431144Sdrh 3189d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 3199d9cf229Sdrh /* 3200b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab 3210b9f50d8Sdrh ** which is in database iDb. Return the register number for the register 3229ef5e770Sdrh ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT 3239ef5e770Sdrh ** table. (Also return zero when doing a VACUUM since we do not want to 3249ef5e770Sdrh ** update the AUTOINCREMENT counters during a VACUUM.) 3259d9cf229Sdrh ** 3260b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the 3270b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within 3280b9f50d8Sdrh ** triggers. A new AutoincInfo structure is created if this is the 3290b9f50d8Sdrh ** first use of table pTab. On 2nd and subsequent uses, the original 3300b9f50d8Sdrh ** AutoincInfo structure is used. 3319d9cf229Sdrh ** 332c8abbc11Sdrh ** Four consecutive registers are allocated: 3330b9f50d8Sdrh ** 334c8abbc11Sdrh ** (1) The name of the pTab table. 335c8abbc11Sdrh ** (2) The maximum ROWID of pTab. 336c8abbc11Sdrh ** (3) The rowid in sqlite_sequence of pTab 337c8abbc11Sdrh ** (4) The original value of the max ROWID in pTab, or NULL if none 3380b9f50d8Sdrh ** 3390b9f50d8Sdrh ** The 2nd register is the one that is returned. That is all the 3400b9f50d8Sdrh ** insert routine needs to know about. 3419d9cf229Sdrh */ 3429d9cf229Sdrh static int autoIncBegin( 3439d9cf229Sdrh Parse *pParse, /* Parsing context */ 3449d9cf229Sdrh int iDb, /* Index of the database holding pTab */ 3459d9cf229Sdrh Table *pTab /* The table we are writing to */ 3469d9cf229Sdrh ){ 3476a288a33Sdrh int memId = 0; /* Register holding maximum rowid */ 348186ebd41Sdrh assert( pParse->db->aDb[iDb].pSchema!=0 ); 3499ef5e770Sdrh if( (pTab->tabFlags & TF_Autoincrement)!=0 3508257aa8dSdrh && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0 3519ef5e770Sdrh ){ 35265a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 3530b9f50d8Sdrh AutoincInfo *pInfo; 354186ebd41Sdrh Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab; 355186ebd41Sdrh 356186ebd41Sdrh /* Verify that the sqlite_sequence table exists and is an ordinary 357186ebd41Sdrh ** rowid table with exactly two columns. 358186ebd41Sdrh ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */ 359186ebd41Sdrh if( pSeqTab==0 360186ebd41Sdrh || !HasRowid(pSeqTab) 3610003d878Sdrh || NEVER(IsVirtual(pSeqTab)) 362186ebd41Sdrh || pSeqTab->nCol!=2 363186ebd41Sdrh ){ 364186ebd41Sdrh pParse->nErr++; 365186ebd41Sdrh pParse->rc = SQLITE_CORRUPT_SEQUENCE; 366186ebd41Sdrh return 0; 367186ebd41Sdrh } 3680b9f50d8Sdrh 36965a7cd16Sdan pInfo = pToplevel->pAinc; 3700b9f50d8Sdrh while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } 3710b9f50d8Sdrh if( pInfo==0 ){ 372575fad65Sdrh pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo)); 37321d4f5b5Sdrh sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo); 37421d4f5b5Sdrh testcase( pParse->earlyCleanup ); 37521d4f5b5Sdrh if( pParse->db->mallocFailed ) return 0; 37665a7cd16Sdan pInfo->pNext = pToplevel->pAinc; 37765a7cd16Sdan pToplevel->pAinc = pInfo; 3780b9f50d8Sdrh pInfo->pTab = pTab; 3790b9f50d8Sdrh pInfo->iDb = iDb; 38065a7cd16Sdan pToplevel->nMem++; /* Register to hold name of table */ 38165a7cd16Sdan pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ 382c8abbc11Sdrh pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */ 3830b9f50d8Sdrh } 3840b9f50d8Sdrh memId = pInfo->regCtr; 3859d9cf229Sdrh } 3869d9cf229Sdrh return memId; 3879d9cf229Sdrh } 3889d9cf229Sdrh 3899d9cf229Sdrh /* 3900b9f50d8Sdrh ** This routine generates code that will initialize all of the 3910b9f50d8Sdrh ** register used by the autoincrement tracker. 3920b9f50d8Sdrh */ 3930b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){ 3940b9f50d8Sdrh AutoincInfo *p; /* Information about an AUTOINCREMENT */ 3950b9f50d8Sdrh sqlite3 *db = pParse->db; /* The database connection */ 3960b9f50d8Sdrh Db *pDb; /* Database only autoinc table */ 3970b9f50d8Sdrh int memId; /* Register holding max rowid */ 3980b9f50d8Sdrh Vdbe *v = pParse->pVdbe; /* VDBE under construction */ 3990b9f50d8Sdrh 400345ba7dbSdrh /* This routine is never called during trigger-generation. It is 401345ba7dbSdrh ** only called from the top-level */ 402345ba7dbSdrh assert( pParse->pTriggerTab==0 ); 403c149f18fSdrh assert( sqlite3IsToplevel(pParse) ); 40476d462eeSdan 4050b9f50d8Sdrh assert( v ); /* We failed long ago if this is not so */ 4060b9f50d8Sdrh for(p = pParse->pAinc; p; p = p->pNext){ 4071b32554bSdrh static const int iLn = VDBE_OFFSET_LINENO(2); 4081b32554bSdrh static const VdbeOpList autoInc[] = { 4091b32554bSdrh /* 0 */ {OP_Null, 0, 0, 0}, 410c8abbc11Sdrh /* 1 */ {OP_Rewind, 0, 10, 0}, 4111b32554bSdrh /* 2 */ {OP_Column, 0, 0, 0}, 412c8abbc11Sdrh /* 3 */ {OP_Ne, 0, 9, 0}, 4131b32554bSdrh /* 4 */ {OP_Rowid, 0, 0, 0}, 4141b32554bSdrh /* 5 */ {OP_Column, 0, 1, 0}, 415c8abbc11Sdrh /* 6 */ {OP_AddImm, 0, 0, 0}, 416c8abbc11Sdrh /* 7 */ {OP_Copy, 0, 0, 0}, 417c8abbc11Sdrh /* 8 */ {OP_Goto, 0, 11, 0}, 418c8abbc11Sdrh /* 9 */ {OP_Next, 0, 2, 0}, 419c8abbc11Sdrh /* 10 */ {OP_Integer, 0, 0, 0}, 420c8abbc11Sdrh /* 11 */ {OP_Close, 0, 0, 0} 4211b32554bSdrh }; 4221b32554bSdrh VdbeOp *aOp; 4230b9f50d8Sdrh pDb = &db->aDb[p->iDb]; 4240b9f50d8Sdrh memId = p->regCtr; 4252120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 4260b9f50d8Sdrh sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); 427076e85f5Sdrh sqlite3VdbeLoadString(v, memId-1, p->pTab->zName); 4281b32554bSdrh aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn); 4291b32554bSdrh if( aOp==0 ) break; 4301b32554bSdrh aOp[0].p2 = memId; 431c8abbc11Sdrh aOp[0].p3 = memId+2; 4321b32554bSdrh aOp[2].p3 = memId; 4331b32554bSdrh aOp[3].p1 = memId-1; 4341b32554bSdrh aOp[3].p3 = memId; 4351b32554bSdrh aOp[3].p5 = SQLITE_JUMPIFNULL; 4361b32554bSdrh aOp[4].p2 = memId+1; 4371b32554bSdrh aOp[5].p3 = memId; 438c8abbc11Sdrh aOp[6].p1 = memId; 439c8abbc11Sdrh aOp[7].p2 = memId+2; 440c8abbc11Sdrh aOp[7].p1 = memId; 441c8abbc11Sdrh aOp[10].p2 = memId; 44204ab586bSdrh if( pParse->nTab==0 ) pParse->nTab = 1; 4430b9f50d8Sdrh } 4440b9f50d8Sdrh } 4450b9f50d8Sdrh 4460b9f50d8Sdrh /* 4479d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation. 4489d9cf229Sdrh ** 4491b32554bSdrh ** This routine should be called when the regRowid register holds a 4509d9cf229Sdrh ** new rowid that is about to be inserted. If that new rowid is 4519d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the 4521b32554bSdrh ** memory cell is updated. 4539d9cf229Sdrh */ 4546a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){ 4559d9cf229Sdrh if( memId>0 ){ 4566a288a33Sdrh sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); 4579d9cf229Sdrh } 4589d9cf229Sdrh } 4599d9cf229Sdrh 4609d9cf229Sdrh /* 4610b9f50d8Sdrh ** This routine generates the code needed to write autoincrement 4620b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register. 4630b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement 4640b9f50d8Sdrh ** table (either directly or through triggers) needs to call this 4650b9f50d8Sdrh ** routine just before the "exit" code. 4669d9cf229Sdrh */ 4671b32554bSdrh static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ 4680b9f50d8Sdrh AutoincInfo *p; 4699d9cf229Sdrh Vdbe *v = pParse->pVdbe; 4700b9f50d8Sdrh sqlite3 *db = pParse->db; 4716a288a33Sdrh 4729d9cf229Sdrh assert( v ); 4730b9f50d8Sdrh for(p = pParse->pAinc; p; p = p->pNext){ 4741b32554bSdrh static const int iLn = VDBE_OFFSET_LINENO(2); 4751b32554bSdrh static const VdbeOpList autoIncEnd[] = { 4761b32554bSdrh /* 0 */ {OP_NotNull, 0, 2, 0}, 4771b32554bSdrh /* 1 */ {OP_NewRowid, 0, 0, 0}, 4781b32554bSdrh /* 2 */ {OP_MakeRecord, 0, 2, 0}, 4791b32554bSdrh /* 3 */ {OP_Insert, 0, 0, 0}, 4801b32554bSdrh /* 4 */ {OP_Close, 0, 0, 0} 4811b32554bSdrh }; 4821b32554bSdrh VdbeOp *aOp; 4830b9f50d8Sdrh Db *pDb = &db->aDb[p->iDb]; 4840b9f50d8Sdrh int iRec; 4850b9f50d8Sdrh int memId = p->regCtr; 4860b9f50d8Sdrh 4870b9f50d8Sdrh iRec = sqlite3GetTempReg(pParse); 4882120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 489c8abbc11Sdrh sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId); 490c8abbc11Sdrh VdbeCoverage(v); 4910b9f50d8Sdrh sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); 4921b32554bSdrh aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn); 4931b32554bSdrh if( aOp==0 ) break; 4941b32554bSdrh aOp[0].p1 = memId+1; 4951b32554bSdrh aOp[1].p2 = memId+1; 4961b32554bSdrh aOp[2].p1 = memId-1; 4971b32554bSdrh aOp[2].p3 = iRec; 4981b32554bSdrh aOp[3].p2 = iRec; 4991b32554bSdrh aOp[3].p3 = memId+1; 5001b32554bSdrh aOp[3].p5 = OPFLAG_APPEND; 5010b9f50d8Sdrh sqlite3ReleaseTempReg(pParse, iRec); 5029d9cf229Sdrh } 5039d9cf229Sdrh } 5041b32554bSdrh void sqlite3AutoincrementEnd(Parse *pParse){ 5051b32554bSdrh if( pParse->pAinc ) autoIncrementEnd(pParse); 5061b32554bSdrh } 5079d9cf229Sdrh #else 5089d9cf229Sdrh /* 5099d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines 5109d9cf229Sdrh ** above are all no-ops 5119d9cf229Sdrh */ 5129d9cf229Sdrh # define autoIncBegin(A,B,C) (0) 513287fb61cSdanielk1977 # define autoIncStep(A,B,C) 5149d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */ 5159d9cf229Sdrh 5169d9cf229Sdrh 5179d9cf229Sdrh /* Forward declaration */ 5189d9cf229Sdrh static int xferOptimization( 5199d9cf229Sdrh Parse *pParse, /* Parser context */ 5209d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 5219d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 5229d9cf229Sdrh int onError, /* How to handle constraint errors */ 5239d9cf229Sdrh int iDbDest /* The database of pDest */ 5249d9cf229Sdrh ); 5259d9cf229Sdrh 5263d1bfeaaSdanielk1977 /* 527d82b5021Sdrh ** This routine is called to handle SQL of the following forms: 528cce7d176Sdrh ** 529a21f78b9Sdrh ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),... 5301ccde15dSdrh ** insert into TABLE (IDLIST) select 531a21f78b9Sdrh ** insert into TABLE (IDLIST) default values 532cce7d176Sdrh ** 5331ccde15dSdrh ** The IDLIST following the table name is always optional. If omitted, 534a21f78b9Sdrh ** then a list of all (non-hidden) columns for the table is substituted. 535a21f78b9Sdrh ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST 536a21f78b9Sdrh ** is omitted. 5371ccde15dSdrh ** 538a21f78b9Sdrh ** For the pSelect parameter holds the values to be inserted for the 539a21f78b9Sdrh ** first two forms shown above. A VALUES clause is really just short-hand 540a21f78b9Sdrh ** for a SELECT statement that omits the FROM clause and everything else 541a21f78b9Sdrh ** that follows. If the pSelect parameter is NULL, that means that the 542a21f78b9Sdrh ** DEFAULT VALUES form of the INSERT statement is intended. 543142e30dfSdrh ** 5449d9cf229Sdrh ** The code generated follows one of four templates. For a simple 545a21f78b9Sdrh ** insert with data coming from a single-row VALUES clause, the code executes 546e00ee6ebSdrh ** once straight down through. Pseudo-code follows (we call this 547e00ee6ebSdrh ** the "1st template"): 548142e30dfSdrh ** 549142e30dfSdrh ** open write cursor to <table> and its indices 550ec95c441Sdrh ** put VALUES clause expressions into registers 551142e30dfSdrh ** write the resulting record into <table> 552142e30dfSdrh ** cleanup 553142e30dfSdrh ** 5549d9cf229Sdrh ** The three remaining templates assume the statement is of the form 555142e30dfSdrh ** 556142e30dfSdrh ** INSERT INTO <table> SELECT ... 557142e30dfSdrh ** 5589d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - 5599d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table 5609d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and 5619d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical 5629d9cf229Sdrh ** schemas, including all the same indices, then a special optimization 5639d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>. 5649d9cf229Sdrh ** See the xferOptimization() function for the implementation of this 565e00ee6ebSdrh ** template. This is the 2nd template. 5669d9cf229Sdrh ** 5679d9cf229Sdrh ** open a write cursor to <table> 5689d9cf229Sdrh ** open read cursor on <table2> 5699d9cf229Sdrh ** transfer all records in <table2> over to <table> 5709d9cf229Sdrh ** close cursors 5719d9cf229Sdrh ** foreach index on <table> 5729d9cf229Sdrh ** open a write cursor on the <table> index 5739d9cf229Sdrh ** open a read cursor on the corresponding <table2> index 5749d9cf229Sdrh ** transfer all records from the read to the write cursors 5759d9cf229Sdrh ** close cursors 5769d9cf229Sdrh ** end foreach 5779d9cf229Sdrh ** 578e00ee6ebSdrh ** The 3rd template is for when the second template does not apply 5799d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time. 5809d9cf229Sdrh ** The generated code follows this template: 581142e30dfSdrh ** 582e00ee6ebSdrh ** X <- A 583142e30dfSdrh ** goto B 584142e30dfSdrh ** A: setup for the SELECT 5859d9cf229Sdrh ** loop over the rows in the SELECT 586e00ee6ebSdrh ** load values into registers R..R+n 587e00ee6ebSdrh ** yield X 588142e30dfSdrh ** end loop 589142e30dfSdrh ** cleanup after the SELECT 59081cf13ecSdrh ** end-coroutine X 591e00ee6ebSdrh ** B: open write cursor to <table> and its indices 59281cf13ecSdrh ** C: yield X, at EOF goto D 593e00ee6ebSdrh ** insert the select result into <table> from R..R+n 594e00ee6ebSdrh ** goto C 595142e30dfSdrh ** D: cleanup 596142e30dfSdrh ** 597e00ee6ebSdrh ** The 4th template is used if the insert statement takes its 598142e30dfSdrh ** values from a SELECT but the data is being inserted into a table 599142e30dfSdrh ** that is also read as part of the SELECT. In the third form, 60060ec914cSpeter.d.reid ** we have to use an intermediate table to store the results of 601142e30dfSdrh ** the select. The template is like this: 602142e30dfSdrh ** 603e00ee6ebSdrh ** X <- A 604142e30dfSdrh ** goto B 605142e30dfSdrh ** A: setup for the SELECT 606142e30dfSdrh ** loop over the tables in the SELECT 607e00ee6ebSdrh ** load value into register R..R+n 608e00ee6ebSdrh ** yield X 609142e30dfSdrh ** end loop 610142e30dfSdrh ** cleanup after the SELECT 61181cf13ecSdrh ** end co-routine R 612e00ee6ebSdrh ** B: open temp table 61381cf13ecSdrh ** L: yield X, at EOF goto M 614e00ee6ebSdrh ** insert row from R..R+n into temp table 615e00ee6ebSdrh ** goto L 616e00ee6ebSdrh ** M: open write cursor to <table> and its indices 617e00ee6ebSdrh ** rewind temp table 618e00ee6ebSdrh ** C: loop over rows of intermediate table 619142e30dfSdrh ** transfer values form intermediate table into <table> 620e00ee6ebSdrh ** end loop 621e00ee6ebSdrh ** D: cleanup 622cce7d176Sdrh */ 6234adee20fSdanielk1977 void sqlite3Insert( 624cce7d176Sdrh Parse *pParse, /* Parser context */ 625113088ecSdrh SrcList *pTabList, /* Name of table into which we are inserting */ 6265974a30fSdrh Select *pSelect, /* A SELECT statement to use as the data source */ 627f5f1915dSdrh IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */ 6282c2e844aSdrh int onError, /* How to handle constraint errors */ 62946d2e5c3Sdrh Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */ 630cce7d176Sdrh ){ 6316a288a33Sdrh sqlite3 *db; /* The main database structure */ 6326a288a33Sdrh Table *pTab; /* The table to insert into. aka TABLE */ 63360ffc807Sdrh int i, j; /* Loop counters */ 6345974a30fSdrh Vdbe *v; /* Generate code into this virtual machine */ 6355974a30fSdrh Index *pIdx; /* For looping over indices of the table */ 636967e8b73Sdrh int nColumn; /* Number of columns in the data */ 6376a288a33Sdrh int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ 63826198bb4Sdrh int iDataCur = 0; /* VDBE cursor that is the main data repository */ 63926198bb4Sdrh int iIdxCur = 0; /* First index cursor */ 640d82b5021Sdrh int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ 6410ca3e24bSdrh int endOfLoop; /* Label for the end of the insertion loop */ 642cfe9a69fSdanielk1977 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ 643e00ee6ebSdrh int addrInsTop = 0; /* Jump to label "D" */ 644e00ee6ebSdrh int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ 6452eb95377Sdrh SelectDest dest; /* Destination for SELECT on rhs of INSERT */ 6466a288a33Sdrh int iDb; /* Index of database holding TABLE */ 64705a86c5cSdrh u8 useTempTable = 0; /* Store SELECT results in intermediate table */ 64805a86c5cSdrh u8 appendFlag = 0; /* True if the insert is likely to be an append */ 64905a86c5cSdrh u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ 650a21f78b9Sdrh u8 bIdListInOrder; /* True if IDLIST is in table order */ 65175593d96Sdrh ExprList *pList = 0; /* List of VALUES() to be inserted */ 652c27ea2aeSdrh int iRegStore; /* Register in which to store next column */ 653cce7d176Sdrh 6546a288a33Sdrh /* Register allocations */ 6551bd10f8aSdrh int regFromSelect = 0;/* Base register for data coming from SELECT */ 6566a288a33Sdrh int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ 6576a288a33Sdrh int regRowCount = 0; /* Memory cell used for the row counter */ 6586a288a33Sdrh int regIns; /* Block of regs holding rowid+data being inserted */ 6596a288a33Sdrh int regRowid; /* registers holding insert rowid */ 6606a288a33Sdrh int regData; /* register holding first column to insert */ 661aa9b8963Sdrh int *aRegIdx = 0; /* One register allocated to each index */ 6626a288a33Sdrh 663798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER 664798da52cSdrh int isView; /* True if attempting to insert into a view */ 6652f886d1dSdanielk1977 Trigger *pTrigger; /* List of triggers on pTab, if required */ 6662f886d1dSdanielk1977 int tmask; /* Mask of trigger times */ 667798da52cSdrh #endif 668c3f9bad2Sdanielk1977 66917435752Sdrh db = pParse->db; 67017435752Sdrh if( pParse->nErr || db->mallocFailed ){ 6716f7adc8aSdrh goto insert_cleanup; 6726f7adc8aSdrh } 6734c883487Sdrh dest.iSDParm = 0; /* Suppress a harmless compiler warning */ 674daffd0e5Sdrh 67575593d96Sdrh /* If the Select object is really just a simple VALUES() list with a 676a21f78b9Sdrh ** single row (the common case) then keep that one row of values 677a21f78b9Sdrh ** and discard the other (unused) parts of the pSelect object 67875593d96Sdrh */ 67975593d96Sdrh if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){ 68075593d96Sdrh pList = pSelect->pEList; 68175593d96Sdrh pSelect->pEList = 0; 68275593d96Sdrh sqlite3SelectDelete(db, pSelect); 68375593d96Sdrh pSelect = 0; 68475593d96Sdrh } 68575593d96Sdrh 6861ccde15dSdrh /* Locate the table into which we will be inserting new information. 6871ccde15dSdrh */ 688113088ecSdrh assert( pTabList->nSrc==1 ); 6894adee20fSdanielk1977 pTab = sqlite3SrcListLookup(pParse, pTabList); 690c3f9bad2Sdanielk1977 if( pTab==0 ){ 691c3f9bad2Sdanielk1977 goto insert_cleanup; 692c3f9bad2Sdanielk1977 } 693da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 694da184236Sdanielk1977 assert( iDb<db->nDb ); 695a0daa751Sdrh if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, 696a0daa751Sdrh db->aDb[iDb].zDbSName) ){ 6971962bda7Sdrh goto insert_cleanup; 6981962bda7Sdrh } 699ec95c441Sdrh withoutRowid = !HasRowid(pTab); 700c3f9bad2Sdanielk1977 701b7f9164eSdrh /* Figure out if we have any triggers and if the table being 702b7f9164eSdrh ** inserted into is a view 703b7f9164eSdrh */ 704b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER 7052f886d1dSdanielk1977 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); 706b7f9164eSdrh isView = pTab->pSelect!=0; 707b7f9164eSdrh #else 7082f886d1dSdanielk1977 # define pTrigger 0 7092f886d1dSdanielk1977 # define tmask 0 710b7f9164eSdrh # define isView 0 711b7f9164eSdrh #endif 712b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW 713b7f9164eSdrh # undef isView 714b7f9164eSdrh # define isView 0 715b7f9164eSdrh #endif 7162f886d1dSdanielk1977 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); 717b7f9164eSdrh 718f573c99bSdrh /* If pTab is really a view, make sure it has been initialized. 719d82b5021Sdrh ** ViewGetColumnNames() is a no-op if pTab is not a view. 720f573c99bSdrh */ 721b3d24bf8Sdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 722f573c99bSdrh goto insert_cleanup; 723f573c99bSdrh } 724f573c99bSdrh 725d82b5021Sdrh /* Cannot insert into a read-only table. 726595a523aSdanielk1977 */ 727595a523aSdanielk1977 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ 728595a523aSdanielk1977 goto insert_cleanup; 729595a523aSdanielk1977 } 730595a523aSdanielk1977 7311ccde15dSdrh /* Allocate a VDBE 7321ccde15dSdrh */ 7334adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 7345974a30fSdrh if( v==0 ) goto insert_cleanup; 7354794f735Sdrh if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 7362f886d1dSdanielk1977 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); 7371ccde15dSdrh 7389d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 7399d9cf229Sdrh /* If the statement is of the form 7409d9cf229Sdrh ** 7419d9cf229Sdrh ** INSERT INTO <table1> SELECT * FROM <table2>; 7429d9cf229Sdrh ** 7439d9cf229Sdrh ** Then special optimizations can be applied that make the transfer 7449d9cf229Sdrh ** very fast and which reduce fragmentation of indices. 745e00ee6ebSdrh ** 746e00ee6ebSdrh ** This is the 2nd template. 7479d9cf229Sdrh */ 7489d9cf229Sdrh if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ 7492f886d1dSdanielk1977 assert( !pTrigger ); 7509d9cf229Sdrh assert( pList==0 ); 7510b9f50d8Sdrh goto insert_end; 7529d9cf229Sdrh } 7539d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 7549d9cf229Sdrh 7552958a4e6Sdrh /* If this is an AUTOINCREMENT table, look up the sequence number in the 7566a288a33Sdrh ** sqlite_sequence table and store it in memory cell regAutoinc. 7572958a4e6Sdrh */ 7586a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDb, pTab); 7592958a4e6Sdrh 760f5f1915dSdrh /* Allocate a block registers to hold the rowid and the values 761f5f1915dSdrh ** for all columns of the new row. 7621ccde15dSdrh */ 76305a86c5cSdrh regRowid = regIns = pParse->nMem+1; 76405a86c5cSdrh pParse->nMem += pTab->nCol + 1; 765034ca14fSdanielk1977 if( IsVirtual(pTab) ){ 76605a86c5cSdrh regRowid++; 76705a86c5cSdrh pParse->nMem++; 768034ca14fSdanielk1977 } 76905a86c5cSdrh regData = regRowid+1; 7701ccde15dSdrh 7711ccde15dSdrh /* If the INSERT statement included an IDLIST term, then make sure 7721ccde15dSdrh ** all elements of the IDLIST really are columns of the table and 7731ccde15dSdrh ** remember the column indices. 774c8392586Sdrh ** 775c8392586Sdrh ** If the table has an INTEGER PRIMARY KEY column and that column 776d82b5021Sdrh ** is named in the IDLIST, then record in the ipkColumn variable 777d82b5021Sdrh ** the index into IDLIST of the primary key column. ipkColumn is 778c8392586Sdrh ** the index of the primary key as it appears in IDLIST, not as 779d82b5021Sdrh ** is appears in the original table. (The index of the INTEGER 780f5f1915dSdrh ** PRIMARY KEY in the original table is pTab->iPKey.) After this 781f5f1915dSdrh ** loop, if ipkColumn==(-1), that means that integer primary key 782f5f1915dSdrh ** is unspecified, and hence the table is either WITHOUT ROWID or 783f5f1915dSdrh ** it will automatically generated an integer primary key. 784f5f1915dSdrh ** 785f5f1915dSdrh ** bIdListInOrder is true if the columns in IDLIST are in storage 786f5f1915dSdrh ** order. This enables an optimization that avoids shuffling the 787f5f1915dSdrh ** columns into storage order. False negatives are harmless, 788f5f1915dSdrh ** but false positives will cause database corruption. 7891ccde15dSdrh */ 790d4cd292cSdrh bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0; 791967e8b73Sdrh if( pColumn ){ 792967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 793967e8b73Sdrh pColumn->a[i].idx = -1; 794cce7d176Sdrh } 795967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 796cce7d176Sdrh for(j=0; j<pTab->nCol; j++){ 7974adee20fSdanielk1977 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ 798967e8b73Sdrh pColumn->a[i].idx = j; 79905a86c5cSdrh if( i!=j ) bIdListInOrder = 0; 8004a32431cSdrh if( j==pTab->iPKey ){ 801d82b5021Sdrh ipkColumn = i; assert( !withoutRowid ); 8024a32431cSdrh } 8037e508f1eSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 8047e508f1eSdrh if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){ 8057e508f1eSdrh sqlite3ErrorMsg(pParse, 8067e508f1eSdrh "cannot INSERT into generated column \"%s\"", 8077e508f1eSdrh pTab->aCol[j].zName); 8087e508f1eSdrh goto insert_cleanup; 8097e508f1eSdrh } 8107e508f1eSdrh #endif 811cce7d176Sdrh break; 812cce7d176Sdrh } 813cce7d176Sdrh } 814cce7d176Sdrh if( j>=pTab->nCol ){ 815ec95c441Sdrh if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ 816d82b5021Sdrh ipkColumn = i; 817e48ae715Sdrh bIdListInOrder = 0; 818a0217ba7Sdrh }else{ 8194adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %S has no column named %s", 820a979993bSdrh pTabList->a, pColumn->a[i].zName); 8211db95106Sdan pParse->checkSchema = 1; 822cce7d176Sdrh goto insert_cleanup; 823cce7d176Sdrh } 824cce7d176Sdrh } 825cce7d176Sdrh } 826a0217ba7Sdrh } 8271ccde15dSdrh 828cce7d176Sdrh /* Figure out how many columns of data are supplied. If the data 829cce7d176Sdrh ** is coming from a SELECT statement, then generate a co-routine that 830cce7d176Sdrh ** produces a single row of the SELECT on each invocation. The 831cce7d176Sdrh ** co-routine is the common header to the 3rd and 4th templates. 832cce7d176Sdrh */ 8335f085269Sdrh if( pSelect ){ 834a21f78b9Sdrh /* Data is coming from a SELECT or from a multi-row VALUES clause. 835a21f78b9Sdrh ** Generate a co-routine to run the SELECT. */ 83605a86c5cSdrh int regYield; /* Register holding co-routine entry-point */ 83705a86c5cSdrh int addrTop; /* Top of the co-routine */ 83805a86c5cSdrh int rc; /* Result code */ 839cce7d176Sdrh 84005a86c5cSdrh regYield = ++pParse->nMem; 84105a86c5cSdrh addrTop = sqlite3VdbeCurrentAddr(v) + 1; 84205a86c5cSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 84305a86c5cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 84405a86c5cSdrh dest.iSdst = bIdListInOrder ? regData : 0; 84505a86c5cSdrh dest.nSdst = pTab->nCol; 84605a86c5cSdrh rc = sqlite3Select(pParse, pSelect, &dest); 8472b596da8Sdrh regFromSelect = dest.iSdst; 848992590beSdrh if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup; 8492fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regYield); 85005a86c5cSdrh sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ 851cce7d176Sdrh assert( pSelect->pEList ); 852cce7d176Sdrh nColumn = pSelect->pEList->nExpr; 853cce7d176Sdrh 854cce7d176Sdrh /* Set useTempTable to TRUE if the result of the SELECT statement 855cce7d176Sdrh ** should be written into a temporary table (template 4). Set to 856cce7d176Sdrh ** FALSE if each output row of the SELECT can be written directly into 857cce7d176Sdrh ** the destination table (template 3). 858cce7d176Sdrh ** 859cce7d176Sdrh ** A temp table must be used if the table being updated is also one 860cce7d176Sdrh ** of the tables being read by the SELECT statement. Also use a 861cce7d176Sdrh ** temp table in the case of row triggers. 862cce7d176Sdrh */ 86305a86c5cSdrh if( pTrigger || readsTable(pParse, iDb, pTab) ){ 864cce7d176Sdrh useTempTable = 1; 865cce7d176Sdrh } 866cce7d176Sdrh 867cce7d176Sdrh if( useTempTable ){ 868cce7d176Sdrh /* Invoke the coroutine to extract information from the SELECT 869cce7d176Sdrh ** and add it to a transient table srcTab. The code generated 870cce7d176Sdrh ** here is from the 4th template: 871cce7d176Sdrh ** 872cce7d176Sdrh ** B: open temp table 87381cf13ecSdrh ** L: yield X, goto M at EOF 874cce7d176Sdrh ** insert row from R..R+n into temp table 875cce7d176Sdrh ** goto L 876cce7d176Sdrh ** M: ... 877cce7d176Sdrh */ 878cce7d176Sdrh int regRec; /* Register to hold packed record */ 879cce7d176Sdrh int regTempRowid; /* Register to hold temp table ROWID */ 88006280ee5Sdrh int addrL; /* Label "L" */ 881cce7d176Sdrh 882cce7d176Sdrh srcTab = pParse->nTab++; 883cce7d176Sdrh regRec = sqlite3GetTempReg(pParse); 884cce7d176Sdrh regTempRowid = sqlite3GetTempReg(pParse); 885cce7d176Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); 88606280ee5Sdrh addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); 887cce7d176Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); 888cce7d176Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); 889cce7d176Sdrh sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); 890076e85f5Sdrh sqlite3VdbeGoto(v, addrL); 89106280ee5Sdrh sqlite3VdbeJumpHere(v, addrL); 892cce7d176Sdrh sqlite3ReleaseTempReg(pParse, regRec); 893cce7d176Sdrh sqlite3ReleaseTempReg(pParse, regTempRowid); 894cce7d176Sdrh } 895cce7d176Sdrh }else{ 896a21f78b9Sdrh /* This is the case if the data for the INSERT is coming from a 897a21f78b9Sdrh ** single-row VALUES clause 898cce7d176Sdrh */ 899cce7d176Sdrh NameContext sNC; 900cce7d176Sdrh memset(&sNC, 0, sizeof(sNC)); 901cce7d176Sdrh sNC.pParse = pParse; 902cce7d176Sdrh srcTab = -1; 903cce7d176Sdrh assert( useTempTable==0 ); 904fea870beSdrh if( pList ){ 905fea870beSdrh nColumn = pList->nExpr; 906fea870beSdrh if( sqlite3ResolveExprListNames(&sNC, pList) ){ 907cce7d176Sdrh goto insert_cleanup; 908cce7d176Sdrh } 909fea870beSdrh }else{ 910fea870beSdrh nColumn = 0; 911cce7d176Sdrh } 912cce7d176Sdrh } 913cce7d176Sdrh 914aacc543eSdrh /* If there is no IDLIST term but the table has an integer primary 915d82b5021Sdrh ** key, the set the ipkColumn variable to the integer primary key 916d82b5021Sdrh ** column index in the original table definition. 9174a32431cSdrh */ 918147d0cccSdrh if( pColumn==0 && nColumn>0 ){ 919d82b5021Sdrh ipkColumn = pTab->iPKey; 920427b96aeSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 9216ab61d70Sdrh if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){ 922427b96aeSdrh testcase( pTab->tabFlags & TF_HasVirtual ); 9236ab61d70Sdrh testcase( pTab->tabFlags & TF_HasStored ); 924427b96aeSdrh for(i=ipkColumn-1; i>=0; i--){ 925427b96aeSdrh if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ 926427b96aeSdrh testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ); 9276ab61d70Sdrh testcase( pTab->aCol[i].colFlags & COLFLAG_STORED ); 928427b96aeSdrh ipkColumn--; 929427b96aeSdrh } 930427b96aeSdrh } 931427b96aeSdrh } 932427b96aeSdrh #endif 9334a32431cSdrh 934cce7d176Sdrh /* Make sure the number of columns in the source data matches the number 935cce7d176Sdrh ** of columns to be inserted into the table. 936cce7d176Sdrh */ 9376f6e60ddSdrh assert( TF_HasHidden==COLFLAG_HIDDEN ); 9386f6e60ddSdrh assert( TF_HasGenerated==COLFLAG_GENERATED ); 9396f6e60ddSdrh assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) ); 9406f6e60ddSdrh if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){ 941cce7d176Sdrh for(i=0; i<pTab->nCol; i++){ 9427e508f1eSdrh if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++; 943cce7d176Sdrh } 944c7e93f58Sdrh } 945c7e93f58Sdrh if( nColumn!=(pTab->nCol-nHidden) ){ 946cce7d176Sdrh sqlite3ErrorMsg(pParse, 947cce7d176Sdrh "table %S has %d columns but %d values were supplied", 948a979993bSdrh pTabList->a, pTab->nCol-nHidden, nColumn); 949cce7d176Sdrh goto insert_cleanup; 950cce7d176Sdrh } 951c7e93f58Sdrh } 952cce7d176Sdrh if( pColumn!=0 && nColumn!=pColumn->nId ){ 953cce7d176Sdrh sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 954cce7d176Sdrh goto insert_cleanup; 955cce7d176Sdrh } 956cce7d176Sdrh 957c3f9bad2Sdanielk1977 /* Initialize the count of rows to be inserted 9581ccde15dSdrh */ 95979636913Sdrh if( (db->flags & SQLITE_CountRows)!=0 96079636913Sdrh && !pParse->nested 96179636913Sdrh && !pParse->pTriggerTab 962d086aa0aSdrh && !pParse->bReturning 96379636913Sdrh ){ 9646a288a33Sdrh regRowCount = ++pParse->nMem; 9656a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 966c3f9bad2Sdanielk1977 } 967c3f9bad2Sdanielk1977 968e448dc4aSdanielk1977 /* If this is not a view, open the table and and all indices */ 969e448dc4aSdanielk1977 if( !isView ){ 970aa9b8963Sdrh int nIdx; 971fd261ec6Sdan nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0, 97226198bb4Sdrh &iDataCur, &iIdxCur); 973a7c3b93fSdrh aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2)); 974aa9b8963Sdrh if( aRegIdx==0 ){ 975aa9b8963Sdrh goto insert_cleanup; 976aa9b8963Sdrh } 9772c4dfc30Sdrh for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){ 9782c4dfc30Sdrh assert( pIdx ); 979aa9b8963Sdrh aRegIdx[i] = ++pParse->nMem; 9802c4dfc30Sdrh pParse->nMem += pIdx->nColumn; 981aa9b8963Sdrh } 982a7c3b93fSdrh aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */ 983feeb1394Sdrh } 984788d55aaSdrh #ifndef SQLITE_OMIT_UPSERT 9850b30a116Sdrh if( pUpsert ){ 98620b86324Sdrh Upsert *pNx; 987b042d921Sdrh if( IsVirtual(pTab) ){ 988b042d921Sdrh sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"", 989b042d921Sdrh pTab->zName); 990b042d921Sdrh goto insert_cleanup; 991b042d921Sdrh } 992c6b24ab1Sdrh if( pTab->pSelect ){ 993c6b24ab1Sdrh sqlite3ErrorMsg(pParse, "cannot UPSERT a view"); 994c6b24ab1Sdrh goto insert_cleanup; 995c6b24ab1Sdrh } 9969105fd51Sdan if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){ 9979105fd51Sdan goto insert_cleanup; 9989105fd51Sdan } 999788d55aaSdrh pTabList->a[0].iCursor = iDataCur; 100020b86324Sdrh pNx = pUpsert; 100120b86324Sdrh do{ 100220b86324Sdrh pNx->pUpsertSrc = pTabList; 100320b86324Sdrh pNx->regData = regData; 100420b86324Sdrh pNx->iDataCur = iDataCur; 100520b86324Sdrh pNx->iIdxCur = iIdxCur; 100620b86324Sdrh if( pNx->pUpsertTarget ){ 100793eb9064Sdan if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx) ){ 100893eb9064Sdan goto insert_cleanup; 100993eb9064Sdan } 1010788d55aaSdrh } 101120b86324Sdrh pNx = pNx->pNextUpsert; 101220b86324Sdrh }while( pNx!=0 ); 10130b30a116Sdrh } 1014788d55aaSdrh #endif 1015788d55aaSdrh 1016feeb1394Sdrh 1017e00ee6ebSdrh /* This is the top of the main insertion loop */ 1018142e30dfSdrh if( useTempTable ){ 1019e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 1020e00ee6ebSdrh ** following pseudocode (template 4): 1021e00ee6ebSdrh ** 102281cf13ecSdrh ** rewind temp table, if empty goto D 1023e00ee6ebSdrh ** C: loop over rows of intermediate table 1024e00ee6ebSdrh ** transfer values form intermediate table into <table> 1025e00ee6ebSdrh ** end loop 1026e00ee6ebSdrh ** D: ... 1027e00ee6ebSdrh */ 1028688852abSdrh addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); 1029e00ee6ebSdrh addrCont = sqlite3VdbeCurrentAddr(v); 1030142e30dfSdrh }else if( pSelect ){ 1031e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 1032e00ee6ebSdrh ** following pseudocode (template 3): 1033e00ee6ebSdrh ** 103481cf13ecSdrh ** C: yield X, at EOF goto D 1035e00ee6ebSdrh ** insert the select result into <table> from R..R+n 1036e00ee6ebSdrh ** goto C 1037e00ee6ebSdrh ** D: ... 1038e00ee6ebSdrh */ 10393aef2fb1Sdrh sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0); 104081cf13ecSdrh addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 1041688852abSdrh VdbeCoverage(v); 1042f5f1915dSdrh if( ipkColumn>=0 ){ 1043f5f1915dSdrh /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the 1044f5f1915dSdrh ** SELECT, go ahead and copy the value into the rowid slot now, so that 1045f5f1915dSdrh ** the value does not get overwritten by a NULL at tag-20191021-002. */ 1046f5f1915dSdrh sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); 1047bed8690fSdrh } 1048f5f1915dSdrh } 1049f5f1915dSdrh 1050f5f1915dSdrh /* Compute data for ordinary columns of the new entry. Values 1051f5f1915dSdrh ** are written in storage order into registers starting with regData. 1052f5f1915dSdrh ** Only ordinary columns are computed in this loop. The rowid 1053f5f1915dSdrh ** (if there is one) is computed later and generated columns are 1054f5f1915dSdrh ** computed after the rowid since they might depend on the value 1055f5f1915dSdrh ** of the rowid. 1056f5f1915dSdrh */ 1057f5f1915dSdrh nHidden = 0; 1058f5f1915dSdrh iRegStore = regData; assert( regData==regRowid+1 ); 1059f5f1915dSdrh for(i=0; i<pTab->nCol; i++, iRegStore++){ 1060f5f1915dSdrh int k; 1061f5f1915dSdrh u32 colFlags; 1062f5f1915dSdrh assert( i>=nHidden ); 1063f5f1915dSdrh if( i==pTab->iPKey ){ 1064f5f1915dSdrh /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled 1065f5f1915dSdrh ** using the rowid. So put a NULL in the IPK slot of the record to avoid 1066f5f1915dSdrh ** using excess space. The file format definition requires this extra 1067f5f1915dSdrh ** NULL - we cannot optimize further by skipping the column completely */ 1068f5f1915dSdrh sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); 1069f5f1915dSdrh continue; 1070f5f1915dSdrh } 1071f5f1915dSdrh if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){ 1072f5f1915dSdrh nHidden++; 1073f5f1915dSdrh if( (colFlags & COLFLAG_VIRTUAL)!=0 ){ 1074f5f1915dSdrh /* Virtual columns do not participate in OP_MakeRecord. So back up 1075f5f1915dSdrh ** iRegStore by one slot to compensate for the iRegStore++ in the 1076f5f1915dSdrh ** outer for() loop */ 1077f5f1915dSdrh iRegStore--; 1078f5f1915dSdrh continue; 1079f5f1915dSdrh }else if( (colFlags & COLFLAG_STORED)!=0 ){ 1080f5f1915dSdrh /* Stored columns are computed later. But if there are BEFORE 1081f5f1915dSdrh ** triggers, the slots used for stored columns will be OP_Copy-ed 1082f5f1915dSdrh ** to a second block of registers, so the register needs to be 1083f5f1915dSdrh ** initialized to NULL to avoid an uninitialized register read */ 1084f5f1915dSdrh if( tmask & TRIGGER_BEFORE ){ 1085f5f1915dSdrh sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); 1086f5f1915dSdrh } 1087f5f1915dSdrh continue; 1088f5f1915dSdrh }else if( pColumn==0 ){ 1089f5f1915dSdrh /* Hidden columns that are not explicitly named in the INSERT 1090f5f1915dSdrh ** get there default value */ 1091f5f1915dSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 1092f5f1915dSdrh continue; 1093f5f1915dSdrh } 1094f5f1915dSdrh } 1095f5f1915dSdrh if( pColumn ){ 1096f5f1915dSdrh for(j=0; j<pColumn->nId && pColumn->a[j].idx!=i; j++){} 1097f5f1915dSdrh if( j>=pColumn->nId ){ 1098f5f1915dSdrh /* A column not named in the insert column list gets its 1099f5f1915dSdrh ** default value */ 1100f5f1915dSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 1101f5f1915dSdrh continue; 1102f5f1915dSdrh } 1103f5f1915dSdrh k = j; 1104f5f1915dSdrh }else if( nColumn==0 ){ 1105f5f1915dSdrh /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */ 1106f5f1915dSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 1107f5f1915dSdrh continue; 1108f5f1915dSdrh }else{ 1109f5f1915dSdrh k = i - nHidden; 1110f5f1915dSdrh } 1111f5f1915dSdrh 1112f5f1915dSdrh if( useTempTable ){ 1113f5f1915dSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore); 1114f5f1915dSdrh }else if( pSelect ){ 1115f5f1915dSdrh if( regFromSelect!=regData ){ 1116f5f1915dSdrh sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore); 1117f5f1915dSdrh } 1118f5f1915dSdrh }else{ 1119f5f1915dSdrh sqlite3ExprCode(pParse, pList->a[k].pExpr, iRegStore); 1120f5f1915dSdrh } 1121f5f1915dSdrh } 1122f5f1915dSdrh 11231ccde15dSdrh 11245cf590c1Sdrh /* Run the BEFORE and INSTEAD OF triggers, if there are any 112570ce3f0cSdrh */ 1126ec4ccdbcSdrh endOfLoop = sqlite3VdbeMakeLabel(pParse); 11272f886d1dSdanielk1977 if( tmask & TRIGGER_BEFORE ){ 112876d462eeSdan int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); 1129c3f9bad2Sdanielk1977 113070ce3f0cSdrh /* build the NEW.* reference row. Note that if there is an INTEGER 113170ce3f0cSdrh ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 113270ce3f0cSdrh ** translated into a unique ID for the row. But on a BEFORE trigger, 113370ce3f0cSdrh ** we do not know what the unique ID will be (because the insert has 113470ce3f0cSdrh ** not happened yet) so we substitute a rowid of -1 113570ce3f0cSdrh */ 1136d82b5021Sdrh if( ipkColumn<0 ){ 113776d462eeSdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 113870ce3f0cSdrh }else{ 1139728e0f91Sdrh int addr1; 1140ec95c441Sdrh assert( !withoutRowid ); 11417fe45908Sdrh if( useTempTable ){ 1142d82b5021Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); 11437fe45908Sdrh }else{ 1144d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 1145d82b5021Sdrh sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); 11467fe45908Sdrh } 1147728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); 114876d462eeSdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 1149728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 1150688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); 115170ce3f0cSdrh } 115270ce3f0cSdrh 1153f5f1915dSdrh /* Copy the new data already generated. */ 1154f5f1915dSdrh assert( pTab->nNVCol>0 ); 1155f5f1915dSdrh sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1); 1156f5f1915dSdrh 1157f5f1915dSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1158f5f1915dSdrh /* Compute the new value for generated columns after all other 1159f5f1915dSdrh ** columns have already been computed. This must be done after 1160f5f1915dSdrh ** computing the ROWID in case one of the generated columns 1161f5f1915dSdrh ** refers to the ROWID. */ 1162427b96aeSdrh if( pTab->tabFlags & TF_HasGenerated ){ 1163427b96aeSdrh testcase( pTab->tabFlags & TF_HasVirtual ); 1164427b96aeSdrh testcase( pTab->tabFlags & TF_HasStored ); 1165f5f1915dSdrh sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab); 1166c3f9bad2Sdanielk1977 } 1167f5f1915dSdrh #endif 1168a37cdde0Sdanielk1977 1169a37cdde0Sdanielk1977 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 1170a37cdde0Sdanielk1977 ** do not attempt any conversions before assembling the record. 1171a37cdde0Sdanielk1977 ** If this is a real table, attempt conversions as required by the 1172a37cdde0Sdanielk1977 ** table column affinities. 1173a37cdde0Sdanielk1977 */ 1174a37cdde0Sdanielk1977 if( !isView ){ 117557bf4a8eSdrh sqlite3TableAffinity(v, pTab, regCols+1); 1176a37cdde0Sdanielk1977 } 1177c3f9bad2Sdanielk1977 11785cf590c1Sdrh /* Fire BEFORE or INSTEAD OF triggers */ 1179165921a7Sdan sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 118094d7f50aSdan pTab, regCols-pTab->nCol-1, onError, endOfLoop); 1181165921a7Sdan 118276d462eeSdan sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); 118370ce3f0cSdrh } 1184c3f9bad2Sdanielk1977 11855cf590c1Sdrh if( !isView ){ 11864cbdda9eSdrh if( IsVirtual(pTab) ){ 11874cbdda9eSdrh /* The row that the VUpdate opcode will delete: none */ 11886a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); 11894cbdda9eSdrh } 1190d82b5021Sdrh if( ipkColumn>=0 ){ 1191f5f1915dSdrh /* Compute the new rowid */ 1192142e30dfSdrh if( useTempTable ){ 1193d82b5021Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); 1194142e30dfSdrh }else if( pSelect ){ 1195f5f1915dSdrh /* Rowid already initialized at tag-20191021-001 */ 11964a32431cSdrh }else{ 119704fcef00Sdrh Expr *pIpk = pList->a[ipkColumn].pExpr; 119804fcef00Sdrh if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){ 119904fcef00Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 1200e4d90813Sdrh appendFlag = 1; 120104fcef00Sdrh }else{ 120204fcef00Sdrh sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); 1203e4d90813Sdrh } 120427a32783Sdrh } 1205f0863fe5Sdrh /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 1206e1e68f49Sdrh ** to generate a unique primary key value. 1207e1e68f49Sdrh */ 1208e4d90813Sdrh if( !appendFlag ){ 1209728e0f91Sdrh int addr1; 1210bb50e7adSdanielk1977 if( !IsVirtual(pTab) ){ 1211728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); 121226198bb4Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 1213728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 1214bb50e7adSdanielk1977 }else{ 1215728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 1216728e0f91Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); 1217bb50e7adSdanielk1977 } 1218688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); 1219e4d90813Sdrh } 1220ec95c441Sdrh }else if( IsVirtual(pTab) || withoutRowid ){ 12216a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); 12224a32431cSdrh }else{ 122326198bb4Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 1224e4d90813Sdrh appendFlag = 1; 12254a32431cSdrh } 12266a288a33Sdrh autoIncStep(pParse, regAutoinc, regRowid); 12274a32431cSdrh 1228c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1229dd6cc9b5Sdrh /* Compute the new value for generated columns after all other 1230f5f1915dSdrh ** columns have already been computed. This must be done after 1231f5f1915dSdrh ** computing the ROWID in case one of the generated columns 1232b5f6243fSdrh ** is derived from the INTEGER PRIMARY KEY. */ 1233427b96aeSdrh if( pTab->tabFlags & TF_HasGenerated ){ 1234dd6cc9b5Sdrh sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab); 12354a32431cSdrh } 1236c1431144Sdrh #endif 12371ccde15dSdrh 12380ca3e24bSdrh /* Generate code to check constraints and generate index keys and 12390ca3e24bSdrh ** do the insertion. 12404a32431cSdrh */ 12414cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 12424cbdda9eSdrh if( IsVirtual(pTab) ){ 1243595a523aSdanielk1977 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 12444f3dd150Sdrh sqlite3VtabMakeWritable(pParse, pTab); 1245595a523aSdanielk1977 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); 1246b061d058Sdan sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); 1247e0af83acSdan sqlite3MayAbort(pParse); 12484cbdda9eSdrh }else 12494cbdda9eSdrh #endif 12504cbdda9eSdrh { 125111fbee24Sdan int isReplace = 0;/* Set to true if constraints may cause a replace */ 12523b908d41Sdan int bUseSeek; /* True to use OPFLAG_SEEKRESULT */ 1253f8ffb278Sdrh sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, 1254788d55aaSdrh regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert 125504adf416Sdrh ); 12568ff2d956Sdan sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); 12573b908d41Sdan 12583b908d41Sdan /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE 12593b908d41Sdan ** constraints or (b) there are no triggers and this table is not a 12603b908d41Sdan ** parent table in a foreign key constraint. It is safe to set the 12613b908d41Sdan ** flag in the second case as if any REPLACE constraint is hit, an 12623b908d41Sdan ** OP_Delete or OP_IdxDelete instruction will be executed on each 12633b908d41Sdan ** cursor that is disturbed. And these instructions both clear the 12643b908d41Sdan ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT 12653b908d41Sdan ** functionality. */ 126606baba54Sdrh bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v)); 126726198bb4Sdrh sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, 12683b908d41Sdan regIns, aRegIdx, 0, appendFlag, bUseSeek 12693b908d41Sdan ); 12705cf590c1Sdrh } 12716e5020e8Sdrh #ifdef SQLITE_ALLOW_ROWID_IN_VIEW 12722a1aeaa3Sdan }else if( pParse->bReturning ){ 12732a1aeaa3Sdan /* If there is a RETURNING clause, populate the rowid register with 12742a1aeaa3Sdan ** constant value -1, in case one or more of the returned expressions 12752a1aeaa3Sdan ** refer to the "rowid" of the view. */ 12762a1aeaa3Sdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid); 12776e5020e8Sdrh #endif 12784cbdda9eSdrh } 12791bee3d7bSdrh 1280feeb1394Sdrh /* Update the count of rows that are inserted 12811bee3d7bSdrh */ 128279636913Sdrh if( regRowCount ){ 12836a288a33Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 12841bee3d7bSdrh } 1285c3f9bad2Sdanielk1977 12862f886d1dSdanielk1977 if( pTrigger ){ 1287c3f9bad2Sdanielk1977 /* Code AFTER triggers */ 1288165921a7Sdan sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 128994d7f50aSdan pTab, regData-2-pTab->nCol, onError, endOfLoop); 1290c3f9bad2Sdanielk1977 } 12911bee3d7bSdrh 1292e00ee6ebSdrh /* The bottom of the main insertion loop, if the data source 1293e00ee6ebSdrh ** is a SELECT statement. 12941ccde15dSdrh */ 12954adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, endOfLoop); 1296142e30dfSdrh if( useTempTable ){ 1297688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); 1298e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 12992eb95377Sdrh sqlite3VdbeAddOp1(v, OP_Close, srcTab); 1300142e30dfSdrh }else if( pSelect ){ 1301076e85f5Sdrh sqlite3VdbeGoto(v, addrCont); 1302d9670abbSdrh #ifdef SQLITE_DEBUG 1303d9670abbSdrh /* If we are jumping back to an OP_Yield that is preceded by an 1304d9670abbSdrh ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the 1305d9670abbSdrh ** OP_ReleaseReg will be included in the loop. */ 1306d9670abbSdrh if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){ 1307d9670abbSdrh assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield ); 1308d9670abbSdrh sqlite3VdbeChangeP5(v, 1); 1309d9670abbSdrh } 1310d9670abbSdrh #endif 1311e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 13126b56344dSdrh } 1313c3f9bad2Sdanielk1977 1314d6665c51Smistachkin #ifndef SQLITE_OMIT_XFER_OPT 13150b9f50d8Sdrh insert_end: 1316d6665c51Smistachkin #endif /* SQLITE_OMIT_XFER_OPT */ 1317f3388144Sdrh /* Update the sqlite_sequence table by storing the content of the 13180b9f50d8Sdrh ** maximum rowid counter values recorded while inserting into 13190b9f50d8Sdrh ** autoincrement tables. 13202958a4e6Sdrh */ 1321165921a7Sdan if( pParse->nested==0 && pParse->pTriggerTab==0 ){ 13220b9f50d8Sdrh sqlite3AutoincrementEnd(pParse); 13230b9f50d8Sdrh } 13242958a4e6Sdrh 13251bee3d7bSdrh /* 1326e7de6f25Sdanielk1977 ** Return the number of rows inserted. If this routine is 1327e7de6f25Sdanielk1977 ** generating code because of a call to sqlite3NestedParse(), do not 1328e7de6f25Sdanielk1977 ** invoke the callback function. 13291bee3d7bSdrh */ 133079636913Sdrh if( regRowCount ){ 133118e56072Sdrh sqlite3VdbeAddOp2(v, OP_ChngCntRow, regRowCount, 1); 133222322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, 1); 133310fb749bSdanielk1977 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); 13341bee3d7bSdrh } 1335cce7d176Sdrh 1336cce7d176Sdrh insert_cleanup: 1337633e6d57Sdrh sqlite3SrcListDelete(db, pTabList); 1338633e6d57Sdrh sqlite3ExprListDelete(db, pList); 133946d2e5c3Sdrh sqlite3UpsertDelete(db, pUpsert); 1340633e6d57Sdrh sqlite3SelectDelete(db, pSelect); 1341633e6d57Sdrh sqlite3IdListDelete(db, pColumn); 1342633e6d57Sdrh sqlite3DbFree(db, aRegIdx); 1343cce7d176Sdrh } 13449cfcf5d4Sdrh 134575cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise 134660ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file 134775cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation). */ 134875cbd984Sdan #ifdef isView 134975cbd984Sdan #undef isView 135075cbd984Sdan #endif 135175cbd984Sdan #ifdef pTrigger 135275cbd984Sdan #undef pTrigger 135375cbd984Sdan #endif 135475cbd984Sdan #ifdef tmask 135575cbd984Sdan #undef tmask 135675cbd984Sdan #endif 135775cbd984Sdan 13589cfcf5d4Sdrh /* 1359e9816d82Sdrh ** Meanings of bits in of pWalker->eCode for 1360e9816d82Sdrh ** sqlite3ExprReferencesUpdatedColumn() 136198bfa16dSdrh */ 136298bfa16dSdrh #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */ 136398bfa16dSdrh #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */ 136498bfa16dSdrh 1365e9816d82Sdrh /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn(). 1366e9816d82Sdrh * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this 1367e9816d82Sdrh ** expression node references any of the 13682a0b527bSdrh ** columns that are being modifed by an UPDATE statement. 13692a0b527bSdrh */ 13702a0b527bSdrh static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){ 137198bfa16dSdrh if( pExpr->op==TK_COLUMN ){ 137298bfa16dSdrh assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 ); 137398bfa16dSdrh if( pExpr->iColumn>=0 ){ 137498bfa16dSdrh if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){ 137598bfa16dSdrh pWalker->eCode |= CKCNSTRNT_COLUMN; 137698bfa16dSdrh } 137798bfa16dSdrh }else{ 137898bfa16dSdrh pWalker->eCode |= CKCNSTRNT_ROWID; 137998bfa16dSdrh } 13802a0b527bSdrh } 13812a0b527bSdrh return WRC_Continue; 13822a0b527bSdrh } 13832a0b527bSdrh 13842a0b527bSdrh /* 13852a0b527bSdrh ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The 13862a0b527bSdrh ** only columns that are modified by the UPDATE are those for which 138798bfa16dSdrh ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true. 138898bfa16dSdrh ** 1389e9816d82Sdrh ** Return true if CHECK constraint pExpr uses any of the 139098bfa16dSdrh ** changing columns (or the rowid if it is changing). In other words, 1391e9816d82Sdrh ** return true if this CHECK constraint must be validated for 139298bfa16dSdrh ** the new row in the UPDATE statement. 1393e9816d82Sdrh ** 1394e9816d82Sdrh ** 2018-09-15: pExpr might also be an expression for an index-on-expressions. 1395e9816d82Sdrh ** The operation of this routine is the same - return true if an only if 1396e9816d82Sdrh ** the expression uses one or more of columns identified by the second and 1397e9816d82Sdrh ** third arguments. 13982a0b527bSdrh */ 1399e9816d82Sdrh int sqlite3ExprReferencesUpdatedColumn( 1400e9816d82Sdrh Expr *pExpr, /* The expression to be checked */ 1401e9816d82Sdrh int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */ 1402e9816d82Sdrh int chngRowid /* True if UPDATE changes the rowid */ 1403e9816d82Sdrh ){ 14042a0b527bSdrh Walker w; 14052a0b527bSdrh memset(&w, 0, sizeof(w)); 140698bfa16dSdrh w.eCode = 0; 14072a0b527bSdrh w.xExprCallback = checkConstraintExprNode; 14082a0b527bSdrh w.u.aiCol = aiChng; 14092a0b527bSdrh sqlite3WalkExpr(&w, pExpr); 141005723a9eSdrh if( !chngRowid ){ 141105723a9eSdrh testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 ); 141205723a9eSdrh w.eCode &= ~CKCNSTRNT_ROWID; 141305723a9eSdrh } 141405723a9eSdrh testcase( w.eCode==0 ); 141505723a9eSdrh testcase( w.eCode==CKCNSTRNT_COLUMN ); 141605723a9eSdrh testcase( w.eCode==CKCNSTRNT_ROWID ); 141705723a9eSdrh testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) ); 1418e9816d82Sdrh return w.eCode!=0; 14192a0b527bSdrh } 14202a0b527bSdrh 142111e85273Sdrh /* 1422daf2761cSdrh ** The sqlite3GenerateConstraintChecks() routine usually wants to visit 1423daf2761cSdrh ** the indexes of a table in the order provided in the Table->pIndex list. 1424daf2761cSdrh ** However, sometimes (rarely - when there is an upsert) it wants to visit 1425daf2761cSdrh ** the indexes in a different order. The following data structures accomplish 1426daf2761cSdrh ** this. 1427daf2761cSdrh ** 1428daf2761cSdrh ** The IndexIterator object is used to walk through all of the indexes 1429daf2761cSdrh ** of a table in either Index.pNext order, or in some other order established 1430daf2761cSdrh ** by an array of IndexListTerm objects. 1431daf2761cSdrh */ 1432daf2761cSdrh typedef struct IndexListTerm IndexListTerm; 1433daf2761cSdrh typedef struct IndexIterator IndexIterator; 1434daf2761cSdrh struct IndexIterator { 1435daf2761cSdrh int eType; /* 0 for Index.pNext list. 1 for an array of IndexListTerm */ 1436daf2761cSdrh int i; /* Index of the current item from the list */ 1437daf2761cSdrh union { 1438daf2761cSdrh struct { /* Use this object for eType==0: A Index.pNext list */ 1439daf2761cSdrh Index *pIdx; /* The current Index */ 1440daf2761cSdrh } lx; 1441daf2761cSdrh struct { /* Use this object for eType==1; Array of IndexListTerm */ 1442daf2761cSdrh int nIdx; /* Size of the array */ 1443daf2761cSdrh IndexListTerm *aIdx; /* Array of IndexListTerms */ 1444daf2761cSdrh } ax; 1445daf2761cSdrh } u; 1446daf2761cSdrh }; 1447daf2761cSdrh 1448daf2761cSdrh /* When IndexIterator.eType==1, then each index is an array of instances 1449daf2761cSdrh ** of the following object 1450daf2761cSdrh */ 1451daf2761cSdrh struct IndexListTerm { 1452daf2761cSdrh Index *p; /* The index */ 1453daf2761cSdrh int ix; /* Which entry in the original Table.pIndex list is this index*/ 1454daf2761cSdrh }; 1455daf2761cSdrh 1456daf2761cSdrh /* Return the first index on the list */ 1457daf2761cSdrh static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){ 1458ed4c5469Sdrh assert( pIter->i==0 ); 1459ed4c5469Sdrh if( pIter->eType ){ 1460ed4c5469Sdrh *pIx = pIter->u.ax.aIdx[0].ix; 1461ed4c5469Sdrh return pIter->u.ax.aIdx[0].p; 1462ed4c5469Sdrh }else{ 1463ed4c5469Sdrh *pIx = 0; 1464ed4c5469Sdrh return pIter->u.lx.pIdx; 1465ed4c5469Sdrh } 1466daf2761cSdrh } 1467daf2761cSdrh 1468daf2761cSdrh /* Return the next index from the list. Return NULL when out of indexes */ 1469daf2761cSdrh static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){ 1470daf2761cSdrh if( pIter->eType ){ 1471d3e21a10Sdrh int i = ++pIter->i; 147261e280adSdrh if( i>=pIter->u.ax.nIdx ){ 147361e280adSdrh *pIx = i; 147461e280adSdrh return 0; 147561e280adSdrh } 1476daf2761cSdrh *pIx = pIter->u.ax.aIdx[i].ix; 1477daf2761cSdrh return pIter->u.ax.aIdx[i].p; 1478daf2761cSdrh }else{ 1479d3e21a10Sdrh ++(*pIx); 1480daf2761cSdrh pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext; 1481daf2761cSdrh return pIter->u.lx.pIdx; 1482daf2761cSdrh } 1483daf2761cSdrh } 1484daf2761cSdrh 1485daf2761cSdrh /* 14866934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE 14876934fc7bSdrh ** on table pTab. 14889cfcf5d4Sdrh ** 14896934fc7bSdrh ** The regNewData parameter is the first register in a range that contains 14906934fc7bSdrh ** the data to be inserted or the data after the update. There will be 14916934fc7bSdrh ** pTab->nCol+1 registers in this range. The first register (the one 14926934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the 14936934fc7bSdrh ** case of a WITHOUT ROWID table. The second register in the range will 14946934fc7bSdrh ** contain the content of the first table column. The third register will 14956934fc7bSdrh ** contain the content of the second table column. And so forth. 14960ca3e24bSdrh ** 1497f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains 1498f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards. regOldData is zero 1499f8ffb278Sdrh ** for an INSERT. This routine can distinguish between UPDATE and INSERT by 1500f8ffb278Sdrh ** checking regOldData for zero. 15010ca3e24bSdrh ** 1502f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the 1503f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) 1504f8ffb278Sdrh ** might be modified by the UPDATE. If pkChng is false, then the key of 1505f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE. 15060ca3e24bSdrh ** 1507f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid 1508f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement. If pkChng 1509f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or 1510f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, 1511f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer 1512f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias. 15130ca3e24bSdrh ** 15146934fc7bSdrh ** The code generated by this routine will store new index entries into 1515aa9b8963Sdrh ** registers identified by aRegIdx[]. No index entry is created for 1516aa9b8963Sdrh ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is 1517aa9b8963Sdrh ** the same as the order of indices on the linked list of indices 15186934fc7bSdrh ** at pTab->pIndex. 15196934fc7bSdrh ** 1520a7c3b93fSdrh ** (2019-05-07) The generated code also creates a new record for the 1521a7c3b93fSdrh ** main table, if pTab is a rowid table, and stores that record in the 1522a7c3b93fSdrh ** register identified by aRegIdx[nIdx] - in other words in the first 1523a7c3b93fSdrh ** entry of aRegIdx[] past the last index. It is important that the 1524a7c3b93fSdrh ** record be generated during constraint checks to avoid affinity changes 1525a7c3b93fSdrh ** to the register content that occur after constraint checks but before 1526a7c3b93fSdrh ** the new record is inserted. 1527a7c3b93fSdrh ** 15286934fc7bSdrh ** The caller must have already opened writeable cursors on the main 15296934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which 15306934fc7bSdrh ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when 15316934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY 15326934fc7bSdrh ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor 15336934fc7bSdrh ** for the first index in the pTab->pIndex list. Cursors for other indices 15346934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list. 15359cfcf5d4Sdrh ** 15369cfcf5d4Sdrh ** This routine also generates code to check constraints. NOT NULL, 15379cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 15381c92853dSdrh ** then the appropriate action is performed. There are five possible 15391c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 15409cfcf5d4Sdrh ** 15419cfcf5d4Sdrh ** Constraint type Action What Happens 15429cfcf5d4Sdrh ** --------------- ---------- ---------------------------------------- 15431c92853dSdrh ** any ROLLBACK The current transaction is rolled back and 15446934fc7bSdrh ** sqlite3_step() returns immediately with a 15459cfcf5d4Sdrh ** return code of SQLITE_CONSTRAINT. 15469cfcf5d4Sdrh ** 15471c92853dSdrh ** any ABORT Back out changes from the current command 15481c92853dSdrh ** only (do not do a complete rollback) then 15496934fc7bSdrh ** cause sqlite3_step() to return immediately 15501c92853dSdrh ** with SQLITE_CONSTRAINT. 15511c92853dSdrh ** 15526934fc7bSdrh ** any FAIL Sqlite3_step() returns immediately with a 15531c92853dSdrh ** return code of SQLITE_CONSTRAINT. The 15541c92853dSdrh ** transaction is not rolled back and any 15556934fc7bSdrh ** changes to prior rows are retained. 15561c92853dSdrh ** 15576934fc7bSdrh ** any IGNORE The attempt in insert or update the current 15586934fc7bSdrh ** row is skipped, without throwing an error. 15596934fc7bSdrh ** Processing continues with the next row. 15606934fc7bSdrh ** (There is an immediate jump to ignoreDest.) 15619cfcf5d4Sdrh ** 15629cfcf5d4Sdrh ** NOT NULL REPLACE The NULL value is replace by the default 15639cfcf5d4Sdrh ** value for that column. If the default value 15649cfcf5d4Sdrh ** is NULL, the action is the same as ABORT. 15659cfcf5d4Sdrh ** 15669cfcf5d4Sdrh ** UNIQUE REPLACE The other row that conflicts with the row 15679cfcf5d4Sdrh ** being inserted is removed. 15689cfcf5d4Sdrh ** 15699cfcf5d4Sdrh ** CHECK REPLACE Illegal. The results in an exception. 15709cfcf5d4Sdrh ** 15711c92853dSdrh ** Which action to take is determined by the overrideError parameter. 15721c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter 15731c92853dSdrh ** is used. Or if pParse->onError==OE_Default then the onError value 15741c92853dSdrh ** for the constraint is used. 15759cfcf5d4Sdrh */ 15764adee20fSdanielk1977 void sqlite3GenerateConstraintChecks( 15779cfcf5d4Sdrh Parse *pParse, /* The parser context */ 15786934fc7bSdrh Table *pTab, /* The table being inserted or updated */ 1579f8ffb278Sdrh int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ 15806934fc7bSdrh int iDataCur, /* Canonical data cursor (main table or PK index) */ 158126198bb4Sdrh int iIdxCur, /* First index cursor */ 15826934fc7bSdrh int regNewData, /* First register in a range holding values to insert */ 1583f8ffb278Sdrh int regOldData, /* Previous content. 0 for INSERTs */ 1584f8ffb278Sdrh u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ 1585f8ffb278Sdrh u8 overrideError, /* Override onError to this if not OE_Default */ 1586de630353Sdanielk1977 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ 1587bdb00225Sdrh int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */ 1588788d55aaSdrh int *aiChng, /* column i is unchanged if aiChng[i]<0 */ 1589788d55aaSdrh Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */ 15909cfcf5d4Sdrh ){ 15911b7ecbb4Sdrh Vdbe *v; /* VDBE under constrution */ 15921b7ecbb4Sdrh Index *pIdx; /* Pointer to one of the indices */ 1593e84ad92fSdrh Index *pPk = 0; /* The PRIMARY KEY index for WITHOUT ROWID tables */ 15942938f924Sdrh sqlite3 *db; /* Database connection */ 1595f8ffb278Sdrh int i; /* loop counter */ 1596f8ffb278Sdrh int ix; /* Index loop counter */ 15979cfcf5d4Sdrh int nCol; /* Number of columns */ 15989cfcf5d4Sdrh int onError; /* Conflict resolution strategy */ 15991b7ecbb4Sdrh int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ 16006fbe41acSdrh int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ 160161e280adSdrh Upsert *pUpsertClause = 0; /* The specific ON CONFLICT clause for pIdx */ 16028d1b82e4Sdrh u8 isUpdate; /* True if this is an UPDATE operation */ 160357bf4a8eSdrh u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ 160461e280adSdrh int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */ 160561e280adSdrh int upsertIpkDelay = 0; /* Address of Goto to bypass initial IPK check */ 160684304506Sdrh int ipkTop = 0; /* Top of the IPK uniqueness check */ 160784304506Sdrh int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */ 1608a407eccbSdrh /* Variables associated with retesting uniqueness constraints after 1609a407eccbSdrh ** replace triggers fire have run */ 1610a407eccbSdrh int regTrigCnt; /* Register used to count replace trigger invocations */ 1611a407eccbSdrh int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */ 1612a407eccbSdrh int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */ 1613a407eccbSdrh Trigger *pTrigger; /* List of DELETE triggers on the table pTab */ 1614a407eccbSdrh int nReplaceTrig = 0; /* Number of replace triggers coded */ 161561e280adSdrh IndexIterator sIdxIter; /* Index iterator */ 16169cfcf5d4Sdrh 1617f8ffb278Sdrh isUpdate = regOldData!=0; 16182938f924Sdrh db = pParse->db; 1619f0b41745Sdrh v = pParse->pVdbe; 16209cfcf5d4Sdrh assert( v!=0 ); 1621417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 16229cfcf5d4Sdrh nCol = pTab->nCol; 1623aa9b8963Sdrh 16246934fc7bSdrh /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for 16256934fc7bSdrh ** normal rowid tables. nPkField is the number of key fields in the 16266934fc7bSdrh ** pPk index or 1 for a rowid table. In other words, nPkField is the 16276934fc7bSdrh ** number of fields in the true primary key of the table. */ 162826198bb4Sdrh if( HasRowid(pTab) ){ 162926198bb4Sdrh pPk = 0; 163026198bb4Sdrh nPkField = 1; 163126198bb4Sdrh }else{ 163226198bb4Sdrh pPk = sqlite3PrimaryKeyIndex(pTab); 163326198bb4Sdrh nPkField = pPk->nKeyCol; 163426198bb4Sdrh } 16356fbe41acSdrh 16366fbe41acSdrh /* Record that this module has started */ 16376fbe41acSdrh VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", 16386934fc7bSdrh iDataCur, iIdxCur, regNewData, regOldData, pkChng)); 16399cfcf5d4Sdrh 16409cfcf5d4Sdrh /* Test all NOT NULL constraints. 16419cfcf5d4Sdrh */ 1642cbda9c7aSdrh if( pTab->tabFlags & TF_HasNotNull ){ 1643ad5f1577Sdrh int b2ndPass = 0; /* True if currently running 2nd pass */ 1644ad5f1577Sdrh int nSeenReplace = 0; /* Number of ON CONFLICT REPLACE operations */ 1645ad5f1577Sdrh int nGenerated = 0; /* Number of generated columns with NOT NULL */ 1646ad5f1577Sdrh while(1){ /* Make 2 passes over columns. Exit loop via "break" */ 16479cfcf5d4Sdrh for(i=0; i<nCol; i++){ 1648ad5f1577Sdrh int iReg; /* Register holding column value */ 1649ad5f1577Sdrh Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */ 1650ad5f1577Sdrh int isGenerated; /* non-zero if column is generated */ 1651ad5f1577Sdrh onError = pCol->notNull; 1652cbda9c7aSdrh if( onError==OE_None ) continue; /* No NOT NULL on this column */ 16530ca3e24bSdrh if( i==pTab->iPKey ){ 1654bdb00225Sdrh continue; /* ROWID is never NULL */ 1655bdb00225Sdrh } 1656ad5f1577Sdrh isGenerated = pCol->colFlags & COLFLAG_GENERATED; 1657ad5f1577Sdrh if( isGenerated && !b2ndPass ){ 1658ad5f1577Sdrh nGenerated++; 1659ad5f1577Sdrh continue; /* Generated columns processed on 2nd pass */ 1660ad5f1577Sdrh } 1661ad5f1577Sdrh if( aiChng && aiChng[i]<0 && !isGenerated ){ 1662ad5f1577Sdrh /* Do not check NOT NULL on columns that do not change */ 16630ca3e24bSdrh continue; 16640ca3e24bSdrh } 16659cfcf5d4Sdrh if( overrideError!=OE_Default ){ 16669cfcf5d4Sdrh onError = overrideError; 1667a996e477Sdrh }else if( onError==OE_Default ){ 1668a996e477Sdrh onError = OE_Abort; 16699cfcf5d4Sdrh } 1670ad5f1577Sdrh if( onError==OE_Replace ){ 1671ad5f1577Sdrh if( b2ndPass /* REPLACE becomes ABORT on the 2nd pass */ 1672ad5f1577Sdrh || pCol->pDflt==0 /* REPLACE is ABORT if no DEFAULT value */ 1673ad5f1577Sdrh ){ 1674ad5f1577Sdrh testcase( pCol->colFlags & COLFLAG_VIRTUAL ); 1675ad5f1577Sdrh testcase( pCol->colFlags & COLFLAG_STORED ); 1676ad5f1577Sdrh testcase( pCol->colFlags & COLFLAG_GENERATED ); 16779cfcf5d4Sdrh onError = OE_Abort; 1678ad5f1577Sdrh }else{ 1679ad5f1577Sdrh assert( !isGenerated ); 1680ad5f1577Sdrh } 1681ad5f1577Sdrh }else if( b2ndPass && !isGenerated ){ 1682ad5f1577Sdrh continue; 16839cfcf5d4Sdrh } 1684b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1685b84f96f8Sdanielk1977 || onError==OE_Ignore || onError==OE_Replace ); 1686c5f808d8Sdrh testcase( i!=sqlite3TableColumnToStorage(pTab, i) ); 1687b9bcf7caSdrh iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1; 16889cfcf5d4Sdrh switch( onError ){ 16899bfb0794Sdrh case OE_Replace: { 1690ad5f1577Sdrh int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg); 16919bfb0794Sdrh VdbeCoverage(v); 1692ad5f1577Sdrh assert( (pCol->colFlags & COLFLAG_GENERATED)==0 ); 1693ad5f1577Sdrh nSeenReplace++; 16945cf1b611Sdrh sqlite3ExprCodeCopy(pParse, pCol->pDflt, iReg); 1695ad5f1577Sdrh sqlite3VdbeJumpHere(v, addr1); 1696ad5f1577Sdrh break; 16979bfb0794Sdrh } 16981c92853dSdrh case OE_Abort: 1699e0af83acSdan sqlite3MayAbort(pParse); 170008b92086Sdrh /* no break */ deliberate_fall_through 1701e0af83acSdan case OE_Rollback: 17021c92853dSdrh case OE_Fail: { 1703f9c8ce3cSdrh char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, 1704ad5f1577Sdrh pCol->zName); 1705cbda9c7aSdrh sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, 1706a88c8c1aSdrh onError, iReg); 17072700acaaSdrh sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC); 1708f9c8ce3cSdrh sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); 1709688852abSdrh VdbeCoverage(v); 17109cfcf5d4Sdrh break; 17119cfcf5d4Sdrh } 1712098d1684Sdrh default: { 17139bfb0794Sdrh assert( onError==OE_Ignore ); 17148e10d74bSdrh sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest); 1715728e0f91Sdrh VdbeCoverage(v); 17169cfcf5d4Sdrh break; 17179cfcf5d4Sdrh } 1718ad5f1577Sdrh } /* end switch(onError) */ 1719ad5f1577Sdrh } /* end loop i over columns */ 1720ad5f1577Sdrh if( nGenerated==0 && nSeenReplace==0 ){ 1721ad5f1577Sdrh /* If there are no generated columns with NOT NULL constraints 1722ad5f1577Sdrh ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single 1723ad5f1577Sdrh ** pass is sufficient */ 1724ad5f1577Sdrh break; 17259cfcf5d4Sdrh } 1726ad5f1577Sdrh if( b2ndPass ) break; /* Never need more than 2 passes */ 1727ad5f1577Sdrh b2ndPass = 1; 1728ef9f719dSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1729ad5f1577Sdrh if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){ 1730ad5f1577Sdrh /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the 1731ad5f1577Sdrh ** first pass, recomputed values for all generated columns, as 1732ad5f1577Sdrh ** those values might depend on columns affected by the REPLACE. 1733ad5f1577Sdrh */ 1734ad5f1577Sdrh sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab); 17359cfcf5d4Sdrh } 1736ef9f719dSdrh #endif 1737ad5f1577Sdrh } /* end of 2-pass loop */ 1738ad5f1577Sdrh } /* end if( has-not-null-constraints ) */ 17399cfcf5d4Sdrh 17409cfcf5d4Sdrh /* Test all CHECK constraints 17419cfcf5d4Sdrh */ 1742ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 17432938f924Sdrh if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ 17442938f924Sdrh ExprList *pCheck = pTab->pCheck; 17456e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 1746aa01c7e2Sdrh onError = overrideError!=OE_Default ? overrideError : OE_Abort; 17472938f924Sdrh for(i=0; i<pCheck->nExpr; i++){ 174805723a9eSdrh int allOk; 17495cf1b611Sdrh Expr *pCopy; 17502a0b527bSdrh Expr *pExpr = pCheck->a[i].pExpr; 1751e9816d82Sdrh if( aiChng 1752e9816d82Sdrh && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng) 1753e9816d82Sdrh ){ 1754e9816d82Sdrh /* The check constraints do not reference any of the columns being 1755e9816d82Sdrh ** updated so there is no point it verifying the check constraint */ 1756e9816d82Sdrh continue; 1757e9816d82Sdrh } 17589dce0ef4Sdrh if( bAffinityDone==0 ){ 17599dce0ef4Sdrh sqlite3TableAffinity(v, pTab, regNewData+1); 17609dce0ef4Sdrh bAffinityDone = 1; 17619dce0ef4Sdrh } 1762ec4ccdbcSdrh allOk = sqlite3VdbeMakeLabel(pParse); 17634031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 17645cf1b611Sdrh pCopy = sqlite3ExprDup(db, pExpr, 0); 17655cf1b611Sdrh if( !db->mallocFailed ){ 17665cf1b611Sdrh sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL); 17675cf1b611Sdrh } 17685cf1b611Sdrh sqlite3ExprDelete(db, pCopy); 17692e06c67cSdrh if( onError==OE_Ignore ){ 1770076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 1771aa01c7e2Sdrh }else{ 177241cee668Sdrh char *zName = pCheck->a[i].zEName; 1773e2678b93Sdrh assert( zName!=0 || pParse->db->mallocFailed ); 17740ce974d1Sdrh if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */ 1775d91c1a17Sdrh sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, 1776f9c8ce3cSdrh onError, zName, P4_TRANSIENT, 1777f9c8ce3cSdrh P5_ConstraintCheck); 1778aa01c7e2Sdrh } 1779ffe07b2dSdrh sqlite3VdbeResolveLabel(v, allOk); 1780ffe07b2dSdrh } 17816e97f8ecSdrh pParse->iSelfTab = 0; 17822938f924Sdrh } 1783ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */ 17849cfcf5d4Sdrh 1785096fd476Sdrh /* UNIQUE and PRIMARY KEY constraints should be handled in the following 1786096fd476Sdrh ** order: 1787096fd476Sdrh ** 178884304506Sdrh ** (1) OE_Update 178984304506Sdrh ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore 1790096fd476Sdrh ** (3) OE_Replace 1791096fd476Sdrh ** 1792096fd476Sdrh ** OE_Fail and OE_Ignore must happen before any changes are made. 1793096fd476Sdrh ** OE_Update guarantees that only a single row will change, so it 1794096fd476Sdrh ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback 1795096fd476Sdrh ** could happen in any order, but they are grouped up front for 1796096fd476Sdrh ** convenience. 1797096fd476Sdrh ** 179884304506Sdrh ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43 179984304506Sdrh ** The order of constraints used to have OE_Update as (2) and OE_Abort 180084304506Sdrh ** and so forth as (1). But apparently PostgreSQL checks the OE_Update 180184304506Sdrh ** constraint before any others, so it had to be moved. 180284304506Sdrh ** 1803096fd476Sdrh ** Constraint checking code is generated in this order: 1804096fd476Sdrh ** (A) The rowid constraint 1805096fd476Sdrh ** (B) Unique index constraints that do not have OE_Replace as their 1806096fd476Sdrh ** default conflict resolution strategy 1807096fd476Sdrh ** (C) Unique index that do use OE_Replace by default. 1808096fd476Sdrh ** 1809096fd476Sdrh ** The ordering of (2) and (3) is accomplished by making sure the linked 1810096fd476Sdrh ** list of indexes attached to a table puts all OE_Replace indexes last 1811096fd476Sdrh ** in the list. See sqlite3CreateIndex() for where that happens. 1812096fd476Sdrh */ 181361e280adSdrh sIdxIter.eType = 0; 181461e280adSdrh sIdxIter.i = 0; 1815d3e21a10Sdrh sIdxIter.u.ax.aIdx = 0; /* Silence harmless compiler warning */ 181661e280adSdrh sIdxIter.u.lx.pIdx = pTab->pIndex; 1817096fd476Sdrh if( pUpsert ){ 1818096fd476Sdrh if( pUpsert->pUpsertTarget==0 ){ 181961e280adSdrh /* There is just on ON CONFLICT clause and it has no constraint-target */ 182061e280adSdrh assert( pUpsert->pNextUpsert==0 ); 1821255c1c15Sdrh if( pUpsert->isDoUpdate==0 ){ 182261e280adSdrh /* A single ON CONFLICT DO NOTHING clause, without a constraint-target. 1823096fd476Sdrh ** Make all unique constraint resolution be OE_Ignore */ 1824096fd476Sdrh overrideError = OE_Ignore; 1825096fd476Sdrh pUpsert = 0; 182661e280adSdrh }else{ 182761e280adSdrh /* A single ON CONFLICT DO UPDATE. Make all resolutions OE_Update */ 182861e280adSdrh overrideError = OE_Update; 182961e280adSdrh } 183061e280adSdrh }else if( pTab->pIndex!=0 ){ 183161e280adSdrh /* Otherwise, we'll need to run the IndexListTerm array version of the 183261e280adSdrh ** iterator to ensure that all of the ON CONFLICT conditions are 183361e280adSdrh ** checked first and in order. */ 183461e280adSdrh int nIdx, jj; 183561e280adSdrh u64 nByte; 183661e280adSdrh Upsert *pTerm; 183761e280adSdrh u8 *bUsed; 183861e280adSdrh for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ 183961e280adSdrh assert( aRegIdx[nIdx]>0 ); 184061e280adSdrh } 184161e280adSdrh sIdxIter.eType = 1; 184261e280adSdrh sIdxIter.u.ax.nIdx = nIdx; 184361e280adSdrh nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx; 184461e280adSdrh sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte); 184561e280adSdrh if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */ 184661e280adSdrh bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx]; 184761e280adSdrh pUpsert->pToFree = sIdxIter.u.ax.aIdx; 184861e280adSdrh for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){ 184961e280adSdrh if( pTerm->pUpsertTarget==0 ) break; 185061e280adSdrh if( pTerm->pUpsertIdx==0 ) continue; /* Skip ON CONFLICT for the IPK */ 185161e280adSdrh jj = 0; 185261e280adSdrh pIdx = pTab->pIndex; 185361e280adSdrh while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){ 185461e280adSdrh pIdx = pIdx->pNext; 185561e280adSdrh jj++; 185661e280adSdrh } 185761e280adSdrh if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */ 185861e280adSdrh bUsed[jj] = 1; 185961e280adSdrh sIdxIter.u.ax.aIdx[i].p = pIdx; 186061e280adSdrh sIdxIter.u.ax.aIdx[i].ix = jj; 186161e280adSdrh i++; 186261e280adSdrh } 186361e280adSdrh for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){ 186461e280adSdrh if( bUsed[jj] ) continue; 186561e280adSdrh sIdxIter.u.ax.aIdx[i].p = pIdx; 186661e280adSdrh sIdxIter.u.ax.aIdx[i].ix = jj; 186761e280adSdrh i++; 186861e280adSdrh } 186961e280adSdrh assert( i==nIdx ); 1870096fd476Sdrh } 1871096fd476Sdrh } 1872096fd476Sdrh 1873a407eccbSdrh /* Determine if it is possible that triggers (either explicitly coded 1874a407eccbSdrh ** triggers or FK resolution actions) might run as a result of deletes 1875a407eccbSdrh ** that happen when OE_Replace conflict resolution occurs. (Call these 1876a407eccbSdrh ** "replace triggers".) If any replace triggers run, we will need to 1877a407eccbSdrh ** recheck all of the uniqueness constraints after they have all run. 1878a407eccbSdrh ** But on the recheck, the resolution is OE_Abort instead of OE_Replace. 1879a407eccbSdrh ** 1880a407eccbSdrh ** If replace triggers are a possibility, then 1881a407eccbSdrh ** 1882a407eccbSdrh ** (1) Allocate register regTrigCnt and initialize it to zero. 1883a407eccbSdrh ** That register will count the number of replace triggers that 1884d3c468b7Sdrh ** fire. Constraint recheck only occurs if the number is positive. 1885d3c468b7Sdrh ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab. 1886a407eccbSdrh ** (3) Initialize addrRecheck and lblRecheckOk 1887a407eccbSdrh ** 1888a407eccbSdrh ** The uniqueness rechecking code will create a series of tests to run 1889a407eccbSdrh ** in a second pass. The addrRecheck and lblRecheckOk variables are 1890a407eccbSdrh ** used to link together these tests which are separated from each other 1891a407eccbSdrh ** in the generate bytecode. 1892a407eccbSdrh */ 1893a407eccbSdrh if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){ 1894a407eccbSdrh /* There are not DELETE triggers nor FK constraints. No constraint 1895a407eccbSdrh ** rechecks are needed. */ 1896a407eccbSdrh pTrigger = 0; 1897a407eccbSdrh regTrigCnt = 0; 1898a407eccbSdrh }else{ 1899a407eccbSdrh if( db->flags&SQLITE_RecTriggers ){ 1900a407eccbSdrh pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 1901a407eccbSdrh regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0); 1902a407eccbSdrh }else{ 1903a407eccbSdrh pTrigger = 0; 1904a407eccbSdrh regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0); 1905a407eccbSdrh } 1906a407eccbSdrh if( regTrigCnt ){ 1907a407eccbSdrh /* Replace triggers might exist. Allocate the counter and 1908a407eccbSdrh ** initialize it to zero. */ 1909a407eccbSdrh regTrigCnt = ++pParse->nMem; 1910a407eccbSdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt); 1911a407eccbSdrh VdbeComment((v, "trigger count")); 1912a407eccbSdrh lblRecheckOk = sqlite3VdbeMakeLabel(pParse); 1913a407eccbSdrh addrRecheck = lblRecheckOk; 1914a407eccbSdrh } 1915a407eccbSdrh } 1916a407eccbSdrh 1917f8ffb278Sdrh /* If rowid is changing, make sure the new rowid does not previously 1918f8ffb278Sdrh ** exist in the table. 19199cfcf5d4Sdrh */ 19206fbe41acSdrh if( pkChng && pPk==0 ){ 1921ec4ccdbcSdrh int addrRowidOk = sqlite3VdbeMakeLabel(pParse); 192211e85273Sdrh 1923f8ffb278Sdrh /* Figure out what action to take in case of a rowid collision */ 19240ca3e24bSdrh onError = pTab->keyConf; 19250ca3e24bSdrh if( overrideError!=OE_Default ){ 19260ca3e24bSdrh onError = overrideError; 1927a996e477Sdrh }else if( onError==OE_Default ){ 1928a996e477Sdrh onError = OE_Abort; 19290ca3e24bSdrh } 1930a0217ba7Sdrh 1931c8a0c90bSdrh /* figure out whether or not upsert applies in this case */ 193261e280adSdrh if( pUpsert ){ 193361e280adSdrh pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0); 193461e280adSdrh if( pUpsertClause!=0 ){ 1935255c1c15Sdrh if( pUpsertClause->isDoUpdate==0 ){ 1936c8a0c90bSdrh onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */ 1937c8a0c90bSdrh }else{ 1938c8a0c90bSdrh onError = OE_Update; /* DO UPDATE */ 1939c8a0c90bSdrh } 1940c8a0c90bSdrh } 194161e280adSdrh if( pUpsertClause!=pUpsert ){ 194261e280adSdrh /* The first ON CONFLICT clause has a conflict target other than 194361e280adSdrh ** the IPK. We have to jump ahead to that first ON CONFLICT clause 194461e280adSdrh ** and then come back here and deal with the IPK afterwards */ 194561e280adSdrh upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto); 194661e280adSdrh } 194761e280adSdrh } 1948c8a0c90bSdrh 19498d1b82e4Sdrh /* If the response to a rowid conflict is REPLACE but the response 19508d1b82e4Sdrh ** to some other UNIQUE constraint is FAIL or IGNORE, then we need 19518d1b82e4Sdrh ** to defer the running of the rowid conflict checking until after 19528d1b82e4Sdrh ** the UNIQUE constraints have run. 19538d1b82e4Sdrh */ 195484304506Sdrh if( onError==OE_Replace /* IPK rule is REPLACE */ 19559a60e716Smistachkin && onError!=overrideError /* Rules for other constraints are different */ 195684304506Sdrh && pTab->pIndex /* There exist other constraints */ 1957096fd476Sdrh ){ 195884304506Sdrh ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1; 195984304506Sdrh VdbeComment((v, "defer IPK REPLACE until last")); 19608d1b82e4Sdrh } 19618d1b82e4Sdrh 1962bb6b1ca7Sdrh if( isUpdate ){ 1963bb6b1ca7Sdrh /* pkChng!=0 does not mean that the rowid has changed, only that 1964bb6b1ca7Sdrh ** it might have changed. Skip the conflict logic below if the rowid 1965bb6b1ca7Sdrh ** is unchanged. */ 1966bb6b1ca7Sdrh sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); 1967bb6b1ca7Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1968bb6b1ca7Sdrh VdbeCoverage(v); 1969bb6b1ca7Sdrh } 1970bb6b1ca7Sdrh 1971f8ffb278Sdrh /* Check to see if the new rowid already exists in the table. Skip 1972f8ffb278Sdrh ** the following conflict logic if it does not. */ 19737f5f306bSdrh VdbeNoopComment((v, "uniqueness check for ROWID")); 19744031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 19756934fc7bSdrh sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); 1976688852abSdrh VdbeCoverage(v); 1977f8ffb278Sdrh 19780ca3e24bSdrh switch( onError ){ 1979a0217ba7Sdrh default: { 1980a0217ba7Sdrh onError = OE_Abort; 198108b92086Sdrh /* no break */ deliberate_fall_through 1982a0217ba7Sdrh } 19831c92853dSdrh case OE_Rollback: 19841c92853dSdrh case OE_Abort: 19851c92853dSdrh case OE_Fail: { 19869916048bSdrh testcase( onError==OE_Rollback ); 19879916048bSdrh testcase( onError==OE_Abort ); 19889916048bSdrh testcase( onError==OE_Fail ); 1989f9c8ce3cSdrh sqlite3RowidConstraint(pParse, onError, pTab); 19900ca3e24bSdrh break; 19910ca3e24bSdrh } 19925383ae5cSdrh case OE_Replace: { 19932283d46cSdan /* If there are DELETE triggers on this table and the 19942283d46cSdan ** recursive-triggers flag is set, call GenerateRowDelete() to 1995d5578433Smistachkin ** remove the conflicting row from the table. This will fire 19962283d46cSdan ** the triggers and remove both the table and index b-tree entries. 19972283d46cSdan ** 19982283d46cSdan ** Otherwise, if there are no triggers or the recursive-triggers 1999da730f6eSdan ** flag is not set, but the table has one or more indexes, call 2000da730f6eSdan ** GenerateRowIndexDelete(). This removes the index b-tree entries 2001da730f6eSdan ** only. The table b-tree entry will be replaced by the new entry 2002da730f6eSdan ** when it is inserted. 2003da730f6eSdan ** 2004da730f6eSdan ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, 2005da730f6eSdan ** also invoke MultiWrite() to indicate that this VDBE may require 2006da730f6eSdan ** statement rollback (if the statement is aborted after the delete 2007da730f6eSdan ** takes place). Earlier versions called sqlite3MultiWrite() regardless, 2008da730f6eSdan ** but being more selective here allows statements like: 2009da730f6eSdan ** 2010da730f6eSdan ** REPLACE INTO t(rowid) VALUES($newrowid) 2011da730f6eSdan ** 2012da730f6eSdan ** to run without a statement journal if there are no indexes on the 2013da730f6eSdan ** table. 2014da730f6eSdan */ 2015a407eccbSdrh if( regTrigCnt ){ 2016da730f6eSdan sqlite3MultiWrite(pParse); 201726198bb4Sdrh sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 2018438b8815Sdan regNewData, 1, 0, OE_Replace, 1, -1); 2019a407eccbSdrh sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */ 2020a407eccbSdrh nReplaceTrig++; 202146c47d46Sdan }else{ 20229b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 202354f2cd90Sdrh assert( HasRowid(pTab) ); 202446c47d46Sdan /* This OP_Delete opcode fires the pre-update-hook only. It does 202546c47d46Sdan ** not modify the b-tree. It is more efficient to let the coming 202646c47d46Sdan ** OP_Insert replace the existing entry than it is to delete the 202746c47d46Sdan ** existing entry and then insert a new one. */ 2028cbf1b8efSdrh sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP); 2029f14b7fb7Sdrh sqlite3VdbeAppendP4(v, pTab, P4_TABLE); 20309b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ 203146c47d46Sdan if( pTab->pIndex ){ 2032da730f6eSdan sqlite3MultiWrite(pParse); 2033f0ee1d3cSdan sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); 20342283d46cSdan } 203546c47d46Sdan } 20365383ae5cSdrh seenReplace = 1; 20375383ae5cSdrh break; 20385383ae5cSdrh } 20399eddacadSdrh #ifndef SQLITE_OMIT_UPSERT 20409eddacadSdrh case OE_Update: { 20412cc00423Sdan sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur); 204208b92086Sdrh /* no break */ deliberate_fall_through 20439eddacadSdrh } 20449eddacadSdrh #endif 20450ca3e24bSdrh case OE_Ignore: { 20469916048bSdrh testcase( onError==OE_Ignore ); 2047076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 20480ca3e24bSdrh break; 20490ca3e24bSdrh } 20500ca3e24bSdrh } 205111e85273Sdrh sqlite3VdbeResolveLabel(v, addrRowidOk); 205261e280adSdrh if( pUpsert && pUpsertClause!=pUpsert ){ 205361e280adSdrh upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto); 205461e280adSdrh }else if( ipkTop ){ 205584304506Sdrh ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); 205684304506Sdrh sqlite3VdbeJumpHere(v, ipkTop-1); 2057a05a722fSdrh } 20580ca3e24bSdrh } 20590bd1f4eaSdrh 20600bd1f4eaSdrh /* Test all UNIQUE constraints by creating entries for each UNIQUE 20610bd1f4eaSdrh ** index and making sure that duplicate entries do not already exist. 206211e85273Sdrh ** Compute the revised record entries for indices as we go. 2063f8ffb278Sdrh ** 2064f8ffb278Sdrh ** This loop also handles the case of the PRIMARY KEY index for a 2065f8ffb278Sdrh ** WITHOUT ROWID table. 20660bd1f4eaSdrh */ 206761e280adSdrh for(pIdx = indexIteratorFirst(&sIdxIter, &ix); 2068daf2761cSdrh pIdx; 206961e280adSdrh pIdx = indexIteratorNext(&sIdxIter, &ix) 2070daf2761cSdrh ){ 20716934fc7bSdrh int regIdx; /* Range of registers hold conent for pIdx */ 20726934fc7bSdrh int regR; /* Range of registers holding conflicting PK */ 20736934fc7bSdrh int iThisCur; /* Cursor for this UNIQUE index */ 20746934fc7bSdrh int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ 2075a407eccbSdrh int addrConflictCk; /* First opcode in the conflict check logic */ 20762184fc75Sdrh 207726198bb4Sdrh if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ 207861e280adSdrh if( pUpsert ){ 207961e280adSdrh pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx); 208061e280adSdrh if( upsertIpkDelay && pUpsertClause==pUpsert ){ 208161e280adSdrh sqlite3VdbeJumpHere(v, upsertIpkDelay); 20827f5f306bSdrh } 208361e280adSdrh } 208461e280adSdrh addrUniqueOk = sqlite3VdbeMakeLabel(pParse); 208561e280adSdrh if( bAffinityDone==0 ){ 208684304506Sdrh sqlite3TableAffinity(v, pTab, regNewData+1); 208784304506Sdrh bAffinityDone = 1; 208884304506Sdrh } 20898e50d65aSdrh VdbeNoopComment((v, "prep index %s", pIdx->zName)); 20906934fc7bSdrh iThisCur = iIdxCur+ix; 20917f5f306bSdrh 2092b2fe7d8cSdrh 2093f8ffb278Sdrh /* Skip partial indices for which the WHERE clause is not true */ 2094b2b9d3d7Sdrh if( pIdx->pPartIdxWhere ){ 209526198bb4Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); 20966e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 209772bc8208Sdrh sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, 2098b2b9d3d7Sdrh SQLITE_JUMPIFNULL); 20996e97f8ecSdrh pParse->iSelfTab = 0; 2100b2b9d3d7Sdrh } 2101b2b9d3d7Sdrh 21026934fc7bSdrh /* Create a record for this index entry as it should appear after 2103f8ffb278Sdrh ** the insert or update. Store that record in the aRegIdx[ix] register 2104f8ffb278Sdrh */ 2105bf2f5739Sdrh regIdx = aRegIdx[ix]+1; 21069cfcf5d4Sdrh for(i=0; i<pIdx->nColumn; i++){ 21076934fc7bSdrh int iField = pIdx->aiColumn[i]; 2108f82b9afcSdrh int x; 21094b92f98cSdrh if( iField==XN_EXPR ){ 21106e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 21111c75c9d7Sdrh sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); 21126e97f8ecSdrh pParse->iSelfTab = 0; 21131f9ca2c8Sdrh VdbeComment((v, "%s column %d", pIdx->zName, i)); 2114463e76ffSdrh }else if( iField==XN_ROWID || iField==pTab->iPKey ){ 2115f82b9afcSdrh x = regNewData; 2116463e76ffSdrh sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i); 2117463e76ffSdrh VdbeComment((v, "rowid")); 21189cfcf5d4Sdrh }else{ 2119c5f808d8Sdrh testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField ); 2120b9bcf7caSdrh x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1; 2121463e76ffSdrh sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i); 2122463e76ffSdrh VdbeComment((v, "%s", pTab->aCol[iField].zName)); 21239cfcf5d4Sdrh } 21241f9ca2c8Sdrh } 212526198bb4Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); 212626198bb4Sdrh VdbeComment((v, "for %s", pIdx->zName)); 21277e4acf7bSdrh #ifdef SQLITE_ENABLE_NULL_TRIM 21289df385ecSdrh if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){ 21299df385ecSdrh sqlite3SetMakeRecordP5(v, pIdx->pTable); 21309df385ecSdrh } 21317e4acf7bSdrh #endif 21323aef2fb1Sdrh sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0); 2133b2fe7d8cSdrh 2134f8ffb278Sdrh /* In an UPDATE operation, if this index is the PRIMARY KEY index 2135f8ffb278Sdrh ** of a WITHOUT ROWID table and there has been no change the 2136f8ffb278Sdrh ** primary key, then no collision is possible. The collision detection 2137f8ffb278Sdrh ** logic below can all be skipped. */ 213800012df4Sdrh if( isUpdate && pPk==pIdx && pkChng==0 ){ 2139da475b8dSdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 2140da475b8dSdrh continue; 2141da475b8dSdrh } 2142f8ffb278Sdrh 21436934fc7bSdrh /* Find out what action to take in case there is a uniqueness conflict */ 21449cfcf5d4Sdrh onError = pIdx->onError; 2145de630353Sdanielk1977 if( onError==OE_None ){ 214611e85273Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 2147de630353Sdanielk1977 continue; /* pIdx is not a UNIQUE index */ 2148de630353Sdanielk1977 } 21499cfcf5d4Sdrh if( overrideError!=OE_Default ){ 21509cfcf5d4Sdrh onError = overrideError; 2151a996e477Sdrh }else if( onError==OE_Default ){ 2152a996e477Sdrh onError = OE_Abort; 21539cfcf5d4Sdrh } 21545383ae5cSdrh 2155c8a0c90bSdrh /* Figure out if the upsert clause applies to this index */ 215661e280adSdrh if( pUpsertClause ){ 2157255c1c15Sdrh if( pUpsertClause->isDoUpdate==0 ){ 2158c8a0c90bSdrh onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */ 2159c8a0c90bSdrh }else{ 2160c8a0c90bSdrh onError = OE_Update; /* DO UPDATE */ 2161c8a0c90bSdrh } 2162c8a0c90bSdrh } 2163c8a0c90bSdrh 2164801f55d8Sdrh /* Collision detection may be omitted if all of the following are true: 2165801f55d8Sdrh ** (1) The conflict resolution algorithm is REPLACE 2166801f55d8Sdrh ** (2) The table is a WITHOUT ROWID table 2167801f55d8Sdrh ** (3) There are no secondary indexes on the table 2168801f55d8Sdrh ** (4) No delete triggers need to be fired if there is a conflict 2169f9a12a10Sdan ** (5) No FK constraint counters need to be updated if a conflict occurs. 2170418454c6Sdan ** 2171418454c6Sdan ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row 2172418454c6Sdan ** must be explicitly deleted in order to ensure any pre-update hook 2173418454c6Sdan ** is invoked. */ 2174418454c6Sdan #ifndef SQLITE_ENABLE_PREUPDATE_HOOK 2175801f55d8Sdrh if( (ix==0 && pIdx->pNext==0) /* Condition 3 */ 2176801f55d8Sdrh && pPk==pIdx /* Condition 2 */ 2177801f55d8Sdrh && onError==OE_Replace /* Condition 1 */ 2178801f55d8Sdrh && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */ 2179801f55d8Sdrh 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0)) 2180f9a12a10Sdan && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */ 2181f9a12a10Sdan (0==pTab->pFKey && 0==sqlite3FkReferences(pTab))) 21824e1f0efbSdan ){ 2183c6c9e158Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 2184c6c9e158Sdrh continue; 2185c6c9e158Sdrh } 2186418454c6Sdan #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */ 2187c6c9e158Sdrh 2188b2fe7d8cSdrh /* Check to see if the new index entry will be unique */ 21894031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 2190a407eccbSdrh addrConflictCk = 219126198bb4Sdrh sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, 2192688852abSdrh regIdx, pIdx->nKeyCol); VdbeCoverage(v); 2193f8ffb278Sdrh 2194f8ffb278Sdrh /* Generate code to handle collisions */ 2195d3e21a10Sdrh regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField); 219646d03fcbSdrh if( isUpdate || onError==OE_Replace ){ 219711e85273Sdrh if( HasRowid(pTab) ){ 21986934fc7bSdrh sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); 21990978d4ffSdrh /* Conflict only if the rowid of the existing index entry 22000978d4ffSdrh ** is different from old-rowid */ 2201f8ffb278Sdrh if( isUpdate ){ 22026934fc7bSdrh sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); 22033d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 2204688852abSdrh VdbeCoverage(v); 2205f8ffb278Sdrh } 220626198bb4Sdrh }else{ 2207ccc79f02Sdrh int x; 220826198bb4Sdrh /* Extract the PRIMARY KEY from the end of the index entry and 2209da475b8dSdrh ** store it in registers regR..regR+nPk-1 */ 2210a021f121Sdrh if( pIdx!=pPk ){ 221126198bb4Sdrh for(i=0; i<pPk->nKeyCol; i++){ 22124b92f98cSdrh assert( pPk->aiColumn[i]>=0 ); 2213b9bcf7caSdrh x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]); 221426198bb4Sdrh sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); 221526198bb4Sdrh VdbeComment((v, "%s.%s", pTab->zName, 221626198bb4Sdrh pTab->aCol[pPk->aiColumn[i]].zName)); 221726198bb4Sdrh } 2218da475b8dSdrh } 2219da475b8dSdrh if( isUpdate ){ 2220e83267daSdan /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 2221e83267daSdan ** table, only conflict if the new PRIMARY KEY values are actually 2222e83267daSdan ** different from the old. 2223e83267daSdan ** 2224e83267daSdan ** For a UNIQUE index, only conflict if the PRIMARY KEY values 2225e83267daSdan ** of the matched index row are different from the original PRIMARY 2226e83267daSdan ** KEY values of this row before the update. */ 2227e83267daSdan int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; 2228e83267daSdan int op = OP_Ne; 222948dd1d8eSdrh int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); 2230e83267daSdan 2231e83267daSdan for(i=0; i<pPk->nKeyCol; i++){ 2232e83267daSdan char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); 2233ccc79f02Sdrh x = pPk->aiColumn[i]; 22344b92f98cSdrh assert( x>=0 ); 2235e83267daSdan if( i==(pPk->nKeyCol-1) ){ 2236e83267daSdan addrJump = addrUniqueOk; 2237e83267daSdan op = OP_Eq; 223811e85273Sdrh } 2239b6d861e5Sdrh x = sqlite3TableColumnToStorage(pTab, x); 2240e83267daSdan sqlite3VdbeAddOp4(v, op, 2241e83267daSdan regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ 2242e83267daSdan ); 22433d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 22443d77dee9Sdrh VdbeCoverageIf(v, op==OP_Eq); 22453d77dee9Sdrh VdbeCoverageIf(v, op==OP_Ne); 2246da475b8dSdrh } 224711e85273Sdrh } 224826198bb4Sdrh } 224946d03fcbSdrh } 2250b2fe7d8cSdrh 2251b2fe7d8cSdrh /* Generate code that executes if the new index entry is not unique */ 2252b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 22539eddacadSdrh || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update ); 22549cfcf5d4Sdrh switch( onError ){ 22551c92853dSdrh case OE_Rollback: 22561c92853dSdrh case OE_Abort: 22571c92853dSdrh case OE_Fail: { 22589916048bSdrh testcase( onError==OE_Rollback ); 22599916048bSdrh testcase( onError==OE_Abort ); 22609916048bSdrh testcase( onError==OE_Fail ); 2261f9c8ce3cSdrh sqlite3UniqueConstraint(pParse, onError, pIdx); 22629cfcf5d4Sdrh break; 22639cfcf5d4Sdrh } 22649eddacadSdrh #ifndef SQLITE_OMIT_UPSERT 22659eddacadSdrh case OE_Update: { 22662cc00423Sdan sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix); 226708b92086Sdrh /* no break */ deliberate_fall_through 22689eddacadSdrh } 22699eddacadSdrh #endif 22709cfcf5d4Sdrh case OE_Ignore: { 22719916048bSdrh testcase( onError==OE_Ignore ); 2272076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 22739cfcf5d4Sdrh break; 22749cfcf5d4Sdrh } 2275098d1684Sdrh default: { 2276a407eccbSdrh int nConflictCk; /* Number of opcodes in conflict check logic */ 2277a407eccbSdrh 2278098d1684Sdrh assert( onError==OE_Replace ); 2279a407eccbSdrh nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk; 2280d3c468b7Sdrh assert( nConflictCk>0 ); 2281d3c468b7Sdrh testcase( nConflictCk>1 ); 2282a407eccbSdrh if( regTrigCnt ){ 2283fecfb318Sdan sqlite3MultiWrite(pParse); 2284a407eccbSdrh nReplaceTrig++; 2285fecfb318Sdan } 22867b14b65dSdrh if( pTrigger && isUpdate ){ 22877b14b65dSdrh sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur); 22887b14b65dSdrh } 228926198bb4Sdrh sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 2290b0264eecSdrh regR, nPkField, 0, OE_Replace, 229168116939Sdrh (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur); 22927b14b65dSdrh if( pTrigger && isUpdate ){ 22937b14b65dSdrh sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur); 22947b14b65dSdrh } 2295a407eccbSdrh if( regTrigCnt ){ 2296a407eccbSdrh int addrBypass; /* Jump destination to bypass recheck logic */ 2297a407eccbSdrh 2298a407eccbSdrh sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */ 2299a407eccbSdrh addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */ 2300a407eccbSdrh VdbeComment((v, "bypass recheck")); 2301a407eccbSdrh 2302a407eccbSdrh /* Here we insert code that will be invoked after all constraint 2303a407eccbSdrh ** checks have run, if and only if one or more replace triggers 2304a407eccbSdrh ** fired. */ 2305a407eccbSdrh sqlite3VdbeResolveLabel(v, lblRecheckOk); 2306a407eccbSdrh lblRecheckOk = sqlite3VdbeMakeLabel(pParse); 2307a407eccbSdrh if( pIdx->pPartIdxWhere ){ 2308a407eccbSdrh /* Bypass the recheck if this partial index is not defined 2309a407eccbSdrh ** for the current row */ 23100660884eSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk); 2311a407eccbSdrh VdbeCoverage(v); 2312a407eccbSdrh } 2313a407eccbSdrh /* Copy the constraint check code from above, except change 2314a407eccbSdrh ** the constraint-ok jump destination to be the address of 2315a407eccbSdrh ** the next retest block */ 2316d3c468b7Sdrh while( nConflictCk>0 ){ 2317d901b168Sdrh VdbeOp x; /* Conflict check opcode to copy */ 2318d901b168Sdrh /* The sqlite3VdbeAddOp4() call might reallocate the opcode array. 2319d901b168Sdrh ** Hence, make a complete copy of the opcode, rather than using 2320d901b168Sdrh ** a pointer to the opcode. */ 2321d901b168Sdrh x = *sqlite3VdbeGetOp(v, addrConflictCk); 2322d901b168Sdrh if( x.opcode!=OP_IdxRowid ){ 2323d901b168Sdrh int p2; /* New P2 value for copied conflict check opcode */ 2324b9f2e5f7Sdrh const char *zP4; 2325d901b168Sdrh if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){ 2326a407eccbSdrh p2 = lblRecheckOk; 2327a407eccbSdrh }else{ 2328d901b168Sdrh p2 = x.p2; 2329a407eccbSdrh } 2330b9f2e5f7Sdrh zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z; 2331b9f2e5f7Sdrh sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type); 2332d901b168Sdrh sqlite3VdbeChangeP5(v, x.p5); 2333d901b168Sdrh VdbeCoverageIf(v, p2!=x.p2); 2334a407eccbSdrh } 2335a407eccbSdrh nConflictCk--; 2336d901b168Sdrh addrConflictCk++; 2337a407eccbSdrh } 2338a407eccbSdrh /* If the retest fails, issue an abort */ 23392da8d6feSdrh sqlite3UniqueConstraint(pParse, OE_Abort, pIdx); 2340a407eccbSdrh 2341a407eccbSdrh sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */ 23422da8d6feSdrh } 23430ca3e24bSdrh seenReplace = 1; 23449cfcf5d4Sdrh break; 23459cfcf5d4Sdrh } 23469cfcf5d4Sdrh } 234711e85273Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 2348392ee21dSdrh if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); 2349ed4c5469Sdrh if( pUpsertClause 2350ed4c5469Sdrh && upsertIpkReturn 2351ed4c5469Sdrh && sqlite3UpsertNextIsIPK(pUpsertClause) 2352ed4c5469Sdrh ){ 235361e280adSdrh sqlite3VdbeGoto(v, upsertIpkDelay+1); 235461e280adSdrh sqlite3VdbeJumpHere(v, upsertIpkReturn); 235558b18a47Sdrh upsertIpkReturn = 0; 235661e280adSdrh } 23579cfcf5d4Sdrh } 235884304506Sdrh 235984304506Sdrh /* If the IPK constraint is a REPLACE, run it last */ 236084304506Sdrh if( ipkTop ){ 23616214d939Sdrh sqlite3VdbeGoto(v, ipkTop); 236284304506Sdrh VdbeComment((v, "Do IPK REPLACE")); 236384304506Sdrh sqlite3VdbeJumpHere(v, ipkBottom); 236484304506Sdrh } 2365de630353Sdanielk1977 2366a407eccbSdrh /* Recheck all uniqueness constraints after replace triggers have run */ 2367a407eccbSdrh testcase( regTrigCnt!=0 && nReplaceTrig==0 ); 2368d3c468b7Sdrh assert( regTrigCnt!=0 || nReplaceTrig==0 ); 2369a407eccbSdrh if( nReplaceTrig ){ 2370a407eccbSdrh sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v); 2371a407eccbSdrh if( !pPk ){ 2372a407eccbSdrh if( isUpdate ){ 2373a407eccbSdrh sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData); 2374a407eccbSdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 2375a407eccbSdrh VdbeCoverage(v); 2376a407eccbSdrh } 2377a407eccbSdrh sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData); 2378a407eccbSdrh VdbeCoverage(v); 2379a407eccbSdrh sqlite3RowidConstraint(pParse, OE_Abort, pTab); 2380a407eccbSdrh }else{ 2381a407eccbSdrh sqlite3VdbeGoto(v, addrRecheck); 2382a407eccbSdrh } 2383a407eccbSdrh sqlite3VdbeResolveLabel(v, lblRecheckOk); 2384a407eccbSdrh } 2385a407eccbSdrh 2386a7c3b93fSdrh /* Generate the table record */ 2387a7c3b93fSdrh if( HasRowid(pTab) ){ 2388a7c3b93fSdrh int regRec = aRegIdx[ix]; 23890b0b3a95Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec); 2390a7c3b93fSdrh sqlite3SetMakeRecordP5(v, pTab); 2391a7c3b93fSdrh if( !bAffinityDone ){ 2392a7c3b93fSdrh sqlite3TableAffinity(v, pTab, 0); 2393a7c3b93fSdrh } 2394a7c3b93fSdrh } 2395a7c3b93fSdrh 2396de630353Sdanielk1977 *pbMayReplace = seenReplace; 2397ce60aa46Sdrh VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); 23989cfcf5d4Sdrh } 23990ca3e24bSdrh 2400d447dcedSdrh #ifdef SQLITE_ENABLE_NULL_TRIM 24010ca3e24bSdrh /* 2402585ce192Sdrh ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord) 2403585ce192Sdrh ** to be the number of columns in table pTab that must not be NULL-trimmed. 2404585ce192Sdrh ** 2405585ce192Sdrh ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero. 2406585ce192Sdrh */ 2407585ce192Sdrh void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){ 2408585ce192Sdrh u16 i; 2409585ce192Sdrh 2410585ce192Sdrh /* Records with omitted columns are only allowed for schema format 2411585ce192Sdrh ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */ 2412585ce192Sdrh if( pTab->pSchema->file_format<2 ) return; 2413585ce192Sdrh 24147e4acf7bSdrh for(i=pTab->nCol-1; i>0; i--){ 24157e4acf7bSdrh if( pTab->aCol[i].pDflt!=0 ) break; 24167e4acf7bSdrh if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break; 24177e4acf7bSdrh } 24187e4acf7bSdrh sqlite3VdbeChangeP5(v, i+1); 2419585ce192Sdrh } 2420d447dcedSdrh #endif 2421585ce192Sdrh 24220ca3e24bSdrh /* 2423fadc0e34Sdan ** Table pTab is a WITHOUT ROWID table that is being written to. The cursor 2424fadc0e34Sdan ** number is iCur, and register regData contains the new record for the 2425fadc0e34Sdan ** PK index. This function adds code to invoke the pre-update hook, 2426fadc0e34Sdan ** if one is registered. 2427fadc0e34Sdan */ 2428fadc0e34Sdan #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 2429fadc0e34Sdan static void codeWithoutRowidPreupdate( 2430fadc0e34Sdan Parse *pParse, /* Parse context */ 2431fadc0e34Sdan Table *pTab, /* Table being updated */ 2432fadc0e34Sdan int iCur, /* Cursor number for table */ 2433fadc0e34Sdan int regData /* Data containing new record */ 2434fadc0e34Sdan ){ 2435fadc0e34Sdan Vdbe *v = pParse->pVdbe; 2436fadc0e34Sdan int r = sqlite3GetTempReg(pParse); 2437fadc0e34Sdan assert( !HasRowid(pTab) ); 2438d01206ffSdrh assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB ); 2439fadc0e34Sdan sqlite3VdbeAddOp2(v, OP_Integer, 0, r); 2440fadc0e34Sdan sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE); 2441fadc0e34Sdan sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP); 2442fadc0e34Sdan sqlite3ReleaseTempReg(pParse, r); 2443fadc0e34Sdan } 2444fadc0e34Sdan #else 2445fadc0e34Sdan # define codeWithoutRowidPreupdate(a,b,c,d) 2446fadc0e34Sdan #endif 2447fadc0e34Sdan 2448fadc0e34Sdan /* 24490ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation 24504adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 24516934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the 245204adf416Sdrh ** rowid and the content to be inserted. 24530ca3e24bSdrh ** 2454b419a926Sdrh ** The arguments to this routine should be the same as the first six 24554adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks. 24560ca3e24bSdrh */ 24574adee20fSdanielk1977 void sqlite3CompleteInsertion( 24580ca3e24bSdrh Parse *pParse, /* The parser context */ 24590ca3e24bSdrh Table *pTab, /* the table into which we are inserting */ 246026198bb4Sdrh int iDataCur, /* Cursor of the canonical data source */ 246126198bb4Sdrh int iIdxCur, /* First index cursor */ 24626934fc7bSdrh int regNewData, /* Range of content */ 2463aa9b8963Sdrh int *aRegIdx, /* Register used by each index. 0 for unused indices */ 2464f91c1318Sdan int update_flags, /* True for UPDATE, False for INSERT */ 2465de630353Sdanielk1977 int appendBias, /* True if this is likely to be an append */ 2466de630353Sdanielk1977 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ 24670ca3e24bSdrh ){ 24686934fc7bSdrh Vdbe *v; /* Prepared statements under construction */ 24696934fc7bSdrh Index *pIdx; /* An index being inserted or updated */ 24706934fc7bSdrh u8 pik_flags; /* flag values passed to the btree insert */ 24716934fc7bSdrh int i; /* Loop counter */ 24720ca3e24bSdrh 2473f91c1318Sdan assert( update_flags==0 2474f91c1318Sdan || update_flags==OPFLAG_ISUPDATE 2475f91c1318Sdan || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION) 2476f91c1318Sdan ); 2477f91c1318Sdan 2478f0b41745Sdrh v = pParse->pVdbe; 24790ca3e24bSdrh assert( v!=0 ); 2480417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 2481b2b9d3d7Sdrh for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 2482d35bdd6cSdrh /* All REPLACE indexes are at the end of the list */ 2483d35bdd6cSdrh assert( pIdx->onError!=OE_Replace 2484d35bdd6cSdrh || pIdx->pNext==0 2485d35bdd6cSdrh || pIdx->pNext->onError==OE_Replace ); 2486aa9b8963Sdrh if( aRegIdx[i]==0 ) continue; 2487b2b9d3d7Sdrh if( pIdx->pPartIdxWhere ){ 2488b2b9d3d7Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); 2489688852abSdrh VdbeCoverage(v); 2490b2b9d3d7Sdrh } 2491cb9a3643Sdan pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0); 249248dd1d8eSdrh if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 24934308e348Sdrh assert( pParse->nested==0 ); 24946546af14Sdrh pik_flags |= OPFLAG_NCHANGE; 2495f91c1318Sdan pik_flags |= (update_flags & OPFLAG_SAVEPOSITION); 2496cb9a3643Sdan if( update_flags==0 ){ 2497fadc0e34Sdan codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]); 2498de630353Sdanielk1977 } 2499cb9a3643Sdan } 2500cb9a3643Sdan sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i], 2501cb9a3643Sdan aRegIdx[i]+1, 2502cb9a3643Sdan pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn); 25039b34abeeSdrh sqlite3VdbeChangeP5(v, pik_flags); 25040ca3e24bSdrh } 2505ec95c441Sdrh if( !HasRowid(pTab) ) return; 25064794f735Sdrh if( pParse->nested ){ 25074794f735Sdrh pik_flags = 0; 25084794f735Sdrh }else{ 250994eb6a14Sdanielk1977 pik_flags = OPFLAG_NCHANGE; 2510f91c1318Sdan pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID); 25114794f735Sdrh } 2512e4d90813Sdrh if( appendBias ){ 2513e4d90813Sdrh pik_flags |= OPFLAG_APPEND; 2514e4d90813Sdrh } 2515de630353Sdanielk1977 if( useSeekResult ){ 2516de630353Sdanielk1977 pik_flags |= OPFLAG_USESEEKRESULT; 2517de630353Sdanielk1977 } 2518a7c3b93fSdrh sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData); 251994eb6a14Sdanielk1977 if( !pParse->nested ){ 2520f14b7fb7Sdrh sqlite3VdbeAppendP4(v, pTab, P4_TABLE); 252194eb6a14Sdanielk1977 } 2522b7654111Sdrh sqlite3VdbeChangeP5(v, pik_flags); 25230ca3e24bSdrh } 2524cd44690aSdrh 2525cd44690aSdrh /* 252626198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate 252726198bb4Sdrh ** code to open and initialized those cursors. 2528aa9b8963Sdrh ** 252926198bb4Sdrh ** The cursor for the object that contains the complete data (normally 253026198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT 253126198bb4Sdrh ** ROWID table) is returned in *piDataCur. The first index cursor is 253226198bb4Sdrh ** returned in *piIdxCur. The number of indices is returned. 253326198bb4Sdrh ** 253426198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables 253526198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative. 253626198bb4Sdrh ** If iBase is negative, then allocate the next available cursor. 253726198bb4Sdrh ** 253826198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. 253926198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range 254026198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the 254126198bb4Sdrh ** pTab->pIndex list. 2542b6b4b79fSdrh ** 2543b6b4b79fSdrh ** If pTab is a virtual table, then this routine is a no-op and the 2544b6b4b79fSdrh ** *piDataCur and *piIdxCur values are left uninitialized. 2545cd44690aSdrh */ 2546aa9b8963Sdrh int sqlite3OpenTableAndIndices( 2547290c1948Sdrh Parse *pParse, /* Parsing context */ 2548290c1948Sdrh Table *pTab, /* Table to be opened */ 254926198bb4Sdrh int op, /* OP_OpenRead or OP_OpenWrite */ 2550b89aeb6aSdrh u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */ 255126198bb4Sdrh int iBase, /* Use this for the table cursor, if there is one */ 25526a53499aSdrh u8 *aToOpen, /* If not NULL: boolean for each table and index */ 255326198bb4Sdrh int *piDataCur, /* Write the database source cursor number here */ 255426198bb4Sdrh int *piIdxCur /* Write the first index cursor number here */ 2555290c1948Sdrh ){ 2556cd44690aSdrh int i; 25574cbdda9eSdrh int iDb; 25586a53499aSdrh int iDataCur; 2559cd44690aSdrh Index *pIdx; 25604cbdda9eSdrh Vdbe *v; 25614cbdda9eSdrh 256226198bb4Sdrh assert( op==OP_OpenRead || op==OP_OpenWrite ); 2563fd261ec6Sdan assert( op==OP_OpenWrite || p5==0 ); 256426198bb4Sdrh if( IsVirtual(pTab) ){ 2565b6b4b79fSdrh /* This routine is a no-op for virtual tables. Leave the output 2566b6b4b79fSdrh ** variables *piDataCur and *piIdxCur uninitialized so that valgrind 2567b6b4b79fSdrh ** can detect if they are used by mistake in the caller. */ 256826198bb4Sdrh return 0; 256926198bb4Sdrh } 25704cbdda9eSdrh iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 2571f0b41745Sdrh v = pParse->pVdbe; 2572cd44690aSdrh assert( v!=0 ); 257326198bb4Sdrh if( iBase<0 ) iBase = pParse->nTab; 25746a53499aSdrh iDataCur = iBase++; 25756a53499aSdrh if( piDataCur ) *piDataCur = iDataCur; 25766a53499aSdrh if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ 25776a53499aSdrh sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); 25786fbe41acSdrh }else{ 257926198bb4Sdrh sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); 25806fbe41acSdrh } 25816a53499aSdrh if( piIdxCur ) *piIdxCur = iBase; 258226198bb4Sdrh for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 258326198bb4Sdrh int iIdxCur = iBase++; 2584da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 258561441c34Sdan if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 258661441c34Sdan if( piDataCur ) *piDataCur = iIdxCur; 258761441c34Sdan p5 = 0; 258861441c34Sdan } 25896a53499aSdrh if( aToOpen==0 || aToOpen[i+1] ){ 25902ec2fb22Sdrh sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); 25912ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 2592b89aeb6aSdrh sqlite3VdbeChangeP5(v, p5); 259361441c34Sdan VdbeComment((v, "%s", pIdx->zName)); 2594b89aeb6aSdrh } 25956a53499aSdrh } 259626198bb4Sdrh if( iBase>pParse->nTab ) pParse->nTab = iBase; 259726198bb4Sdrh return i; 2598cd44690aSdrh } 25999d9cf229Sdrh 260091c58e23Sdrh 260191c58e23Sdrh #ifdef SQLITE_TEST 260291c58e23Sdrh /* 260391c58e23Sdrh ** The following global variable is incremented whenever the 260491c58e23Sdrh ** transfer optimization is used. This is used for testing 260591c58e23Sdrh ** purposes only - to make sure the transfer optimization really 260660ec914cSpeter.d.reid ** is happening when it is supposed to. 260791c58e23Sdrh */ 260891c58e23Sdrh int sqlite3_xferopt_count; 260991c58e23Sdrh #endif /* SQLITE_TEST */ 261091c58e23Sdrh 261191c58e23Sdrh 26129d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 26139d9cf229Sdrh /* 26149d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data 26159d9cf229Sdrh ** for index pDest in an insert transfer optimization. The rules 26169d9cf229Sdrh ** for a compatible index: 26179d9cf229Sdrh ** 26189d9cf229Sdrh ** * The index is over the same set of columns 26199d9cf229Sdrh ** * The same DESC and ASC markings occurs on all columns 26209d9cf229Sdrh ** * The same onError processing (OE_Abort, OE_Ignore, etc) 26219d9cf229Sdrh ** * The same collating sequence on each column 2622b2b9d3d7Sdrh ** * The index has the exact same WHERE clause 26239d9cf229Sdrh */ 26249d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 26259d9cf229Sdrh int i; 26269d9cf229Sdrh assert( pDest && pSrc ); 26279d9cf229Sdrh assert( pDest->pTable!=pSrc->pTable ); 26281e7c00e6Sdrh if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){ 26299d9cf229Sdrh return 0; /* Different number of columns */ 26309d9cf229Sdrh } 26319d9cf229Sdrh if( pDest->onError!=pSrc->onError ){ 26329d9cf229Sdrh return 0; /* Different conflict resolution strategies */ 26339d9cf229Sdrh } 2634bbbdc83bSdrh for(i=0; i<pSrc->nKeyCol; i++){ 26359d9cf229Sdrh if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 26369d9cf229Sdrh return 0; /* Different columns indexed */ 26379d9cf229Sdrh } 26384b92f98cSdrh if( pSrc->aiColumn[i]==XN_EXPR ){ 26391f9ca2c8Sdrh assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); 26405aa550cfSdan if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr, 26411f9ca2c8Sdrh pDest->aColExpr->a[i].pExpr, -1)!=0 ){ 26421f9ca2c8Sdrh return 0; /* Different expressions in the index */ 26431f9ca2c8Sdrh } 26441f9ca2c8Sdrh } 26459d9cf229Sdrh if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 26469d9cf229Sdrh return 0; /* Different sort orders */ 26479d9cf229Sdrh } 26480472af91Sdrh if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){ 264960a713c6Sdrh return 0; /* Different collating sequences */ 26509d9cf229Sdrh } 26519d9cf229Sdrh } 26525aa550cfSdan if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ 2653b2b9d3d7Sdrh return 0; /* Different WHERE clauses */ 2654b2b9d3d7Sdrh } 26559d9cf229Sdrh 26569d9cf229Sdrh /* If no test above fails then the indices must be compatible */ 26579d9cf229Sdrh return 1; 26589d9cf229Sdrh } 26599d9cf229Sdrh 26609d9cf229Sdrh /* 26619d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form 26629d9cf229Sdrh ** 26639d9cf229Sdrh ** INSERT INTO tab1 SELECT * FROM tab2; 26649d9cf229Sdrh ** 2665ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1. 266660ec914cSpeter.d.reid ** Columns are not decoded and reassembled, which greatly improves 2667ccdf1baeSdrh ** performance. Raw index records are transferred in the same way. 26689d9cf229Sdrh ** 2669ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible. 2670ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments 2671ccdf1baeSdrh ** embedded in the code for details. 26729d9cf229Sdrh ** 2673ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used. 2674ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table 2675ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time. In that 2676ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also 2677ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the 2678ccdf1baeSdrh ** xfer optimization code if the test fails. In that case, this routine 2679ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate 2680ccdf1baeSdrh ** an unoptimized transfer. This routine also returns FALSE if there 2681ccdf1baeSdrh ** is no chance that the xfer optimization can be applied. 26829d9cf229Sdrh ** 2683ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster. 26849d9cf229Sdrh */ 26859d9cf229Sdrh static int xferOptimization( 26869d9cf229Sdrh Parse *pParse, /* Parser context */ 26879d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 26889d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 26899d9cf229Sdrh int onError, /* How to handle constraint errors */ 26909d9cf229Sdrh int iDbDest /* The database of pDest */ 26919d9cf229Sdrh ){ 2692e34162b1Sdan sqlite3 *db = pParse->db; 26939d9cf229Sdrh ExprList *pEList; /* The result set of the SELECT */ 26949d9cf229Sdrh Table *pSrc; /* The table in the FROM clause of SELECT */ 26959d9cf229Sdrh Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 26967601294aSdrh SrcItem *pItem; /* An element of pSelect->pSrc */ 26979d9cf229Sdrh int i; /* Loop counter */ 26989d9cf229Sdrh int iDbSrc; /* The database of pSrc */ 26999d9cf229Sdrh int iSrc, iDest; /* Cursors from source and destination */ 27009d9cf229Sdrh int addr1, addr2; /* Loop addresses */ 2701da475b8dSdrh int emptyDestTest = 0; /* Address of test for empty pDest */ 2702da475b8dSdrh int emptySrcTest = 0; /* Address of test for empty pSrc */ 27039d9cf229Sdrh Vdbe *v; /* The VDBE we are building */ 27046a288a33Sdrh int regAutoinc; /* Memory register used by AUTOINC */ 2705f33c9fadSdrh int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 2706b7654111Sdrh int regData, regRowid; /* Registers holding data and rowid */ 27079d9cf229Sdrh 27089d9cf229Sdrh if( pSelect==0 ){ 27099d9cf229Sdrh return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 27109d9cf229Sdrh } 2711ebbf08a0Sdan if( pParse->pWith || pSelect->pWith ){ 2712ebbf08a0Sdan /* Do not attempt to process this query if there are an WITH clauses 2713ebbf08a0Sdan ** attached to it. Proceeding may generate a false "no such table: xxx" 2714ebbf08a0Sdan ** error if pSelect reads from a CTE named "xxx". */ 2715ebbf08a0Sdan return 0; 2716ebbf08a0Sdan } 27172f886d1dSdanielk1977 if( sqlite3TriggerList(pParse, pDest) ){ 27189d9cf229Sdrh return 0; /* tab1 must not have triggers */ 27199d9cf229Sdrh } 27209d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 272144266ec6Sdrh if( IsVirtual(pDest) ){ 27229d9cf229Sdrh return 0; /* tab1 must not be a virtual table */ 27239d9cf229Sdrh } 27249d9cf229Sdrh #endif 27259d9cf229Sdrh if( onError==OE_Default ){ 2726e7224a01Sdrh if( pDest->iPKey>=0 ) onError = pDest->keyConf; 2727e7224a01Sdrh if( onError==OE_Default ) onError = OE_Abort; 27289d9cf229Sdrh } 27295ce240a6Sdanielk1977 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 27309d9cf229Sdrh if( pSelect->pSrc->nSrc!=1 ){ 27319d9cf229Sdrh return 0; /* FROM clause must have exactly one term */ 27329d9cf229Sdrh } 27339d9cf229Sdrh if( pSelect->pSrc->a[0].pSelect ){ 27349d9cf229Sdrh return 0; /* FROM clause cannot contain a subquery */ 27359d9cf229Sdrh } 27369d9cf229Sdrh if( pSelect->pWhere ){ 27379d9cf229Sdrh return 0; /* SELECT may not have a WHERE clause */ 27389d9cf229Sdrh } 27399d9cf229Sdrh if( pSelect->pOrderBy ){ 27409d9cf229Sdrh return 0; /* SELECT may not have an ORDER BY clause */ 27419d9cf229Sdrh } 27428103b7d2Sdrh /* Do not need to test for a HAVING clause. If HAVING is present but 27438103b7d2Sdrh ** there is no ORDER BY, we will get an error. */ 27449d9cf229Sdrh if( pSelect->pGroupBy ){ 27459d9cf229Sdrh return 0; /* SELECT may not have a GROUP BY clause */ 27469d9cf229Sdrh } 27479d9cf229Sdrh if( pSelect->pLimit ){ 27489d9cf229Sdrh return 0; /* SELECT may not have a LIMIT clause */ 27499d9cf229Sdrh } 27509d9cf229Sdrh if( pSelect->pPrior ){ 27519d9cf229Sdrh return 0; /* SELECT may not be a compound query */ 27529d9cf229Sdrh } 27537d10d5a6Sdrh if( pSelect->selFlags & SF_Distinct ){ 27549d9cf229Sdrh return 0; /* SELECT may not be DISTINCT */ 27559d9cf229Sdrh } 27569d9cf229Sdrh pEList = pSelect->pEList; 27579d9cf229Sdrh assert( pEList!=0 ); 27589d9cf229Sdrh if( pEList->nExpr!=1 ){ 27599d9cf229Sdrh return 0; /* The result set must have exactly one column */ 27609d9cf229Sdrh } 27619d9cf229Sdrh assert( pEList->a[0].pExpr ); 27621a1d3cd2Sdrh if( pEList->a[0].pExpr->op!=TK_ASTERISK ){ 27639d9cf229Sdrh return 0; /* The result set must be the special operator "*" */ 27649d9cf229Sdrh } 27659d9cf229Sdrh 27669d9cf229Sdrh /* At this point we have established that the statement is of the 27679d9cf229Sdrh ** correct syntactic form to participate in this optimization. Now 27689d9cf229Sdrh ** we have to check the semantics. 27699d9cf229Sdrh */ 27709d9cf229Sdrh pItem = pSelect->pSrc->a; 277141fb5cd1Sdan pSrc = sqlite3LocateTableItem(pParse, 0, pItem); 27729d9cf229Sdrh if( pSrc==0 ){ 27739d9cf229Sdrh return 0; /* FROM clause does not contain a real table */ 27749d9cf229Sdrh } 277521908b21Sdrh if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){ 27761e32bed3Sdrh testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */ 27779d9cf229Sdrh return 0; /* tab1 and tab2 may not be the same table */ 27789d9cf229Sdrh } 277955548273Sdrh if( HasRowid(pDest)!=HasRowid(pSrc) ){ 278055548273Sdrh return 0; /* source and destination must both be WITHOUT ROWID or not */ 278155548273Sdrh } 27829d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 278344266ec6Sdrh if( IsVirtual(pSrc) ){ 27849d9cf229Sdrh return 0; /* tab2 must not be a virtual table */ 27859d9cf229Sdrh } 27869d9cf229Sdrh #endif 27879d9cf229Sdrh if( pSrc->pSelect ){ 27889d9cf229Sdrh return 0; /* tab2 may not be a view */ 27899d9cf229Sdrh } 27909d9cf229Sdrh if( pDest->nCol!=pSrc->nCol ){ 27919d9cf229Sdrh return 0; /* Number of columns must be the same in tab1 and tab2 */ 27929d9cf229Sdrh } 27939d9cf229Sdrh if( pDest->iPKey!=pSrc->iPKey ){ 27949d9cf229Sdrh return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 27959d9cf229Sdrh } 27969d9cf229Sdrh for(i=0; i<pDest->nCol; i++){ 27979940e2aaSdan Column *pDestCol = &pDest->aCol[i]; 27989940e2aaSdan Column *pSrcCol = &pSrc->aCol[i]; 2799ba68f8f3Sdan #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS 28008257aa8dSdrh if( (db->mDbFlags & DBFLAG_Vacuum)==0 2801aaea3143Sdan && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN 2802aaea3143Sdan ){ 2803ba68f8f3Sdan return 0; /* Neither table may have __hidden__ columns */ 2804ba68f8f3Sdan } 2805ba68f8f3Sdan #endif 28066ab61d70Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 28076ab61d70Sdrh /* Even if tables t1 and t2 have identical schemas, if they contain 28086ab61d70Sdrh ** generated columns, then this statement is semantically incorrect: 28096ab61d70Sdrh ** 28106ab61d70Sdrh ** INSERT INTO t2 SELECT * FROM t1; 28116ab61d70Sdrh ** 28126ab61d70Sdrh ** The reason is that generated column values are returned by the 28136ab61d70Sdrh ** the SELECT statement on the right but the INSERT statement on the 28146ab61d70Sdrh ** left wants them to be omitted. 28156ab61d70Sdrh ** 28166ab61d70Sdrh ** Nevertheless, this is a useful notational shorthand to tell SQLite 28176ab61d70Sdrh ** to do a bulk transfer all of the content from t1 over to t2. 28186ab61d70Sdrh ** 28196ab61d70Sdrh ** We could, in theory, disable this (except for internal use by the 28206ab61d70Sdrh ** VACUUM command where it is actually needed). But why do that? It 28216ab61d70Sdrh ** seems harmless enough, and provides a useful service. 28226ab61d70Sdrh */ 2823ae3977a8Sdrh if( (pDestCol->colFlags & COLFLAG_GENERATED) != 2824ae3977a8Sdrh (pSrcCol->colFlags & COLFLAG_GENERATED) ){ 28256ab61d70Sdrh return 0; /* Both columns have the same generated-column type */ 2826ae3977a8Sdrh } 28276ab61d70Sdrh /* But the transfer is only allowed if both the source and destination 28286ab61d70Sdrh ** tables have the exact same expressions for generated columns. 28296ab61d70Sdrh ** This requirement could be relaxed for VIRTUAL columns, I suppose. 28306ab61d70Sdrh */ 28316ab61d70Sdrh if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){ 28326ab61d70Sdrh if( sqlite3ExprCompare(0, pSrcCol->pDflt, pDestCol->pDflt, -1)!=0 ){ 28336ab61d70Sdrh testcase( pDestCol->colFlags & COLFLAG_VIRTUAL ); 28346ab61d70Sdrh testcase( pDestCol->colFlags & COLFLAG_STORED ); 28356ab61d70Sdrh return 0; /* Different generator expressions */ 28366ab61d70Sdrh } 28376ab61d70Sdrh } 28386ab61d70Sdrh #endif 28399940e2aaSdan if( pDestCol->affinity!=pSrcCol->affinity ){ 28409d9cf229Sdrh return 0; /* Affinity must be the same on all columns */ 28419d9cf229Sdrh } 28420472af91Sdrh if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){ 28439d9cf229Sdrh return 0; /* Collating sequence must be the same on all columns */ 28449d9cf229Sdrh } 28459940e2aaSdan if( pDestCol->notNull && !pSrcCol->notNull ){ 28469d9cf229Sdrh return 0; /* tab2 must be NOT NULL if tab1 is */ 28479d9cf229Sdrh } 2848453e0261Sdrh /* Default values for second and subsequent columns need to match. */ 2849ae3977a8Sdrh if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){ 285094fa9c41Sdrh assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN ); 285194fa9c41Sdrh assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN ); 285294fa9c41Sdrh if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) 285394fa9c41Sdrh || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken, 285494fa9c41Sdrh pSrcCol->pDflt->u.zToken)!=0) 28559940e2aaSdan ){ 28569940e2aaSdan return 0; /* Default values must be the same for all columns */ 28579940e2aaSdan } 28589d9cf229Sdrh } 285994fa9c41Sdrh } 28609d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 28615f1d1d9cSdrh if( IsUniqueIndex(pDestIdx) ){ 2862f33c9fadSdrh destHasUniqueIdx = 1; 2863f33c9fadSdrh } 28649d9cf229Sdrh for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 28659d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 28669d9cf229Sdrh } 28679d9cf229Sdrh if( pSrcIdx==0 ){ 28689d9cf229Sdrh return 0; /* pDestIdx has no corresponding index in pSrc */ 28699d9cf229Sdrh } 2870e3bd232eSdrh if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema 2871e3bd232eSdrh && sqlite3FaultSim(411)==SQLITE_OK ){ 2872e3bd232eSdrh /* The sqlite3FaultSim() call allows this corruption test to be 2873e3bd232eSdrh ** bypassed during testing, in order to exercise other corruption tests 2874e3bd232eSdrh ** further downstream. */ 287586223e8dSdrh return 0; /* Corrupt schema - two indexes on the same btree */ 287686223e8dSdrh } 28779d9cf229Sdrh } 28787fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK 2879619a1305Sdrh if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ 28808103b7d2Sdrh return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 28818103b7d2Sdrh } 28827fc2f41bSdrh #endif 2883713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY 2884713de341Sdrh /* Disallow the transfer optimization if the destination table constains 2885713de341Sdrh ** any foreign key constraints. This is more restrictive than necessary. 2886713de341Sdrh ** But the main beneficiary of the transfer optimization is the VACUUM 2887713de341Sdrh ** command, and the VACUUM command disables foreign key constraints. So 2888713de341Sdrh ** the extra complication to make this rule less restrictive is probably 2889713de341Sdrh ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] 2890713de341Sdrh */ 2891e34162b1Sdan if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ 2892713de341Sdrh return 0; 2893713de341Sdrh } 2894713de341Sdrh #endif 2895e34162b1Sdan if( (db->flags & SQLITE_CountRows)!=0 ){ 2896ccdf1baeSdrh return 0; /* xfer opt does not play well with PRAGMA count_changes */ 28971696124dSdan } 28989d9cf229Sdrh 2899ccdf1baeSdrh /* If we get this far, it means that the xfer optimization is at 2900ccdf1baeSdrh ** least a possibility, though it might only work if the destination 2901ccdf1baeSdrh ** table (tab1) is initially empty. 29029d9cf229Sdrh */ 2903dd73521bSdrh #ifdef SQLITE_TEST 2904dd73521bSdrh sqlite3_xferopt_count++; 2905dd73521bSdrh #endif 2906e34162b1Sdan iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); 29079d9cf229Sdrh v = sqlite3GetVdbe(pParse); 2908f53e9b5aSdrh sqlite3CodeVerifySchema(pParse, iDbSrc); 29099d9cf229Sdrh iSrc = pParse->nTab++; 29109d9cf229Sdrh iDest = pParse->nTab++; 29116a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 291255548273Sdrh regData = sqlite3GetTempReg(pParse); 29137aae7358Sdan sqlite3VdbeAddOp2(v, OP_Null, 0, regData); 291455548273Sdrh regRowid = sqlite3GetTempReg(pParse); 29159d9cf229Sdrh sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 2916427ebba1Sdan assert( HasRowid(pDest) || destHasUniqueIdx ); 29178257aa8dSdrh if( (db->mDbFlags & DBFLAG_Vacuum)==0 && ( 2918e34162b1Sdan (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ 2919ccdf1baeSdrh || destHasUniqueIdx /* (2) */ 2920ccdf1baeSdrh || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ 2921e34162b1Sdan )){ 2922ccdf1baeSdrh /* In some circumstances, we are able to run the xfer optimization 2923e34162b1Sdan ** only if the destination table is initially empty. Unless the 29248257aa8dSdrh ** DBFLAG_Vacuum flag is set, this block generates code to make 29258257aa8dSdrh ** that determination. If DBFLAG_Vacuum is set, then the destination 2926e34162b1Sdan ** table is always empty. 2927e34162b1Sdan ** 2928e34162b1Sdan ** Conditions under which the destination must be empty: 2929f33c9fadSdrh ** 2930ccdf1baeSdrh ** (1) There is no INTEGER PRIMARY KEY but there are indices. 2931ccdf1baeSdrh ** (If the destination is not initially empty, the rowid fields 2932ccdf1baeSdrh ** of index entries might need to change.) 2933ccdf1baeSdrh ** 2934ccdf1baeSdrh ** (2) The destination has a unique index. (The xfer optimization 2935ccdf1baeSdrh ** is unable to test uniqueness.) 2936ccdf1baeSdrh ** 2937ccdf1baeSdrh ** (3) onError is something other than OE_Abort and OE_Rollback. 29389d9cf229Sdrh */ 2939688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); 29402991ba05Sdrh emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); 29419d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 29429d9cf229Sdrh } 2943427ebba1Sdan if( HasRowid(pSrc) ){ 2944c9b9deaeSdrh u8 insFlags; 29459d9cf229Sdrh sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 2946688852abSdrh emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 294742242dedSdrh if( pDest->iPKey>=0 ){ 2948b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 2949036e0675Sdan if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){ 29504031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 2951b7654111Sdrh addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 2952688852abSdrh VdbeCoverage(v); 2953f9c8ce3cSdrh sqlite3RowidConstraint(pParse, onError, pDest); 29549d9cf229Sdrh sqlite3VdbeJumpHere(v, addr2); 2955036e0675Sdan } 2956b7654111Sdrh autoIncStep(pParse, regAutoinc, regRowid); 29574e61e883Sdrh }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){ 2958b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 295995bad4c7Sdrh }else{ 2960b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 29617d10d5a6Sdrh assert( (pDest->tabFlags & TF_Autoincrement)==0 ); 296295bad4c7Sdrh } 29637aae7358Sdan 29648257aa8dSdrh if( db->mDbFlags & DBFLAG_Vacuum ){ 296586b40dfdSdrh sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); 29667aae7358Sdan insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT; 2967c9b9deaeSdrh }else{ 29687aae7358Sdan insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT; 29697aae7358Sdan } 29707aae7358Sdan #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 2971a55a839aSdan if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){ 297251f37b2bSdrh sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); 29737aae7358Sdan insFlags &= ~OPFLAG_PREFORMAT; 2974a55a839aSdan }else 2975fadc0e34Sdan #endif 2976a55a839aSdan { 2977a55a839aSdan sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid); 2978a55a839aSdan } 2979a55a839aSdan sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); 2980a55a839aSdan if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){ 2981a55a839aSdan sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE); 2982a55a839aSdan } 2983c9b9deaeSdrh sqlite3VdbeChangeP5(v, insFlags); 29847aae7358Sdan 2985688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); 298655548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 298755548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2988da475b8dSdrh }else{ 2989da475b8dSdrh sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); 2990da475b8dSdrh sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); 299155548273Sdrh } 29929d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 299341b9ca25Sdrh u8 idxInsFlags = 0; 29941b7ecbb4Sdrh for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ 29959d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 29969d9cf229Sdrh } 29979d9cf229Sdrh assert( pSrcIdx ); 29982ec2fb22Sdrh sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); 29992ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); 3000d4e70ebdSdrh VdbeComment((v, "%s", pSrcIdx->zName)); 30012ec2fb22Sdrh sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); 30022ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); 300359885728Sdan sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); 3004207872a4Sdanielk1977 VdbeComment((v, "%s", pDestIdx->zName)); 3005688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 30068257aa8dSdrh if( db->mDbFlags & DBFLAG_Vacuum ){ 3007e34162b1Sdan /* This INSERT command is part of a VACUUM operation, which guarantees 3008e34162b1Sdan ** that the destination table is empty. If all indexed columns use 3009e34162b1Sdan ** collation sequence BINARY, then it can also be assumed that the 3010e34162b1Sdan ** index will be populated by inserting keys in strictly sorted 3011e34162b1Sdan ** order. In this case, instead of seeking within the b-tree as part 301286b40dfdSdrh ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the 3013e34162b1Sdan ** OP_IdxInsert to seek to the point within the b-tree where each key 3014e34162b1Sdan ** should be inserted. This is faster. 3015e34162b1Sdan ** 3016e34162b1Sdan ** If any of the indexed columns use a collation sequence other than 3017e34162b1Sdan ** BINARY, this optimization is disabled. This is because the user 3018e34162b1Sdan ** might change the definition of a collation sequence and then run 3019e34162b1Sdan ** a VACUUM command. In that case keys may not be written in strictly 3020e34162b1Sdan ** sorted order. */ 3021e34162b1Sdan for(i=0; i<pSrcIdx->nColumn; i++){ 3022f19aa5faSdrh const char *zColl = pSrcIdx->azColl[i]; 3023f19aa5faSdrh if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break; 3024e34162b1Sdan } 3025e34162b1Sdan if( i==pSrcIdx->nColumn ){ 30267aae7358Sdan idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT; 302786b40dfdSdrh sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); 3028a06eafc8Sdrh sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc); 3029e34162b1Sdan } 3030c84ad318Sdrh }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){ 303141b9ca25Sdrh idxInsFlags |= OPFLAG_NCHANGE; 303241b9ca25Sdrh } 30337aae7358Sdan if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){ 303451f37b2bSdrh sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); 3035a55a839aSdan if( (db->mDbFlags & DBFLAG_Vacuum)==0 3036a55a839aSdan && !HasRowid(pDest) 3037a55a839aSdan && IsPrimaryKeyIndex(pDestIdx) 3038a55a839aSdan ){ 3039fadc0e34Sdan codeWithoutRowidPreupdate(pParse, pDest, iDest, regData); 3040fadc0e34Sdan } 30417aae7358Sdan } 30429b4eaebcSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData); 30439b4eaebcSdrh sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND); 3044688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); 30459d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 304655548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 304755548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 30489d9cf229Sdrh } 3049aceb31b1Sdrh if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); 3050b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 3051b7654111Sdrh sqlite3ReleaseTempReg(pParse, regData); 30529d9cf229Sdrh if( emptyDestTest ){ 30531dd518cfSdrh sqlite3AutoincrementEnd(pParse); 305466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 30559d9cf229Sdrh sqlite3VdbeJumpHere(v, emptyDestTest); 305666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 30579d9cf229Sdrh return 0; 30589d9cf229Sdrh }else{ 30599d9cf229Sdrh return 1; 30609d9cf229Sdrh } 30619d9cf229Sdrh } 30629d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 3063