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) ); 352ec2fb22Sdrh v = sqlite3GetVdbe(pParse); 36bbb5e4e0Sdrh assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); 372ec2fb22Sdrh sqlite3TableLock(pParse, iDb, pTab->tnum, 382ec2fb22Sdrh (opcode==OP_OpenWrite)?1:0, pTab->zName); 39ec95c441Sdrh if( HasRowid(pTab) ){ 400b0b3a95Sdrh sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol); 41bbb5e4e0Sdrh VdbeComment((v, "%s", pTab->zName)); 4226198bb4Sdrh }else{ 43dd9930efSdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab); 44dd9930efSdrh assert( pPk!=0 ); 45afe028a8Sdrh assert( pPk->tnum==pTab->tnum ); 462ec2fb22Sdrh sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb); 472ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pPk); 48bbb5e4e0Sdrh VdbeComment((v, "%s", pTab->zName)); 49bbb5e4e0Sdrh } 50bbb5e4e0Sdrh } 51bbb5e4e0Sdrh 52bbb5e4e0Sdrh /* 5369f8bb9cSdan ** Return a pointer to the column affinity string associated with index 5469f8bb9cSdan ** pIdx. A column affinity string has one character for each column in 5569f8bb9cSdan ** the table, according to the affinity of the column: 563d1bfeaaSdanielk1977 ** 573d1bfeaaSdanielk1977 ** Character Column affinity 583d1bfeaaSdanielk1977 ** ------------------------------ 5905883a34Sdrh ** 'A' BLOB 604583c37cSdrh ** 'B' TEXT 614583c37cSdrh ** 'C' NUMERIC 624583c37cSdrh ** 'D' INTEGER 634583c37cSdrh ** 'F' REAL 642d401ab8Sdrh ** 654583c37cSdrh ** An extra 'D' is appended to the end of the string to cover the 662d401ab8Sdrh ** rowid that appears as the last column in every index. 6769f8bb9cSdan ** 6869f8bb9cSdan ** Memory for the buffer containing the column index affinity string 6969f8bb9cSdan ** is managed along with the rest of the Index structure. It will be 7069f8bb9cSdan ** released when sqlite3DeleteIndex() is called. 713d1bfeaaSdanielk1977 */ 72e9107698Sdrh const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){ 73a37cdde0Sdanielk1977 if( !pIdx->zColAff ){ 74e014a838Sdanielk1977 /* The first time a column affinity string for a particular index is 75a37cdde0Sdanielk1977 ** required, it is allocated and populated here. It is then stored as 76e014a838Sdanielk1977 ** a member of the Index structure for subsequent use. 77a37cdde0Sdanielk1977 ** 78a37cdde0Sdanielk1977 ** The column affinity string will eventually be deleted by 79e014a838Sdanielk1977 ** sqliteDeleteIndex() when the Index structure itself is cleaned 80a37cdde0Sdanielk1977 ** up. 81a37cdde0Sdanielk1977 */ 82a37cdde0Sdanielk1977 int n; 83a37cdde0Sdanielk1977 Table *pTab = pIdx->pTable; 84ad124329Sdrh pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1); 85a37cdde0Sdanielk1977 if( !pIdx->zColAff ){ 864a642b60Sdrh sqlite3OomFault(db); 8769f8bb9cSdan return 0; 88a37cdde0Sdanielk1977 } 89a37cdde0Sdanielk1977 for(n=0; n<pIdx->nColumn; n++){ 90ad124329Sdrh i16 x = pIdx->aiColumn[n]; 916860e6faSdrh char aff; 9281506b88Sdrh if( x>=0 ){ 9381506b88Sdrh aff = pTab->aCol[x].affinity; 9481506b88Sdrh }else if( x==XN_ROWID ){ 9581506b88Sdrh aff = SQLITE_AFF_INTEGER; 9681506b88Sdrh }else{ 974b92f98cSdrh assert( x==XN_EXPR ); 981f9ca2c8Sdrh assert( pIdx->aColExpr!=0 ); 996860e6faSdrh aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr); 10081506b88Sdrh } 10196fb16eeSdrh if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB; 1027314495fSdrh if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC; 1036860e6faSdrh pIdx->zColAff[n] = aff; 1041f9ca2c8Sdrh } 1052d401ab8Sdrh pIdx->zColAff[n] = 0; 106a37cdde0Sdanielk1977 } 1073d1bfeaaSdanielk1977 10869f8bb9cSdan return pIdx->zColAff; 109a37cdde0Sdanielk1977 } 110a37cdde0Sdanielk1977 111a37cdde0Sdanielk1977 /* 11257bf4a8eSdrh ** Compute the affinity string for table pTab, if it has not already been 11305883a34Sdrh ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities. 11457bf4a8eSdrh ** 11505883a34Sdrh ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and 11657bf4a8eSdrh ** if iReg>0 then code an OP_Affinity opcode that will set the affinities 11757bf4a8eSdrh ** for register iReg and following. Or if affinities exists and iReg==0, 11857bf4a8eSdrh ** then just set the P4 operand of the previous opcode (which should be 11957bf4a8eSdrh ** an OP_MakeRecord) to the affinity string. 12057bf4a8eSdrh ** 121b6e8fd10Sdrh ** A column affinity string has one character per column: 122a37cdde0Sdanielk1977 ** 123a37cdde0Sdanielk1977 ** Character Column affinity 124a37cdde0Sdanielk1977 ** ------------------------------ 12505883a34Sdrh ** 'A' BLOB 1264583c37cSdrh ** 'B' TEXT 1274583c37cSdrh ** 'C' NUMERIC 1284583c37cSdrh ** 'D' INTEGER 1294583c37cSdrh ** 'E' REAL 130a37cdde0Sdanielk1977 */ 13157bf4a8eSdrh void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ 132ab45fc04Sdrh int i, j; 13357bf4a8eSdrh char *zColAff = pTab->zColAff; 13457bf4a8eSdrh if( zColAff==0 ){ 135abb6fcabSdrh sqlite3 *db = sqlite3VdbeDb(v); 136b975598eSdrh zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); 1373d1bfeaaSdanielk1977 if( !zColAff ){ 1384a642b60Sdrh sqlite3OomFault(db); 139a37cdde0Sdanielk1977 return; 1403d1bfeaaSdanielk1977 } 1413d1bfeaaSdanielk1977 142ab45fc04Sdrh for(i=j=0; i<pTab->nCol; i++){ 14396fb16eeSdrh assert( pTab->aCol[i].affinity!=0 ); 144ab45fc04Sdrh if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){ 145ab45fc04Sdrh zColAff[j++] = pTab->aCol[i].affinity; 146ab45fc04Sdrh } 1473d1bfeaaSdanielk1977 } 14857bf4a8eSdrh do{ 149ab45fc04Sdrh zColAff[j--] = 0; 150ab45fc04Sdrh }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB ); 1513d1bfeaaSdanielk1977 pTab->zColAff = zColAff; 1523d1bfeaaSdanielk1977 } 1537301e774Sdrh assert( zColAff!=0 ); 1547301e774Sdrh i = sqlite3Strlen30NN(zColAff); 15557bf4a8eSdrh if( i ){ 15657bf4a8eSdrh if( iReg ){ 15757bf4a8eSdrh sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i); 15857bf4a8eSdrh }else{ 15957bf4a8eSdrh sqlite3VdbeChangeP4(v, -1, zColAff, i); 16057bf4a8eSdrh } 16157bf4a8eSdrh } 1623d1bfeaaSdanielk1977 } 1633d1bfeaaSdanielk1977 1644d88778bSdanielk1977 /* 16548d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices 166b6e8fd10Sdrh ** have been opened at any point in the VDBE program. This is used to see if 16748d1178aSdrh ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can 168b6e8fd10Sdrh ** run without using a temporary table for the results of the SELECT. 1694d88778bSdanielk1977 */ 17005a86c5cSdrh static int readsTable(Parse *p, int iDb, Table *pTab){ 171595a523aSdanielk1977 Vdbe *v = sqlite3GetVdbe(p); 1724d88778bSdanielk1977 int i; 17348d1178aSdrh int iEnd = sqlite3VdbeCurrentAddr(v); 174595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 175595a523aSdanielk1977 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; 176595a523aSdanielk1977 #endif 177595a523aSdanielk1977 17805a86c5cSdrh for(i=1; i<iEnd; i++){ 17948d1178aSdrh VdbeOp *pOp = sqlite3VdbeGetOp(v, i); 180ef0bea92Sdrh assert( pOp!=0 ); 181207872a4Sdanielk1977 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ 18248d1178aSdrh Index *pIndex; 183207872a4Sdanielk1977 int tnum = pOp->p2; 18448d1178aSdrh if( tnum==pTab->tnum ){ 18548d1178aSdrh return 1; 18648d1178aSdrh } 18748d1178aSdrh for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 18848d1178aSdrh if( tnum==pIndex->tnum ){ 18948d1178aSdrh return 1; 19048d1178aSdrh } 19148d1178aSdrh } 19248d1178aSdrh } 193543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 194595a523aSdanielk1977 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){ 1952dca4ac1Sdanielk1977 assert( pOp->p4.pVtab!=0 ); 19666a5167bSdrh assert( pOp->p4type==P4_VTAB ); 19748d1178aSdrh return 1; 1984d88778bSdanielk1977 } 199543165efSdrh #endif 2004d88778bSdanielk1977 } 2014d88778bSdanielk1977 return 0; 2024d88778bSdanielk1977 } 2033d1bfeaaSdanielk1977 204dfa15270Sdrh /* This walker callback will compute the union of colFlags flags for all 205*7dc76d8bSdrh ** referenced columns in a CHECK constraint or generated column expression. 206dfa15270Sdrh */ 207dfa15270Sdrh static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){ 208*7dc76d8bSdrh if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){ 209*7dc76d8bSdrh assert( pExpr->iColumn < pWalker->u.pTab->nCol ); 210dfa15270Sdrh pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags; 211dfa15270Sdrh } 212dfa15270Sdrh return WRC_Continue; 213dfa15270Sdrh } 214dfa15270Sdrh 215c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 216c1431144Sdrh /* 217c1431144Sdrh ** All regular columns for table pTab have been puts into registers 218c1431144Sdrh ** starting with iRegStore. The registers that correspond to STORED 219dd6cc9b5Sdrh ** or VIRTUAL columns have not yet been initialized. This routine goes 220dd6cc9b5Sdrh ** back and computes the values for those columns based on the previously 221dd6cc9b5Sdrh ** computed normal columns. 222c1431144Sdrh */ 223dd6cc9b5Sdrh void sqlite3ComputeGeneratedColumns( 224c1431144Sdrh Parse *pParse, /* Parsing context */ 225c1431144Sdrh int iRegStore, /* Register holding the first column */ 226c1431144Sdrh Table *pTab /* The table */ 227c1431144Sdrh ){ 228c1431144Sdrh int i; 229dfa15270Sdrh Walker w; 230dfa15270Sdrh Column *pRedo; 231dfa15270Sdrh int eProgress; 232dfa15270Sdrh 233dd6cc9b5Sdrh /* Because there can be multiple generated columns that refer to one another, 234dd6cc9b5Sdrh ** this is a two-pass algorithm. On the first pass, mark all generated 235dd6cc9b5Sdrh ** columns as "not available". 2369942ef0dSdrh */ 2379942ef0dSdrh for(i=0; i<pTab->nCol; i++){ 238dd6cc9b5Sdrh if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ 239ab0992f0Sdrh testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ); 240ab0992f0Sdrh testcase( pTab->aCol[i].colFlags & COLFLAG_STORED ); 2419942ef0dSdrh pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL; 2429942ef0dSdrh } 2439942ef0dSdrh } 244dfa15270Sdrh 245dfa15270Sdrh w.u.pTab = pTab; 246dfa15270Sdrh w.xExprCallback = exprColumnFlagUnion; 247dfa15270Sdrh w.xSelectCallback = 0; 248dfa15270Sdrh w.xSelectCallback2 = 0; 249dfa15270Sdrh 2509942ef0dSdrh /* On the second pass, compute the value of each NOT-AVAILABLE column. 2519942ef0dSdrh ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will 2529942ef0dSdrh ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as 2539942ef0dSdrh ** they are needed. 2549942ef0dSdrh */ 255c1431144Sdrh pParse->iSelfTab = -iRegStore; 256dfa15270Sdrh do{ 257dfa15270Sdrh eProgress = 0; 258dfa15270Sdrh pRedo = 0; 259dfa15270Sdrh for(i=0; i<pTab->nCol; i++){ 260dfa15270Sdrh Column *pCol = pTab->aCol + i; 261dfa15270Sdrh if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){ 262dfa15270Sdrh int x; 263dfa15270Sdrh pCol->colFlags |= COLFLAG_BUSY; 264dfa15270Sdrh w.eCode = 0; 265dfa15270Sdrh sqlite3WalkExpr(&w, pCol->pDflt); 266dfa15270Sdrh pCol->colFlags &= ~COLFLAG_BUSY; 267dfa15270Sdrh if( w.eCode & COLFLAG_NOTAVAIL ){ 268dfa15270Sdrh pRedo = pCol; 269dfa15270Sdrh continue; 270dd6cc9b5Sdrh } 271dfa15270Sdrh eProgress = 1; 272dfa15270Sdrh assert( pCol->colFlags & COLFLAG_GENERATED ); 273dfa15270Sdrh x = sqlite3TableColumnToStorage(pTab, i) + iRegStore; 274dfa15270Sdrh sqlite3ExprCodeGeneratedColumn(pParse, pCol, x); 275dfa15270Sdrh pCol->colFlags &= ~COLFLAG_NOTAVAIL; 276c1431144Sdrh } 277dfa15270Sdrh } 278dfa15270Sdrh }while( pRedo && eProgress ); 279dfa15270Sdrh if( pRedo ){ 280dfa15270Sdrh sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zName); 281c1431144Sdrh } 282c1431144Sdrh pParse->iSelfTab = 0; 283c1431144Sdrh } 284c1431144Sdrh #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 285c1431144Sdrh 286c1431144Sdrh 2879d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 2889d9cf229Sdrh /* 2890b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab 2900b9f50d8Sdrh ** which is in database iDb. Return the register number for the register 2919ef5e770Sdrh ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT 2929ef5e770Sdrh ** table. (Also return zero when doing a VACUUM since we do not want to 2939ef5e770Sdrh ** update the AUTOINCREMENT counters during a VACUUM.) 2949d9cf229Sdrh ** 2950b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the 2960b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within 2970b9f50d8Sdrh ** triggers. A new AutoincInfo structure is created if this is the 2980b9f50d8Sdrh ** first use of table pTab. On 2nd and subsequent uses, the original 2990b9f50d8Sdrh ** AutoincInfo structure is used. 3009d9cf229Sdrh ** 301c8abbc11Sdrh ** Four consecutive registers are allocated: 3020b9f50d8Sdrh ** 303c8abbc11Sdrh ** (1) The name of the pTab table. 304c8abbc11Sdrh ** (2) The maximum ROWID of pTab. 305c8abbc11Sdrh ** (3) The rowid in sqlite_sequence of pTab 306c8abbc11Sdrh ** (4) The original value of the max ROWID in pTab, or NULL if none 3070b9f50d8Sdrh ** 3080b9f50d8Sdrh ** The 2nd register is the one that is returned. That is all the 3090b9f50d8Sdrh ** insert routine needs to know about. 3109d9cf229Sdrh */ 3119d9cf229Sdrh static int autoIncBegin( 3129d9cf229Sdrh Parse *pParse, /* Parsing context */ 3139d9cf229Sdrh int iDb, /* Index of the database holding pTab */ 3149d9cf229Sdrh Table *pTab /* The table we are writing to */ 3159d9cf229Sdrh ){ 3166a288a33Sdrh int memId = 0; /* Register holding maximum rowid */ 317186ebd41Sdrh assert( pParse->db->aDb[iDb].pSchema!=0 ); 3189ef5e770Sdrh if( (pTab->tabFlags & TF_Autoincrement)!=0 3198257aa8dSdrh && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0 3209ef5e770Sdrh ){ 32165a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 3220b9f50d8Sdrh AutoincInfo *pInfo; 323186ebd41Sdrh Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab; 324186ebd41Sdrh 325186ebd41Sdrh /* Verify that the sqlite_sequence table exists and is an ordinary 326186ebd41Sdrh ** rowid table with exactly two columns. 327186ebd41Sdrh ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */ 328186ebd41Sdrh if( pSeqTab==0 329186ebd41Sdrh || !HasRowid(pSeqTab) 330186ebd41Sdrh || IsVirtual(pSeqTab) 331186ebd41Sdrh || pSeqTab->nCol!=2 332186ebd41Sdrh ){ 333186ebd41Sdrh pParse->nErr++; 334186ebd41Sdrh pParse->rc = SQLITE_CORRUPT_SEQUENCE; 335186ebd41Sdrh return 0; 336186ebd41Sdrh } 3370b9f50d8Sdrh 33865a7cd16Sdan pInfo = pToplevel->pAinc; 3390b9f50d8Sdrh while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } 3400b9f50d8Sdrh if( pInfo==0 ){ 341575fad65Sdrh pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo)); 3420b9f50d8Sdrh if( pInfo==0 ) return 0; 34365a7cd16Sdan pInfo->pNext = pToplevel->pAinc; 34465a7cd16Sdan pToplevel->pAinc = pInfo; 3450b9f50d8Sdrh pInfo->pTab = pTab; 3460b9f50d8Sdrh pInfo->iDb = iDb; 34765a7cd16Sdan pToplevel->nMem++; /* Register to hold name of table */ 34865a7cd16Sdan pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ 349c8abbc11Sdrh pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */ 3500b9f50d8Sdrh } 3510b9f50d8Sdrh memId = pInfo->regCtr; 3529d9cf229Sdrh } 3539d9cf229Sdrh return memId; 3549d9cf229Sdrh } 3559d9cf229Sdrh 3569d9cf229Sdrh /* 3570b9f50d8Sdrh ** This routine generates code that will initialize all of the 3580b9f50d8Sdrh ** register used by the autoincrement tracker. 3590b9f50d8Sdrh */ 3600b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){ 3610b9f50d8Sdrh AutoincInfo *p; /* Information about an AUTOINCREMENT */ 3620b9f50d8Sdrh sqlite3 *db = pParse->db; /* The database connection */ 3630b9f50d8Sdrh Db *pDb; /* Database only autoinc table */ 3640b9f50d8Sdrh int memId; /* Register holding max rowid */ 3650b9f50d8Sdrh Vdbe *v = pParse->pVdbe; /* VDBE under construction */ 3660b9f50d8Sdrh 367345ba7dbSdrh /* This routine is never called during trigger-generation. It is 368345ba7dbSdrh ** only called from the top-level */ 369345ba7dbSdrh assert( pParse->pTriggerTab==0 ); 370c149f18fSdrh assert( sqlite3IsToplevel(pParse) ); 37176d462eeSdan 3720b9f50d8Sdrh assert( v ); /* We failed long ago if this is not so */ 3730b9f50d8Sdrh for(p = pParse->pAinc; p; p = p->pNext){ 3741b32554bSdrh static const int iLn = VDBE_OFFSET_LINENO(2); 3751b32554bSdrh static const VdbeOpList autoInc[] = { 3761b32554bSdrh /* 0 */ {OP_Null, 0, 0, 0}, 377c8abbc11Sdrh /* 1 */ {OP_Rewind, 0, 10, 0}, 3781b32554bSdrh /* 2 */ {OP_Column, 0, 0, 0}, 379c8abbc11Sdrh /* 3 */ {OP_Ne, 0, 9, 0}, 3801b32554bSdrh /* 4 */ {OP_Rowid, 0, 0, 0}, 3811b32554bSdrh /* 5 */ {OP_Column, 0, 1, 0}, 382c8abbc11Sdrh /* 6 */ {OP_AddImm, 0, 0, 0}, 383c8abbc11Sdrh /* 7 */ {OP_Copy, 0, 0, 0}, 384c8abbc11Sdrh /* 8 */ {OP_Goto, 0, 11, 0}, 385c8abbc11Sdrh /* 9 */ {OP_Next, 0, 2, 0}, 386c8abbc11Sdrh /* 10 */ {OP_Integer, 0, 0, 0}, 387c8abbc11Sdrh /* 11 */ {OP_Close, 0, 0, 0} 3881b32554bSdrh }; 3891b32554bSdrh VdbeOp *aOp; 3900b9f50d8Sdrh pDb = &db->aDb[p->iDb]; 3910b9f50d8Sdrh memId = p->regCtr; 3922120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 3930b9f50d8Sdrh sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); 394076e85f5Sdrh sqlite3VdbeLoadString(v, memId-1, p->pTab->zName); 3951b32554bSdrh aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn); 3961b32554bSdrh if( aOp==0 ) break; 3971b32554bSdrh aOp[0].p2 = memId; 398c8abbc11Sdrh aOp[0].p3 = memId+2; 3991b32554bSdrh aOp[2].p3 = memId; 4001b32554bSdrh aOp[3].p1 = memId-1; 4011b32554bSdrh aOp[3].p3 = memId; 4021b32554bSdrh aOp[3].p5 = SQLITE_JUMPIFNULL; 4031b32554bSdrh aOp[4].p2 = memId+1; 4041b32554bSdrh aOp[5].p3 = memId; 405c8abbc11Sdrh aOp[6].p1 = memId; 406c8abbc11Sdrh aOp[7].p2 = memId+2; 407c8abbc11Sdrh aOp[7].p1 = memId; 408c8abbc11Sdrh aOp[10].p2 = memId; 40904ab586bSdrh if( pParse->nTab==0 ) pParse->nTab = 1; 4100b9f50d8Sdrh } 4110b9f50d8Sdrh } 4120b9f50d8Sdrh 4130b9f50d8Sdrh /* 4149d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation. 4159d9cf229Sdrh ** 4161b32554bSdrh ** This routine should be called when the regRowid register holds a 4179d9cf229Sdrh ** new rowid that is about to be inserted. If that new rowid is 4189d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the 4191b32554bSdrh ** memory cell is updated. 4209d9cf229Sdrh */ 4216a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){ 4229d9cf229Sdrh if( memId>0 ){ 4236a288a33Sdrh sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); 4249d9cf229Sdrh } 4259d9cf229Sdrh } 4269d9cf229Sdrh 4279d9cf229Sdrh /* 4280b9f50d8Sdrh ** This routine generates the code needed to write autoincrement 4290b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register. 4300b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement 4310b9f50d8Sdrh ** table (either directly or through triggers) needs to call this 4320b9f50d8Sdrh ** routine just before the "exit" code. 4339d9cf229Sdrh */ 4341b32554bSdrh static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ 4350b9f50d8Sdrh AutoincInfo *p; 4369d9cf229Sdrh Vdbe *v = pParse->pVdbe; 4370b9f50d8Sdrh sqlite3 *db = pParse->db; 4386a288a33Sdrh 4399d9cf229Sdrh assert( v ); 4400b9f50d8Sdrh for(p = pParse->pAinc; p; p = p->pNext){ 4411b32554bSdrh static const int iLn = VDBE_OFFSET_LINENO(2); 4421b32554bSdrh static const VdbeOpList autoIncEnd[] = { 4431b32554bSdrh /* 0 */ {OP_NotNull, 0, 2, 0}, 4441b32554bSdrh /* 1 */ {OP_NewRowid, 0, 0, 0}, 4451b32554bSdrh /* 2 */ {OP_MakeRecord, 0, 2, 0}, 4461b32554bSdrh /* 3 */ {OP_Insert, 0, 0, 0}, 4471b32554bSdrh /* 4 */ {OP_Close, 0, 0, 0} 4481b32554bSdrh }; 4491b32554bSdrh VdbeOp *aOp; 4500b9f50d8Sdrh Db *pDb = &db->aDb[p->iDb]; 4510b9f50d8Sdrh int iRec; 4520b9f50d8Sdrh int memId = p->regCtr; 4530b9f50d8Sdrh 4540b9f50d8Sdrh iRec = sqlite3GetTempReg(pParse); 4552120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 456c8abbc11Sdrh sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId); 457c8abbc11Sdrh VdbeCoverage(v); 4580b9f50d8Sdrh sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); 4591b32554bSdrh aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn); 4601b32554bSdrh if( aOp==0 ) break; 4611b32554bSdrh aOp[0].p1 = memId+1; 4621b32554bSdrh aOp[1].p2 = memId+1; 4631b32554bSdrh aOp[2].p1 = memId-1; 4641b32554bSdrh aOp[2].p3 = iRec; 4651b32554bSdrh aOp[3].p2 = iRec; 4661b32554bSdrh aOp[3].p3 = memId+1; 4671b32554bSdrh aOp[3].p5 = OPFLAG_APPEND; 4680b9f50d8Sdrh sqlite3ReleaseTempReg(pParse, iRec); 4699d9cf229Sdrh } 4709d9cf229Sdrh } 4711b32554bSdrh void sqlite3AutoincrementEnd(Parse *pParse){ 4721b32554bSdrh if( pParse->pAinc ) autoIncrementEnd(pParse); 4731b32554bSdrh } 4749d9cf229Sdrh #else 4759d9cf229Sdrh /* 4769d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines 4779d9cf229Sdrh ** above are all no-ops 4789d9cf229Sdrh */ 4799d9cf229Sdrh # define autoIncBegin(A,B,C) (0) 480287fb61cSdanielk1977 # define autoIncStep(A,B,C) 4819d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */ 4829d9cf229Sdrh 4839d9cf229Sdrh 4849d9cf229Sdrh /* Forward declaration */ 4859d9cf229Sdrh static int xferOptimization( 4869d9cf229Sdrh Parse *pParse, /* Parser context */ 4879d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 4889d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 4899d9cf229Sdrh int onError, /* How to handle constraint errors */ 4909d9cf229Sdrh int iDbDest /* The database of pDest */ 4919d9cf229Sdrh ); 4929d9cf229Sdrh 4933d1bfeaaSdanielk1977 /* 494d82b5021Sdrh ** This routine is called to handle SQL of the following forms: 495cce7d176Sdrh ** 496a21f78b9Sdrh ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),... 4971ccde15dSdrh ** insert into TABLE (IDLIST) select 498a21f78b9Sdrh ** insert into TABLE (IDLIST) default values 499cce7d176Sdrh ** 5001ccde15dSdrh ** The IDLIST following the table name is always optional. If omitted, 501a21f78b9Sdrh ** then a list of all (non-hidden) columns for the table is substituted. 502a21f78b9Sdrh ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST 503a21f78b9Sdrh ** is omitted. 5041ccde15dSdrh ** 505a21f78b9Sdrh ** For the pSelect parameter holds the values to be inserted for the 506a21f78b9Sdrh ** first two forms shown above. A VALUES clause is really just short-hand 507a21f78b9Sdrh ** for a SELECT statement that omits the FROM clause and everything else 508a21f78b9Sdrh ** that follows. If the pSelect parameter is NULL, that means that the 509a21f78b9Sdrh ** DEFAULT VALUES form of the INSERT statement is intended. 510142e30dfSdrh ** 5119d9cf229Sdrh ** The code generated follows one of four templates. For a simple 512a21f78b9Sdrh ** insert with data coming from a single-row VALUES clause, the code executes 513e00ee6ebSdrh ** once straight down through. Pseudo-code follows (we call this 514e00ee6ebSdrh ** the "1st template"): 515142e30dfSdrh ** 516142e30dfSdrh ** open write cursor to <table> and its indices 517ec95c441Sdrh ** put VALUES clause expressions into registers 518142e30dfSdrh ** write the resulting record into <table> 519142e30dfSdrh ** cleanup 520142e30dfSdrh ** 5219d9cf229Sdrh ** The three remaining templates assume the statement is of the form 522142e30dfSdrh ** 523142e30dfSdrh ** INSERT INTO <table> SELECT ... 524142e30dfSdrh ** 5259d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - 5269d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table 5279d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and 5289d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical 5299d9cf229Sdrh ** schemas, including all the same indices, then a special optimization 5309d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>. 5319d9cf229Sdrh ** See the xferOptimization() function for the implementation of this 532e00ee6ebSdrh ** template. This is the 2nd template. 5339d9cf229Sdrh ** 5349d9cf229Sdrh ** open a write cursor to <table> 5359d9cf229Sdrh ** open read cursor on <table2> 5369d9cf229Sdrh ** transfer all records in <table2> over to <table> 5379d9cf229Sdrh ** close cursors 5389d9cf229Sdrh ** foreach index on <table> 5399d9cf229Sdrh ** open a write cursor on the <table> index 5409d9cf229Sdrh ** open a read cursor on the corresponding <table2> index 5419d9cf229Sdrh ** transfer all records from the read to the write cursors 5429d9cf229Sdrh ** close cursors 5439d9cf229Sdrh ** end foreach 5449d9cf229Sdrh ** 545e00ee6ebSdrh ** The 3rd template is for when the second template does not apply 5469d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time. 5479d9cf229Sdrh ** The generated code follows this template: 548142e30dfSdrh ** 549e00ee6ebSdrh ** X <- A 550142e30dfSdrh ** goto B 551142e30dfSdrh ** A: setup for the SELECT 5529d9cf229Sdrh ** loop over the rows in the SELECT 553e00ee6ebSdrh ** load values into registers R..R+n 554e00ee6ebSdrh ** yield X 555142e30dfSdrh ** end loop 556142e30dfSdrh ** cleanup after the SELECT 55781cf13ecSdrh ** end-coroutine X 558e00ee6ebSdrh ** B: open write cursor to <table> and its indices 55981cf13ecSdrh ** C: yield X, at EOF goto D 560e00ee6ebSdrh ** insert the select result into <table> from R..R+n 561e00ee6ebSdrh ** goto C 562142e30dfSdrh ** D: cleanup 563142e30dfSdrh ** 564e00ee6ebSdrh ** The 4th template is used if the insert statement takes its 565142e30dfSdrh ** values from a SELECT but the data is being inserted into a table 566142e30dfSdrh ** that is also read as part of the SELECT. In the third form, 56760ec914cSpeter.d.reid ** we have to use an intermediate table to store the results of 568142e30dfSdrh ** the select. The template is like this: 569142e30dfSdrh ** 570e00ee6ebSdrh ** X <- A 571142e30dfSdrh ** goto B 572142e30dfSdrh ** A: setup for the SELECT 573142e30dfSdrh ** loop over the tables in the SELECT 574e00ee6ebSdrh ** load value into register R..R+n 575e00ee6ebSdrh ** yield X 576142e30dfSdrh ** end loop 577142e30dfSdrh ** cleanup after the SELECT 57881cf13ecSdrh ** end co-routine R 579e00ee6ebSdrh ** B: open temp table 58081cf13ecSdrh ** L: yield X, at EOF goto M 581e00ee6ebSdrh ** insert row from R..R+n into temp table 582e00ee6ebSdrh ** goto L 583e00ee6ebSdrh ** M: open write cursor to <table> and its indices 584e00ee6ebSdrh ** rewind temp table 585e00ee6ebSdrh ** C: loop over rows of intermediate table 586142e30dfSdrh ** transfer values form intermediate table into <table> 587e00ee6ebSdrh ** end loop 588e00ee6ebSdrh ** D: cleanup 589cce7d176Sdrh */ 5904adee20fSdanielk1977 void sqlite3Insert( 591cce7d176Sdrh Parse *pParse, /* Parser context */ 592113088ecSdrh SrcList *pTabList, /* Name of table into which we are inserting */ 5935974a30fSdrh Select *pSelect, /* A SELECT statement to use as the data source */ 594f5f1915dSdrh IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */ 5952c2e844aSdrh int onError, /* How to handle constraint errors */ 59646d2e5c3Sdrh Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */ 597cce7d176Sdrh ){ 5986a288a33Sdrh sqlite3 *db; /* The main database structure */ 5996a288a33Sdrh Table *pTab; /* The table to insert into. aka TABLE */ 60060ffc807Sdrh int i, j; /* Loop counters */ 6015974a30fSdrh Vdbe *v; /* Generate code into this virtual machine */ 6025974a30fSdrh Index *pIdx; /* For looping over indices of the table */ 603967e8b73Sdrh int nColumn; /* Number of columns in the data */ 6046a288a33Sdrh int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ 60526198bb4Sdrh int iDataCur = 0; /* VDBE cursor that is the main data repository */ 60626198bb4Sdrh int iIdxCur = 0; /* First index cursor */ 607d82b5021Sdrh int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ 6080ca3e24bSdrh int endOfLoop; /* Label for the end of the insertion loop */ 609cfe9a69fSdanielk1977 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ 610e00ee6ebSdrh int addrInsTop = 0; /* Jump to label "D" */ 611e00ee6ebSdrh int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ 6122eb95377Sdrh SelectDest dest; /* Destination for SELECT on rhs of INSERT */ 6136a288a33Sdrh int iDb; /* Index of database holding TABLE */ 61405a86c5cSdrh u8 useTempTable = 0; /* Store SELECT results in intermediate table */ 61505a86c5cSdrh u8 appendFlag = 0; /* True if the insert is likely to be an append */ 61605a86c5cSdrh u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ 617a21f78b9Sdrh u8 bIdListInOrder; /* True if IDLIST is in table order */ 61875593d96Sdrh ExprList *pList = 0; /* List of VALUES() to be inserted */ 619c27ea2aeSdrh int iRegStore; /* Register in which to store next column */ 620cce7d176Sdrh 6216a288a33Sdrh /* Register allocations */ 6221bd10f8aSdrh int regFromSelect = 0;/* Base register for data coming from SELECT */ 6236a288a33Sdrh int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ 6246a288a33Sdrh int regRowCount = 0; /* Memory cell used for the row counter */ 6256a288a33Sdrh int regIns; /* Block of regs holding rowid+data being inserted */ 6266a288a33Sdrh int regRowid; /* registers holding insert rowid */ 6276a288a33Sdrh int regData; /* register holding first column to insert */ 628aa9b8963Sdrh int *aRegIdx = 0; /* One register allocated to each index */ 6296a288a33Sdrh 630798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER 631798da52cSdrh int isView; /* True if attempting to insert into a view */ 6322f886d1dSdanielk1977 Trigger *pTrigger; /* List of triggers on pTab, if required */ 6332f886d1dSdanielk1977 int tmask; /* Mask of trigger times */ 634798da52cSdrh #endif 635c3f9bad2Sdanielk1977 63617435752Sdrh db = pParse->db; 63717435752Sdrh if( pParse->nErr || db->mallocFailed ){ 6386f7adc8aSdrh goto insert_cleanup; 6396f7adc8aSdrh } 6404c883487Sdrh dest.iSDParm = 0; /* Suppress a harmless compiler warning */ 641daffd0e5Sdrh 64275593d96Sdrh /* If the Select object is really just a simple VALUES() list with a 643a21f78b9Sdrh ** single row (the common case) then keep that one row of values 644a21f78b9Sdrh ** and discard the other (unused) parts of the pSelect object 64575593d96Sdrh */ 64675593d96Sdrh if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){ 64775593d96Sdrh pList = pSelect->pEList; 64875593d96Sdrh pSelect->pEList = 0; 64975593d96Sdrh sqlite3SelectDelete(db, pSelect); 65075593d96Sdrh pSelect = 0; 65175593d96Sdrh } 65275593d96Sdrh 6531ccde15dSdrh /* Locate the table into which we will be inserting new information. 6541ccde15dSdrh */ 655113088ecSdrh assert( pTabList->nSrc==1 ); 6564adee20fSdanielk1977 pTab = sqlite3SrcListLookup(pParse, pTabList); 657c3f9bad2Sdanielk1977 if( pTab==0 ){ 658c3f9bad2Sdanielk1977 goto insert_cleanup; 659c3f9bad2Sdanielk1977 } 660da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 661da184236Sdanielk1977 assert( iDb<db->nDb ); 662a0daa751Sdrh if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, 663a0daa751Sdrh db->aDb[iDb].zDbSName) ){ 6641962bda7Sdrh goto insert_cleanup; 6651962bda7Sdrh } 666ec95c441Sdrh withoutRowid = !HasRowid(pTab); 667c3f9bad2Sdanielk1977 668b7f9164eSdrh /* Figure out if we have any triggers and if the table being 669b7f9164eSdrh ** inserted into is a view 670b7f9164eSdrh */ 671b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER 6722f886d1dSdanielk1977 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); 673b7f9164eSdrh isView = pTab->pSelect!=0; 674b7f9164eSdrh #else 6752f886d1dSdanielk1977 # define pTrigger 0 6762f886d1dSdanielk1977 # define tmask 0 677b7f9164eSdrh # define isView 0 678b7f9164eSdrh #endif 679b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW 680b7f9164eSdrh # undef isView 681b7f9164eSdrh # define isView 0 682b7f9164eSdrh #endif 6832f886d1dSdanielk1977 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); 684b7f9164eSdrh 685f573c99bSdrh /* If pTab is really a view, make sure it has been initialized. 686d82b5021Sdrh ** ViewGetColumnNames() is a no-op if pTab is not a view. 687f573c99bSdrh */ 688b3d24bf8Sdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 689f573c99bSdrh goto insert_cleanup; 690f573c99bSdrh } 691f573c99bSdrh 692d82b5021Sdrh /* Cannot insert into a read-only table. 693595a523aSdanielk1977 */ 694595a523aSdanielk1977 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ 695595a523aSdanielk1977 goto insert_cleanup; 696595a523aSdanielk1977 } 697595a523aSdanielk1977 6981ccde15dSdrh /* Allocate a VDBE 6991ccde15dSdrh */ 7004adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 7015974a30fSdrh if( v==0 ) goto insert_cleanup; 7024794f735Sdrh if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 7032f886d1dSdanielk1977 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); 7041ccde15dSdrh 7059d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 7069d9cf229Sdrh /* If the statement is of the form 7079d9cf229Sdrh ** 7089d9cf229Sdrh ** INSERT INTO <table1> SELECT * FROM <table2>; 7099d9cf229Sdrh ** 7109d9cf229Sdrh ** Then special optimizations can be applied that make the transfer 7119d9cf229Sdrh ** very fast and which reduce fragmentation of indices. 712e00ee6ebSdrh ** 713e00ee6ebSdrh ** This is the 2nd template. 7149d9cf229Sdrh */ 7159d9cf229Sdrh if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ 7162f886d1dSdanielk1977 assert( !pTrigger ); 7179d9cf229Sdrh assert( pList==0 ); 7180b9f50d8Sdrh goto insert_end; 7199d9cf229Sdrh } 7209d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 7219d9cf229Sdrh 7222958a4e6Sdrh /* If this is an AUTOINCREMENT table, look up the sequence number in the 7236a288a33Sdrh ** sqlite_sequence table and store it in memory cell regAutoinc. 7242958a4e6Sdrh */ 7256a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDb, pTab); 7262958a4e6Sdrh 727f5f1915dSdrh /* Allocate a block registers to hold the rowid and the values 728f5f1915dSdrh ** for all columns of the new row. 7291ccde15dSdrh */ 73005a86c5cSdrh regRowid = regIns = pParse->nMem+1; 73105a86c5cSdrh pParse->nMem += pTab->nCol + 1; 732034ca14fSdanielk1977 if( IsVirtual(pTab) ){ 73305a86c5cSdrh regRowid++; 73405a86c5cSdrh pParse->nMem++; 735034ca14fSdanielk1977 } 73605a86c5cSdrh regData = regRowid+1; 7371ccde15dSdrh 7381ccde15dSdrh /* If the INSERT statement included an IDLIST term, then make sure 7391ccde15dSdrh ** all elements of the IDLIST really are columns of the table and 7401ccde15dSdrh ** remember the column indices. 741c8392586Sdrh ** 742c8392586Sdrh ** If the table has an INTEGER PRIMARY KEY column and that column 743d82b5021Sdrh ** is named in the IDLIST, then record in the ipkColumn variable 744d82b5021Sdrh ** the index into IDLIST of the primary key column. ipkColumn is 745c8392586Sdrh ** the index of the primary key as it appears in IDLIST, not as 746d82b5021Sdrh ** is appears in the original table. (The index of the INTEGER 747f5f1915dSdrh ** PRIMARY KEY in the original table is pTab->iPKey.) After this 748f5f1915dSdrh ** loop, if ipkColumn==(-1), that means that integer primary key 749f5f1915dSdrh ** is unspecified, and hence the table is either WITHOUT ROWID or 750f5f1915dSdrh ** it will automatically generated an integer primary key. 751f5f1915dSdrh ** 752f5f1915dSdrh ** bIdListInOrder is true if the columns in IDLIST are in storage 753f5f1915dSdrh ** order. This enables an optimization that avoids shuffling the 754f5f1915dSdrh ** columns into storage order. False negatives are harmless, 755f5f1915dSdrh ** but false positives will cause database corruption. 7561ccde15dSdrh */ 757d4cd292cSdrh bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0; 758967e8b73Sdrh if( pColumn ){ 759967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 760967e8b73Sdrh pColumn->a[i].idx = -1; 761cce7d176Sdrh } 762967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 763cce7d176Sdrh for(j=0; j<pTab->nCol; j++){ 7644adee20fSdanielk1977 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ 765967e8b73Sdrh pColumn->a[i].idx = j; 76605a86c5cSdrh if( i!=j ) bIdListInOrder = 0; 7674a32431cSdrh if( j==pTab->iPKey ){ 768d82b5021Sdrh ipkColumn = i; assert( !withoutRowid ); 7694a32431cSdrh } 7707e508f1eSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 7717e508f1eSdrh if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){ 7727e508f1eSdrh sqlite3ErrorMsg(pParse, 7737e508f1eSdrh "cannot INSERT into generated column \"%s\"", 7747e508f1eSdrh pTab->aCol[j].zName); 7757e508f1eSdrh goto insert_cleanup; 7767e508f1eSdrh } 7777e508f1eSdrh #endif 778cce7d176Sdrh break; 779cce7d176Sdrh } 780cce7d176Sdrh } 781cce7d176Sdrh if( j>=pTab->nCol ){ 782ec95c441Sdrh if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ 783d82b5021Sdrh ipkColumn = i; 784e48ae715Sdrh bIdListInOrder = 0; 785a0217ba7Sdrh }else{ 7864adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %S has no column named %s", 787da93d238Sdrh pTabList, 0, pColumn->a[i].zName); 7881db95106Sdan pParse->checkSchema = 1; 789cce7d176Sdrh goto insert_cleanup; 790cce7d176Sdrh } 791cce7d176Sdrh } 792cce7d176Sdrh } 793a0217ba7Sdrh } 7941ccde15dSdrh 795cce7d176Sdrh /* Figure out how many columns of data are supplied. If the data 796cce7d176Sdrh ** is coming from a SELECT statement, then generate a co-routine that 797cce7d176Sdrh ** produces a single row of the SELECT on each invocation. The 798cce7d176Sdrh ** co-routine is the common header to the 3rd and 4th templates. 799cce7d176Sdrh */ 8005f085269Sdrh if( pSelect ){ 801a21f78b9Sdrh /* Data is coming from a SELECT or from a multi-row VALUES clause. 802a21f78b9Sdrh ** Generate a co-routine to run the SELECT. */ 80305a86c5cSdrh int regYield; /* Register holding co-routine entry-point */ 80405a86c5cSdrh int addrTop; /* Top of the co-routine */ 80505a86c5cSdrh int rc; /* Result code */ 806cce7d176Sdrh 80705a86c5cSdrh regYield = ++pParse->nMem; 80805a86c5cSdrh addrTop = sqlite3VdbeCurrentAddr(v) + 1; 80905a86c5cSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 81005a86c5cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 81105a86c5cSdrh dest.iSdst = bIdListInOrder ? regData : 0; 81205a86c5cSdrh dest.nSdst = pTab->nCol; 81305a86c5cSdrh rc = sqlite3Select(pParse, pSelect, &dest); 8142b596da8Sdrh regFromSelect = dest.iSdst; 815992590beSdrh if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup; 8162fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regYield); 81705a86c5cSdrh sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ 818cce7d176Sdrh assert( pSelect->pEList ); 819cce7d176Sdrh nColumn = pSelect->pEList->nExpr; 820cce7d176Sdrh 821cce7d176Sdrh /* Set useTempTable to TRUE if the result of the SELECT statement 822cce7d176Sdrh ** should be written into a temporary table (template 4). Set to 823cce7d176Sdrh ** FALSE if each output row of the SELECT can be written directly into 824cce7d176Sdrh ** the destination table (template 3). 825cce7d176Sdrh ** 826cce7d176Sdrh ** A temp table must be used if the table being updated is also one 827cce7d176Sdrh ** of the tables being read by the SELECT statement. Also use a 828cce7d176Sdrh ** temp table in the case of row triggers. 829cce7d176Sdrh */ 83005a86c5cSdrh if( pTrigger || readsTable(pParse, iDb, pTab) ){ 831cce7d176Sdrh useTempTable = 1; 832cce7d176Sdrh } 833cce7d176Sdrh 834cce7d176Sdrh if( useTempTable ){ 835cce7d176Sdrh /* Invoke the coroutine to extract information from the SELECT 836cce7d176Sdrh ** and add it to a transient table srcTab. The code generated 837cce7d176Sdrh ** here is from the 4th template: 838cce7d176Sdrh ** 839cce7d176Sdrh ** B: open temp table 84081cf13ecSdrh ** L: yield X, goto M at EOF 841cce7d176Sdrh ** insert row from R..R+n into temp table 842cce7d176Sdrh ** goto L 843cce7d176Sdrh ** M: ... 844cce7d176Sdrh */ 845cce7d176Sdrh int regRec; /* Register to hold packed record */ 846cce7d176Sdrh int regTempRowid; /* Register to hold temp table ROWID */ 84706280ee5Sdrh int addrL; /* Label "L" */ 848cce7d176Sdrh 849cce7d176Sdrh srcTab = pParse->nTab++; 850cce7d176Sdrh regRec = sqlite3GetTempReg(pParse); 851cce7d176Sdrh regTempRowid = sqlite3GetTempReg(pParse); 852cce7d176Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); 85306280ee5Sdrh addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); 854cce7d176Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); 855cce7d176Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); 856cce7d176Sdrh sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); 857076e85f5Sdrh sqlite3VdbeGoto(v, addrL); 85806280ee5Sdrh sqlite3VdbeJumpHere(v, addrL); 859cce7d176Sdrh sqlite3ReleaseTempReg(pParse, regRec); 860cce7d176Sdrh sqlite3ReleaseTempReg(pParse, regTempRowid); 861cce7d176Sdrh } 862cce7d176Sdrh }else{ 863a21f78b9Sdrh /* This is the case if the data for the INSERT is coming from a 864a21f78b9Sdrh ** single-row VALUES clause 865cce7d176Sdrh */ 866cce7d176Sdrh NameContext sNC; 867cce7d176Sdrh memset(&sNC, 0, sizeof(sNC)); 868cce7d176Sdrh sNC.pParse = pParse; 869cce7d176Sdrh srcTab = -1; 870cce7d176Sdrh assert( useTempTable==0 ); 871fea870beSdrh if( pList ){ 872fea870beSdrh nColumn = pList->nExpr; 873fea870beSdrh if( sqlite3ResolveExprListNames(&sNC, pList) ){ 874cce7d176Sdrh goto insert_cleanup; 875cce7d176Sdrh } 876fea870beSdrh }else{ 877fea870beSdrh nColumn = 0; 878cce7d176Sdrh } 879cce7d176Sdrh } 880cce7d176Sdrh 881aacc543eSdrh /* If there is no IDLIST term but the table has an integer primary 882d82b5021Sdrh ** key, the set the ipkColumn variable to the integer primary key 883d82b5021Sdrh ** column index in the original table definition. 8844a32431cSdrh */ 885147d0cccSdrh if( pColumn==0 && nColumn>0 ){ 886d82b5021Sdrh ipkColumn = pTab->iPKey; 887427b96aeSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 8886ab61d70Sdrh if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){ 889427b96aeSdrh testcase( pTab->tabFlags & TF_HasVirtual ); 8906ab61d70Sdrh testcase( pTab->tabFlags & TF_HasStored ); 891427b96aeSdrh for(i=ipkColumn-1; i>=0; i--){ 892427b96aeSdrh if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ 893427b96aeSdrh testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ); 8946ab61d70Sdrh testcase( pTab->aCol[i].colFlags & COLFLAG_STORED ); 895427b96aeSdrh ipkColumn--; 896427b96aeSdrh } 897427b96aeSdrh } 898427b96aeSdrh } 899427b96aeSdrh #endif 9004a32431cSdrh } 9014a32431cSdrh 902cce7d176Sdrh /* Make sure the number of columns in the source data matches the number 903cce7d176Sdrh ** of columns to be inserted into the table. 904cce7d176Sdrh */ 905cce7d176Sdrh for(i=0; i<pTab->nCol; i++){ 9067e508f1eSdrh if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++; 907cce7d176Sdrh } 908cce7d176Sdrh if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ 909cce7d176Sdrh sqlite3ErrorMsg(pParse, 910cce7d176Sdrh "table %S has %d columns but %d values were supplied", 911cce7d176Sdrh pTabList, 0, pTab->nCol-nHidden, nColumn); 912cce7d176Sdrh goto insert_cleanup; 913cce7d176Sdrh } 914cce7d176Sdrh if( pColumn!=0 && nColumn!=pColumn->nId ){ 915cce7d176Sdrh sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 916cce7d176Sdrh goto insert_cleanup; 917cce7d176Sdrh } 918cce7d176Sdrh 919c3f9bad2Sdanielk1977 /* Initialize the count of rows to be inserted 9201ccde15dSdrh */ 92179636913Sdrh if( (db->flags & SQLITE_CountRows)!=0 92279636913Sdrh && !pParse->nested 92379636913Sdrh && !pParse->pTriggerTab 92479636913Sdrh ){ 9256a288a33Sdrh regRowCount = ++pParse->nMem; 9266a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 927c3f9bad2Sdanielk1977 } 928c3f9bad2Sdanielk1977 929e448dc4aSdanielk1977 /* If this is not a view, open the table and and all indices */ 930e448dc4aSdanielk1977 if( !isView ){ 931aa9b8963Sdrh int nIdx; 932fd261ec6Sdan nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0, 93326198bb4Sdrh &iDataCur, &iIdxCur); 934a7c3b93fSdrh aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2)); 935aa9b8963Sdrh if( aRegIdx==0 ){ 936aa9b8963Sdrh goto insert_cleanup; 937aa9b8963Sdrh } 9382c4dfc30Sdrh for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){ 9392c4dfc30Sdrh assert( pIdx ); 940aa9b8963Sdrh aRegIdx[i] = ++pParse->nMem; 9412c4dfc30Sdrh pParse->nMem += pIdx->nColumn; 942aa9b8963Sdrh } 943a7c3b93fSdrh aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */ 944feeb1394Sdrh } 945788d55aaSdrh #ifndef SQLITE_OMIT_UPSERT 9460b30a116Sdrh if( pUpsert ){ 947b042d921Sdrh if( IsVirtual(pTab) ){ 948b042d921Sdrh sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"", 949b042d921Sdrh pTab->zName); 950b042d921Sdrh goto insert_cleanup; 951b042d921Sdrh } 9529105fd51Sdan if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){ 9539105fd51Sdan goto insert_cleanup; 9549105fd51Sdan } 955788d55aaSdrh pTabList->a[0].iCursor = iDataCur; 9560b30a116Sdrh pUpsert->pUpsertSrc = pTabList; 957eac9fabbSdrh pUpsert->regData = regData; 9587fc3aba8Sdrh pUpsert->iDataCur = iDataCur; 9597fc3aba8Sdrh pUpsert->iIdxCur = iIdxCur; 9600b30a116Sdrh if( pUpsert->pUpsertTarget ){ 961e9c2e772Sdrh sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert); 962788d55aaSdrh } 9630b30a116Sdrh } 964788d55aaSdrh #endif 965788d55aaSdrh 966feeb1394Sdrh 967e00ee6ebSdrh /* This is the top of the main insertion loop */ 968142e30dfSdrh if( useTempTable ){ 969e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 970e00ee6ebSdrh ** following pseudocode (template 4): 971e00ee6ebSdrh ** 97281cf13ecSdrh ** rewind temp table, if empty goto D 973e00ee6ebSdrh ** C: loop over rows of intermediate table 974e00ee6ebSdrh ** transfer values form intermediate table into <table> 975e00ee6ebSdrh ** end loop 976e00ee6ebSdrh ** D: ... 977e00ee6ebSdrh */ 978688852abSdrh addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); 979e00ee6ebSdrh addrCont = sqlite3VdbeCurrentAddr(v); 980142e30dfSdrh }else if( pSelect ){ 981e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 982e00ee6ebSdrh ** following pseudocode (template 3): 983e00ee6ebSdrh ** 98481cf13ecSdrh ** C: yield X, at EOF goto D 985e00ee6ebSdrh ** insert the select result into <table> from R..R+n 986e00ee6ebSdrh ** goto C 987e00ee6ebSdrh ** D: ... 988e00ee6ebSdrh */ 98981cf13ecSdrh addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 990688852abSdrh VdbeCoverage(v); 991f5f1915dSdrh if( ipkColumn>=0 ){ 992f5f1915dSdrh /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the 993f5f1915dSdrh ** SELECT, go ahead and copy the value into the rowid slot now, so that 994f5f1915dSdrh ** the value does not get overwritten by a NULL at tag-20191021-002. */ 995f5f1915dSdrh sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); 996bed8690fSdrh } 997f5f1915dSdrh } 998f5f1915dSdrh 999f5f1915dSdrh /* Compute data for ordinary columns of the new entry. Values 1000f5f1915dSdrh ** are written in storage order into registers starting with regData. 1001f5f1915dSdrh ** Only ordinary columns are computed in this loop. The rowid 1002f5f1915dSdrh ** (if there is one) is computed later and generated columns are 1003f5f1915dSdrh ** computed after the rowid since they might depend on the value 1004f5f1915dSdrh ** of the rowid. 1005f5f1915dSdrh */ 1006f5f1915dSdrh nHidden = 0; 1007f5f1915dSdrh iRegStore = regData; assert( regData==regRowid+1 ); 1008f5f1915dSdrh for(i=0; i<pTab->nCol; i++, iRegStore++){ 1009f5f1915dSdrh int k; 1010f5f1915dSdrh u32 colFlags; 1011f5f1915dSdrh assert( i>=nHidden ); 1012f5f1915dSdrh if( i==pTab->iPKey ){ 1013f5f1915dSdrh /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled 1014f5f1915dSdrh ** using the rowid. So put a NULL in the IPK slot of the record to avoid 1015f5f1915dSdrh ** using excess space. The file format definition requires this extra 1016f5f1915dSdrh ** NULL - we cannot optimize further by skipping the column completely */ 1017f5f1915dSdrh sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); 1018f5f1915dSdrh continue; 1019f5f1915dSdrh } 1020f5f1915dSdrh if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){ 1021f5f1915dSdrh nHidden++; 1022f5f1915dSdrh if( (colFlags & COLFLAG_VIRTUAL)!=0 ){ 1023f5f1915dSdrh /* Virtual columns do not participate in OP_MakeRecord. So back up 1024f5f1915dSdrh ** iRegStore by one slot to compensate for the iRegStore++ in the 1025f5f1915dSdrh ** outer for() loop */ 1026f5f1915dSdrh iRegStore--; 1027f5f1915dSdrh continue; 1028f5f1915dSdrh }else if( (colFlags & COLFLAG_STORED)!=0 ){ 1029f5f1915dSdrh /* Stored columns are computed later. But if there are BEFORE 1030f5f1915dSdrh ** triggers, the slots used for stored columns will be OP_Copy-ed 1031f5f1915dSdrh ** to a second block of registers, so the register needs to be 1032f5f1915dSdrh ** initialized to NULL to avoid an uninitialized register read */ 1033f5f1915dSdrh if( tmask & TRIGGER_BEFORE ){ 1034f5f1915dSdrh sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); 1035f5f1915dSdrh } 1036f5f1915dSdrh continue; 1037f5f1915dSdrh }else if( pColumn==0 ){ 1038f5f1915dSdrh /* Hidden columns that are not explicitly named in the INSERT 1039f5f1915dSdrh ** get there default value */ 1040f5f1915dSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 1041f5f1915dSdrh continue; 1042f5f1915dSdrh } 1043f5f1915dSdrh } 1044f5f1915dSdrh if( pColumn ){ 1045f5f1915dSdrh for(j=0; j<pColumn->nId && pColumn->a[j].idx!=i; j++){} 1046f5f1915dSdrh if( j>=pColumn->nId ){ 1047f5f1915dSdrh /* A column not named in the insert column list gets its 1048f5f1915dSdrh ** default value */ 1049f5f1915dSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 1050f5f1915dSdrh continue; 1051f5f1915dSdrh } 1052f5f1915dSdrh k = j; 1053f5f1915dSdrh }else if( nColumn==0 ){ 1054f5f1915dSdrh /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */ 1055f5f1915dSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 1056f5f1915dSdrh continue; 1057f5f1915dSdrh }else{ 1058f5f1915dSdrh k = i - nHidden; 1059f5f1915dSdrh } 1060f5f1915dSdrh 1061f5f1915dSdrh if( useTempTable ){ 1062f5f1915dSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore); 1063f5f1915dSdrh }else if( pSelect ){ 1064f5f1915dSdrh if( regFromSelect!=regData ){ 1065f5f1915dSdrh sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore); 1066f5f1915dSdrh } 1067f5f1915dSdrh }else{ 1068f5f1915dSdrh sqlite3ExprCode(pParse, pList->a[k].pExpr, iRegStore); 1069f5f1915dSdrh } 1070f5f1915dSdrh } 1071f5f1915dSdrh 10721ccde15dSdrh 10735cf590c1Sdrh /* Run the BEFORE and INSTEAD OF triggers, if there are any 107470ce3f0cSdrh */ 1075ec4ccdbcSdrh endOfLoop = sqlite3VdbeMakeLabel(pParse); 10762f886d1dSdanielk1977 if( tmask & TRIGGER_BEFORE ){ 107776d462eeSdan int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); 1078c3f9bad2Sdanielk1977 107970ce3f0cSdrh /* build the NEW.* reference row. Note that if there is an INTEGER 108070ce3f0cSdrh ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 108170ce3f0cSdrh ** translated into a unique ID for the row. But on a BEFORE trigger, 108270ce3f0cSdrh ** we do not know what the unique ID will be (because the insert has 108370ce3f0cSdrh ** not happened yet) so we substitute a rowid of -1 108470ce3f0cSdrh */ 1085d82b5021Sdrh if( ipkColumn<0 ){ 108676d462eeSdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 108770ce3f0cSdrh }else{ 1088728e0f91Sdrh int addr1; 1089ec95c441Sdrh assert( !withoutRowid ); 10907fe45908Sdrh if( useTempTable ){ 1091d82b5021Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); 10927fe45908Sdrh }else{ 1093d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 1094d82b5021Sdrh sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); 10957fe45908Sdrh } 1096728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); 109776d462eeSdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 1098728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 1099688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); 110070ce3f0cSdrh } 110170ce3f0cSdrh 1102034ca14fSdanielk1977 /* Cannot have triggers on a virtual table. If it were possible, 1103034ca14fSdanielk1977 ** this block would have to account for hidden column. 1104034ca14fSdanielk1977 */ 1105034ca14fSdanielk1977 assert( !IsVirtual(pTab) ); 1106034ca14fSdanielk1977 1107f5f1915dSdrh /* Copy the new data already generated. */ 1108f5f1915dSdrh assert( pTab->nNVCol>0 ); 1109f5f1915dSdrh sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1); 1110f5f1915dSdrh 1111f5f1915dSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1112f5f1915dSdrh /* Compute the new value for generated columns after all other 1113f5f1915dSdrh ** columns have already been computed. This must be done after 1114f5f1915dSdrh ** computing the ROWID in case one of the generated columns 1115f5f1915dSdrh ** refers to the ROWID. */ 1116427b96aeSdrh if( pTab->tabFlags & TF_HasGenerated ){ 1117427b96aeSdrh testcase( pTab->tabFlags & TF_HasVirtual ); 1118427b96aeSdrh testcase( pTab->tabFlags & TF_HasStored ); 1119f5f1915dSdrh sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab); 1120c3f9bad2Sdanielk1977 } 1121f5f1915dSdrh #endif 1122a37cdde0Sdanielk1977 1123a37cdde0Sdanielk1977 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 1124a37cdde0Sdanielk1977 ** do not attempt any conversions before assembling the record. 1125a37cdde0Sdanielk1977 ** If this is a real table, attempt conversions as required by the 1126a37cdde0Sdanielk1977 ** table column affinities. 1127a37cdde0Sdanielk1977 */ 1128a37cdde0Sdanielk1977 if( !isView ){ 112957bf4a8eSdrh sqlite3TableAffinity(v, pTab, regCols+1); 1130a37cdde0Sdanielk1977 } 1131c3f9bad2Sdanielk1977 11325cf590c1Sdrh /* Fire BEFORE or INSTEAD OF triggers */ 1133165921a7Sdan sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 113494d7f50aSdan pTab, regCols-pTab->nCol-1, onError, endOfLoop); 1135165921a7Sdan 113676d462eeSdan sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); 113770ce3f0cSdrh } 1138c3f9bad2Sdanielk1977 11395cf590c1Sdrh if( !isView ){ 11404cbdda9eSdrh if( IsVirtual(pTab) ){ 11414cbdda9eSdrh /* The row that the VUpdate opcode will delete: none */ 11426a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); 11434cbdda9eSdrh } 1144d82b5021Sdrh if( ipkColumn>=0 ){ 1145f5f1915dSdrh /* Compute the new rowid */ 1146142e30dfSdrh if( useTempTable ){ 1147d82b5021Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); 1148142e30dfSdrh }else if( pSelect ){ 1149f5f1915dSdrh /* Rowid already initialized at tag-20191021-001 */ 11504a32431cSdrh }else{ 115104fcef00Sdrh Expr *pIpk = pList->a[ipkColumn].pExpr; 115204fcef00Sdrh if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){ 115304fcef00Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 1154e4d90813Sdrh appendFlag = 1; 115504fcef00Sdrh }else{ 115604fcef00Sdrh sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); 1157e4d90813Sdrh } 115827a32783Sdrh } 1159f0863fe5Sdrh /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 1160e1e68f49Sdrh ** to generate a unique primary key value. 1161e1e68f49Sdrh */ 1162e4d90813Sdrh if( !appendFlag ){ 1163728e0f91Sdrh int addr1; 1164bb50e7adSdanielk1977 if( !IsVirtual(pTab) ){ 1165728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); 116626198bb4Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 1167728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 1168bb50e7adSdanielk1977 }else{ 1169728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 1170728e0f91Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); 1171bb50e7adSdanielk1977 } 1172688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); 1173e4d90813Sdrh } 1174ec95c441Sdrh }else if( IsVirtual(pTab) || withoutRowid ){ 11756a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); 11764a32431cSdrh }else{ 117726198bb4Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 1178e4d90813Sdrh appendFlag = 1; 11794a32431cSdrh } 11806a288a33Sdrh autoIncStep(pParse, regAutoinc, regRowid); 11814a32431cSdrh 1182c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1183dd6cc9b5Sdrh /* Compute the new value for generated columns after all other 1184f5f1915dSdrh ** columns have already been computed. This must be done after 1185f5f1915dSdrh ** computing the ROWID in case one of the generated columns 1186f5f1915dSdrh ** refers to the ROWID. */ 1187427b96aeSdrh if( pTab->tabFlags & TF_HasGenerated ){ 1188427b96aeSdrh testcase( pTab->tabFlags & TF_HasVirtual ); 1189427b96aeSdrh testcase( pTab->tabFlags & TF_HasStored ); 1190dd6cc9b5Sdrh sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab); 11914a32431cSdrh } 1192c1431144Sdrh #endif 11931ccde15dSdrh 11940ca3e24bSdrh /* Generate code to check constraints and generate index keys and 11950ca3e24bSdrh ** do the insertion. 11964a32431cSdrh */ 11974cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 11984cbdda9eSdrh if( IsVirtual(pTab) ){ 1199595a523aSdanielk1977 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 12004f3dd150Sdrh sqlite3VtabMakeWritable(pParse, pTab); 1201595a523aSdanielk1977 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); 1202b061d058Sdan sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); 1203e0af83acSdan sqlite3MayAbort(pParse); 12044cbdda9eSdrh }else 12054cbdda9eSdrh #endif 12064cbdda9eSdrh { 1207de630353Sdanielk1977 int isReplace; /* Set to true if constraints may cause a replace */ 12083b908d41Sdan int bUseSeek; /* True to use OPFLAG_SEEKRESULT */ 1209f8ffb278Sdrh sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, 1210788d55aaSdrh regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert 121104adf416Sdrh ); 12128ff2d956Sdan sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); 12133b908d41Sdan 12143b908d41Sdan /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE 12153b908d41Sdan ** constraints or (b) there are no triggers and this table is not a 12163b908d41Sdan ** parent table in a foreign key constraint. It is safe to set the 12173b908d41Sdan ** flag in the second case as if any REPLACE constraint is hit, an 12183b908d41Sdan ** OP_Delete or OP_IdxDelete instruction will be executed on each 12193b908d41Sdan ** cursor that is disturbed. And these instructions both clear the 12203b908d41Sdan ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT 12213b908d41Sdan ** functionality. */ 122206baba54Sdrh bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v)); 122326198bb4Sdrh sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, 12243b908d41Sdan regIns, aRegIdx, 0, appendFlag, bUseSeek 12253b908d41Sdan ); 12265cf590c1Sdrh } 12274cbdda9eSdrh } 12281bee3d7bSdrh 1229feeb1394Sdrh /* Update the count of rows that are inserted 12301bee3d7bSdrh */ 123179636913Sdrh if( regRowCount ){ 12326a288a33Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 12331bee3d7bSdrh } 1234c3f9bad2Sdanielk1977 12352f886d1dSdanielk1977 if( pTrigger ){ 1236c3f9bad2Sdanielk1977 /* Code AFTER triggers */ 1237165921a7Sdan sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 123894d7f50aSdan pTab, regData-2-pTab->nCol, onError, endOfLoop); 1239c3f9bad2Sdanielk1977 } 12401bee3d7bSdrh 1241e00ee6ebSdrh /* The bottom of the main insertion loop, if the data source 1242e00ee6ebSdrh ** is a SELECT statement. 12431ccde15dSdrh */ 12444adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, endOfLoop); 1245142e30dfSdrh if( useTempTable ){ 1246688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); 1247e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 12482eb95377Sdrh sqlite3VdbeAddOp1(v, OP_Close, srcTab); 1249142e30dfSdrh }else if( pSelect ){ 1250076e85f5Sdrh sqlite3VdbeGoto(v, addrCont); 1251e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 12526b56344dSdrh } 1253c3f9bad2Sdanielk1977 12540b9f50d8Sdrh insert_end: 1255f3388144Sdrh /* Update the sqlite_sequence table by storing the content of the 12560b9f50d8Sdrh ** maximum rowid counter values recorded while inserting into 12570b9f50d8Sdrh ** autoincrement tables. 12582958a4e6Sdrh */ 1259165921a7Sdan if( pParse->nested==0 && pParse->pTriggerTab==0 ){ 12600b9f50d8Sdrh sqlite3AutoincrementEnd(pParse); 12610b9f50d8Sdrh } 12622958a4e6Sdrh 12631bee3d7bSdrh /* 1264e7de6f25Sdanielk1977 ** Return the number of rows inserted. If this routine is 1265e7de6f25Sdanielk1977 ** generating code because of a call to sqlite3NestedParse(), do not 1266e7de6f25Sdanielk1977 ** invoke the callback function. 12671bee3d7bSdrh */ 126879636913Sdrh if( regRowCount ){ 12696a288a33Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); 127022322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, 1); 127110fb749bSdanielk1977 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); 12721bee3d7bSdrh } 1273cce7d176Sdrh 1274cce7d176Sdrh insert_cleanup: 1275633e6d57Sdrh sqlite3SrcListDelete(db, pTabList); 1276633e6d57Sdrh sqlite3ExprListDelete(db, pList); 127746d2e5c3Sdrh sqlite3UpsertDelete(db, pUpsert); 1278633e6d57Sdrh sqlite3SelectDelete(db, pSelect); 1279633e6d57Sdrh sqlite3IdListDelete(db, pColumn); 1280633e6d57Sdrh sqlite3DbFree(db, aRegIdx); 1281cce7d176Sdrh } 12829cfcf5d4Sdrh 128375cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise 128460ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file 128575cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation). */ 128675cbd984Sdan #ifdef isView 128775cbd984Sdan #undef isView 128875cbd984Sdan #endif 128975cbd984Sdan #ifdef pTrigger 129075cbd984Sdan #undef pTrigger 129175cbd984Sdan #endif 129275cbd984Sdan #ifdef tmask 129375cbd984Sdan #undef tmask 129475cbd984Sdan #endif 129575cbd984Sdan 12969cfcf5d4Sdrh /* 1297e9816d82Sdrh ** Meanings of bits in of pWalker->eCode for 1298e9816d82Sdrh ** sqlite3ExprReferencesUpdatedColumn() 129998bfa16dSdrh */ 130098bfa16dSdrh #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */ 130198bfa16dSdrh #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */ 130298bfa16dSdrh 1303e9816d82Sdrh /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn(). 1304e9816d82Sdrh * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this 1305e9816d82Sdrh ** expression node references any of the 13062a0b527bSdrh ** columns that are being modifed by an UPDATE statement. 13072a0b527bSdrh */ 13082a0b527bSdrh static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){ 130998bfa16dSdrh if( pExpr->op==TK_COLUMN ){ 131098bfa16dSdrh assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 ); 131198bfa16dSdrh if( pExpr->iColumn>=0 ){ 131298bfa16dSdrh if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){ 131398bfa16dSdrh pWalker->eCode |= CKCNSTRNT_COLUMN; 131498bfa16dSdrh } 131598bfa16dSdrh }else{ 131698bfa16dSdrh pWalker->eCode |= CKCNSTRNT_ROWID; 131798bfa16dSdrh } 13182a0b527bSdrh } 13192a0b527bSdrh return WRC_Continue; 13202a0b527bSdrh } 13212a0b527bSdrh 13222a0b527bSdrh /* 13232a0b527bSdrh ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The 13242a0b527bSdrh ** only columns that are modified by the UPDATE are those for which 132598bfa16dSdrh ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true. 132698bfa16dSdrh ** 1327e9816d82Sdrh ** Return true if CHECK constraint pExpr uses any of the 132898bfa16dSdrh ** changing columns (or the rowid if it is changing). In other words, 1329e9816d82Sdrh ** return true if this CHECK constraint must be validated for 133098bfa16dSdrh ** the new row in the UPDATE statement. 1331e9816d82Sdrh ** 1332e9816d82Sdrh ** 2018-09-15: pExpr might also be an expression for an index-on-expressions. 1333e9816d82Sdrh ** The operation of this routine is the same - return true if an only if 1334e9816d82Sdrh ** the expression uses one or more of columns identified by the second and 1335e9816d82Sdrh ** third arguments. 13362a0b527bSdrh */ 1337e9816d82Sdrh int sqlite3ExprReferencesUpdatedColumn( 1338e9816d82Sdrh Expr *pExpr, /* The expression to be checked */ 1339e9816d82Sdrh int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */ 1340e9816d82Sdrh int chngRowid /* True if UPDATE changes the rowid */ 1341e9816d82Sdrh ){ 13422a0b527bSdrh Walker w; 13432a0b527bSdrh memset(&w, 0, sizeof(w)); 134498bfa16dSdrh w.eCode = 0; 13452a0b527bSdrh w.xExprCallback = checkConstraintExprNode; 13462a0b527bSdrh w.u.aiCol = aiChng; 13472a0b527bSdrh sqlite3WalkExpr(&w, pExpr); 134805723a9eSdrh if( !chngRowid ){ 134905723a9eSdrh testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 ); 135005723a9eSdrh w.eCode &= ~CKCNSTRNT_ROWID; 135105723a9eSdrh } 135205723a9eSdrh testcase( w.eCode==0 ); 135305723a9eSdrh testcase( w.eCode==CKCNSTRNT_COLUMN ); 135405723a9eSdrh testcase( w.eCode==CKCNSTRNT_ROWID ); 135505723a9eSdrh testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) ); 1356e9816d82Sdrh return w.eCode!=0; 13572a0b527bSdrh } 13582a0b527bSdrh 135911e85273Sdrh /* 13606934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE 13616934fc7bSdrh ** on table pTab. 13629cfcf5d4Sdrh ** 13636934fc7bSdrh ** The regNewData parameter is the first register in a range that contains 13646934fc7bSdrh ** the data to be inserted or the data after the update. There will be 13656934fc7bSdrh ** pTab->nCol+1 registers in this range. The first register (the one 13666934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the 13676934fc7bSdrh ** case of a WITHOUT ROWID table. The second register in the range will 13686934fc7bSdrh ** contain the content of the first table column. The third register will 13696934fc7bSdrh ** contain the content of the second table column. And so forth. 13700ca3e24bSdrh ** 1371f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains 1372f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards. regOldData is zero 1373f8ffb278Sdrh ** for an INSERT. This routine can distinguish between UPDATE and INSERT by 1374f8ffb278Sdrh ** checking regOldData for zero. 13750ca3e24bSdrh ** 1376f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the 1377f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) 1378f8ffb278Sdrh ** might be modified by the UPDATE. If pkChng is false, then the key of 1379f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE. 13800ca3e24bSdrh ** 1381f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid 1382f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement. If pkChng 1383f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or 1384f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, 1385f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer 1386f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias. 13870ca3e24bSdrh ** 13886934fc7bSdrh ** The code generated by this routine will store new index entries into 1389aa9b8963Sdrh ** registers identified by aRegIdx[]. No index entry is created for 1390aa9b8963Sdrh ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is 1391aa9b8963Sdrh ** the same as the order of indices on the linked list of indices 13926934fc7bSdrh ** at pTab->pIndex. 13936934fc7bSdrh ** 1394a7c3b93fSdrh ** (2019-05-07) The generated code also creates a new record for the 1395a7c3b93fSdrh ** main table, if pTab is a rowid table, and stores that record in the 1396a7c3b93fSdrh ** register identified by aRegIdx[nIdx] - in other words in the first 1397a7c3b93fSdrh ** entry of aRegIdx[] past the last index. It is important that the 1398a7c3b93fSdrh ** record be generated during constraint checks to avoid affinity changes 1399a7c3b93fSdrh ** to the register content that occur after constraint checks but before 1400a7c3b93fSdrh ** the new record is inserted. 1401a7c3b93fSdrh ** 14026934fc7bSdrh ** The caller must have already opened writeable cursors on the main 14036934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which 14046934fc7bSdrh ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when 14056934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY 14066934fc7bSdrh ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor 14076934fc7bSdrh ** for the first index in the pTab->pIndex list. Cursors for other indices 14086934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list. 14099cfcf5d4Sdrh ** 14109cfcf5d4Sdrh ** This routine also generates code to check constraints. NOT NULL, 14119cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 14121c92853dSdrh ** then the appropriate action is performed. There are five possible 14131c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 14149cfcf5d4Sdrh ** 14159cfcf5d4Sdrh ** Constraint type Action What Happens 14169cfcf5d4Sdrh ** --------------- ---------- ---------------------------------------- 14171c92853dSdrh ** any ROLLBACK The current transaction is rolled back and 14186934fc7bSdrh ** sqlite3_step() returns immediately with a 14199cfcf5d4Sdrh ** return code of SQLITE_CONSTRAINT. 14209cfcf5d4Sdrh ** 14211c92853dSdrh ** any ABORT Back out changes from the current command 14221c92853dSdrh ** only (do not do a complete rollback) then 14236934fc7bSdrh ** cause sqlite3_step() to return immediately 14241c92853dSdrh ** with SQLITE_CONSTRAINT. 14251c92853dSdrh ** 14266934fc7bSdrh ** any FAIL Sqlite3_step() returns immediately with a 14271c92853dSdrh ** return code of SQLITE_CONSTRAINT. The 14281c92853dSdrh ** transaction is not rolled back and any 14296934fc7bSdrh ** changes to prior rows are retained. 14301c92853dSdrh ** 14316934fc7bSdrh ** any IGNORE The attempt in insert or update the current 14326934fc7bSdrh ** row is skipped, without throwing an error. 14336934fc7bSdrh ** Processing continues with the next row. 14346934fc7bSdrh ** (There is an immediate jump to ignoreDest.) 14359cfcf5d4Sdrh ** 14369cfcf5d4Sdrh ** NOT NULL REPLACE The NULL value is replace by the default 14379cfcf5d4Sdrh ** value for that column. If the default value 14389cfcf5d4Sdrh ** is NULL, the action is the same as ABORT. 14399cfcf5d4Sdrh ** 14409cfcf5d4Sdrh ** UNIQUE REPLACE The other row that conflicts with the row 14419cfcf5d4Sdrh ** being inserted is removed. 14429cfcf5d4Sdrh ** 14439cfcf5d4Sdrh ** CHECK REPLACE Illegal. The results in an exception. 14449cfcf5d4Sdrh ** 14451c92853dSdrh ** Which action to take is determined by the overrideError parameter. 14461c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter 14471c92853dSdrh ** is used. Or if pParse->onError==OE_Default then the onError value 14481c92853dSdrh ** for the constraint is used. 14499cfcf5d4Sdrh */ 14504adee20fSdanielk1977 void sqlite3GenerateConstraintChecks( 14519cfcf5d4Sdrh Parse *pParse, /* The parser context */ 14526934fc7bSdrh Table *pTab, /* The table being inserted or updated */ 1453f8ffb278Sdrh int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ 14546934fc7bSdrh int iDataCur, /* Canonical data cursor (main table or PK index) */ 145526198bb4Sdrh int iIdxCur, /* First index cursor */ 14566934fc7bSdrh int regNewData, /* First register in a range holding values to insert */ 1457f8ffb278Sdrh int regOldData, /* Previous content. 0 for INSERTs */ 1458f8ffb278Sdrh u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ 1459f8ffb278Sdrh u8 overrideError, /* Override onError to this if not OE_Default */ 1460de630353Sdanielk1977 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ 1461bdb00225Sdrh int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */ 1462788d55aaSdrh int *aiChng, /* column i is unchanged if aiChng[i]<0 */ 1463788d55aaSdrh Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */ 14649cfcf5d4Sdrh ){ 14651b7ecbb4Sdrh Vdbe *v; /* VDBE under constrution */ 14661b7ecbb4Sdrh Index *pIdx; /* Pointer to one of the indices */ 146711e85273Sdrh Index *pPk = 0; /* The PRIMARY KEY index */ 14682938f924Sdrh sqlite3 *db; /* Database connection */ 1469f8ffb278Sdrh int i; /* loop counter */ 1470f8ffb278Sdrh int ix; /* Index loop counter */ 14719cfcf5d4Sdrh int nCol; /* Number of columns */ 14729cfcf5d4Sdrh int onError; /* Conflict resolution strategy */ 1473728e0f91Sdrh int addr1; /* Address of jump instruction */ 14741b7ecbb4Sdrh int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ 14756fbe41acSdrh int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ 1476096fd476Sdrh Index *pUpIdx = 0; /* Index to which to apply the upsert */ 14778d1b82e4Sdrh u8 isUpdate; /* True if this is an UPDATE operation */ 147857bf4a8eSdrh u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ 1479096fd476Sdrh int upsertBypass = 0; /* Address of Goto to bypass upsert subroutine */ 148084304506Sdrh int upsertJump = 0; /* Address of Goto that jumps into upsert subroutine */ 148184304506Sdrh int ipkTop = 0; /* Top of the IPK uniqueness check */ 148284304506Sdrh int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */ 1483a407eccbSdrh /* Variables associated with retesting uniqueness constraints after 1484a407eccbSdrh ** replace triggers fire have run */ 1485a407eccbSdrh int regTrigCnt; /* Register used to count replace trigger invocations */ 1486a407eccbSdrh int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */ 1487a407eccbSdrh int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */ 1488a407eccbSdrh Trigger *pTrigger; /* List of DELETE triggers on the table pTab */ 1489a407eccbSdrh int nReplaceTrig = 0; /* Number of replace triggers coded */ 14909cfcf5d4Sdrh 1491f8ffb278Sdrh isUpdate = regOldData!=0; 14922938f924Sdrh db = pParse->db; 14934adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 14949cfcf5d4Sdrh assert( v!=0 ); 1495417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 14969cfcf5d4Sdrh nCol = pTab->nCol; 1497aa9b8963Sdrh 14986934fc7bSdrh /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for 14996934fc7bSdrh ** normal rowid tables. nPkField is the number of key fields in the 15006934fc7bSdrh ** pPk index or 1 for a rowid table. In other words, nPkField is the 15016934fc7bSdrh ** number of fields in the true primary key of the table. */ 150226198bb4Sdrh if( HasRowid(pTab) ){ 150326198bb4Sdrh pPk = 0; 150426198bb4Sdrh nPkField = 1; 150526198bb4Sdrh }else{ 150626198bb4Sdrh pPk = sqlite3PrimaryKeyIndex(pTab); 150726198bb4Sdrh nPkField = pPk->nKeyCol; 150826198bb4Sdrh } 15096fbe41acSdrh 15106fbe41acSdrh /* Record that this module has started */ 15116fbe41acSdrh VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", 15126934fc7bSdrh iDataCur, iIdxCur, regNewData, regOldData, pkChng)); 15139cfcf5d4Sdrh 15149cfcf5d4Sdrh /* Test all NOT NULL constraints. 15159cfcf5d4Sdrh */ 1516cbda9c7aSdrh if( pTab->tabFlags & TF_HasNotNull ){ 15179cfcf5d4Sdrh for(i=0; i<nCol; i++){ 15188e10d74bSdrh int iReg; 1519cbda9c7aSdrh onError = pTab->aCol[i].notNull; 1520cbda9c7aSdrh if( onError==OE_None ) continue; /* No NOT NULL on this column */ 15210ca3e24bSdrh if( i==pTab->iPKey ){ 1522bdb00225Sdrh continue; /* ROWID is never NULL */ 1523bdb00225Sdrh } 1524bdb00225Sdrh if( aiChng && aiChng[i]<0 ){ 1525bdb00225Sdrh /* Don't bother checking for NOT NULL on columns that do not change */ 15260ca3e24bSdrh continue; 15270ca3e24bSdrh } 15289cfcf5d4Sdrh if( overrideError!=OE_Default ){ 15299cfcf5d4Sdrh onError = overrideError; 1530a996e477Sdrh }else if( onError==OE_Default ){ 1531a996e477Sdrh onError = OE_Abort; 15329cfcf5d4Sdrh } 15337977a17fSdanielk1977 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ 15349cfcf5d4Sdrh onError = OE_Abort; 15359cfcf5d4Sdrh } 1536b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1537b84f96f8Sdanielk1977 || onError==OE_Ignore || onError==OE_Replace ); 15389bfb0794Sdrh addr1 = 0; 1539c5f808d8Sdrh testcase( i!=sqlite3TableColumnToStorage(pTab, i) ); 1540dd6cc9b5Sdrh testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ); 1541dd6cc9b5Sdrh testcase( pTab->aCol[i].colFlags & COLFLAG_STORED ); 1542b9bcf7caSdrh iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1; 15439cfcf5d4Sdrh switch( onError ){ 15449bfb0794Sdrh case OE_Replace: { 15459bfb0794Sdrh assert( onError==OE_Replace ); 1546ec4ccdbcSdrh addr1 = sqlite3VdbeMakeLabel(pParse); 15478e10d74bSdrh sqlite3VdbeAddOp2(v, OP_NotNull, iReg, addr1); 15489bfb0794Sdrh VdbeCoverage(v); 1549b1129c42Sdrh if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ){ 15509bfb0794Sdrh sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); 15518e10d74bSdrh sqlite3VdbeAddOp2(v, OP_NotNull, iReg, addr1); 15529bfb0794Sdrh VdbeCoverage(v); 1553b1129c42Sdrh } 15549bfb0794Sdrh onError = OE_Abort; 15559bfb0794Sdrh /* Fall through into the OE_Abort case to generate code that runs 15569bfb0794Sdrh ** if both the input and the default value are NULL */ 15579bfb0794Sdrh } 15581c92853dSdrh case OE_Abort: 1559e0af83acSdan sqlite3MayAbort(pParse); 15600978d4ffSdrh /* Fall through */ 1561e0af83acSdan case OE_Rollback: 15621c92853dSdrh case OE_Fail: { 1563f9c8ce3cSdrh char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, 1564f9c8ce3cSdrh pTab->aCol[i].zName); 1565cbda9c7aSdrh sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, 1566a88c8c1aSdrh onError, iReg); 15672700acaaSdrh sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC); 1568f9c8ce3cSdrh sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); 1569688852abSdrh VdbeCoverage(v); 15709bfb0794Sdrh if( addr1 ) sqlite3VdbeResolveLabel(v, addr1); 15719cfcf5d4Sdrh break; 15729cfcf5d4Sdrh } 1573098d1684Sdrh default: { 15749bfb0794Sdrh assert( onError==OE_Ignore ); 15758e10d74bSdrh sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest); 1576728e0f91Sdrh VdbeCoverage(v); 15779cfcf5d4Sdrh break; 15789cfcf5d4Sdrh } 15799cfcf5d4Sdrh } 15809cfcf5d4Sdrh } 1581cbda9c7aSdrh } 15829cfcf5d4Sdrh 15839cfcf5d4Sdrh /* Test all CHECK constraints 15849cfcf5d4Sdrh */ 1585ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 15862938f924Sdrh if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ 15872938f924Sdrh ExprList *pCheck = pTab->pCheck; 15886e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 1589aa01c7e2Sdrh onError = overrideError!=OE_Default ? overrideError : OE_Abort; 15902938f924Sdrh for(i=0; i<pCheck->nExpr; i++){ 159105723a9eSdrh int allOk; 15922a0b527bSdrh Expr *pExpr = pCheck->a[i].pExpr; 1593e9816d82Sdrh if( aiChng 1594e9816d82Sdrh && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng) 1595e9816d82Sdrh ){ 1596e9816d82Sdrh /* The check constraints do not reference any of the columns being 1597e9816d82Sdrh ** updated so there is no point it verifying the check constraint */ 1598e9816d82Sdrh continue; 1599e9816d82Sdrh } 1600ec4ccdbcSdrh allOk = sqlite3VdbeMakeLabel(pParse); 16014031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 16022a0b527bSdrh sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL); 16032e06c67cSdrh if( onError==OE_Ignore ){ 1604076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 1605aa01c7e2Sdrh }else{ 1606f9c8ce3cSdrh char *zName = pCheck->a[i].zName; 1607f9c8ce3cSdrh if( zName==0 ) zName = pTab->zName; 16080ce974d1Sdrh if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */ 1609d91c1a17Sdrh sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, 1610f9c8ce3cSdrh onError, zName, P4_TRANSIENT, 1611f9c8ce3cSdrh P5_ConstraintCheck); 1612aa01c7e2Sdrh } 1613ffe07b2dSdrh sqlite3VdbeResolveLabel(v, allOk); 1614ffe07b2dSdrh } 16156e97f8ecSdrh pParse->iSelfTab = 0; 16162938f924Sdrh } 1617ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */ 16189cfcf5d4Sdrh 1619096fd476Sdrh /* UNIQUE and PRIMARY KEY constraints should be handled in the following 1620096fd476Sdrh ** order: 1621096fd476Sdrh ** 162284304506Sdrh ** (1) OE_Update 162384304506Sdrh ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore 1624096fd476Sdrh ** (3) OE_Replace 1625096fd476Sdrh ** 1626096fd476Sdrh ** OE_Fail and OE_Ignore must happen before any changes are made. 1627096fd476Sdrh ** OE_Update guarantees that only a single row will change, so it 1628096fd476Sdrh ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback 1629096fd476Sdrh ** could happen in any order, but they are grouped up front for 1630096fd476Sdrh ** convenience. 1631096fd476Sdrh ** 163284304506Sdrh ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43 163384304506Sdrh ** The order of constraints used to have OE_Update as (2) and OE_Abort 163484304506Sdrh ** and so forth as (1). But apparently PostgreSQL checks the OE_Update 163584304506Sdrh ** constraint before any others, so it had to be moved. 163684304506Sdrh ** 1637096fd476Sdrh ** Constraint checking code is generated in this order: 1638096fd476Sdrh ** (A) The rowid constraint 1639096fd476Sdrh ** (B) Unique index constraints that do not have OE_Replace as their 1640096fd476Sdrh ** default conflict resolution strategy 1641096fd476Sdrh ** (C) Unique index that do use OE_Replace by default. 1642096fd476Sdrh ** 1643096fd476Sdrh ** The ordering of (2) and (3) is accomplished by making sure the linked 1644096fd476Sdrh ** list of indexes attached to a table puts all OE_Replace indexes last 1645096fd476Sdrh ** in the list. See sqlite3CreateIndex() for where that happens. 1646096fd476Sdrh */ 1647096fd476Sdrh 1648096fd476Sdrh if( pUpsert ){ 1649096fd476Sdrh if( pUpsert->pUpsertTarget==0 ){ 1650096fd476Sdrh /* An ON CONFLICT DO NOTHING clause, without a constraint-target. 1651096fd476Sdrh ** Make all unique constraint resolution be OE_Ignore */ 1652dedbc508Sdrh assert( pUpsert->pUpsertSet==0 ); 1653096fd476Sdrh overrideError = OE_Ignore; 1654096fd476Sdrh pUpsert = 0; 1655096fd476Sdrh }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){ 165684304506Sdrh /* If the constraint-target uniqueness check must be run first. 165784304506Sdrh ** Jump to that uniqueness check now */ 165884304506Sdrh upsertJump = sqlite3VdbeAddOp0(v, OP_Goto); 165984304506Sdrh VdbeComment((v, "UPSERT constraint goes first")); 1660096fd476Sdrh } 1661096fd476Sdrh } 1662096fd476Sdrh 1663a407eccbSdrh /* Determine if it is possible that triggers (either explicitly coded 1664a407eccbSdrh ** triggers or FK resolution actions) might run as a result of deletes 1665a407eccbSdrh ** that happen when OE_Replace conflict resolution occurs. (Call these 1666a407eccbSdrh ** "replace triggers".) If any replace triggers run, we will need to 1667a407eccbSdrh ** recheck all of the uniqueness constraints after they have all run. 1668a407eccbSdrh ** But on the recheck, the resolution is OE_Abort instead of OE_Replace. 1669a407eccbSdrh ** 1670a407eccbSdrh ** If replace triggers are a possibility, then 1671a407eccbSdrh ** 1672a407eccbSdrh ** (1) Allocate register regTrigCnt and initialize it to zero. 1673a407eccbSdrh ** That register will count the number of replace triggers that 1674d3c468b7Sdrh ** fire. Constraint recheck only occurs if the number is positive. 1675d3c468b7Sdrh ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab. 1676a407eccbSdrh ** (3) Initialize addrRecheck and lblRecheckOk 1677a407eccbSdrh ** 1678a407eccbSdrh ** The uniqueness rechecking code will create a series of tests to run 1679a407eccbSdrh ** in a second pass. The addrRecheck and lblRecheckOk variables are 1680a407eccbSdrh ** used to link together these tests which are separated from each other 1681a407eccbSdrh ** in the generate bytecode. 1682a407eccbSdrh */ 1683a407eccbSdrh if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){ 1684a407eccbSdrh /* There are not DELETE triggers nor FK constraints. No constraint 1685a407eccbSdrh ** rechecks are needed. */ 1686a407eccbSdrh pTrigger = 0; 1687a407eccbSdrh regTrigCnt = 0; 1688a407eccbSdrh }else{ 1689a407eccbSdrh if( db->flags&SQLITE_RecTriggers ){ 1690a407eccbSdrh pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 1691a407eccbSdrh regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0); 1692a407eccbSdrh }else{ 1693a407eccbSdrh pTrigger = 0; 1694a407eccbSdrh regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0); 1695a407eccbSdrh } 1696a407eccbSdrh if( regTrigCnt ){ 1697a407eccbSdrh /* Replace triggers might exist. Allocate the counter and 1698a407eccbSdrh ** initialize it to zero. */ 1699a407eccbSdrh regTrigCnt = ++pParse->nMem; 1700a407eccbSdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt); 1701a407eccbSdrh VdbeComment((v, "trigger count")); 1702a407eccbSdrh lblRecheckOk = sqlite3VdbeMakeLabel(pParse); 1703a407eccbSdrh addrRecheck = lblRecheckOk; 1704a407eccbSdrh } 1705a407eccbSdrh } 1706a407eccbSdrh 1707f8ffb278Sdrh /* If rowid is changing, make sure the new rowid does not previously 1708f8ffb278Sdrh ** exist in the table. 17099cfcf5d4Sdrh */ 17106fbe41acSdrh if( pkChng && pPk==0 ){ 1711ec4ccdbcSdrh int addrRowidOk = sqlite3VdbeMakeLabel(pParse); 171211e85273Sdrh 1713f8ffb278Sdrh /* Figure out what action to take in case of a rowid collision */ 17140ca3e24bSdrh onError = pTab->keyConf; 17150ca3e24bSdrh if( overrideError!=OE_Default ){ 17160ca3e24bSdrh onError = overrideError; 1717a996e477Sdrh }else if( onError==OE_Default ){ 1718a996e477Sdrh onError = OE_Abort; 17190ca3e24bSdrh } 1720a0217ba7Sdrh 1721c8a0c90bSdrh /* figure out whether or not upsert applies in this case */ 1722096fd476Sdrh if( pUpsert && pUpsert->pUpsertIdx==0 ){ 1723c8a0c90bSdrh if( pUpsert->pUpsertSet==0 ){ 1724c8a0c90bSdrh onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */ 1725c8a0c90bSdrh }else{ 1726c8a0c90bSdrh onError = OE_Update; /* DO UPDATE */ 1727c8a0c90bSdrh } 1728c8a0c90bSdrh } 1729c8a0c90bSdrh 17308d1b82e4Sdrh /* If the response to a rowid conflict is REPLACE but the response 17318d1b82e4Sdrh ** to some other UNIQUE constraint is FAIL or IGNORE, then we need 17328d1b82e4Sdrh ** to defer the running of the rowid conflict checking until after 17338d1b82e4Sdrh ** the UNIQUE constraints have run. 17348d1b82e4Sdrh */ 173584304506Sdrh if( onError==OE_Replace /* IPK rule is REPLACE */ 173684304506Sdrh && onError!=overrideError /* Rules for other contraints are different */ 173784304506Sdrh && pTab->pIndex /* There exist other constraints */ 1738096fd476Sdrh ){ 173984304506Sdrh ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1; 174084304506Sdrh VdbeComment((v, "defer IPK REPLACE until last")); 17418d1b82e4Sdrh } 17428d1b82e4Sdrh 1743bb6b1ca7Sdrh if( isUpdate ){ 1744bb6b1ca7Sdrh /* pkChng!=0 does not mean that the rowid has changed, only that 1745bb6b1ca7Sdrh ** it might have changed. Skip the conflict logic below if the rowid 1746bb6b1ca7Sdrh ** is unchanged. */ 1747bb6b1ca7Sdrh sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); 1748bb6b1ca7Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1749bb6b1ca7Sdrh VdbeCoverage(v); 1750bb6b1ca7Sdrh } 1751bb6b1ca7Sdrh 1752f8ffb278Sdrh /* Check to see if the new rowid already exists in the table. Skip 1753f8ffb278Sdrh ** the following conflict logic if it does not. */ 17547f5f306bSdrh VdbeNoopComment((v, "uniqueness check for ROWID")); 17554031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 17566934fc7bSdrh sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); 1757688852abSdrh VdbeCoverage(v); 1758f8ffb278Sdrh 17590ca3e24bSdrh switch( onError ){ 1760a0217ba7Sdrh default: { 1761a0217ba7Sdrh onError = OE_Abort; 1762a0217ba7Sdrh /* Fall thru into the next case */ 1763a0217ba7Sdrh } 17641c92853dSdrh case OE_Rollback: 17651c92853dSdrh case OE_Abort: 17661c92853dSdrh case OE_Fail: { 17679916048bSdrh testcase( onError==OE_Rollback ); 17689916048bSdrh testcase( onError==OE_Abort ); 17699916048bSdrh testcase( onError==OE_Fail ); 1770f9c8ce3cSdrh sqlite3RowidConstraint(pParse, onError, pTab); 17710ca3e24bSdrh break; 17720ca3e24bSdrh } 17735383ae5cSdrh case OE_Replace: { 17742283d46cSdan /* If there are DELETE triggers on this table and the 17752283d46cSdan ** recursive-triggers flag is set, call GenerateRowDelete() to 1776d5578433Smistachkin ** remove the conflicting row from the table. This will fire 17772283d46cSdan ** the triggers and remove both the table and index b-tree entries. 17782283d46cSdan ** 17792283d46cSdan ** Otherwise, if there are no triggers or the recursive-triggers 1780da730f6eSdan ** flag is not set, but the table has one or more indexes, call 1781da730f6eSdan ** GenerateRowIndexDelete(). This removes the index b-tree entries 1782da730f6eSdan ** only. The table b-tree entry will be replaced by the new entry 1783da730f6eSdan ** when it is inserted. 1784da730f6eSdan ** 1785da730f6eSdan ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, 1786da730f6eSdan ** also invoke MultiWrite() to indicate that this VDBE may require 1787da730f6eSdan ** statement rollback (if the statement is aborted after the delete 1788da730f6eSdan ** takes place). Earlier versions called sqlite3MultiWrite() regardless, 1789da730f6eSdan ** but being more selective here allows statements like: 1790da730f6eSdan ** 1791da730f6eSdan ** REPLACE INTO t(rowid) VALUES($newrowid) 1792da730f6eSdan ** 1793da730f6eSdan ** to run without a statement journal if there are no indexes on the 1794da730f6eSdan ** table. 1795da730f6eSdan */ 1796a407eccbSdrh if( regTrigCnt ){ 1797da730f6eSdan sqlite3MultiWrite(pParse); 179826198bb4Sdrh sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1799438b8815Sdan regNewData, 1, 0, OE_Replace, 1, -1); 1800a407eccbSdrh sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */ 1801a407eccbSdrh nReplaceTrig++; 180246c47d46Sdan }else{ 18039b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 180454f2cd90Sdrh assert( HasRowid(pTab) ); 180546c47d46Sdan /* This OP_Delete opcode fires the pre-update-hook only. It does 180646c47d46Sdan ** not modify the b-tree. It is more efficient to let the coming 180746c47d46Sdan ** OP_Insert replace the existing entry than it is to delete the 180846c47d46Sdan ** existing entry and then insert a new one. */ 1809cbf1b8efSdrh sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP); 1810f14b7fb7Sdrh sqlite3VdbeAppendP4(v, pTab, P4_TABLE); 18119b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ 181246c47d46Sdan if( pTab->pIndex ){ 1813da730f6eSdan sqlite3MultiWrite(pParse); 1814f0ee1d3cSdan sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); 18152283d46cSdan } 181646c47d46Sdan } 18175383ae5cSdrh seenReplace = 1; 18185383ae5cSdrh break; 18195383ae5cSdrh } 18209eddacadSdrh #ifndef SQLITE_OMIT_UPSERT 18219eddacadSdrh case OE_Update: { 18222cc00423Sdan sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur); 18239eddacadSdrh /* Fall through */ 18249eddacadSdrh } 18259eddacadSdrh #endif 18260ca3e24bSdrh case OE_Ignore: { 18279916048bSdrh testcase( onError==OE_Ignore ); 1828076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 18290ca3e24bSdrh break; 18300ca3e24bSdrh } 18310ca3e24bSdrh } 183211e85273Sdrh sqlite3VdbeResolveLabel(v, addrRowidOk); 183384304506Sdrh if( ipkTop ){ 183484304506Sdrh ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); 183584304506Sdrh sqlite3VdbeJumpHere(v, ipkTop-1); 1836a05a722fSdrh } 18370ca3e24bSdrh } 18380bd1f4eaSdrh 18390bd1f4eaSdrh /* Test all UNIQUE constraints by creating entries for each UNIQUE 18400bd1f4eaSdrh ** index and making sure that duplicate entries do not already exist. 184111e85273Sdrh ** Compute the revised record entries for indices as we go. 1842f8ffb278Sdrh ** 1843f8ffb278Sdrh ** This loop also handles the case of the PRIMARY KEY index for a 1844f8ffb278Sdrh ** WITHOUT ROWID table. 18450bd1f4eaSdrh */ 184626198bb4Sdrh for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ 18476934fc7bSdrh int regIdx; /* Range of registers hold conent for pIdx */ 18486934fc7bSdrh int regR; /* Range of registers holding conflicting PK */ 18496934fc7bSdrh int iThisCur; /* Cursor for this UNIQUE index */ 18506934fc7bSdrh int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ 1851a407eccbSdrh int addrConflictCk; /* First opcode in the conflict check logic */ 18522184fc75Sdrh 185326198bb4Sdrh if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ 18547f5f306bSdrh if( pUpIdx==pIdx ){ 185584304506Sdrh addrUniqueOk = upsertJump+1; 18567f5f306bSdrh upsertBypass = sqlite3VdbeGoto(v, 0); 18577f5f306bSdrh VdbeComment((v, "Skip upsert subroutine")); 185884304506Sdrh sqlite3VdbeJumpHere(v, upsertJump); 18597f5f306bSdrh }else{ 1860ec4ccdbcSdrh addrUniqueOk = sqlite3VdbeMakeLabel(pParse); 18617f5f306bSdrh } 186284304506Sdrh if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){ 186384304506Sdrh sqlite3TableAffinity(v, pTab, regNewData+1); 186484304506Sdrh bAffinityDone = 1; 186584304506Sdrh } 18667f5f306bSdrh VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName)); 18676934fc7bSdrh iThisCur = iIdxCur+ix; 18687f5f306bSdrh 1869b2fe7d8cSdrh 1870f8ffb278Sdrh /* Skip partial indices for which the WHERE clause is not true */ 1871b2b9d3d7Sdrh if( pIdx->pPartIdxWhere ){ 187226198bb4Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); 18736e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 187472bc8208Sdrh sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, 1875b2b9d3d7Sdrh SQLITE_JUMPIFNULL); 18766e97f8ecSdrh pParse->iSelfTab = 0; 1877b2b9d3d7Sdrh } 1878b2b9d3d7Sdrh 18796934fc7bSdrh /* Create a record for this index entry as it should appear after 1880f8ffb278Sdrh ** the insert or update. Store that record in the aRegIdx[ix] register 1881f8ffb278Sdrh */ 1882bf2f5739Sdrh regIdx = aRegIdx[ix]+1; 18839cfcf5d4Sdrh for(i=0; i<pIdx->nColumn; i++){ 18846934fc7bSdrh int iField = pIdx->aiColumn[i]; 1885f82b9afcSdrh int x; 18864b92f98cSdrh if( iField==XN_EXPR ){ 18876e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 18881c75c9d7Sdrh sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); 18896e97f8ecSdrh pParse->iSelfTab = 0; 18901f9ca2c8Sdrh VdbeComment((v, "%s column %d", pIdx->zName, i)); 1891463e76ffSdrh }else if( iField==XN_ROWID || iField==pTab->iPKey ){ 1892f82b9afcSdrh x = regNewData; 1893463e76ffSdrh sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i); 1894463e76ffSdrh VdbeComment((v, "rowid")); 18959cfcf5d4Sdrh }else{ 1896c5f808d8Sdrh testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField ); 1897b9bcf7caSdrh x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1; 1898463e76ffSdrh sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i); 1899463e76ffSdrh VdbeComment((v, "%s", pTab->aCol[iField].zName)); 19009cfcf5d4Sdrh } 19011f9ca2c8Sdrh } 190226198bb4Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); 190326198bb4Sdrh VdbeComment((v, "for %s", pIdx->zName)); 19047e4acf7bSdrh #ifdef SQLITE_ENABLE_NULL_TRIM 19059df385ecSdrh if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){ 19069df385ecSdrh sqlite3SetMakeRecordP5(v, pIdx->pTable); 19079df385ecSdrh } 19087e4acf7bSdrh #endif 1909b2fe7d8cSdrh 1910f8ffb278Sdrh /* In an UPDATE operation, if this index is the PRIMARY KEY index 1911f8ffb278Sdrh ** of a WITHOUT ROWID table and there has been no change the 1912f8ffb278Sdrh ** primary key, then no collision is possible. The collision detection 1913f8ffb278Sdrh ** logic below can all be skipped. */ 191400012df4Sdrh if( isUpdate && pPk==pIdx && pkChng==0 ){ 1915da475b8dSdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1916da475b8dSdrh continue; 1917da475b8dSdrh } 1918f8ffb278Sdrh 19196934fc7bSdrh /* Find out what action to take in case there is a uniqueness conflict */ 19209cfcf5d4Sdrh onError = pIdx->onError; 1921de630353Sdanielk1977 if( onError==OE_None ){ 192211e85273Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1923de630353Sdanielk1977 continue; /* pIdx is not a UNIQUE index */ 1924de630353Sdanielk1977 } 19259cfcf5d4Sdrh if( overrideError!=OE_Default ){ 19269cfcf5d4Sdrh onError = overrideError; 1927a996e477Sdrh }else if( onError==OE_Default ){ 1928a996e477Sdrh onError = OE_Abort; 19299cfcf5d4Sdrh } 19305383ae5cSdrh 1931c8a0c90bSdrh /* Figure out if the upsert clause applies to this index */ 1932096fd476Sdrh if( pUpIdx==pIdx ){ 1933c8a0c90bSdrh if( pUpsert->pUpsertSet==0 ){ 1934c8a0c90bSdrh onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */ 1935c8a0c90bSdrh }else{ 1936c8a0c90bSdrh onError = OE_Update; /* DO UPDATE */ 1937c8a0c90bSdrh } 1938c8a0c90bSdrh } 1939c8a0c90bSdrh 1940801f55d8Sdrh /* Collision detection may be omitted if all of the following are true: 1941801f55d8Sdrh ** (1) The conflict resolution algorithm is REPLACE 1942801f55d8Sdrh ** (2) The table is a WITHOUT ROWID table 1943801f55d8Sdrh ** (3) There are no secondary indexes on the table 1944801f55d8Sdrh ** (4) No delete triggers need to be fired if there is a conflict 1945f9a12a10Sdan ** (5) No FK constraint counters need to be updated if a conflict occurs. 1946418454c6Sdan ** 1947418454c6Sdan ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row 1948418454c6Sdan ** must be explicitly deleted in order to ensure any pre-update hook 1949418454c6Sdan ** is invoked. */ 1950418454c6Sdan #ifndef SQLITE_ENABLE_PREUPDATE_HOOK 1951801f55d8Sdrh if( (ix==0 && pIdx->pNext==0) /* Condition 3 */ 1952801f55d8Sdrh && pPk==pIdx /* Condition 2 */ 1953801f55d8Sdrh && onError==OE_Replace /* Condition 1 */ 1954801f55d8Sdrh && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */ 1955801f55d8Sdrh 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0)) 1956f9a12a10Sdan && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */ 1957f9a12a10Sdan (0==pTab->pFKey && 0==sqlite3FkReferences(pTab))) 19584e1f0efbSdan ){ 1959c6c9e158Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1960c6c9e158Sdrh continue; 1961c6c9e158Sdrh } 1962418454c6Sdan #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */ 1963c6c9e158Sdrh 1964b2fe7d8cSdrh /* Check to see if the new index entry will be unique */ 19654031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 1966a407eccbSdrh addrConflictCk = 196726198bb4Sdrh sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, 1968688852abSdrh regIdx, pIdx->nKeyCol); VdbeCoverage(v); 1969f8ffb278Sdrh 1970f8ffb278Sdrh /* Generate code to handle collisions */ 1971392ee21dSdrh regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); 197246d03fcbSdrh if( isUpdate || onError==OE_Replace ){ 197311e85273Sdrh if( HasRowid(pTab) ){ 19746934fc7bSdrh sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); 19750978d4ffSdrh /* Conflict only if the rowid of the existing index entry 19760978d4ffSdrh ** is different from old-rowid */ 1977f8ffb278Sdrh if( isUpdate ){ 19786934fc7bSdrh sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); 19793d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1980688852abSdrh VdbeCoverage(v); 1981f8ffb278Sdrh } 198226198bb4Sdrh }else{ 1983ccc79f02Sdrh int x; 198426198bb4Sdrh /* Extract the PRIMARY KEY from the end of the index entry and 1985da475b8dSdrh ** store it in registers regR..regR+nPk-1 */ 1986a021f121Sdrh if( pIdx!=pPk ){ 198726198bb4Sdrh for(i=0; i<pPk->nKeyCol; i++){ 19884b92f98cSdrh assert( pPk->aiColumn[i]>=0 ); 1989b9bcf7caSdrh x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]); 199026198bb4Sdrh sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); 199126198bb4Sdrh VdbeComment((v, "%s.%s", pTab->zName, 199226198bb4Sdrh pTab->aCol[pPk->aiColumn[i]].zName)); 199326198bb4Sdrh } 1994da475b8dSdrh } 1995da475b8dSdrh if( isUpdate ){ 1996e83267daSdan /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 1997e83267daSdan ** table, only conflict if the new PRIMARY KEY values are actually 1998e83267daSdan ** different from the old. 1999e83267daSdan ** 2000e83267daSdan ** For a UNIQUE index, only conflict if the PRIMARY KEY values 2001e83267daSdan ** of the matched index row are different from the original PRIMARY 2002e83267daSdan ** KEY values of this row before the update. */ 2003e83267daSdan int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; 2004e83267daSdan int op = OP_Ne; 200548dd1d8eSdrh int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); 2006e83267daSdan 2007e83267daSdan for(i=0; i<pPk->nKeyCol; i++){ 2008e83267daSdan char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); 2009ccc79f02Sdrh x = pPk->aiColumn[i]; 20104b92f98cSdrh assert( x>=0 ); 2011e83267daSdan if( i==(pPk->nKeyCol-1) ){ 2012e83267daSdan addrJump = addrUniqueOk; 2013e83267daSdan op = OP_Eq; 201411e85273Sdrh } 2015b6d861e5Sdrh x = sqlite3TableColumnToStorage(pTab, x); 2016e83267daSdan sqlite3VdbeAddOp4(v, op, 2017e83267daSdan regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ 2018e83267daSdan ); 20193d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 20203d77dee9Sdrh VdbeCoverageIf(v, op==OP_Eq); 20213d77dee9Sdrh VdbeCoverageIf(v, op==OP_Ne); 2022da475b8dSdrh } 202311e85273Sdrh } 202426198bb4Sdrh } 202546d03fcbSdrh } 2026b2fe7d8cSdrh 2027b2fe7d8cSdrh /* Generate code that executes if the new index entry is not unique */ 2028b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 20299eddacadSdrh || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update ); 20309cfcf5d4Sdrh switch( onError ){ 20311c92853dSdrh case OE_Rollback: 20321c92853dSdrh case OE_Abort: 20331c92853dSdrh case OE_Fail: { 20349916048bSdrh testcase( onError==OE_Rollback ); 20359916048bSdrh testcase( onError==OE_Abort ); 20369916048bSdrh testcase( onError==OE_Fail ); 2037f9c8ce3cSdrh sqlite3UniqueConstraint(pParse, onError, pIdx); 20389cfcf5d4Sdrh break; 20399cfcf5d4Sdrh } 20409eddacadSdrh #ifndef SQLITE_OMIT_UPSERT 20419eddacadSdrh case OE_Update: { 20422cc00423Sdan sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix); 20439eddacadSdrh /* Fall through */ 20449eddacadSdrh } 20459eddacadSdrh #endif 20469cfcf5d4Sdrh case OE_Ignore: { 20479916048bSdrh testcase( onError==OE_Ignore ); 2048076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 20499cfcf5d4Sdrh break; 20509cfcf5d4Sdrh } 2051098d1684Sdrh default: { 2052a407eccbSdrh int nConflictCk; /* Number of opcodes in conflict check logic */ 2053a407eccbSdrh 2054098d1684Sdrh assert( onError==OE_Replace ); 2055a407eccbSdrh nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk; 2056d3c468b7Sdrh assert( nConflictCk>0 ); 2057d3c468b7Sdrh testcase( nConflictCk>1 ); 2058a407eccbSdrh if( regTrigCnt ){ 2059fecfb318Sdan sqlite3MultiWrite(pParse); 2060a407eccbSdrh nReplaceTrig++; 2061fecfb318Sdan } 206226198bb4Sdrh sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 2063b0264eecSdrh regR, nPkField, 0, OE_Replace, 206468116939Sdrh (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur); 2065a407eccbSdrh if( regTrigCnt ){ 2066a407eccbSdrh int addrBypass; /* Jump destination to bypass recheck logic */ 2067a407eccbSdrh 2068a407eccbSdrh sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */ 2069a407eccbSdrh addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */ 2070a407eccbSdrh VdbeComment((v, "bypass recheck")); 2071a407eccbSdrh 2072a407eccbSdrh /* Here we insert code that will be invoked after all constraint 2073a407eccbSdrh ** checks have run, if and only if one or more replace triggers 2074a407eccbSdrh ** fired. */ 2075a407eccbSdrh sqlite3VdbeResolveLabel(v, lblRecheckOk); 2076a407eccbSdrh lblRecheckOk = sqlite3VdbeMakeLabel(pParse); 2077a407eccbSdrh if( pIdx->pPartIdxWhere ){ 2078a407eccbSdrh /* Bypass the recheck if this partial index is not defined 2079a407eccbSdrh ** for the current row */ 20800660884eSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk); 2081a407eccbSdrh VdbeCoverage(v); 2082a407eccbSdrh } 2083a407eccbSdrh /* Copy the constraint check code from above, except change 2084a407eccbSdrh ** the constraint-ok jump destination to be the address of 2085a407eccbSdrh ** the next retest block */ 2086d3c468b7Sdrh while( nConflictCk>0 ){ 2087d901b168Sdrh VdbeOp x; /* Conflict check opcode to copy */ 2088d901b168Sdrh /* The sqlite3VdbeAddOp4() call might reallocate the opcode array. 2089d901b168Sdrh ** Hence, make a complete copy of the opcode, rather than using 2090d901b168Sdrh ** a pointer to the opcode. */ 2091d901b168Sdrh x = *sqlite3VdbeGetOp(v, addrConflictCk); 2092d901b168Sdrh if( x.opcode!=OP_IdxRowid ){ 2093d901b168Sdrh int p2; /* New P2 value for copied conflict check opcode */ 2094d901b168Sdrh if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){ 2095a407eccbSdrh p2 = lblRecheckOk; 2096a407eccbSdrh }else{ 2097d901b168Sdrh p2 = x.p2; 2098a407eccbSdrh } 2099d901b168Sdrh sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, x.p4.z, x.p4type); 2100d901b168Sdrh sqlite3VdbeChangeP5(v, x.p5); 2101d901b168Sdrh VdbeCoverageIf(v, p2!=x.p2); 2102a407eccbSdrh } 2103a407eccbSdrh nConflictCk--; 2104d901b168Sdrh addrConflictCk++; 2105a407eccbSdrh } 2106a407eccbSdrh /* If the retest fails, issue an abort */ 21072da8d6feSdrh sqlite3UniqueConstraint(pParse, OE_Abort, pIdx); 2108a407eccbSdrh 2109a407eccbSdrh sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */ 21102da8d6feSdrh } 21110ca3e24bSdrh seenReplace = 1; 21129cfcf5d4Sdrh break; 21139cfcf5d4Sdrh } 21149cfcf5d4Sdrh } 21157f5f306bSdrh if( pUpIdx==pIdx ){ 211684304506Sdrh sqlite3VdbeGoto(v, upsertJump+1); 21177f5f306bSdrh sqlite3VdbeJumpHere(v, upsertBypass); 21187f5f306bSdrh }else{ 211911e85273Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 21207f5f306bSdrh } 2121392ee21dSdrh if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); 21229cfcf5d4Sdrh } 212384304506Sdrh 212484304506Sdrh /* If the IPK constraint is a REPLACE, run it last */ 212584304506Sdrh if( ipkTop ){ 21266214d939Sdrh sqlite3VdbeGoto(v, ipkTop); 212784304506Sdrh VdbeComment((v, "Do IPK REPLACE")); 212884304506Sdrh sqlite3VdbeJumpHere(v, ipkBottom); 212984304506Sdrh } 2130de630353Sdanielk1977 2131a407eccbSdrh /* Recheck all uniqueness constraints after replace triggers have run */ 2132a407eccbSdrh testcase( regTrigCnt!=0 && nReplaceTrig==0 ); 2133d3c468b7Sdrh assert( regTrigCnt!=0 || nReplaceTrig==0 ); 2134a407eccbSdrh if( nReplaceTrig ){ 2135a407eccbSdrh sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v); 2136a407eccbSdrh if( !pPk ){ 2137a407eccbSdrh if( isUpdate ){ 2138a407eccbSdrh sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData); 2139a407eccbSdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 2140a407eccbSdrh VdbeCoverage(v); 2141a407eccbSdrh } 2142a407eccbSdrh sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData); 2143a407eccbSdrh VdbeCoverage(v); 2144a407eccbSdrh sqlite3RowidConstraint(pParse, OE_Abort, pTab); 2145a407eccbSdrh }else{ 2146a407eccbSdrh sqlite3VdbeGoto(v, addrRecheck); 2147a407eccbSdrh } 2148a407eccbSdrh sqlite3VdbeResolveLabel(v, lblRecheckOk); 2149a407eccbSdrh } 2150a407eccbSdrh 2151a7c3b93fSdrh /* Generate the table record */ 2152a7c3b93fSdrh if( HasRowid(pTab) ){ 2153a7c3b93fSdrh int regRec = aRegIdx[ix]; 21540b0b3a95Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec); 2155a7c3b93fSdrh sqlite3SetMakeRecordP5(v, pTab); 2156a7c3b93fSdrh if( !bAffinityDone ){ 2157a7c3b93fSdrh sqlite3TableAffinity(v, pTab, 0); 2158a7c3b93fSdrh } 2159a7c3b93fSdrh } 2160a7c3b93fSdrh 2161de630353Sdanielk1977 *pbMayReplace = seenReplace; 2162ce60aa46Sdrh VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); 21639cfcf5d4Sdrh } 21640ca3e24bSdrh 2165d447dcedSdrh #ifdef SQLITE_ENABLE_NULL_TRIM 21660ca3e24bSdrh /* 2167585ce192Sdrh ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord) 2168585ce192Sdrh ** to be the number of columns in table pTab that must not be NULL-trimmed. 2169585ce192Sdrh ** 2170585ce192Sdrh ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero. 2171585ce192Sdrh */ 2172585ce192Sdrh void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){ 2173585ce192Sdrh u16 i; 2174585ce192Sdrh 2175585ce192Sdrh /* Records with omitted columns are only allowed for schema format 2176585ce192Sdrh ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */ 2177585ce192Sdrh if( pTab->pSchema->file_format<2 ) return; 2178585ce192Sdrh 21797e4acf7bSdrh for(i=pTab->nCol-1; i>0; i--){ 21807e4acf7bSdrh if( pTab->aCol[i].pDflt!=0 ) break; 21817e4acf7bSdrh if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break; 21827e4acf7bSdrh } 21837e4acf7bSdrh sqlite3VdbeChangeP5(v, i+1); 2184585ce192Sdrh } 2185d447dcedSdrh #endif 2186585ce192Sdrh 21870ca3e24bSdrh /* 21880ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation 21894adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 21906934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the 219104adf416Sdrh ** rowid and the content to be inserted. 21920ca3e24bSdrh ** 2193b419a926Sdrh ** The arguments to this routine should be the same as the first six 21944adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks. 21950ca3e24bSdrh */ 21964adee20fSdanielk1977 void sqlite3CompleteInsertion( 21970ca3e24bSdrh Parse *pParse, /* The parser context */ 21980ca3e24bSdrh Table *pTab, /* the table into which we are inserting */ 219926198bb4Sdrh int iDataCur, /* Cursor of the canonical data source */ 220026198bb4Sdrh int iIdxCur, /* First index cursor */ 22016934fc7bSdrh int regNewData, /* Range of content */ 2202aa9b8963Sdrh int *aRegIdx, /* Register used by each index. 0 for unused indices */ 2203f91c1318Sdan int update_flags, /* True for UPDATE, False for INSERT */ 2204de630353Sdanielk1977 int appendBias, /* True if this is likely to be an append */ 2205de630353Sdanielk1977 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ 22060ca3e24bSdrh ){ 22076934fc7bSdrh Vdbe *v; /* Prepared statements under construction */ 22086934fc7bSdrh Index *pIdx; /* An index being inserted or updated */ 22096934fc7bSdrh u8 pik_flags; /* flag values passed to the btree insert */ 22106934fc7bSdrh int i; /* Loop counter */ 22110ca3e24bSdrh 2212f91c1318Sdan assert( update_flags==0 2213f91c1318Sdan || update_flags==OPFLAG_ISUPDATE 2214f91c1318Sdan || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION) 2215f91c1318Sdan ); 2216f91c1318Sdan 22174adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 22180ca3e24bSdrh assert( v!=0 ); 2219417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 2220b2b9d3d7Sdrh for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 2221aa9b8963Sdrh if( aRegIdx[i]==0 ) continue; 2222b2b9d3d7Sdrh if( pIdx->pPartIdxWhere ){ 2223b2b9d3d7Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); 2224688852abSdrh VdbeCoverage(v); 2225b2b9d3d7Sdrh } 2226cb9a3643Sdan pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0); 222748dd1d8eSdrh if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 22284308e348Sdrh assert( pParse->nested==0 ); 22296546af14Sdrh pik_flags |= OPFLAG_NCHANGE; 2230f91c1318Sdan pik_flags |= (update_flags & OPFLAG_SAVEPOSITION); 2231cb9a3643Sdan #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 2232cb9a3643Sdan if( update_flags==0 ){ 223350ef6716Sdrh int r = sqlite3GetTempReg(pParse); 223450ef6716Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, r); 223550ef6716Sdrh sqlite3VdbeAddOp4(v, OP_Insert, 223650ef6716Sdrh iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE 2237cb9a3643Sdan ); 2238cb9a3643Sdan sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP); 223950ef6716Sdrh sqlite3ReleaseTempReg(pParse, r); 2240de630353Sdanielk1977 } 2241cb9a3643Sdan #endif 2242cb9a3643Sdan } 2243cb9a3643Sdan sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i], 2244cb9a3643Sdan aRegIdx[i]+1, 2245cb9a3643Sdan pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn); 22469b34abeeSdrh sqlite3VdbeChangeP5(v, pik_flags); 22470ca3e24bSdrh } 2248ec95c441Sdrh if( !HasRowid(pTab) ) return; 22494794f735Sdrh if( pParse->nested ){ 22504794f735Sdrh pik_flags = 0; 22514794f735Sdrh }else{ 225294eb6a14Sdanielk1977 pik_flags = OPFLAG_NCHANGE; 2253f91c1318Sdan pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID); 22544794f735Sdrh } 2255e4d90813Sdrh if( appendBias ){ 2256e4d90813Sdrh pik_flags |= OPFLAG_APPEND; 2257e4d90813Sdrh } 2258de630353Sdanielk1977 if( useSeekResult ){ 2259de630353Sdanielk1977 pik_flags |= OPFLAG_USESEEKRESULT; 2260de630353Sdanielk1977 } 2261a7c3b93fSdrh sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData); 226294eb6a14Sdanielk1977 if( !pParse->nested ){ 2263f14b7fb7Sdrh sqlite3VdbeAppendP4(v, pTab, P4_TABLE); 226494eb6a14Sdanielk1977 } 2265b7654111Sdrh sqlite3VdbeChangeP5(v, pik_flags); 22660ca3e24bSdrh } 2267cd44690aSdrh 2268cd44690aSdrh /* 226926198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate 227026198bb4Sdrh ** code to open and initialized those cursors. 2271aa9b8963Sdrh ** 227226198bb4Sdrh ** The cursor for the object that contains the complete data (normally 227326198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT 227426198bb4Sdrh ** ROWID table) is returned in *piDataCur. The first index cursor is 227526198bb4Sdrh ** returned in *piIdxCur. The number of indices is returned. 227626198bb4Sdrh ** 227726198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables 227826198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative. 227926198bb4Sdrh ** If iBase is negative, then allocate the next available cursor. 228026198bb4Sdrh ** 228126198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. 228226198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range 228326198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the 228426198bb4Sdrh ** pTab->pIndex list. 2285b6b4b79fSdrh ** 2286b6b4b79fSdrh ** If pTab is a virtual table, then this routine is a no-op and the 2287b6b4b79fSdrh ** *piDataCur and *piIdxCur values are left uninitialized. 2288cd44690aSdrh */ 2289aa9b8963Sdrh int sqlite3OpenTableAndIndices( 2290290c1948Sdrh Parse *pParse, /* Parsing context */ 2291290c1948Sdrh Table *pTab, /* Table to be opened */ 229226198bb4Sdrh int op, /* OP_OpenRead or OP_OpenWrite */ 2293b89aeb6aSdrh u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */ 229426198bb4Sdrh int iBase, /* Use this for the table cursor, if there is one */ 22956a53499aSdrh u8 *aToOpen, /* If not NULL: boolean for each table and index */ 229626198bb4Sdrh int *piDataCur, /* Write the database source cursor number here */ 229726198bb4Sdrh int *piIdxCur /* Write the first index cursor number here */ 2298290c1948Sdrh ){ 2299cd44690aSdrh int i; 23004cbdda9eSdrh int iDb; 23016a53499aSdrh int iDataCur; 2302cd44690aSdrh Index *pIdx; 23034cbdda9eSdrh Vdbe *v; 23044cbdda9eSdrh 230526198bb4Sdrh assert( op==OP_OpenRead || op==OP_OpenWrite ); 2306fd261ec6Sdan assert( op==OP_OpenWrite || p5==0 ); 230726198bb4Sdrh if( IsVirtual(pTab) ){ 2308b6b4b79fSdrh /* This routine is a no-op for virtual tables. Leave the output 2309b6b4b79fSdrh ** variables *piDataCur and *piIdxCur uninitialized so that valgrind 2310b6b4b79fSdrh ** can detect if they are used by mistake in the caller. */ 231126198bb4Sdrh return 0; 231226198bb4Sdrh } 23134cbdda9eSdrh iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 23144cbdda9eSdrh v = sqlite3GetVdbe(pParse); 2315cd44690aSdrh assert( v!=0 ); 231626198bb4Sdrh if( iBase<0 ) iBase = pParse->nTab; 23176a53499aSdrh iDataCur = iBase++; 23186a53499aSdrh if( piDataCur ) *piDataCur = iDataCur; 23196a53499aSdrh if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ 23206a53499aSdrh sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); 23216fbe41acSdrh }else{ 232226198bb4Sdrh sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); 23236fbe41acSdrh } 23246a53499aSdrh if( piIdxCur ) *piIdxCur = iBase; 232526198bb4Sdrh for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 232626198bb4Sdrh int iIdxCur = iBase++; 2327da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 232861441c34Sdan if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 232961441c34Sdan if( piDataCur ) *piDataCur = iIdxCur; 233061441c34Sdan p5 = 0; 233161441c34Sdan } 23326a53499aSdrh if( aToOpen==0 || aToOpen[i+1] ){ 23332ec2fb22Sdrh sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); 23342ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 2335b89aeb6aSdrh sqlite3VdbeChangeP5(v, p5); 233661441c34Sdan VdbeComment((v, "%s", pIdx->zName)); 2337b89aeb6aSdrh } 23386a53499aSdrh } 233926198bb4Sdrh if( iBase>pParse->nTab ) pParse->nTab = iBase; 234026198bb4Sdrh return i; 2341cd44690aSdrh } 23429d9cf229Sdrh 234391c58e23Sdrh 234491c58e23Sdrh #ifdef SQLITE_TEST 234591c58e23Sdrh /* 234691c58e23Sdrh ** The following global variable is incremented whenever the 234791c58e23Sdrh ** transfer optimization is used. This is used for testing 234891c58e23Sdrh ** purposes only - to make sure the transfer optimization really 234960ec914cSpeter.d.reid ** is happening when it is supposed to. 235091c58e23Sdrh */ 235191c58e23Sdrh int sqlite3_xferopt_count; 235291c58e23Sdrh #endif /* SQLITE_TEST */ 235391c58e23Sdrh 235491c58e23Sdrh 23559d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 23569d9cf229Sdrh /* 23579d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data 23589d9cf229Sdrh ** for index pDest in an insert transfer optimization. The rules 23599d9cf229Sdrh ** for a compatible index: 23609d9cf229Sdrh ** 23619d9cf229Sdrh ** * The index is over the same set of columns 23629d9cf229Sdrh ** * The same DESC and ASC markings occurs on all columns 23639d9cf229Sdrh ** * The same onError processing (OE_Abort, OE_Ignore, etc) 23649d9cf229Sdrh ** * The same collating sequence on each column 2365b2b9d3d7Sdrh ** * The index has the exact same WHERE clause 23669d9cf229Sdrh */ 23679d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 23689d9cf229Sdrh int i; 23699d9cf229Sdrh assert( pDest && pSrc ); 23709d9cf229Sdrh assert( pDest->pTable!=pSrc->pTable ); 23711e7c00e6Sdrh if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){ 23729d9cf229Sdrh return 0; /* Different number of columns */ 23739d9cf229Sdrh } 23749d9cf229Sdrh if( pDest->onError!=pSrc->onError ){ 23759d9cf229Sdrh return 0; /* Different conflict resolution strategies */ 23769d9cf229Sdrh } 2377bbbdc83bSdrh for(i=0; i<pSrc->nKeyCol; i++){ 23789d9cf229Sdrh if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 23799d9cf229Sdrh return 0; /* Different columns indexed */ 23809d9cf229Sdrh } 23814b92f98cSdrh if( pSrc->aiColumn[i]==XN_EXPR ){ 23821f9ca2c8Sdrh assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); 23835aa550cfSdan if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr, 23841f9ca2c8Sdrh pDest->aColExpr->a[i].pExpr, -1)!=0 ){ 23851f9ca2c8Sdrh return 0; /* Different expressions in the index */ 23861f9ca2c8Sdrh } 23871f9ca2c8Sdrh } 23889d9cf229Sdrh if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 23899d9cf229Sdrh return 0; /* Different sort orders */ 23909d9cf229Sdrh } 23910472af91Sdrh if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){ 239260a713c6Sdrh return 0; /* Different collating sequences */ 23939d9cf229Sdrh } 23949d9cf229Sdrh } 23955aa550cfSdan if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ 2396b2b9d3d7Sdrh return 0; /* Different WHERE clauses */ 2397b2b9d3d7Sdrh } 23989d9cf229Sdrh 23999d9cf229Sdrh /* If no test above fails then the indices must be compatible */ 24009d9cf229Sdrh return 1; 24019d9cf229Sdrh } 24029d9cf229Sdrh 24039d9cf229Sdrh /* 24049d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form 24059d9cf229Sdrh ** 24069d9cf229Sdrh ** INSERT INTO tab1 SELECT * FROM tab2; 24079d9cf229Sdrh ** 2408ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1. 240960ec914cSpeter.d.reid ** Columns are not decoded and reassembled, which greatly improves 2410ccdf1baeSdrh ** performance. Raw index records are transferred in the same way. 24119d9cf229Sdrh ** 2412ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible. 2413ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments 2414ccdf1baeSdrh ** embedded in the code for details. 24159d9cf229Sdrh ** 2416ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used. 2417ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table 2418ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time. In that 2419ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also 2420ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the 2421ccdf1baeSdrh ** xfer optimization code if the test fails. In that case, this routine 2422ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate 2423ccdf1baeSdrh ** an unoptimized transfer. This routine also returns FALSE if there 2424ccdf1baeSdrh ** is no chance that the xfer optimization can be applied. 24259d9cf229Sdrh ** 2426ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster. 24279d9cf229Sdrh */ 24289d9cf229Sdrh static int xferOptimization( 24299d9cf229Sdrh Parse *pParse, /* Parser context */ 24309d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 24319d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 24329d9cf229Sdrh int onError, /* How to handle constraint errors */ 24339d9cf229Sdrh int iDbDest /* The database of pDest */ 24349d9cf229Sdrh ){ 2435e34162b1Sdan sqlite3 *db = pParse->db; 24369d9cf229Sdrh ExprList *pEList; /* The result set of the SELECT */ 24379d9cf229Sdrh Table *pSrc; /* The table in the FROM clause of SELECT */ 24389d9cf229Sdrh Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 24399d9cf229Sdrh struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 24409d9cf229Sdrh int i; /* Loop counter */ 24419d9cf229Sdrh int iDbSrc; /* The database of pSrc */ 24429d9cf229Sdrh int iSrc, iDest; /* Cursors from source and destination */ 24439d9cf229Sdrh int addr1, addr2; /* Loop addresses */ 2444da475b8dSdrh int emptyDestTest = 0; /* Address of test for empty pDest */ 2445da475b8dSdrh int emptySrcTest = 0; /* Address of test for empty pSrc */ 24469d9cf229Sdrh Vdbe *v; /* The VDBE we are building */ 24476a288a33Sdrh int regAutoinc; /* Memory register used by AUTOINC */ 2448f33c9fadSdrh int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 2449b7654111Sdrh int regData, regRowid; /* Registers holding data and rowid */ 24509d9cf229Sdrh 24519d9cf229Sdrh if( pSelect==0 ){ 24529d9cf229Sdrh return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 24539d9cf229Sdrh } 2454ebbf08a0Sdan if( pParse->pWith || pSelect->pWith ){ 2455ebbf08a0Sdan /* Do not attempt to process this query if there are an WITH clauses 2456ebbf08a0Sdan ** attached to it. Proceeding may generate a false "no such table: xxx" 2457ebbf08a0Sdan ** error if pSelect reads from a CTE named "xxx". */ 2458ebbf08a0Sdan return 0; 2459ebbf08a0Sdan } 24602f886d1dSdanielk1977 if( sqlite3TriggerList(pParse, pDest) ){ 24619d9cf229Sdrh return 0; /* tab1 must not have triggers */ 24629d9cf229Sdrh } 24639d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 246444266ec6Sdrh if( IsVirtual(pDest) ){ 24659d9cf229Sdrh return 0; /* tab1 must not be a virtual table */ 24669d9cf229Sdrh } 24679d9cf229Sdrh #endif 24689d9cf229Sdrh if( onError==OE_Default ){ 2469e7224a01Sdrh if( pDest->iPKey>=0 ) onError = pDest->keyConf; 2470e7224a01Sdrh if( onError==OE_Default ) onError = OE_Abort; 24719d9cf229Sdrh } 24725ce240a6Sdanielk1977 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 24739d9cf229Sdrh if( pSelect->pSrc->nSrc!=1 ){ 24749d9cf229Sdrh return 0; /* FROM clause must have exactly one term */ 24759d9cf229Sdrh } 24769d9cf229Sdrh if( pSelect->pSrc->a[0].pSelect ){ 24779d9cf229Sdrh return 0; /* FROM clause cannot contain a subquery */ 24789d9cf229Sdrh } 24799d9cf229Sdrh if( pSelect->pWhere ){ 24809d9cf229Sdrh return 0; /* SELECT may not have a WHERE clause */ 24819d9cf229Sdrh } 24829d9cf229Sdrh if( pSelect->pOrderBy ){ 24839d9cf229Sdrh return 0; /* SELECT may not have an ORDER BY clause */ 24849d9cf229Sdrh } 24858103b7d2Sdrh /* Do not need to test for a HAVING clause. If HAVING is present but 24868103b7d2Sdrh ** there is no ORDER BY, we will get an error. */ 24879d9cf229Sdrh if( pSelect->pGroupBy ){ 24889d9cf229Sdrh return 0; /* SELECT may not have a GROUP BY clause */ 24899d9cf229Sdrh } 24909d9cf229Sdrh if( pSelect->pLimit ){ 24919d9cf229Sdrh return 0; /* SELECT may not have a LIMIT clause */ 24929d9cf229Sdrh } 24939d9cf229Sdrh if( pSelect->pPrior ){ 24949d9cf229Sdrh return 0; /* SELECT may not be a compound query */ 24959d9cf229Sdrh } 24967d10d5a6Sdrh if( pSelect->selFlags & SF_Distinct ){ 24979d9cf229Sdrh return 0; /* SELECT may not be DISTINCT */ 24989d9cf229Sdrh } 24999d9cf229Sdrh pEList = pSelect->pEList; 25009d9cf229Sdrh assert( pEList!=0 ); 25019d9cf229Sdrh if( pEList->nExpr!=1 ){ 25029d9cf229Sdrh return 0; /* The result set must have exactly one column */ 25039d9cf229Sdrh } 25049d9cf229Sdrh assert( pEList->a[0].pExpr ); 25051a1d3cd2Sdrh if( pEList->a[0].pExpr->op!=TK_ASTERISK ){ 25069d9cf229Sdrh return 0; /* The result set must be the special operator "*" */ 25079d9cf229Sdrh } 25089d9cf229Sdrh 25099d9cf229Sdrh /* At this point we have established that the statement is of the 25109d9cf229Sdrh ** correct syntactic form to participate in this optimization. Now 25119d9cf229Sdrh ** we have to check the semantics. 25129d9cf229Sdrh */ 25139d9cf229Sdrh pItem = pSelect->pSrc->a; 251441fb5cd1Sdan pSrc = sqlite3LocateTableItem(pParse, 0, pItem); 25159d9cf229Sdrh if( pSrc==0 ){ 25169d9cf229Sdrh return 0; /* FROM clause does not contain a real table */ 25179d9cf229Sdrh } 251821908b21Sdrh if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){ 251921908b21Sdrh testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */ 25209d9cf229Sdrh return 0; /* tab1 and tab2 may not be the same table */ 25219d9cf229Sdrh } 252255548273Sdrh if( HasRowid(pDest)!=HasRowid(pSrc) ){ 252355548273Sdrh return 0; /* source and destination must both be WITHOUT ROWID or not */ 252455548273Sdrh } 25259d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 252644266ec6Sdrh if( IsVirtual(pSrc) ){ 25279d9cf229Sdrh return 0; /* tab2 must not be a virtual table */ 25289d9cf229Sdrh } 25299d9cf229Sdrh #endif 25309d9cf229Sdrh if( pSrc->pSelect ){ 25319d9cf229Sdrh return 0; /* tab2 may not be a view */ 25329d9cf229Sdrh } 25339d9cf229Sdrh if( pDest->nCol!=pSrc->nCol ){ 25349d9cf229Sdrh return 0; /* Number of columns must be the same in tab1 and tab2 */ 25359d9cf229Sdrh } 25369d9cf229Sdrh if( pDest->iPKey!=pSrc->iPKey ){ 25379d9cf229Sdrh return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 25389d9cf229Sdrh } 25399d9cf229Sdrh for(i=0; i<pDest->nCol; i++){ 25409940e2aaSdan Column *pDestCol = &pDest->aCol[i]; 25419940e2aaSdan Column *pSrcCol = &pSrc->aCol[i]; 2542ba68f8f3Sdan #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS 25438257aa8dSdrh if( (db->mDbFlags & DBFLAG_Vacuum)==0 2544aaea3143Sdan && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN 2545aaea3143Sdan ){ 2546ba68f8f3Sdan return 0; /* Neither table may have __hidden__ columns */ 2547ba68f8f3Sdan } 2548ba68f8f3Sdan #endif 25496ab61d70Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 25506ab61d70Sdrh /* Even if tables t1 and t2 have identical schemas, if they contain 25516ab61d70Sdrh ** generated columns, then this statement is semantically incorrect: 25526ab61d70Sdrh ** 25536ab61d70Sdrh ** INSERT INTO t2 SELECT * FROM t1; 25546ab61d70Sdrh ** 25556ab61d70Sdrh ** The reason is that generated column values are returned by the 25566ab61d70Sdrh ** the SELECT statement on the right but the INSERT statement on the 25576ab61d70Sdrh ** left wants them to be omitted. 25586ab61d70Sdrh ** 25596ab61d70Sdrh ** Nevertheless, this is a useful notational shorthand to tell SQLite 25606ab61d70Sdrh ** to do a bulk transfer all of the content from t1 over to t2. 25616ab61d70Sdrh ** 25626ab61d70Sdrh ** We could, in theory, disable this (except for internal use by the 25636ab61d70Sdrh ** VACUUM command where it is actually needed). But why do that? It 25646ab61d70Sdrh ** seems harmless enough, and provides a useful service. 25656ab61d70Sdrh */ 2566ae3977a8Sdrh if( (pDestCol->colFlags & COLFLAG_GENERATED) != 2567ae3977a8Sdrh (pSrcCol->colFlags & COLFLAG_GENERATED) ){ 25686ab61d70Sdrh return 0; /* Both columns have the same generated-column type */ 2569ae3977a8Sdrh } 25706ab61d70Sdrh /* But the transfer is only allowed if both the source and destination 25716ab61d70Sdrh ** tables have the exact same expressions for generated columns. 25726ab61d70Sdrh ** This requirement could be relaxed for VIRTUAL columns, I suppose. 25736ab61d70Sdrh */ 25746ab61d70Sdrh if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){ 25756ab61d70Sdrh if( sqlite3ExprCompare(0, pSrcCol->pDflt, pDestCol->pDflt, -1)!=0 ){ 25766ab61d70Sdrh testcase( pDestCol->colFlags & COLFLAG_VIRTUAL ); 25776ab61d70Sdrh testcase( pDestCol->colFlags & COLFLAG_STORED ); 25786ab61d70Sdrh return 0; /* Different generator expressions */ 25796ab61d70Sdrh } 25806ab61d70Sdrh } 25816ab61d70Sdrh #endif 25829940e2aaSdan if( pDestCol->affinity!=pSrcCol->affinity ){ 25839d9cf229Sdrh return 0; /* Affinity must be the same on all columns */ 25849d9cf229Sdrh } 25850472af91Sdrh if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){ 25869d9cf229Sdrh return 0; /* Collating sequence must be the same on all columns */ 25879d9cf229Sdrh } 25889940e2aaSdan if( pDestCol->notNull && !pSrcCol->notNull ){ 25899d9cf229Sdrh return 0; /* tab2 must be NOT NULL if tab1 is */ 25909d9cf229Sdrh } 2591453e0261Sdrh /* Default values for second and subsequent columns need to match. */ 2592ae3977a8Sdrh if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){ 259394fa9c41Sdrh assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN ); 259494fa9c41Sdrh assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN ); 259594fa9c41Sdrh if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) 259694fa9c41Sdrh || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken, 259794fa9c41Sdrh pSrcCol->pDflt->u.zToken)!=0) 25989940e2aaSdan ){ 25999940e2aaSdan return 0; /* Default values must be the same for all columns */ 26009940e2aaSdan } 26019d9cf229Sdrh } 260294fa9c41Sdrh } 26039d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 26045f1d1d9cSdrh if( IsUniqueIndex(pDestIdx) ){ 2605f33c9fadSdrh destHasUniqueIdx = 1; 2606f33c9fadSdrh } 26079d9cf229Sdrh for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 26089d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 26099d9cf229Sdrh } 26109d9cf229Sdrh if( pSrcIdx==0 ){ 26119d9cf229Sdrh return 0; /* pDestIdx has no corresponding index in pSrc */ 26129d9cf229Sdrh } 2613e3bd232eSdrh if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema 2614e3bd232eSdrh && sqlite3FaultSim(411)==SQLITE_OK ){ 2615e3bd232eSdrh /* The sqlite3FaultSim() call allows this corruption test to be 2616e3bd232eSdrh ** bypassed during testing, in order to exercise other corruption tests 2617e3bd232eSdrh ** further downstream. */ 261886223e8dSdrh return 0; /* Corrupt schema - two indexes on the same btree */ 261986223e8dSdrh } 26209d9cf229Sdrh } 26217fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK 2622619a1305Sdrh if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ 26238103b7d2Sdrh return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 26248103b7d2Sdrh } 26257fc2f41bSdrh #endif 2626713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY 2627713de341Sdrh /* Disallow the transfer optimization if the destination table constains 2628713de341Sdrh ** any foreign key constraints. This is more restrictive than necessary. 2629713de341Sdrh ** But the main beneficiary of the transfer optimization is the VACUUM 2630713de341Sdrh ** command, and the VACUUM command disables foreign key constraints. So 2631713de341Sdrh ** the extra complication to make this rule less restrictive is probably 2632713de341Sdrh ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] 2633713de341Sdrh */ 2634e34162b1Sdan if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ 2635713de341Sdrh return 0; 2636713de341Sdrh } 2637713de341Sdrh #endif 2638e34162b1Sdan if( (db->flags & SQLITE_CountRows)!=0 ){ 2639ccdf1baeSdrh return 0; /* xfer opt does not play well with PRAGMA count_changes */ 26401696124dSdan } 26419d9cf229Sdrh 2642ccdf1baeSdrh /* If we get this far, it means that the xfer optimization is at 2643ccdf1baeSdrh ** least a possibility, though it might only work if the destination 2644ccdf1baeSdrh ** table (tab1) is initially empty. 26459d9cf229Sdrh */ 2646dd73521bSdrh #ifdef SQLITE_TEST 2647dd73521bSdrh sqlite3_xferopt_count++; 2648dd73521bSdrh #endif 2649e34162b1Sdan iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); 26509d9cf229Sdrh v = sqlite3GetVdbe(pParse); 2651f53e9b5aSdrh sqlite3CodeVerifySchema(pParse, iDbSrc); 26529d9cf229Sdrh iSrc = pParse->nTab++; 26539d9cf229Sdrh iDest = pParse->nTab++; 26546a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 265555548273Sdrh regData = sqlite3GetTempReg(pParse); 265655548273Sdrh regRowid = sqlite3GetTempReg(pParse); 26579d9cf229Sdrh sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 2658427ebba1Sdan assert( HasRowid(pDest) || destHasUniqueIdx ); 26598257aa8dSdrh if( (db->mDbFlags & DBFLAG_Vacuum)==0 && ( 2660e34162b1Sdan (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ 2661ccdf1baeSdrh || destHasUniqueIdx /* (2) */ 2662ccdf1baeSdrh || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ 2663e34162b1Sdan )){ 2664ccdf1baeSdrh /* In some circumstances, we are able to run the xfer optimization 2665e34162b1Sdan ** only if the destination table is initially empty. Unless the 26668257aa8dSdrh ** DBFLAG_Vacuum flag is set, this block generates code to make 26678257aa8dSdrh ** that determination. If DBFLAG_Vacuum is set, then the destination 2668e34162b1Sdan ** table is always empty. 2669e34162b1Sdan ** 2670e34162b1Sdan ** Conditions under which the destination must be empty: 2671f33c9fadSdrh ** 2672ccdf1baeSdrh ** (1) There is no INTEGER PRIMARY KEY but there are indices. 2673ccdf1baeSdrh ** (If the destination is not initially empty, the rowid fields 2674ccdf1baeSdrh ** of index entries might need to change.) 2675ccdf1baeSdrh ** 2676ccdf1baeSdrh ** (2) The destination has a unique index. (The xfer optimization 2677ccdf1baeSdrh ** is unable to test uniqueness.) 2678ccdf1baeSdrh ** 2679ccdf1baeSdrh ** (3) onError is something other than OE_Abort and OE_Rollback. 26809d9cf229Sdrh */ 2681688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); 26822991ba05Sdrh emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); 26839d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 26849d9cf229Sdrh } 2685427ebba1Sdan if( HasRowid(pSrc) ){ 2686c9b9deaeSdrh u8 insFlags; 26879d9cf229Sdrh sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 2688688852abSdrh emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 268942242dedSdrh if( pDest->iPKey>=0 ){ 2690b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 26914031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 2692b7654111Sdrh addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 2693688852abSdrh VdbeCoverage(v); 2694f9c8ce3cSdrh sqlite3RowidConstraint(pParse, onError, pDest); 26959d9cf229Sdrh sqlite3VdbeJumpHere(v, addr2); 2696b7654111Sdrh autoIncStep(pParse, regAutoinc, regRowid); 26974e61e883Sdrh }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){ 2698b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 269995bad4c7Sdrh }else{ 2700b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 27017d10d5a6Sdrh assert( (pDest->tabFlags & TF_Autoincrement)==0 ); 270295bad4c7Sdrh } 2703e7b554d6Sdrh sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); 27048257aa8dSdrh if( db->mDbFlags & DBFLAG_Vacuum ){ 270586b40dfdSdrh sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); 2706c9b9deaeSdrh insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID| 2707c9b9deaeSdrh OPFLAG_APPEND|OPFLAG_USESEEKRESULT; 2708c9b9deaeSdrh }else{ 2709c9b9deaeSdrh insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND; 2710c9b9deaeSdrh } 27119b34abeeSdrh sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid, 271220f272c9Sdrh (char*)pDest, P4_TABLE); 2713c9b9deaeSdrh sqlite3VdbeChangeP5(v, insFlags); 2714688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); 271555548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 271655548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2717da475b8dSdrh }else{ 2718da475b8dSdrh sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); 2719da475b8dSdrh sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); 272055548273Sdrh } 27219d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 272241b9ca25Sdrh u8 idxInsFlags = 0; 27231b7ecbb4Sdrh for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ 27249d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 27259d9cf229Sdrh } 27269d9cf229Sdrh assert( pSrcIdx ); 27272ec2fb22Sdrh sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); 27282ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); 2729d4e70ebdSdrh VdbeComment((v, "%s", pSrcIdx->zName)); 27302ec2fb22Sdrh sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); 27312ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); 273259885728Sdan sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); 2733207872a4Sdanielk1977 VdbeComment((v, "%s", pDestIdx->zName)); 2734688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2735e7b554d6Sdrh sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); 27368257aa8dSdrh if( db->mDbFlags & DBFLAG_Vacuum ){ 2737e34162b1Sdan /* This INSERT command is part of a VACUUM operation, which guarantees 2738e34162b1Sdan ** that the destination table is empty. If all indexed columns use 2739e34162b1Sdan ** collation sequence BINARY, then it can also be assumed that the 2740e34162b1Sdan ** index will be populated by inserting keys in strictly sorted 2741e34162b1Sdan ** order. In this case, instead of seeking within the b-tree as part 274286b40dfdSdrh ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the 2743e34162b1Sdan ** OP_IdxInsert to seek to the point within the b-tree where each key 2744e34162b1Sdan ** should be inserted. This is faster. 2745e34162b1Sdan ** 2746e34162b1Sdan ** If any of the indexed columns use a collation sequence other than 2747e34162b1Sdan ** BINARY, this optimization is disabled. This is because the user 2748e34162b1Sdan ** might change the definition of a collation sequence and then run 2749e34162b1Sdan ** a VACUUM command. In that case keys may not be written in strictly 2750e34162b1Sdan ** sorted order. */ 2751e34162b1Sdan for(i=0; i<pSrcIdx->nColumn; i++){ 2752f19aa5faSdrh const char *zColl = pSrcIdx->azColl[i]; 2753f19aa5faSdrh if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break; 2754e34162b1Sdan } 2755e34162b1Sdan if( i==pSrcIdx->nColumn ){ 275641b9ca25Sdrh idxInsFlags = OPFLAG_USESEEKRESULT; 275786b40dfdSdrh sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); 2758e34162b1Sdan } 2759e34162b1Sdan } 27609df385ecSdrh if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){ 276141b9ca25Sdrh idxInsFlags |= OPFLAG_NCHANGE; 276241b9ca25Sdrh } 27639b4eaebcSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData); 27649b4eaebcSdrh sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND); 2765688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); 27669d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 276755548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 276855548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 27699d9cf229Sdrh } 2770aceb31b1Sdrh if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); 2771b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 2772b7654111Sdrh sqlite3ReleaseTempReg(pParse, regData); 27739d9cf229Sdrh if( emptyDestTest ){ 27741dd518cfSdrh sqlite3AutoincrementEnd(pParse); 277566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 27769d9cf229Sdrh sqlite3VdbeJumpHere(v, emptyDestTest); 277766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 27789d9cf229Sdrh return 0; 27799d9cf229Sdrh }else{ 27809d9cf229Sdrh return 1; 27819d9cf229Sdrh } 27829d9cf229Sdrh } 27839d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 2784