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) ){ 40261c02d9Sdrh sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol); 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]; 911f9ca2c8Sdrh if( x>=0 ){ 921f9ca2c8Sdrh pIdx->zColAff[n] = pTab->aCol[x].affinity; 934b92f98cSdrh }else if( x==XN_ROWID ){ 941f9ca2c8Sdrh pIdx->zColAff[n] = SQLITE_AFF_INTEGER; 951f9ca2c8Sdrh }else{ 966860e6faSdrh char aff; 974b92f98cSdrh assert( x==XN_EXPR ); 981f9ca2c8Sdrh assert( pIdx->aColExpr!=0 ); 996860e6faSdrh aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr); 1006860e6faSdrh if( aff==0 ) aff = SQLITE_AFF_BLOB; 1016860e6faSdrh pIdx->zColAff[n] = aff; 1021f9ca2c8Sdrh } 103a37cdde0Sdanielk1977 } 1042d401ab8Sdrh pIdx->zColAff[n] = 0; 105a37cdde0Sdanielk1977 } 1063d1bfeaaSdanielk1977 10769f8bb9cSdan return pIdx->zColAff; 108a37cdde0Sdanielk1977 } 109a37cdde0Sdanielk1977 110a37cdde0Sdanielk1977 /* 11157bf4a8eSdrh ** Compute the affinity string for table pTab, if it has not already been 11205883a34Sdrh ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities. 11357bf4a8eSdrh ** 11405883a34Sdrh ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and 11557bf4a8eSdrh ** if iReg>0 then code an OP_Affinity opcode that will set the affinities 11657bf4a8eSdrh ** for register iReg and following. Or if affinities exists and iReg==0, 11757bf4a8eSdrh ** then just set the P4 operand of the previous opcode (which should be 11857bf4a8eSdrh ** an OP_MakeRecord) to the affinity string. 11957bf4a8eSdrh ** 120b6e8fd10Sdrh ** A column affinity string has one character per column: 121a37cdde0Sdanielk1977 ** 122a37cdde0Sdanielk1977 ** Character Column affinity 123a37cdde0Sdanielk1977 ** ------------------------------ 12405883a34Sdrh ** 'A' BLOB 1254583c37cSdrh ** 'B' TEXT 1264583c37cSdrh ** 'C' NUMERIC 1274583c37cSdrh ** 'D' INTEGER 1284583c37cSdrh ** 'E' REAL 129a37cdde0Sdanielk1977 */ 13057bf4a8eSdrh void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ 1313d1bfeaaSdanielk1977 int i; 13257bf4a8eSdrh char *zColAff = pTab->zColAff; 13357bf4a8eSdrh if( zColAff==0 ){ 134abb6fcabSdrh sqlite3 *db = sqlite3VdbeDb(v); 135b975598eSdrh zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); 1363d1bfeaaSdanielk1977 if( !zColAff ){ 1374a642b60Sdrh sqlite3OomFault(db); 138a37cdde0Sdanielk1977 return; 1393d1bfeaaSdanielk1977 } 1403d1bfeaaSdanielk1977 1413d1bfeaaSdanielk1977 for(i=0; i<pTab->nCol; i++){ 142a37cdde0Sdanielk1977 zColAff[i] = pTab->aCol[i].affinity; 1433d1bfeaaSdanielk1977 } 14457bf4a8eSdrh do{ 14557bf4a8eSdrh zColAff[i--] = 0; 14605883a34Sdrh }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB ); 1473d1bfeaaSdanielk1977 pTab->zColAff = zColAff; 1483d1bfeaaSdanielk1977 } 14957bf4a8eSdrh i = sqlite3Strlen30(zColAff); 15057bf4a8eSdrh if( i ){ 15157bf4a8eSdrh if( iReg ){ 15257bf4a8eSdrh sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i); 15357bf4a8eSdrh }else{ 15457bf4a8eSdrh sqlite3VdbeChangeP4(v, -1, zColAff, i); 15557bf4a8eSdrh } 15657bf4a8eSdrh } 1573d1bfeaaSdanielk1977 } 1583d1bfeaaSdanielk1977 1594d88778bSdanielk1977 /* 16048d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices 161b6e8fd10Sdrh ** have been opened at any point in the VDBE program. This is used to see if 16248d1178aSdrh ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can 163b6e8fd10Sdrh ** run without using a temporary table for the results of the SELECT. 1644d88778bSdanielk1977 */ 16505a86c5cSdrh static int readsTable(Parse *p, int iDb, Table *pTab){ 166595a523aSdanielk1977 Vdbe *v = sqlite3GetVdbe(p); 1674d88778bSdanielk1977 int i; 16848d1178aSdrh int iEnd = sqlite3VdbeCurrentAddr(v); 169595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 170595a523aSdanielk1977 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; 171595a523aSdanielk1977 #endif 172595a523aSdanielk1977 17305a86c5cSdrh for(i=1; i<iEnd; i++){ 17448d1178aSdrh VdbeOp *pOp = sqlite3VdbeGetOp(v, i); 175ef0bea92Sdrh assert( pOp!=0 ); 176207872a4Sdanielk1977 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ 17748d1178aSdrh Index *pIndex; 178207872a4Sdanielk1977 int tnum = pOp->p2; 17948d1178aSdrh if( tnum==pTab->tnum ){ 18048d1178aSdrh return 1; 18148d1178aSdrh } 18248d1178aSdrh for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 18348d1178aSdrh if( tnum==pIndex->tnum ){ 18448d1178aSdrh return 1; 18548d1178aSdrh } 18648d1178aSdrh } 18748d1178aSdrh } 188543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 189595a523aSdanielk1977 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){ 1902dca4ac1Sdanielk1977 assert( pOp->p4.pVtab!=0 ); 19166a5167bSdrh assert( pOp->p4type==P4_VTAB ); 19248d1178aSdrh return 1; 1934d88778bSdanielk1977 } 194543165efSdrh #endif 1954d88778bSdanielk1977 } 1964d88778bSdanielk1977 return 0; 1974d88778bSdanielk1977 } 1983d1bfeaaSdanielk1977 1999d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 2009d9cf229Sdrh /* 2010b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab 2020b9f50d8Sdrh ** which is in database iDb. Return the register number for the register 2039ef5e770Sdrh ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT 2049ef5e770Sdrh ** table. (Also return zero when doing a VACUUM since we do not want to 2059ef5e770Sdrh ** update the AUTOINCREMENT counters during a VACUUM.) 2069d9cf229Sdrh ** 2070b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the 2080b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within 2090b9f50d8Sdrh ** triggers. A new AutoincInfo structure is created if this is the 2100b9f50d8Sdrh ** first use of table pTab. On 2nd and subsequent uses, the original 2110b9f50d8Sdrh ** AutoincInfo structure is used. 2129d9cf229Sdrh ** 213c8abbc11Sdrh ** Four consecutive registers are allocated: 2140b9f50d8Sdrh ** 215c8abbc11Sdrh ** (1) The name of the pTab table. 216c8abbc11Sdrh ** (2) The maximum ROWID of pTab. 217c8abbc11Sdrh ** (3) The rowid in sqlite_sequence of pTab 218c8abbc11Sdrh ** (4) The original value of the max ROWID in pTab, or NULL if none 2190b9f50d8Sdrh ** 2200b9f50d8Sdrh ** The 2nd register is the one that is returned. That is all the 2210b9f50d8Sdrh ** insert routine needs to know about. 2229d9cf229Sdrh */ 2239d9cf229Sdrh static int autoIncBegin( 2249d9cf229Sdrh Parse *pParse, /* Parsing context */ 2259d9cf229Sdrh int iDb, /* Index of the database holding pTab */ 2269d9cf229Sdrh Table *pTab /* The table we are writing to */ 2279d9cf229Sdrh ){ 2286a288a33Sdrh int memId = 0; /* Register holding maximum rowid */ 2299ef5e770Sdrh if( (pTab->tabFlags & TF_Autoincrement)!=0 2308257aa8dSdrh && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0 2319ef5e770Sdrh ){ 23265a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 2330b9f50d8Sdrh AutoincInfo *pInfo; 2340b9f50d8Sdrh 23565a7cd16Sdan pInfo = pToplevel->pAinc; 2360b9f50d8Sdrh while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } 2370b9f50d8Sdrh if( pInfo==0 ){ 238575fad65Sdrh pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo)); 2390b9f50d8Sdrh if( pInfo==0 ) return 0; 24065a7cd16Sdan pInfo->pNext = pToplevel->pAinc; 24165a7cd16Sdan pToplevel->pAinc = pInfo; 2420b9f50d8Sdrh pInfo->pTab = pTab; 2430b9f50d8Sdrh pInfo->iDb = iDb; 24465a7cd16Sdan pToplevel->nMem++; /* Register to hold name of table */ 24565a7cd16Sdan pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ 246c8abbc11Sdrh pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */ 2470b9f50d8Sdrh } 2480b9f50d8Sdrh memId = pInfo->regCtr; 2499d9cf229Sdrh } 2509d9cf229Sdrh return memId; 2519d9cf229Sdrh } 2529d9cf229Sdrh 2539d9cf229Sdrh /* 2540b9f50d8Sdrh ** This routine generates code that will initialize all of the 2550b9f50d8Sdrh ** register used by the autoincrement tracker. 2560b9f50d8Sdrh */ 2570b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){ 2580b9f50d8Sdrh AutoincInfo *p; /* Information about an AUTOINCREMENT */ 2590b9f50d8Sdrh sqlite3 *db = pParse->db; /* The database connection */ 2600b9f50d8Sdrh Db *pDb; /* Database only autoinc table */ 2610b9f50d8Sdrh int memId; /* Register holding max rowid */ 2620b9f50d8Sdrh Vdbe *v = pParse->pVdbe; /* VDBE under construction */ 2630b9f50d8Sdrh 264345ba7dbSdrh /* This routine is never called during trigger-generation. It is 265345ba7dbSdrh ** only called from the top-level */ 266345ba7dbSdrh assert( pParse->pTriggerTab==0 ); 267c149f18fSdrh assert( sqlite3IsToplevel(pParse) ); 26876d462eeSdan 2690b9f50d8Sdrh assert( v ); /* We failed long ago if this is not so */ 2700b9f50d8Sdrh for(p = pParse->pAinc; p; p = p->pNext){ 2711b32554bSdrh static const int iLn = VDBE_OFFSET_LINENO(2); 2721b32554bSdrh static const VdbeOpList autoInc[] = { 2731b32554bSdrh /* 0 */ {OP_Null, 0, 0, 0}, 274c8abbc11Sdrh /* 1 */ {OP_Rewind, 0, 10, 0}, 2751b32554bSdrh /* 2 */ {OP_Column, 0, 0, 0}, 276c8abbc11Sdrh /* 3 */ {OP_Ne, 0, 9, 0}, 2771b32554bSdrh /* 4 */ {OP_Rowid, 0, 0, 0}, 2781b32554bSdrh /* 5 */ {OP_Column, 0, 1, 0}, 279c8abbc11Sdrh /* 6 */ {OP_AddImm, 0, 0, 0}, 280c8abbc11Sdrh /* 7 */ {OP_Copy, 0, 0, 0}, 281c8abbc11Sdrh /* 8 */ {OP_Goto, 0, 11, 0}, 282c8abbc11Sdrh /* 9 */ {OP_Next, 0, 2, 0}, 283c8abbc11Sdrh /* 10 */ {OP_Integer, 0, 0, 0}, 284c8abbc11Sdrh /* 11 */ {OP_Close, 0, 0, 0} 2851b32554bSdrh }; 2861b32554bSdrh VdbeOp *aOp; 2870b9f50d8Sdrh pDb = &db->aDb[p->iDb]; 2880b9f50d8Sdrh memId = p->regCtr; 2892120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 2900b9f50d8Sdrh sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); 291076e85f5Sdrh sqlite3VdbeLoadString(v, memId-1, p->pTab->zName); 2921b32554bSdrh aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn); 2931b32554bSdrh if( aOp==0 ) break; 2941b32554bSdrh aOp[0].p2 = memId; 295c8abbc11Sdrh aOp[0].p3 = memId+2; 2961b32554bSdrh aOp[2].p3 = memId; 2971b32554bSdrh aOp[3].p1 = memId-1; 2981b32554bSdrh aOp[3].p3 = memId; 2991b32554bSdrh aOp[3].p5 = SQLITE_JUMPIFNULL; 3001b32554bSdrh aOp[4].p2 = memId+1; 3011b32554bSdrh aOp[5].p3 = memId; 302c8abbc11Sdrh aOp[6].p1 = memId; 303c8abbc11Sdrh aOp[7].p2 = memId+2; 304c8abbc11Sdrh aOp[7].p1 = memId; 305c8abbc11Sdrh aOp[10].p2 = memId; 3060b9f50d8Sdrh } 3070b9f50d8Sdrh } 3080b9f50d8Sdrh 3090b9f50d8Sdrh /* 3109d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation. 3119d9cf229Sdrh ** 3121b32554bSdrh ** This routine should be called when the regRowid register holds a 3139d9cf229Sdrh ** new rowid that is about to be inserted. If that new rowid is 3149d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the 3151b32554bSdrh ** memory cell is updated. 3169d9cf229Sdrh */ 3176a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){ 3189d9cf229Sdrh if( memId>0 ){ 3196a288a33Sdrh sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); 3209d9cf229Sdrh } 3219d9cf229Sdrh } 3229d9cf229Sdrh 3239d9cf229Sdrh /* 3240b9f50d8Sdrh ** This routine generates the code needed to write autoincrement 3250b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register. 3260b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement 3270b9f50d8Sdrh ** table (either directly or through triggers) needs to call this 3280b9f50d8Sdrh ** routine just before the "exit" code. 3299d9cf229Sdrh */ 3301b32554bSdrh static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ 3310b9f50d8Sdrh AutoincInfo *p; 3329d9cf229Sdrh Vdbe *v = pParse->pVdbe; 3330b9f50d8Sdrh sqlite3 *db = pParse->db; 3346a288a33Sdrh 3359d9cf229Sdrh assert( v ); 3360b9f50d8Sdrh for(p = pParse->pAinc; p; p = p->pNext){ 3371b32554bSdrh static const int iLn = VDBE_OFFSET_LINENO(2); 3381b32554bSdrh static const VdbeOpList autoIncEnd[] = { 3391b32554bSdrh /* 0 */ {OP_NotNull, 0, 2, 0}, 3401b32554bSdrh /* 1 */ {OP_NewRowid, 0, 0, 0}, 3411b32554bSdrh /* 2 */ {OP_MakeRecord, 0, 2, 0}, 3421b32554bSdrh /* 3 */ {OP_Insert, 0, 0, 0}, 3431b32554bSdrh /* 4 */ {OP_Close, 0, 0, 0} 3441b32554bSdrh }; 3451b32554bSdrh VdbeOp *aOp; 3460b9f50d8Sdrh Db *pDb = &db->aDb[p->iDb]; 3470b9f50d8Sdrh int iRec; 3480b9f50d8Sdrh int memId = p->regCtr; 3490b9f50d8Sdrh 3500b9f50d8Sdrh iRec = sqlite3GetTempReg(pParse); 3512120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 352c8abbc11Sdrh sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId); 353c8abbc11Sdrh VdbeCoverage(v); 3540b9f50d8Sdrh sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); 3551b32554bSdrh aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn); 3561b32554bSdrh if( aOp==0 ) break; 3571b32554bSdrh aOp[0].p1 = memId+1; 3581b32554bSdrh aOp[1].p2 = memId+1; 3591b32554bSdrh aOp[2].p1 = memId-1; 3601b32554bSdrh aOp[2].p3 = iRec; 3611b32554bSdrh aOp[3].p2 = iRec; 3621b32554bSdrh aOp[3].p3 = memId+1; 3631b32554bSdrh aOp[3].p5 = OPFLAG_APPEND; 3640b9f50d8Sdrh sqlite3ReleaseTempReg(pParse, iRec); 3659d9cf229Sdrh } 3669d9cf229Sdrh } 3671b32554bSdrh void sqlite3AutoincrementEnd(Parse *pParse){ 3681b32554bSdrh if( pParse->pAinc ) autoIncrementEnd(pParse); 3691b32554bSdrh } 3709d9cf229Sdrh #else 3719d9cf229Sdrh /* 3729d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines 3739d9cf229Sdrh ** above are all no-ops 3749d9cf229Sdrh */ 3759d9cf229Sdrh # define autoIncBegin(A,B,C) (0) 376287fb61cSdanielk1977 # define autoIncStep(A,B,C) 3779d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */ 3789d9cf229Sdrh 3799d9cf229Sdrh 3809d9cf229Sdrh /* Forward declaration */ 3819d9cf229Sdrh static int xferOptimization( 3829d9cf229Sdrh Parse *pParse, /* Parser context */ 3839d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 3849d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 3859d9cf229Sdrh int onError, /* How to handle constraint errors */ 3869d9cf229Sdrh int iDbDest /* The database of pDest */ 3879d9cf229Sdrh ); 3889d9cf229Sdrh 3893d1bfeaaSdanielk1977 /* 390d82b5021Sdrh ** This routine is called to handle SQL of the following forms: 391cce7d176Sdrh ** 392a21f78b9Sdrh ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),... 3931ccde15dSdrh ** insert into TABLE (IDLIST) select 394a21f78b9Sdrh ** insert into TABLE (IDLIST) default values 395cce7d176Sdrh ** 3961ccde15dSdrh ** The IDLIST following the table name is always optional. If omitted, 397a21f78b9Sdrh ** then a list of all (non-hidden) columns for the table is substituted. 398a21f78b9Sdrh ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST 399a21f78b9Sdrh ** is omitted. 4001ccde15dSdrh ** 401a21f78b9Sdrh ** For the pSelect parameter holds the values to be inserted for the 402a21f78b9Sdrh ** first two forms shown above. A VALUES clause is really just short-hand 403a21f78b9Sdrh ** for a SELECT statement that omits the FROM clause and everything else 404a21f78b9Sdrh ** that follows. If the pSelect parameter is NULL, that means that the 405a21f78b9Sdrh ** DEFAULT VALUES form of the INSERT statement is intended. 406142e30dfSdrh ** 4079d9cf229Sdrh ** The code generated follows one of four templates. For a simple 408a21f78b9Sdrh ** insert with data coming from a single-row VALUES clause, the code executes 409e00ee6ebSdrh ** once straight down through. Pseudo-code follows (we call this 410e00ee6ebSdrh ** the "1st template"): 411142e30dfSdrh ** 412142e30dfSdrh ** open write cursor to <table> and its indices 413ec95c441Sdrh ** put VALUES clause expressions into registers 414142e30dfSdrh ** write the resulting record into <table> 415142e30dfSdrh ** cleanup 416142e30dfSdrh ** 4179d9cf229Sdrh ** The three remaining templates assume the statement is of the form 418142e30dfSdrh ** 419142e30dfSdrh ** INSERT INTO <table> SELECT ... 420142e30dfSdrh ** 4219d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - 4229d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table 4239d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and 4249d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical 4259d9cf229Sdrh ** schemas, including all the same indices, then a special optimization 4269d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>. 4279d9cf229Sdrh ** See the xferOptimization() function for the implementation of this 428e00ee6ebSdrh ** template. This is the 2nd template. 4299d9cf229Sdrh ** 4309d9cf229Sdrh ** open a write cursor to <table> 4319d9cf229Sdrh ** open read cursor on <table2> 4329d9cf229Sdrh ** transfer all records in <table2> over to <table> 4339d9cf229Sdrh ** close cursors 4349d9cf229Sdrh ** foreach index on <table> 4359d9cf229Sdrh ** open a write cursor on the <table> index 4369d9cf229Sdrh ** open a read cursor on the corresponding <table2> index 4379d9cf229Sdrh ** transfer all records from the read to the write cursors 4389d9cf229Sdrh ** close cursors 4399d9cf229Sdrh ** end foreach 4409d9cf229Sdrh ** 441e00ee6ebSdrh ** The 3rd template is for when the second template does not apply 4429d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time. 4439d9cf229Sdrh ** The generated code follows this template: 444142e30dfSdrh ** 445e00ee6ebSdrh ** X <- A 446142e30dfSdrh ** goto B 447142e30dfSdrh ** A: setup for the SELECT 4489d9cf229Sdrh ** loop over the rows in the SELECT 449e00ee6ebSdrh ** load values into registers R..R+n 450e00ee6ebSdrh ** yield X 451142e30dfSdrh ** end loop 452142e30dfSdrh ** cleanup after the SELECT 45381cf13ecSdrh ** end-coroutine X 454e00ee6ebSdrh ** B: open write cursor to <table> and its indices 45581cf13ecSdrh ** C: yield X, at EOF goto D 456e00ee6ebSdrh ** insert the select result into <table> from R..R+n 457e00ee6ebSdrh ** goto C 458142e30dfSdrh ** D: cleanup 459142e30dfSdrh ** 460e00ee6ebSdrh ** The 4th template is used if the insert statement takes its 461142e30dfSdrh ** values from a SELECT but the data is being inserted into a table 462142e30dfSdrh ** that is also read as part of the SELECT. In the third form, 46360ec914cSpeter.d.reid ** we have to use an intermediate table to store the results of 464142e30dfSdrh ** the select. The template is like this: 465142e30dfSdrh ** 466e00ee6ebSdrh ** X <- A 467142e30dfSdrh ** goto B 468142e30dfSdrh ** A: setup for the SELECT 469142e30dfSdrh ** loop over the tables in the SELECT 470e00ee6ebSdrh ** load value into register R..R+n 471e00ee6ebSdrh ** yield X 472142e30dfSdrh ** end loop 473142e30dfSdrh ** cleanup after the SELECT 47481cf13ecSdrh ** end co-routine R 475e00ee6ebSdrh ** B: open temp table 47681cf13ecSdrh ** L: yield X, at EOF goto M 477e00ee6ebSdrh ** insert row from R..R+n into temp table 478e00ee6ebSdrh ** goto L 479e00ee6ebSdrh ** M: open write cursor to <table> and its indices 480e00ee6ebSdrh ** rewind temp table 481e00ee6ebSdrh ** C: loop over rows of intermediate table 482142e30dfSdrh ** transfer values form intermediate table into <table> 483e00ee6ebSdrh ** end loop 484e00ee6ebSdrh ** D: cleanup 485cce7d176Sdrh */ 4864adee20fSdanielk1977 void sqlite3Insert( 487cce7d176Sdrh Parse *pParse, /* Parser context */ 488113088ecSdrh SrcList *pTabList, /* Name of table into which we are inserting */ 4895974a30fSdrh Select *pSelect, /* A SELECT statement to use as the data source */ 4909cfcf5d4Sdrh IdList *pColumn, /* Column names corresponding to IDLIST. */ 491*2c2e844aSdrh int onError, /* How to handle constraint errors */ 492*2c2e844aSdrh ExprList *pUpsert /* Upsert values */ 493cce7d176Sdrh ){ 4946a288a33Sdrh sqlite3 *db; /* The main database structure */ 4956a288a33Sdrh Table *pTab; /* The table to insert into. aka TABLE */ 49660ffc807Sdrh int i, j; /* Loop counters */ 4975974a30fSdrh Vdbe *v; /* Generate code into this virtual machine */ 4985974a30fSdrh Index *pIdx; /* For looping over indices of the table */ 499967e8b73Sdrh int nColumn; /* Number of columns in the data */ 5006a288a33Sdrh int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ 50126198bb4Sdrh int iDataCur = 0; /* VDBE cursor that is the main data repository */ 50226198bb4Sdrh int iIdxCur = 0; /* First index cursor */ 503d82b5021Sdrh int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ 5040ca3e24bSdrh int endOfLoop; /* Label for the end of the insertion loop */ 505cfe9a69fSdanielk1977 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ 506e00ee6ebSdrh int addrInsTop = 0; /* Jump to label "D" */ 507e00ee6ebSdrh int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ 5082eb95377Sdrh SelectDest dest; /* Destination for SELECT on rhs of INSERT */ 5096a288a33Sdrh int iDb; /* Index of database holding TABLE */ 51005a86c5cSdrh u8 useTempTable = 0; /* Store SELECT results in intermediate table */ 51105a86c5cSdrh u8 appendFlag = 0; /* True if the insert is likely to be an append */ 51205a86c5cSdrh u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ 513a21f78b9Sdrh u8 bIdListInOrder; /* True if IDLIST is in table order */ 51475593d96Sdrh ExprList *pList = 0; /* List of VALUES() to be inserted */ 515cce7d176Sdrh 5166a288a33Sdrh /* Register allocations */ 5171bd10f8aSdrh int regFromSelect = 0;/* Base register for data coming from SELECT */ 5186a288a33Sdrh int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ 5196a288a33Sdrh int regRowCount = 0; /* Memory cell used for the row counter */ 5206a288a33Sdrh int regIns; /* Block of regs holding rowid+data being inserted */ 5216a288a33Sdrh int regRowid; /* registers holding insert rowid */ 5226a288a33Sdrh int regData; /* register holding first column to insert */ 523aa9b8963Sdrh int *aRegIdx = 0; /* One register allocated to each index */ 5246a288a33Sdrh 525798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER 526798da52cSdrh int isView; /* True if attempting to insert into a view */ 5272f886d1dSdanielk1977 Trigger *pTrigger; /* List of triggers on pTab, if required */ 5282f886d1dSdanielk1977 int tmask; /* Mask of trigger times */ 529798da52cSdrh #endif 530c3f9bad2Sdanielk1977 531*2c2e844aSdrh /* The conflict resolution type is always OE_Update or OE_Replace when 532*2c2e844aSdrh ** there is an upsert clause */ 533*2c2e844aSdrh assert( onError==OE_Update || pUpsert==0 ); 534*2c2e844aSdrh assert( OE_Update==OE_Replace ); 535*2c2e844aSdrh 53617435752Sdrh db = pParse->db; 53717435752Sdrh if( pParse->nErr || db->mallocFailed ){ 5386f7adc8aSdrh goto insert_cleanup; 5396f7adc8aSdrh } 5404c883487Sdrh dest.iSDParm = 0; /* Suppress a harmless compiler warning */ 541daffd0e5Sdrh 54275593d96Sdrh /* If the Select object is really just a simple VALUES() list with a 543a21f78b9Sdrh ** single row (the common case) then keep that one row of values 544a21f78b9Sdrh ** and discard the other (unused) parts of the pSelect object 54575593d96Sdrh */ 54675593d96Sdrh if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){ 54775593d96Sdrh pList = pSelect->pEList; 54875593d96Sdrh pSelect->pEList = 0; 54975593d96Sdrh sqlite3SelectDelete(db, pSelect); 55075593d96Sdrh pSelect = 0; 55175593d96Sdrh } 55275593d96Sdrh 5531ccde15dSdrh /* Locate the table into which we will be inserting new information. 5541ccde15dSdrh */ 555113088ecSdrh assert( pTabList->nSrc==1 ); 5564adee20fSdanielk1977 pTab = sqlite3SrcListLookup(pParse, pTabList); 557c3f9bad2Sdanielk1977 if( pTab==0 ){ 558c3f9bad2Sdanielk1977 goto insert_cleanup; 559c3f9bad2Sdanielk1977 } 560da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 561da184236Sdanielk1977 assert( iDb<db->nDb ); 562a0daa751Sdrh if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, 563a0daa751Sdrh db->aDb[iDb].zDbSName) ){ 5641962bda7Sdrh goto insert_cleanup; 5651962bda7Sdrh } 566ec95c441Sdrh withoutRowid = !HasRowid(pTab); 567c3f9bad2Sdanielk1977 568b7f9164eSdrh /* Figure out if we have any triggers and if the table being 569b7f9164eSdrh ** inserted into is a view 570b7f9164eSdrh */ 571b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER 5722f886d1dSdanielk1977 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); 573b7f9164eSdrh isView = pTab->pSelect!=0; 574b7f9164eSdrh #else 5752f886d1dSdanielk1977 # define pTrigger 0 5762f886d1dSdanielk1977 # define tmask 0 577b7f9164eSdrh # define isView 0 578b7f9164eSdrh #endif 579b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW 580b7f9164eSdrh # undef isView 581b7f9164eSdrh # define isView 0 582b7f9164eSdrh #endif 5832f886d1dSdanielk1977 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); 584b7f9164eSdrh 585f573c99bSdrh /* If pTab is really a view, make sure it has been initialized. 586d82b5021Sdrh ** ViewGetColumnNames() is a no-op if pTab is not a view. 587f573c99bSdrh */ 588b3d24bf8Sdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 589f573c99bSdrh goto insert_cleanup; 590f573c99bSdrh } 591f573c99bSdrh 592d82b5021Sdrh /* Cannot insert into a read-only table. 593595a523aSdanielk1977 */ 594595a523aSdanielk1977 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ 595595a523aSdanielk1977 goto insert_cleanup; 596595a523aSdanielk1977 } 597595a523aSdanielk1977 5981ccde15dSdrh /* Allocate a VDBE 5991ccde15dSdrh */ 6004adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 6015974a30fSdrh if( v==0 ) goto insert_cleanup; 6024794f735Sdrh if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 6032f886d1dSdanielk1977 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); 6041ccde15dSdrh 6059d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 6069d9cf229Sdrh /* If the statement is of the form 6079d9cf229Sdrh ** 6089d9cf229Sdrh ** INSERT INTO <table1> SELECT * FROM <table2>; 6099d9cf229Sdrh ** 6109d9cf229Sdrh ** Then special optimizations can be applied that make the transfer 6119d9cf229Sdrh ** very fast and which reduce fragmentation of indices. 612e00ee6ebSdrh ** 613e00ee6ebSdrh ** This is the 2nd template. 6149d9cf229Sdrh */ 6159d9cf229Sdrh if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ 6162f886d1dSdanielk1977 assert( !pTrigger ); 6179d9cf229Sdrh assert( pList==0 ); 6180b9f50d8Sdrh goto insert_end; 6199d9cf229Sdrh } 6209d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 6219d9cf229Sdrh 6222958a4e6Sdrh /* If this is an AUTOINCREMENT table, look up the sequence number in the 6236a288a33Sdrh ** sqlite_sequence table and store it in memory cell regAutoinc. 6242958a4e6Sdrh */ 6256a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDb, pTab); 6262958a4e6Sdrh 62705a86c5cSdrh /* Allocate registers for holding the rowid of the new row, 62860ec914cSpeter.d.reid ** the content of the new row, and the assembled row record. 6291ccde15dSdrh */ 63005a86c5cSdrh regRowid = regIns = pParse->nMem+1; 63105a86c5cSdrh pParse->nMem += pTab->nCol + 1; 632034ca14fSdanielk1977 if( IsVirtual(pTab) ){ 63305a86c5cSdrh regRowid++; 63405a86c5cSdrh pParse->nMem++; 635034ca14fSdanielk1977 } 63605a86c5cSdrh regData = regRowid+1; 6371ccde15dSdrh 6381ccde15dSdrh /* If the INSERT statement included an IDLIST term, then make sure 6391ccde15dSdrh ** all elements of the IDLIST really are columns of the table and 6401ccde15dSdrh ** remember the column indices. 641c8392586Sdrh ** 642c8392586Sdrh ** If the table has an INTEGER PRIMARY KEY column and that column 643d82b5021Sdrh ** is named in the IDLIST, then record in the ipkColumn variable 644d82b5021Sdrh ** the index into IDLIST of the primary key column. ipkColumn is 645c8392586Sdrh ** the index of the primary key as it appears in IDLIST, not as 646d82b5021Sdrh ** is appears in the original table. (The index of the INTEGER 647d82b5021Sdrh ** PRIMARY KEY in the original table is pTab->iPKey.) 6481ccde15dSdrh */ 649a21f78b9Sdrh bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0; 650967e8b73Sdrh if( pColumn ){ 651967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 652967e8b73Sdrh pColumn->a[i].idx = -1; 653cce7d176Sdrh } 654967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 655cce7d176Sdrh for(j=0; j<pTab->nCol; j++){ 6564adee20fSdanielk1977 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ 657967e8b73Sdrh pColumn->a[i].idx = j; 65805a86c5cSdrh if( i!=j ) bIdListInOrder = 0; 6594a32431cSdrh if( j==pTab->iPKey ){ 660d82b5021Sdrh ipkColumn = i; assert( !withoutRowid ); 6614a32431cSdrh } 662cce7d176Sdrh break; 663cce7d176Sdrh } 664cce7d176Sdrh } 665cce7d176Sdrh if( j>=pTab->nCol ){ 666ec95c441Sdrh if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ 667d82b5021Sdrh ipkColumn = i; 668e48ae715Sdrh bIdListInOrder = 0; 669a0217ba7Sdrh }else{ 6704adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %S has no column named %s", 671da93d238Sdrh pTabList, 0, pColumn->a[i].zName); 6721db95106Sdan pParse->checkSchema = 1; 673cce7d176Sdrh goto insert_cleanup; 674cce7d176Sdrh } 675cce7d176Sdrh } 676cce7d176Sdrh } 677a0217ba7Sdrh } 6781ccde15dSdrh 679cce7d176Sdrh /* Figure out how many columns of data are supplied. If the data 680cce7d176Sdrh ** is coming from a SELECT statement, then generate a co-routine that 681cce7d176Sdrh ** produces a single row of the SELECT on each invocation. The 682cce7d176Sdrh ** co-routine is the common header to the 3rd and 4th templates. 683cce7d176Sdrh */ 6845f085269Sdrh if( pSelect ){ 685a21f78b9Sdrh /* Data is coming from a SELECT or from a multi-row VALUES clause. 686a21f78b9Sdrh ** Generate a co-routine to run the SELECT. */ 68705a86c5cSdrh int regYield; /* Register holding co-routine entry-point */ 68805a86c5cSdrh int addrTop; /* Top of the co-routine */ 68905a86c5cSdrh int rc; /* Result code */ 690cce7d176Sdrh 69105a86c5cSdrh regYield = ++pParse->nMem; 69205a86c5cSdrh addrTop = sqlite3VdbeCurrentAddr(v) + 1; 69305a86c5cSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 69405a86c5cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 69505a86c5cSdrh dest.iSdst = bIdListInOrder ? regData : 0; 69605a86c5cSdrh dest.nSdst = pTab->nCol; 69705a86c5cSdrh rc = sqlite3Select(pParse, pSelect, &dest); 6982b596da8Sdrh regFromSelect = dest.iSdst; 699992590beSdrh if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup; 7002fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regYield); 70105a86c5cSdrh sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ 702cce7d176Sdrh assert( pSelect->pEList ); 703cce7d176Sdrh nColumn = pSelect->pEList->nExpr; 704cce7d176Sdrh 705cce7d176Sdrh /* Set useTempTable to TRUE if the result of the SELECT statement 706cce7d176Sdrh ** should be written into a temporary table (template 4). Set to 707cce7d176Sdrh ** FALSE if each output row of the SELECT can be written directly into 708cce7d176Sdrh ** the destination table (template 3). 709cce7d176Sdrh ** 710cce7d176Sdrh ** A temp table must be used if the table being updated is also one 711cce7d176Sdrh ** of the tables being read by the SELECT statement. Also use a 712cce7d176Sdrh ** temp table in the case of row triggers. 713cce7d176Sdrh */ 71405a86c5cSdrh if( pTrigger || readsTable(pParse, iDb, pTab) ){ 715cce7d176Sdrh useTempTable = 1; 716cce7d176Sdrh } 717cce7d176Sdrh 718cce7d176Sdrh if( useTempTable ){ 719cce7d176Sdrh /* Invoke the coroutine to extract information from the SELECT 720cce7d176Sdrh ** and add it to a transient table srcTab. The code generated 721cce7d176Sdrh ** here is from the 4th template: 722cce7d176Sdrh ** 723cce7d176Sdrh ** B: open temp table 72481cf13ecSdrh ** L: yield X, goto M at EOF 725cce7d176Sdrh ** insert row from R..R+n into temp table 726cce7d176Sdrh ** goto L 727cce7d176Sdrh ** M: ... 728cce7d176Sdrh */ 729cce7d176Sdrh int regRec; /* Register to hold packed record */ 730cce7d176Sdrh int regTempRowid; /* Register to hold temp table ROWID */ 73106280ee5Sdrh int addrL; /* Label "L" */ 732cce7d176Sdrh 733cce7d176Sdrh srcTab = pParse->nTab++; 734cce7d176Sdrh regRec = sqlite3GetTempReg(pParse); 735cce7d176Sdrh regTempRowid = sqlite3GetTempReg(pParse); 736cce7d176Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); 73706280ee5Sdrh addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); 738cce7d176Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); 739cce7d176Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); 740cce7d176Sdrh sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); 741076e85f5Sdrh sqlite3VdbeGoto(v, addrL); 74206280ee5Sdrh sqlite3VdbeJumpHere(v, addrL); 743cce7d176Sdrh sqlite3ReleaseTempReg(pParse, regRec); 744cce7d176Sdrh sqlite3ReleaseTempReg(pParse, regTempRowid); 745cce7d176Sdrh } 746cce7d176Sdrh }else{ 747a21f78b9Sdrh /* This is the case if the data for the INSERT is coming from a 748a21f78b9Sdrh ** single-row VALUES clause 749cce7d176Sdrh */ 750cce7d176Sdrh NameContext sNC; 751cce7d176Sdrh memset(&sNC, 0, sizeof(sNC)); 752cce7d176Sdrh sNC.pParse = pParse; 753cce7d176Sdrh srcTab = -1; 754cce7d176Sdrh assert( useTempTable==0 ); 755fea870beSdrh if( pList ){ 756fea870beSdrh nColumn = pList->nExpr; 757fea870beSdrh if( sqlite3ResolveExprListNames(&sNC, pList) ){ 758cce7d176Sdrh goto insert_cleanup; 759cce7d176Sdrh } 760fea870beSdrh }else{ 761fea870beSdrh nColumn = 0; 762cce7d176Sdrh } 763cce7d176Sdrh } 764cce7d176Sdrh 765aacc543eSdrh /* If there is no IDLIST term but the table has an integer primary 766d82b5021Sdrh ** key, the set the ipkColumn variable to the integer primary key 767d82b5021Sdrh ** column index in the original table definition. 7684a32431cSdrh */ 769147d0cccSdrh if( pColumn==0 && nColumn>0 ){ 770d82b5021Sdrh ipkColumn = pTab->iPKey; 7714a32431cSdrh } 7724a32431cSdrh 773cce7d176Sdrh /* Make sure the number of columns in the source data matches the number 774cce7d176Sdrh ** of columns to be inserted into the table. 775cce7d176Sdrh */ 776cce7d176Sdrh for(i=0; i<pTab->nCol; i++){ 777cce7d176Sdrh nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); 778cce7d176Sdrh } 779cce7d176Sdrh if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ 780cce7d176Sdrh sqlite3ErrorMsg(pParse, 781cce7d176Sdrh "table %S has %d columns but %d values were supplied", 782cce7d176Sdrh pTabList, 0, pTab->nCol-nHidden, nColumn); 783cce7d176Sdrh goto insert_cleanup; 784cce7d176Sdrh } 785cce7d176Sdrh if( pColumn!=0 && nColumn!=pColumn->nId ){ 786cce7d176Sdrh sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 787cce7d176Sdrh goto insert_cleanup; 788cce7d176Sdrh } 789cce7d176Sdrh 790c3f9bad2Sdanielk1977 /* Initialize the count of rows to be inserted 7911ccde15dSdrh */ 792142e30dfSdrh if( db->flags & SQLITE_CountRows ){ 7936a288a33Sdrh regRowCount = ++pParse->nMem; 7946a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 795c3f9bad2Sdanielk1977 } 796c3f9bad2Sdanielk1977 797e448dc4aSdanielk1977 /* If this is not a view, open the table and and all indices */ 798e448dc4aSdanielk1977 if( !isView ){ 799aa9b8963Sdrh int nIdx; 800fd261ec6Sdan nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0, 80126198bb4Sdrh &iDataCur, &iIdxCur); 802575fad65Sdrh aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1)); 803aa9b8963Sdrh if( aRegIdx==0 ){ 804aa9b8963Sdrh goto insert_cleanup; 805aa9b8963Sdrh } 8062c4dfc30Sdrh for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){ 8072c4dfc30Sdrh assert( pIdx ); 808aa9b8963Sdrh aRegIdx[i] = ++pParse->nMem; 8092c4dfc30Sdrh pParse->nMem += pIdx->nColumn; 810aa9b8963Sdrh } 811feeb1394Sdrh } 812feeb1394Sdrh 813e00ee6ebSdrh /* This is the top of the main insertion loop */ 814142e30dfSdrh if( useTempTable ){ 815e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 816e00ee6ebSdrh ** following pseudocode (template 4): 817e00ee6ebSdrh ** 81881cf13ecSdrh ** rewind temp table, if empty goto D 819e00ee6ebSdrh ** C: loop over rows of intermediate table 820e00ee6ebSdrh ** transfer values form intermediate table into <table> 821e00ee6ebSdrh ** end loop 822e00ee6ebSdrh ** D: ... 823e00ee6ebSdrh */ 824688852abSdrh addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); 825e00ee6ebSdrh addrCont = sqlite3VdbeCurrentAddr(v); 826142e30dfSdrh }else if( pSelect ){ 827e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 828e00ee6ebSdrh ** following pseudocode (template 3): 829e00ee6ebSdrh ** 83081cf13ecSdrh ** C: yield X, at EOF goto D 831e00ee6ebSdrh ** insert the select result into <table> from R..R+n 832e00ee6ebSdrh ** goto C 833e00ee6ebSdrh ** D: ... 834e00ee6ebSdrh */ 83581cf13ecSdrh addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 836688852abSdrh VdbeCoverage(v); 837bed8690fSdrh } 8381ccde15dSdrh 8395cf590c1Sdrh /* Run the BEFORE and INSTEAD OF triggers, if there are any 84070ce3f0cSdrh */ 8414adee20fSdanielk1977 endOfLoop = sqlite3VdbeMakeLabel(v); 8422f886d1dSdanielk1977 if( tmask & TRIGGER_BEFORE ){ 84376d462eeSdan int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); 844c3f9bad2Sdanielk1977 84570ce3f0cSdrh /* build the NEW.* reference row. Note that if there is an INTEGER 84670ce3f0cSdrh ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 84770ce3f0cSdrh ** translated into a unique ID for the row. But on a BEFORE trigger, 84870ce3f0cSdrh ** we do not know what the unique ID will be (because the insert has 84970ce3f0cSdrh ** not happened yet) so we substitute a rowid of -1 85070ce3f0cSdrh */ 851d82b5021Sdrh if( ipkColumn<0 ){ 85276d462eeSdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 85370ce3f0cSdrh }else{ 854728e0f91Sdrh int addr1; 855ec95c441Sdrh assert( !withoutRowid ); 8567fe45908Sdrh if( useTempTable ){ 857d82b5021Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); 8587fe45908Sdrh }else{ 859d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 860d82b5021Sdrh sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); 8617fe45908Sdrh } 862728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); 86376d462eeSdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 864728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 865688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); 86670ce3f0cSdrh } 86770ce3f0cSdrh 868034ca14fSdanielk1977 /* Cannot have triggers on a virtual table. If it were possible, 869034ca14fSdanielk1977 ** this block would have to account for hidden column. 870034ca14fSdanielk1977 */ 871034ca14fSdanielk1977 assert( !IsVirtual(pTab) ); 872034ca14fSdanielk1977 87370ce3f0cSdrh /* Create the new column data 87470ce3f0cSdrh */ 875b1daa3f4Sdrh for(i=j=0; i<pTab->nCol; i++){ 876b1daa3f4Sdrh if( pColumn ){ 877c3f9bad2Sdanielk1977 for(j=0; j<pColumn->nId; j++){ 878c3f9bad2Sdanielk1977 if( pColumn->a[j].idx==i ) break; 879c3f9bad2Sdanielk1977 } 880c3f9bad2Sdanielk1977 } 881b1daa3f4Sdrh if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) 88203d69a68Sdrh || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){ 88376d462eeSdan sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1); 884142e30dfSdrh }else if( useTempTable ){ 88576d462eeSdan sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 886c3f9bad2Sdanielk1977 }else{ 887d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 88876d462eeSdan sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); 889c3f9bad2Sdanielk1977 } 89003d69a68Sdrh if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++; 891c3f9bad2Sdanielk1977 } 892a37cdde0Sdanielk1977 893a37cdde0Sdanielk1977 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 894a37cdde0Sdanielk1977 ** do not attempt any conversions before assembling the record. 895a37cdde0Sdanielk1977 ** If this is a real table, attempt conversions as required by the 896a37cdde0Sdanielk1977 ** table column affinities. 897a37cdde0Sdanielk1977 */ 898a37cdde0Sdanielk1977 if( !isView ){ 89957bf4a8eSdrh sqlite3TableAffinity(v, pTab, regCols+1); 900a37cdde0Sdanielk1977 } 901c3f9bad2Sdanielk1977 9025cf590c1Sdrh /* Fire BEFORE or INSTEAD OF triggers */ 903165921a7Sdan sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 90494d7f50aSdan pTab, regCols-pTab->nCol-1, onError, endOfLoop); 905165921a7Sdan 90676d462eeSdan sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); 90770ce3f0cSdrh } 908c3f9bad2Sdanielk1977 909d82b5021Sdrh /* Compute the content of the next row to insert into a range of 910d82b5021Sdrh ** registers beginning at regIns. 9111ccde15dSdrh */ 9125cf590c1Sdrh if( !isView ){ 9134cbdda9eSdrh if( IsVirtual(pTab) ){ 9144cbdda9eSdrh /* The row that the VUpdate opcode will delete: none */ 9156a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); 9164cbdda9eSdrh } 917d82b5021Sdrh if( ipkColumn>=0 ){ 918142e30dfSdrh if( useTempTable ){ 919d82b5021Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); 920142e30dfSdrh }else if( pSelect ){ 92105a86c5cSdrh sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); 9224a32431cSdrh }else{ 923e4d90813Sdrh VdbeOp *pOp; 924d82b5021Sdrh sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); 92520411ea7Sdrh pOp = sqlite3VdbeGetOp(v, -1); 9269d9c41e2Sdrh assert( pOp!=0 ); 9279d9c41e2Sdrh if( pOp->opcode==OP_Null && !IsVirtual(pTab) ){ 928e4d90813Sdrh appendFlag = 1; 929e4d90813Sdrh pOp->opcode = OP_NewRowid; 93026198bb4Sdrh pOp->p1 = iDataCur; 9316a288a33Sdrh pOp->p2 = regRowid; 9326a288a33Sdrh pOp->p3 = regAutoinc; 933e4d90813Sdrh } 93427a32783Sdrh } 935f0863fe5Sdrh /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 936e1e68f49Sdrh ** to generate a unique primary key value. 937e1e68f49Sdrh */ 938e4d90813Sdrh if( !appendFlag ){ 939728e0f91Sdrh int addr1; 940bb50e7adSdanielk1977 if( !IsVirtual(pTab) ){ 941728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); 94226198bb4Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 943728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 944bb50e7adSdanielk1977 }else{ 945728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 946728e0f91Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); 947bb50e7adSdanielk1977 } 948688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); 949e4d90813Sdrh } 950ec95c441Sdrh }else if( IsVirtual(pTab) || withoutRowid ){ 9516a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); 9524a32431cSdrh }else{ 95326198bb4Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 954e4d90813Sdrh appendFlag = 1; 9554a32431cSdrh } 9566a288a33Sdrh autoIncStep(pParse, regAutoinc, regRowid); 9574a32431cSdrh 958d82b5021Sdrh /* Compute data for all columns of the new entry, beginning 9594a32431cSdrh ** with the first column. 9604a32431cSdrh */ 961034ca14fSdanielk1977 nHidden = 0; 962cce7d176Sdrh for(i=0; i<pTab->nCol; i++){ 9636a288a33Sdrh int iRegStore = regRowid+1+i; 9644a32431cSdrh if( i==pTab->iPKey ){ 9654a32431cSdrh /* The value of the INTEGER PRIMARY KEY column is always a NULL. 966d82b5021Sdrh ** Whenever this column is read, the rowid will be substituted 967d82b5021Sdrh ** in its place. Hence, fill this column with a NULL to avoid 96805a86c5cSdrh ** taking up data space with information that will never be used. 96905a86c5cSdrh ** As there may be shallow copies of this value, make it a soft-NULL */ 97005a86c5cSdrh sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); 9714a32431cSdrh continue; 9724a32431cSdrh } 973967e8b73Sdrh if( pColumn==0 ){ 974034ca14fSdanielk1977 if( IsHiddenColumn(&pTab->aCol[i]) ){ 975034ca14fSdanielk1977 j = -1; 976034ca14fSdanielk1977 nHidden++; 977034ca14fSdanielk1977 }else{ 978034ca14fSdanielk1977 j = i - nHidden; 979034ca14fSdanielk1977 } 980cce7d176Sdrh }else{ 981967e8b73Sdrh for(j=0; j<pColumn->nId; j++){ 982967e8b73Sdrh if( pColumn->a[j].idx==i ) break; 983cce7d176Sdrh } 984cce7d176Sdrh } 985034ca14fSdanielk1977 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ 98605a86c5cSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 987142e30dfSdrh }else if( useTempTable ){ 988287fb61cSdanielk1977 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 989142e30dfSdrh }else if( pSelect ){ 99005a86c5cSdrh if( regFromSelect!=regData ){ 991b7654111Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); 99205a86c5cSdrh } 993cce7d176Sdrh }else{ 994287fb61cSdanielk1977 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); 995cce7d176Sdrh } 996cce7d176Sdrh } 9971ccde15dSdrh 9980ca3e24bSdrh /* Generate code to check constraints and generate index keys and 9990ca3e24bSdrh ** do the insertion. 10004a32431cSdrh */ 10014cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 10024cbdda9eSdrh if( IsVirtual(pTab) ){ 1003595a523aSdanielk1977 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 10044f3dd150Sdrh sqlite3VtabMakeWritable(pParse, pTab); 1005595a523aSdanielk1977 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); 1006b061d058Sdan sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); 1007e0af83acSdan sqlite3MayAbort(pParse); 10084cbdda9eSdrh }else 10094cbdda9eSdrh #endif 10104cbdda9eSdrh { 1011de630353Sdanielk1977 int isReplace; /* Set to true if constraints may cause a replace */ 10123b908d41Sdan int bUseSeek; /* True to use OPFLAG_SEEKRESULT */ 1013f8ffb278Sdrh sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, 1014bdb00225Sdrh regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0 101504adf416Sdrh ); 10168ff2d956Sdan sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); 10173b908d41Sdan 10183b908d41Sdan /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE 10193b908d41Sdan ** constraints or (b) there are no triggers and this table is not a 10203b908d41Sdan ** parent table in a foreign key constraint. It is safe to set the 10213b908d41Sdan ** flag in the second case as if any REPLACE constraint is hit, an 10223b908d41Sdan ** OP_Delete or OP_IdxDelete instruction will be executed on each 10233b908d41Sdan ** cursor that is disturbed. And these instructions both clear the 10243b908d41Sdan ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT 10253b908d41Sdan ** functionality. */ 10263b908d41Sdan bUseSeek = (isReplace==0 || (pTrigger==0 && 10273b908d41Sdan ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0) 10283b908d41Sdan )); 102926198bb4Sdrh sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, 10303b908d41Sdan regIns, aRegIdx, 0, appendFlag, bUseSeek 10313b908d41Sdan ); 10325cf590c1Sdrh } 10334cbdda9eSdrh } 10341bee3d7bSdrh 1035feeb1394Sdrh /* Update the count of rows that are inserted 10361bee3d7bSdrh */ 1037142e30dfSdrh if( (db->flags & SQLITE_CountRows)!=0 ){ 10386a288a33Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 10391bee3d7bSdrh } 1040c3f9bad2Sdanielk1977 10412f886d1dSdanielk1977 if( pTrigger ){ 1042c3f9bad2Sdanielk1977 /* Code AFTER triggers */ 1043165921a7Sdan sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 104494d7f50aSdan pTab, regData-2-pTab->nCol, onError, endOfLoop); 1045c3f9bad2Sdanielk1977 } 10461bee3d7bSdrh 1047e00ee6ebSdrh /* The bottom of the main insertion loop, if the data source 1048e00ee6ebSdrh ** is a SELECT statement. 10491ccde15dSdrh */ 10504adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, endOfLoop); 1051142e30dfSdrh if( useTempTable ){ 1052688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); 1053e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 10542eb95377Sdrh sqlite3VdbeAddOp1(v, OP_Close, srcTab); 1055142e30dfSdrh }else if( pSelect ){ 1056076e85f5Sdrh sqlite3VdbeGoto(v, addrCont); 1057e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 10586b56344dSdrh } 1059c3f9bad2Sdanielk1977 10600b9f50d8Sdrh insert_end: 1061f3388144Sdrh /* Update the sqlite_sequence table by storing the content of the 10620b9f50d8Sdrh ** maximum rowid counter values recorded while inserting into 10630b9f50d8Sdrh ** autoincrement tables. 10642958a4e6Sdrh */ 1065165921a7Sdan if( pParse->nested==0 && pParse->pTriggerTab==0 ){ 10660b9f50d8Sdrh sqlite3AutoincrementEnd(pParse); 10670b9f50d8Sdrh } 10682958a4e6Sdrh 10691bee3d7bSdrh /* 1070e7de6f25Sdanielk1977 ** Return the number of rows inserted. If this routine is 1071e7de6f25Sdanielk1977 ** generating code because of a call to sqlite3NestedParse(), do not 1072e7de6f25Sdanielk1977 ** invoke the callback function. 10731bee3d7bSdrh */ 1074165921a7Sdan if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ 10756a288a33Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); 107622322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, 1); 107710fb749bSdanielk1977 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); 10781bee3d7bSdrh } 1079cce7d176Sdrh 1080cce7d176Sdrh insert_cleanup: 1081633e6d57Sdrh sqlite3SrcListDelete(db, pTabList); 1082633e6d57Sdrh sqlite3ExprListDelete(db, pList); 1083*2c2e844aSdrh sqlite3ExprListDelete(db, pUpsert); 1084633e6d57Sdrh sqlite3SelectDelete(db, pSelect); 1085633e6d57Sdrh sqlite3IdListDelete(db, pColumn); 1086633e6d57Sdrh sqlite3DbFree(db, aRegIdx); 1087cce7d176Sdrh } 10889cfcf5d4Sdrh 108975cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise 109060ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file 109175cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation). */ 109275cbd984Sdan #ifdef isView 109375cbd984Sdan #undef isView 109475cbd984Sdan #endif 109575cbd984Sdan #ifdef pTrigger 109675cbd984Sdan #undef pTrigger 109775cbd984Sdan #endif 109875cbd984Sdan #ifdef tmask 109975cbd984Sdan #undef tmask 110075cbd984Sdan #endif 110175cbd984Sdan 11029cfcf5d4Sdrh /* 110398bfa16dSdrh ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged() 110498bfa16dSdrh */ 110598bfa16dSdrh #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */ 110698bfa16dSdrh #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */ 110798bfa16dSdrh 11082a0b527bSdrh /* This is the Walker callback from checkConstraintUnchanged(). Set 110998bfa16dSdrh ** bit 0x01 of pWalker->eCode if 11102a0b527bSdrh ** pWalker->eCode to 0 if this expression node references any of the 11112a0b527bSdrh ** columns that are being modifed by an UPDATE statement. 11122a0b527bSdrh */ 11132a0b527bSdrh static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){ 111498bfa16dSdrh if( pExpr->op==TK_COLUMN ){ 111598bfa16dSdrh assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 ); 111698bfa16dSdrh if( pExpr->iColumn>=0 ){ 111798bfa16dSdrh if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){ 111898bfa16dSdrh pWalker->eCode |= CKCNSTRNT_COLUMN; 111998bfa16dSdrh } 112098bfa16dSdrh }else{ 112198bfa16dSdrh pWalker->eCode |= CKCNSTRNT_ROWID; 112298bfa16dSdrh } 11232a0b527bSdrh } 11242a0b527bSdrh return WRC_Continue; 11252a0b527bSdrh } 11262a0b527bSdrh 11272a0b527bSdrh /* 11282a0b527bSdrh ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The 11292a0b527bSdrh ** only columns that are modified by the UPDATE are those for which 113098bfa16dSdrh ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true. 113198bfa16dSdrh ** 113298bfa16dSdrh ** Return true if CHECK constraint pExpr does not use any of the 113398bfa16dSdrh ** changing columns (or the rowid if it is changing). In other words, 113498bfa16dSdrh ** return true if this CHECK constraint can be skipped when validating 113598bfa16dSdrh ** the new row in the UPDATE statement. 11362a0b527bSdrh */ 113798bfa16dSdrh static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){ 11382a0b527bSdrh Walker w; 11392a0b527bSdrh memset(&w, 0, sizeof(w)); 114098bfa16dSdrh w.eCode = 0; 11412a0b527bSdrh w.xExprCallback = checkConstraintExprNode; 11422a0b527bSdrh w.u.aiCol = aiChng; 11432a0b527bSdrh sqlite3WalkExpr(&w, pExpr); 114405723a9eSdrh if( !chngRowid ){ 114505723a9eSdrh testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 ); 114605723a9eSdrh w.eCode &= ~CKCNSTRNT_ROWID; 114705723a9eSdrh } 114805723a9eSdrh testcase( w.eCode==0 ); 114905723a9eSdrh testcase( w.eCode==CKCNSTRNT_COLUMN ); 115005723a9eSdrh testcase( w.eCode==CKCNSTRNT_ROWID ); 115105723a9eSdrh testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) ); 115298bfa16dSdrh return !w.eCode; 11532a0b527bSdrh } 11542a0b527bSdrh 115511e85273Sdrh /* 11566934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE 11576934fc7bSdrh ** on table pTab. 11589cfcf5d4Sdrh ** 11596934fc7bSdrh ** The regNewData parameter is the first register in a range that contains 11606934fc7bSdrh ** the data to be inserted or the data after the update. There will be 11616934fc7bSdrh ** pTab->nCol+1 registers in this range. The first register (the one 11626934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the 11636934fc7bSdrh ** case of a WITHOUT ROWID table. The second register in the range will 11646934fc7bSdrh ** contain the content of the first table column. The third register will 11656934fc7bSdrh ** contain the content of the second table column. And so forth. 11660ca3e24bSdrh ** 1167f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains 1168f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards. regOldData is zero 1169f8ffb278Sdrh ** for an INSERT. This routine can distinguish between UPDATE and INSERT by 1170f8ffb278Sdrh ** checking regOldData for zero. 11710ca3e24bSdrh ** 1172f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the 1173f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) 1174f8ffb278Sdrh ** might be modified by the UPDATE. If pkChng is false, then the key of 1175f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE. 11760ca3e24bSdrh ** 1177f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid 1178f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement. If pkChng 1179f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or 1180f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, 1181f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer 1182f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias. 11830ca3e24bSdrh ** 11846934fc7bSdrh ** The code generated by this routine will store new index entries into 1185aa9b8963Sdrh ** registers identified by aRegIdx[]. No index entry is created for 1186aa9b8963Sdrh ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is 1187aa9b8963Sdrh ** the same as the order of indices on the linked list of indices 11886934fc7bSdrh ** at pTab->pIndex. 11896934fc7bSdrh ** 11906934fc7bSdrh ** The caller must have already opened writeable cursors on the main 11916934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which 11926934fc7bSdrh ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when 11936934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY 11946934fc7bSdrh ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor 11956934fc7bSdrh ** for the first index in the pTab->pIndex list. Cursors for other indices 11966934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list. 11979cfcf5d4Sdrh ** 11989cfcf5d4Sdrh ** This routine also generates code to check constraints. NOT NULL, 11999cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 12001c92853dSdrh ** then the appropriate action is performed. There are five possible 12011c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 12029cfcf5d4Sdrh ** 12039cfcf5d4Sdrh ** Constraint type Action What Happens 12049cfcf5d4Sdrh ** --------------- ---------- ---------------------------------------- 12051c92853dSdrh ** any ROLLBACK The current transaction is rolled back and 12066934fc7bSdrh ** sqlite3_step() returns immediately with a 12079cfcf5d4Sdrh ** return code of SQLITE_CONSTRAINT. 12089cfcf5d4Sdrh ** 12091c92853dSdrh ** any ABORT Back out changes from the current command 12101c92853dSdrh ** only (do not do a complete rollback) then 12116934fc7bSdrh ** cause sqlite3_step() to return immediately 12121c92853dSdrh ** with SQLITE_CONSTRAINT. 12131c92853dSdrh ** 12146934fc7bSdrh ** any FAIL Sqlite3_step() returns immediately with a 12151c92853dSdrh ** return code of SQLITE_CONSTRAINT. The 12161c92853dSdrh ** transaction is not rolled back and any 12176934fc7bSdrh ** changes to prior rows are retained. 12181c92853dSdrh ** 12196934fc7bSdrh ** any IGNORE The attempt in insert or update the current 12206934fc7bSdrh ** row is skipped, without throwing an error. 12216934fc7bSdrh ** Processing continues with the next row. 12226934fc7bSdrh ** (There is an immediate jump to ignoreDest.) 12239cfcf5d4Sdrh ** 12249cfcf5d4Sdrh ** NOT NULL REPLACE The NULL value is replace by the default 12259cfcf5d4Sdrh ** value for that column. If the default value 12269cfcf5d4Sdrh ** is NULL, the action is the same as ABORT. 12279cfcf5d4Sdrh ** 12289cfcf5d4Sdrh ** UNIQUE REPLACE The other row that conflicts with the row 12299cfcf5d4Sdrh ** being inserted is removed. 12309cfcf5d4Sdrh ** 12319cfcf5d4Sdrh ** CHECK REPLACE Illegal. The results in an exception. 12329cfcf5d4Sdrh ** 12331c92853dSdrh ** Which action to take is determined by the overrideError parameter. 12341c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter 12351c92853dSdrh ** is used. Or if pParse->onError==OE_Default then the onError value 12361c92853dSdrh ** for the constraint is used. 12379cfcf5d4Sdrh */ 12384adee20fSdanielk1977 void sqlite3GenerateConstraintChecks( 12399cfcf5d4Sdrh Parse *pParse, /* The parser context */ 12406934fc7bSdrh Table *pTab, /* The table being inserted or updated */ 1241f8ffb278Sdrh int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ 12426934fc7bSdrh int iDataCur, /* Canonical data cursor (main table or PK index) */ 124326198bb4Sdrh int iIdxCur, /* First index cursor */ 12446934fc7bSdrh int regNewData, /* First register in a range holding values to insert */ 1245f8ffb278Sdrh int regOldData, /* Previous content. 0 for INSERTs */ 1246f8ffb278Sdrh u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ 1247f8ffb278Sdrh u8 overrideError, /* Override onError to this if not OE_Default */ 1248de630353Sdanielk1977 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ 1249bdb00225Sdrh int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */ 1250bdb00225Sdrh int *aiChng /* column i is unchanged if aiChng[i]<0 */ 12519cfcf5d4Sdrh ){ 12521b7ecbb4Sdrh Vdbe *v; /* VDBE under constrution */ 12531b7ecbb4Sdrh Index *pIdx; /* Pointer to one of the indices */ 125411e85273Sdrh Index *pPk = 0; /* The PRIMARY KEY index */ 12552938f924Sdrh sqlite3 *db; /* Database connection */ 1256f8ffb278Sdrh int i; /* loop counter */ 1257f8ffb278Sdrh int ix; /* Index loop counter */ 12589cfcf5d4Sdrh int nCol; /* Number of columns */ 12599cfcf5d4Sdrh int onError; /* Conflict resolution strategy */ 1260728e0f91Sdrh int addr1; /* Address of jump instruction */ 12611b7ecbb4Sdrh int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ 12626fbe41acSdrh int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ 12638d1b82e4Sdrh int ipkTop = 0; /* Top of the rowid change constraint check */ 12648d1b82e4Sdrh int ipkBottom = 0; /* Bottom of the rowid change constraint check */ 12658d1b82e4Sdrh u8 isUpdate; /* True if this is an UPDATE operation */ 126657bf4a8eSdrh u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ 12679cfcf5d4Sdrh 1268f8ffb278Sdrh isUpdate = regOldData!=0; 12692938f924Sdrh db = pParse->db; 12704adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 12719cfcf5d4Sdrh assert( v!=0 ); 1272417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 12739cfcf5d4Sdrh nCol = pTab->nCol; 1274aa9b8963Sdrh 12756934fc7bSdrh /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for 12766934fc7bSdrh ** normal rowid tables. nPkField is the number of key fields in the 12776934fc7bSdrh ** pPk index or 1 for a rowid table. In other words, nPkField is the 12786934fc7bSdrh ** number of fields in the true primary key of the table. */ 127926198bb4Sdrh if( HasRowid(pTab) ){ 128026198bb4Sdrh pPk = 0; 128126198bb4Sdrh nPkField = 1; 128226198bb4Sdrh }else{ 128326198bb4Sdrh pPk = sqlite3PrimaryKeyIndex(pTab); 128426198bb4Sdrh nPkField = pPk->nKeyCol; 128526198bb4Sdrh } 12866fbe41acSdrh 12876fbe41acSdrh /* Record that this module has started */ 12886fbe41acSdrh VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", 12896934fc7bSdrh iDataCur, iIdxCur, regNewData, regOldData, pkChng)); 12909cfcf5d4Sdrh 12919cfcf5d4Sdrh /* Test all NOT NULL constraints. 12929cfcf5d4Sdrh */ 12939cfcf5d4Sdrh for(i=0; i<nCol; i++){ 12940ca3e24bSdrh if( i==pTab->iPKey ){ 1295bdb00225Sdrh continue; /* ROWID is never NULL */ 1296bdb00225Sdrh } 1297bdb00225Sdrh if( aiChng && aiChng[i]<0 ){ 1298bdb00225Sdrh /* Don't bother checking for NOT NULL on columns that do not change */ 12990ca3e24bSdrh continue; 13000ca3e24bSdrh } 13019cfcf5d4Sdrh onError = pTab->aCol[i].notNull; 1302bdb00225Sdrh if( onError==OE_None ) continue; /* This column is allowed to be NULL */ 13039cfcf5d4Sdrh if( overrideError!=OE_Default ){ 13049cfcf5d4Sdrh onError = overrideError; 1305a996e477Sdrh }else if( onError==OE_Default ){ 1306a996e477Sdrh onError = OE_Abort; 13079cfcf5d4Sdrh } 13087977a17fSdanielk1977 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ 13099cfcf5d4Sdrh onError = OE_Abort; 13109cfcf5d4Sdrh } 1311b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1312b84f96f8Sdanielk1977 || onError==OE_Ignore || onError==OE_Replace ); 13139cfcf5d4Sdrh switch( onError ){ 13141c92853dSdrh case OE_Abort: 1315e0af83acSdan sqlite3MayAbort(pParse); 13160978d4ffSdrh /* Fall through */ 1317e0af83acSdan case OE_Rollback: 13181c92853dSdrh case OE_Fail: { 1319f9c8ce3cSdrh char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, 1320f9c8ce3cSdrh pTab->aCol[i].zName); 13212700acaaSdrh sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError, 13222700acaaSdrh regNewData+1+i); 13232700acaaSdrh sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC); 1324f9c8ce3cSdrh sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); 1325688852abSdrh VdbeCoverage(v); 13269cfcf5d4Sdrh break; 13279cfcf5d4Sdrh } 13289cfcf5d4Sdrh case OE_Ignore: { 13296934fc7bSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest); 1330688852abSdrh VdbeCoverage(v); 13319cfcf5d4Sdrh break; 13329cfcf5d4Sdrh } 1333098d1684Sdrh default: { 1334098d1684Sdrh assert( onError==OE_Replace ); 1335728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); 1336728e0f91Sdrh VdbeCoverage(v); 13376934fc7bSdrh sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); 1338728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 13399cfcf5d4Sdrh break; 13409cfcf5d4Sdrh } 13419cfcf5d4Sdrh } 13429cfcf5d4Sdrh } 13439cfcf5d4Sdrh 13449cfcf5d4Sdrh /* Test all CHECK constraints 13459cfcf5d4Sdrh */ 1346ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 13472938f924Sdrh if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ 13482938f924Sdrh ExprList *pCheck = pTab->pCheck; 13496e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 1350aa01c7e2Sdrh onError = overrideError!=OE_Default ? overrideError : OE_Abort; 13512938f924Sdrh for(i=0; i<pCheck->nExpr; i++){ 135205723a9eSdrh int allOk; 13532a0b527bSdrh Expr *pExpr = pCheck->a[i].pExpr; 135498bfa16dSdrh if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue; 135505723a9eSdrh allOk = sqlite3VdbeMakeLabel(v); 13562a0b527bSdrh sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL); 13572e06c67cSdrh if( onError==OE_Ignore ){ 1358076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 1359aa01c7e2Sdrh }else{ 1360f9c8ce3cSdrh char *zName = pCheck->a[i].zName; 1361f9c8ce3cSdrh if( zName==0 ) zName = pTab->zName; 13626dc84902Sdrh if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ 1363d91c1a17Sdrh sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, 1364f9c8ce3cSdrh onError, zName, P4_TRANSIENT, 1365f9c8ce3cSdrh P5_ConstraintCheck); 1366aa01c7e2Sdrh } 1367ffe07b2dSdrh sqlite3VdbeResolveLabel(v, allOk); 1368ffe07b2dSdrh } 13696e97f8ecSdrh pParse->iSelfTab = 0; 13702938f924Sdrh } 1371ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */ 13729cfcf5d4Sdrh 1373f8ffb278Sdrh /* If rowid is changing, make sure the new rowid does not previously 1374f8ffb278Sdrh ** exist in the table. 13759cfcf5d4Sdrh */ 13766fbe41acSdrh if( pkChng && pPk==0 ){ 137711e85273Sdrh int addrRowidOk = sqlite3VdbeMakeLabel(v); 137811e85273Sdrh 1379f8ffb278Sdrh /* Figure out what action to take in case of a rowid collision */ 13800ca3e24bSdrh onError = pTab->keyConf; 13810ca3e24bSdrh if( overrideError!=OE_Default ){ 13820ca3e24bSdrh onError = overrideError; 1383a996e477Sdrh }else if( onError==OE_Default ){ 1384a996e477Sdrh onError = OE_Abort; 13850ca3e24bSdrh } 1386a0217ba7Sdrh 138779b0c956Sdrh if( isUpdate ){ 13887405fa74Sdrh /* pkChng!=0 does not mean that the rowid has changed, only that 1389f8ffb278Sdrh ** it might have changed. Skip the conflict logic below if the rowid 1390f8ffb278Sdrh ** is unchanged. */ 13916934fc7bSdrh sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); 13923d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1393688852abSdrh VdbeCoverage(v); 139479b0c956Sdrh } 1395f8ffb278Sdrh 13968d1b82e4Sdrh /* If the response to a rowid conflict is REPLACE but the response 13978d1b82e4Sdrh ** to some other UNIQUE constraint is FAIL or IGNORE, then we need 13988d1b82e4Sdrh ** to defer the running of the rowid conflict checking until after 13998d1b82e4Sdrh ** the UNIQUE constraints have run. 14008d1b82e4Sdrh */ 14018d1b82e4Sdrh if( onError==OE_Replace && overrideError!=OE_Replace ){ 14028d1b82e4Sdrh for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 14038d1b82e4Sdrh if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){ 14048d1b82e4Sdrh ipkTop = sqlite3VdbeAddOp0(v, OP_Goto); 14058d1b82e4Sdrh break; 14068d1b82e4Sdrh } 14078d1b82e4Sdrh } 14088d1b82e4Sdrh } 14098d1b82e4Sdrh 1410f8ffb278Sdrh /* Check to see if the new rowid already exists in the table. Skip 1411f8ffb278Sdrh ** the following conflict logic if it does not. */ 14126934fc7bSdrh sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); 1413688852abSdrh VdbeCoverage(v); 1414f8ffb278Sdrh 1415f8ffb278Sdrh /* Generate code that deals with a rowid collision */ 14160ca3e24bSdrh switch( onError ){ 1417a0217ba7Sdrh default: { 1418a0217ba7Sdrh onError = OE_Abort; 1419a0217ba7Sdrh /* Fall thru into the next case */ 1420a0217ba7Sdrh } 14211c92853dSdrh case OE_Rollback: 14221c92853dSdrh case OE_Abort: 14231c92853dSdrh case OE_Fail: { 1424f9c8ce3cSdrh sqlite3RowidConstraint(pParse, onError, pTab); 14250ca3e24bSdrh break; 14260ca3e24bSdrh } 14275383ae5cSdrh case OE_Replace: { 14282283d46cSdan /* If there are DELETE triggers on this table and the 14292283d46cSdan ** recursive-triggers flag is set, call GenerateRowDelete() to 1430d5578433Smistachkin ** remove the conflicting row from the table. This will fire 14312283d46cSdan ** the triggers and remove both the table and index b-tree entries. 14322283d46cSdan ** 14332283d46cSdan ** Otherwise, if there are no triggers or the recursive-triggers 1434da730f6eSdan ** flag is not set, but the table has one or more indexes, call 1435da730f6eSdan ** GenerateRowIndexDelete(). This removes the index b-tree entries 1436da730f6eSdan ** only. The table b-tree entry will be replaced by the new entry 1437da730f6eSdan ** when it is inserted. 1438da730f6eSdan ** 1439da730f6eSdan ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, 1440da730f6eSdan ** also invoke MultiWrite() to indicate that this VDBE may require 1441da730f6eSdan ** statement rollback (if the statement is aborted after the delete 1442da730f6eSdan ** takes place). Earlier versions called sqlite3MultiWrite() regardless, 1443da730f6eSdan ** but being more selective here allows statements like: 1444da730f6eSdan ** 1445da730f6eSdan ** REPLACE INTO t(rowid) VALUES($newrowid) 1446da730f6eSdan ** 1447da730f6eSdan ** to run without a statement journal if there are no indexes on the 1448da730f6eSdan ** table. 1449da730f6eSdan */ 14502283d46cSdan Trigger *pTrigger = 0; 14512938f924Sdrh if( db->flags&SQLITE_RecTriggers ){ 14522283d46cSdan pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 14532283d46cSdan } 1454e7a94d81Sdan if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ 1455da730f6eSdan sqlite3MultiWrite(pParse); 145626198bb4Sdrh sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1457438b8815Sdan regNewData, 1, 0, OE_Replace, 1, -1); 145846c47d46Sdan }else{ 14599b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 1460cbf1b8efSdrh if( HasRowid(pTab) ){ 146146c47d46Sdan /* This OP_Delete opcode fires the pre-update-hook only. It does 146246c47d46Sdan ** not modify the b-tree. It is more efficient to let the coming 146346c47d46Sdan ** OP_Insert replace the existing entry than it is to delete the 146446c47d46Sdan ** existing entry and then insert a new one. */ 1465cbf1b8efSdrh sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP); 1466f14b7fb7Sdrh sqlite3VdbeAppendP4(v, pTab, P4_TABLE); 1467cbf1b8efSdrh } 14689b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ 146946c47d46Sdan if( pTab->pIndex ){ 1470da730f6eSdan sqlite3MultiWrite(pParse); 1471f0ee1d3cSdan sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); 14722283d46cSdan } 147346c47d46Sdan } 14745383ae5cSdrh seenReplace = 1; 14755383ae5cSdrh break; 14765383ae5cSdrh } 14770ca3e24bSdrh case OE_Ignore: { 14788d1b82e4Sdrh /*assert( seenReplace==0 );*/ 1479076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 14800ca3e24bSdrh break; 14810ca3e24bSdrh } 14820ca3e24bSdrh } 148311e85273Sdrh sqlite3VdbeResolveLabel(v, addrRowidOk); 14848d1b82e4Sdrh if( ipkTop ){ 14858d1b82e4Sdrh ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); 14868d1b82e4Sdrh sqlite3VdbeJumpHere(v, ipkTop); 1487a05a722fSdrh } 14880ca3e24bSdrh } 14890bd1f4eaSdrh 14900bd1f4eaSdrh /* Test all UNIQUE constraints by creating entries for each UNIQUE 14910bd1f4eaSdrh ** index and making sure that duplicate entries do not already exist. 149211e85273Sdrh ** Compute the revised record entries for indices as we go. 1493f8ffb278Sdrh ** 1494f8ffb278Sdrh ** This loop also handles the case of the PRIMARY KEY index for a 1495f8ffb278Sdrh ** WITHOUT ROWID table. 14960bd1f4eaSdrh */ 149726198bb4Sdrh for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ 14986934fc7bSdrh int regIdx; /* Range of registers hold conent for pIdx */ 14996934fc7bSdrh int regR; /* Range of registers holding conflicting PK */ 15006934fc7bSdrh int iThisCur; /* Cursor for this UNIQUE index */ 15016934fc7bSdrh int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ 15022184fc75Sdrh 150326198bb4Sdrh if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ 150457bf4a8eSdrh if( bAffinityDone==0 ){ 150557bf4a8eSdrh sqlite3TableAffinity(v, pTab, regNewData+1); 150657bf4a8eSdrh bAffinityDone = 1; 150757bf4a8eSdrh } 15086934fc7bSdrh iThisCur = iIdxCur+ix; 15096934fc7bSdrh addrUniqueOk = sqlite3VdbeMakeLabel(v); 1510b2fe7d8cSdrh 1511f8ffb278Sdrh /* Skip partial indices for which the WHERE clause is not true */ 1512b2b9d3d7Sdrh if( pIdx->pPartIdxWhere ){ 151326198bb4Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); 15146e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 151572bc8208Sdrh sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, 1516b2b9d3d7Sdrh SQLITE_JUMPIFNULL); 15176e97f8ecSdrh pParse->iSelfTab = 0; 1518b2b9d3d7Sdrh } 1519b2b9d3d7Sdrh 15206934fc7bSdrh /* Create a record for this index entry as it should appear after 1521f8ffb278Sdrh ** the insert or update. Store that record in the aRegIdx[ix] register 1522f8ffb278Sdrh */ 1523bf2f5739Sdrh regIdx = aRegIdx[ix]+1; 15249cfcf5d4Sdrh for(i=0; i<pIdx->nColumn; i++){ 15256934fc7bSdrh int iField = pIdx->aiColumn[i]; 1526f82b9afcSdrh int x; 15274b92f98cSdrh if( iField==XN_EXPR ){ 15286e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 15291c75c9d7Sdrh sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); 15306e97f8ecSdrh pParse->iSelfTab = 0; 15311f9ca2c8Sdrh VdbeComment((v, "%s column %d", pIdx->zName, i)); 15321f9ca2c8Sdrh }else{ 15334b92f98cSdrh if( iField==XN_ROWID || iField==pTab->iPKey ){ 1534f82b9afcSdrh x = regNewData; 15359cfcf5d4Sdrh }else{ 1536f82b9afcSdrh x = iField + regNewData + 1; 15379cfcf5d4Sdrh } 1538fed7ac6fSdrh sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i); 1539f82b9afcSdrh VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName)); 15409cfcf5d4Sdrh } 15411f9ca2c8Sdrh } 154226198bb4Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); 154326198bb4Sdrh VdbeComment((v, "for %s", pIdx->zName)); 15447e4acf7bSdrh #ifdef SQLITE_ENABLE_NULL_TRIM 15457e4acf7bSdrh if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable); 15467e4acf7bSdrh #endif 1547b2fe7d8cSdrh 1548f8ffb278Sdrh /* In an UPDATE operation, if this index is the PRIMARY KEY index 1549f8ffb278Sdrh ** of a WITHOUT ROWID table and there has been no change the 1550f8ffb278Sdrh ** primary key, then no collision is possible. The collision detection 1551f8ffb278Sdrh ** logic below can all be skipped. */ 155200012df4Sdrh if( isUpdate && pPk==pIdx && pkChng==0 ){ 1553da475b8dSdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1554da475b8dSdrh continue; 1555da475b8dSdrh } 1556f8ffb278Sdrh 15576934fc7bSdrh /* Find out what action to take in case there is a uniqueness conflict */ 15589cfcf5d4Sdrh onError = pIdx->onError; 1559de630353Sdanielk1977 if( onError==OE_None ){ 156011e85273Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1561de630353Sdanielk1977 continue; /* pIdx is not a UNIQUE index */ 1562de630353Sdanielk1977 } 15639cfcf5d4Sdrh if( overrideError!=OE_Default ){ 15649cfcf5d4Sdrh onError = overrideError; 1565a996e477Sdrh }else if( onError==OE_Default ){ 1566a996e477Sdrh onError = OE_Abort; 15679cfcf5d4Sdrh } 15685383ae5cSdrh 1569801f55d8Sdrh /* Collision detection may be omitted if all of the following are true: 1570801f55d8Sdrh ** (1) The conflict resolution algorithm is REPLACE 1571801f55d8Sdrh ** (2) The table is a WITHOUT ROWID table 1572801f55d8Sdrh ** (3) There are no secondary indexes on the table 1573801f55d8Sdrh ** (4) No delete triggers need to be fired if there is a conflict 1574f9a12a10Sdan ** (5) No FK constraint counters need to be updated if a conflict occurs. 1575801f55d8Sdrh */ 1576801f55d8Sdrh if( (ix==0 && pIdx->pNext==0) /* Condition 3 */ 1577801f55d8Sdrh && pPk==pIdx /* Condition 2 */ 1578801f55d8Sdrh && onError==OE_Replace /* Condition 1 */ 1579801f55d8Sdrh && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */ 1580801f55d8Sdrh 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0)) 1581f9a12a10Sdan && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */ 1582f9a12a10Sdan (0==pTab->pFKey && 0==sqlite3FkReferences(pTab))) 15834e1f0efbSdan ){ 1584c6c9e158Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1585c6c9e158Sdrh continue; 1586c6c9e158Sdrh } 1587c6c9e158Sdrh 1588b2fe7d8cSdrh /* Check to see if the new index entry will be unique */ 15894d795ef7Sdrh sqlite3ExprCachePush(pParse); 159026198bb4Sdrh sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, 1591688852abSdrh regIdx, pIdx->nKeyCol); VdbeCoverage(v); 1592f8ffb278Sdrh 1593f8ffb278Sdrh /* Generate code to handle collisions */ 1594392ee21dSdrh regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); 159546d03fcbSdrh if( isUpdate || onError==OE_Replace ){ 159611e85273Sdrh if( HasRowid(pTab) ){ 15976934fc7bSdrh sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); 15980978d4ffSdrh /* Conflict only if the rowid of the existing index entry 15990978d4ffSdrh ** is different from old-rowid */ 1600f8ffb278Sdrh if( isUpdate ){ 16016934fc7bSdrh sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); 16023d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1603688852abSdrh VdbeCoverage(v); 1604f8ffb278Sdrh } 160526198bb4Sdrh }else{ 1606ccc79f02Sdrh int x; 160726198bb4Sdrh /* Extract the PRIMARY KEY from the end of the index entry and 1608da475b8dSdrh ** store it in registers regR..regR+nPk-1 */ 1609a021f121Sdrh if( pIdx!=pPk ){ 161026198bb4Sdrh for(i=0; i<pPk->nKeyCol; i++){ 16114b92f98cSdrh assert( pPk->aiColumn[i]>=0 ); 1612ccc79f02Sdrh x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]); 161326198bb4Sdrh sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); 161426198bb4Sdrh VdbeComment((v, "%s.%s", pTab->zName, 161526198bb4Sdrh pTab->aCol[pPk->aiColumn[i]].zName)); 161626198bb4Sdrh } 1617da475b8dSdrh } 1618da475b8dSdrh if( isUpdate ){ 1619e83267daSdan /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 1620e83267daSdan ** table, only conflict if the new PRIMARY KEY values are actually 1621e83267daSdan ** different from the old. 1622e83267daSdan ** 1623e83267daSdan ** For a UNIQUE index, only conflict if the PRIMARY KEY values 1624e83267daSdan ** of the matched index row are different from the original PRIMARY 1625e83267daSdan ** KEY values of this row before the update. */ 1626e83267daSdan int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; 1627e83267daSdan int op = OP_Ne; 162848dd1d8eSdrh int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); 1629e83267daSdan 1630e83267daSdan for(i=0; i<pPk->nKeyCol; i++){ 1631e83267daSdan char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); 1632ccc79f02Sdrh x = pPk->aiColumn[i]; 16334b92f98cSdrh assert( x>=0 ); 1634e83267daSdan if( i==(pPk->nKeyCol-1) ){ 1635e83267daSdan addrJump = addrUniqueOk; 1636e83267daSdan op = OP_Eq; 163711e85273Sdrh } 1638e83267daSdan sqlite3VdbeAddOp4(v, op, 1639e83267daSdan regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ 1640e83267daSdan ); 16413d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 16423d77dee9Sdrh VdbeCoverageIf(v, op==OP_Eq); 16433d77dee9Sdrh VdbeCoverageIf(v, op==OP_Ne); 1644da475b8dSdrh } 164511e85273Sdrh } 164626198bb4Sdrh } 164746d03fcbSdrh } 1648b2fe7d8cSdrh 1649b2fe7d8cSdrh /* Generate code that executes if the new index entry is not unique */ 1650b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1651b84f96f8Sdanielk1977 || onError==OE_Ignore || onError==OE_Replace ); 16529cfcf5d4Sdrh switch( onError ){ 16531c92853dSdrh case OE_Rollback: 16541c92853dSdrh case OE_Abort: 16551c92853dSdrh case OE_Fail: { 1656f9c8ce3cSdrh sqlite3UniqueConstraint(pParse, onError, pIdx); 16579cfcf5d4Sdrh break; 16589cfcf5d4Sdrh } 16599cfcf5d4Sdrh case OE_Ignore: { 1660076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 16619cfcf5d4Sdrh break; 16629cfcf5d4Sdrh } 1663098d1684Sdrh default: { 16642283d46cSdan Trigger *pTrigger = 0; 1665098d1684Sdrh assert( onError==OE_Replace ); 16661bea559aSdan sqlite3MultiWrite(pParse); 16672938f924Sdrh if( db->flags&SQLITE_RecTriggers ){ 16682283d46cSdan pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 16692283d46cSdan } 167026198bb4Sdrh sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1671b0264eecSdrh regR, nPkField, 0, OE_Replace, 167268116939Sdrh (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur); 16730ca3e24bSdrh seenReplace = 1; 16749cfcf5d4Sdrh break; 16759cfcf5d4Sdrh } 16769cfcf5d4Sdrh } 167711e85273Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 16784d795ef7Sdrh sqlite3ExprCachePop(pParse); 1679392ee21dSdrh if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); 16809cfcf5d4Sdrh } 16818d1b82e4Sdrh if( ipkTop ){ 1682076e85f5Sdrh sqlite3VdbeGoto(v, ipkTop+1); 16838d1b82e4Sdrh sqlite3VdbeJumpHere(v, ipkBottom); 16849cfcf5d4Sdrh } 1685de630353Sdanielk1977 1686de630353Sdanielk1977 *pbMayReplace = seenReplace; 1687ce60aa46Sdrh VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); 16889cfcf5d4Sdrh } 16890ca3e24bSdrh 1690d447dcedSdrh #ifdef SQLITE_ENABLE_NULL_TRIM 16910ca3e24bSdrh /* 1692585ce192Sdrh ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord) 1693585ce192Sdrh ** to be the number of columns in table pTab that must not be NULL-trimmed. 1694585ce192Sdrh ** 1695585ce192Sdrh ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero. 1696585ce192Sdrh */ 1697585ce192Sdrh void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){ 1698585ce192Sdrh u16 i; 1699585ce192Sdrh 1700585ce192Sdrh /* Records with omitted columns are only allowed for schema format 1701585ce192Sdrh ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */ 1702585ce192Sdrh if( pTab->pSchema->file_format<2 ) return; 1703585ce192Sdrh 17047e4acf7bSdrh for(i=pTab->nCol-1; i>0; i--){ 17057e4acf7bSdrh if( pTab->aCol[i].pDflt!=0 ) break; 17067e4acf7bSdrh if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break; 17077e4acf7bSdrh } 17087e4acf7bSdrh sqlite3VdbeChangeP5(v, i+1); 1709585ce192Sdrh } 1710d447dcedSdrh #endif 1711585ce192Sdrh 17120ca3e24bSdrh /* 17130ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation 17144adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 17156934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the 171604adf416Sdrh ** rowid and the content to be inserted. 17170ca3e24bSdrh ** 1718b419a926Sdrh ** The arguments to this routine should be the same as the first six 17194adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks. 17200ca3e24bSdrh */ 17214adee20fSdanielk1977 void sqlite3CompleteInsertion( 17220ca3e24bSdrh Parse *pParse, /* The parser context */ 17230ca3e24bSdrh Table *pTab, /* the table into which we are inserting */ 172426198bb4Sdrh int iDataCur, /* Cursor of the canonical data source */ 172526198bb4Sdrh int iIdxCur, /* First index cursor */ 17266934fc7bSdrh int regNewData, /* Range of content */ 1727aa9b8963Sdrh int *aRegIdx, /* Register used by each index. 0 for unused indices */ 1728f91c1318Sdan int update_flags, /* True for UPDATE, False for INSERT */ 1729de630353Sdanielk1977 int appendBias, /* True if this is likely to be an append */ 1730de630353Sdanielk1977 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ 17310ca3e24bSdrh ){ 17326934fc7bSdrh Vdbe *v; /* Prepared statements under construction */ 17336934fc7bSdrh Index *pIdx; /* An index being inserted or updated */ 17346934fc7bSdrh u8 pik_flags; /* flag values passed to the btree insert */ 17356934fc7bSdrh int regData; /* Content registers (after the rowid) */ 173660ec914cSpeter.d.reid int regRec; /* Register holding assembled record for the table */ 17376934fc7bSdrh int i; /* Loop counter */ 173857bf4a8eSdrh u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */ 17390ca3e24bSdrh 1740f91c1318Sdan assert( update_flags==0 1741f91c1318Sdan || update_flags==OPFLAG_ISUPDATE 1742f91c1318Sdan || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION) 1743f91c1318Sdan ); 1744f91c1318Sdan 17454adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 17460ca3e24bSdrh assert( v!=0 ); 1747417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 1748b2b9d3d7Sdrh for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1749aa9b8963Sdrh if( aRegIdx[i]==0 ) continue; 175057bf4a8eSdrh bAffinityDone = 1; 1751b2b9d3d7Sdrh if( pIdx->pPartIdxWhere ){ 1752b2b9d3d7Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); 1753688852abSdrh VdbeCoverage(v); 1754b2b9d3d7Sdrh } 1755cb9a3643Sdan pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0); 175648dd1d8eSdrh if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 17574308e348Sdrh assert( pParse->nested==0 ); 17586546af14Sdrh pik_flags |= OPFLAG_NCHANGE; 1759f91c1318Sdan pik_flags |= (update_flags & OPFLAG_SAVEPOSITION); 1760cb9a3643Sdan #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 1761cb9a3643Sdan if( update_flags==0 ){ 1762cb9a3643Sdan sqlite3VdbeAddOp4(v, OP_InsertInt, 1763cb9a3643Sdan iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE 1764cb9a3643Sdan ); 1765cb9a3643Sdan sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP); 1766de630353Sdanielk1977 } 1767cb9a3643Sdan #endif 1768cb9a3643Sdan } 1769cb9a3643Sdan sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i], 1770cb9a3643Sdan aRegIdx[i]+1, 1771cb9a3643Sdan pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn); 17729b34abeeSdrh sqlite3VdbeChangeP5(v, pik_flags); 17730ca3e24bSdrh } 1774ec95c441Sdrh if( !HasRowid(pTab) ) return; 17756934fc7bSdrh regData = regNewData + 1; 1776b7654111Sdrh regRec = sqlite3GetTempReg(pParse); 17771db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); 1778585ce192Sdrh sqlite3SetMakeRecordP5(v, pTab); 17792adb878bSdrh if( !bAffinityDone ){ 17802adb878bSdrh sqlite3TableAffinity(v, pTab, 0); 1781da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); 17822adb878bSdrh } 17834794f735Sdrh if( pParse->nested ){ 17844794f735Sdrh pik_flags = 0; 17854794f735Sdrh }else{ 178694eb6a14Sdanielk1977 pik_flags = OPFLAG_NCHANGE; 1787f91c1318Sdan pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID); 17884794f735Sdrh } 1789e4d90813Sdrh if( appendBias ){ 1790e4d90813Sdrh pik_flags |= OPFLAG_APPEND; 1791e4d90813Sdrh } 1792de630353Sdanielk1977 if( useSeekResult ){ 1793de630353Sdanielk1977 pik_flags |= OPFLAG_USESEEKRESULT; 1794de630353Sdanielk1977 } 17956934fc7bSdrh sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData); 179694eb6a14Sdanielk1977 if( !pParse->nested ){ 1797f14b7fb7Sdrh sqlite3VdbeAppendP4(v, pTab, P4_TABLE); 179894eb6a14Sdanielk1977 } 1799b7654111Sdrh sqlite3VdbeChangeP5(v, pik_flags); 18000ca3e24bSdrh } 1801cd44690aSdrh 1802cd44690aSdrh /* 180326198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate 180426198bb4Sdrh ** code to open and initialized those cursors. 1805aa9b8963Sdrh ** 180626198bb4Sdrh ** The cursor for the object that contains the complete data (normally 180726198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT 180826198bb4Sdrh ** ROWID table) is returned in *piDataCur. The first index cursor is 180926198bb4Sdrh ** returned in *piIdxCur. The number of indices is returned. 181026198bb4Sdrh ** 181126198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables 181226198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative. 181326198bb4Sdrh ** If iBase is negative, then allocate the next available cursor. 181426198bb4Sdrh ** 181526198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. 181626198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range 181726198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the 181826198bb4Sdrh ** pTab->pIndex list. 1819b6b4b79fSdrh ** 1820b6b4b79fSdrh ** If pTab is a virtual table, then this routine is a no-op and the 1821b6b4b79fSdrh ** *piDataCur and *piIdxCur values are left uninitialized. 1822cd44690aSdrh */ 1823aa9b8963Sdrh int sqlite3OpenTableAndIndices( 1824290c1948Sdrh Parse *pParse, /* Parsing context */ 1825290c1948Sdrh Table *pTab, /* Table to be opened */ 182626198bb4Sdrh int op, /* OP_OpenRead or OP_OpenWrite */ 1827b89aeb6aSdrh u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */ 182826198bb4Sdrh int iBase, /* Use this for the table cursor, if there is one */ 18296a53499aSdrh u8 *aToOpen, /* If not NULL: boolean for each table and index */ 183026198bb4Sdrh int *piDataCur, /* Write the database source cursor number here */ 183126198bb4Sdrh int *piIdxCur /* Write the first index cursor number here */ 1832290c1948Sdrh ){ 1833cd44690aSdrh int i; 18344cbdda9eSdrh int iDb; 18356a53499aSdrh int iDataCur; 1836cd44690aSdrh Index *pIdx; 18374cbdda9eSdrh Vdbe *v; 18384cbdda9eSdrh 183926198bb4Sdrh assert( op==OP_OpenRead || op==OP_OpenWrite ); 1840fd261ec6Sdan assert( op==OP_OpenWrite || p5==0 ); 184126198bb4Sdrh if( IsVirtual(pTab) ){ 1842b6b4b79fSdrh /* This routine is a no-op for virtual tables. Leave the output 1843b6b4b79fSdrh ** variables *piDataCur and *piIdxCur uninitialized so that valgrind 1844b6b4b79fSdrh ** can detect if they are used by mistake in the caller. */ 184526198bb4Sdrh return 0; 184626198bb4Sdrh } 18474cbdda9eSdrh iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 18484cbdda9eSdrh v = sqlite3GetVdbe(pParse); 1849cd44690aSdrh assert( v!=0 ); 185026198bb4Sdrh if( iBase<0 ) iBase = pParse->nTab; 18516a53499aSdrh iDataCur = iBase++; 18526a53499aSdrh if( piDataCur ) *piDataCur = iDataCur; 18536a53499aSdrh if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ 18546a53499aSdrh sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); 18556fbe41acSdrh }else{ 185626198bb4Sdrh sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); 18576fbe41acSdrh } 18586a53499aSdrh if( piIdxCur ) *piIdxCur = iBase; 185926198bb4Sdrh for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 186026198bb4Sdrh int iIdxCur = iBase++; 1861da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 186261441c34Sdan if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 186361441c34Sdan if( piDataCur ) *piDataCur = iIdxCur; 186461441c34Sdan p5 = 0; 186561441c34Sdan } 18666a53499aSdrh if( aToOpen==0 || aToOpen[i+1] ){ 18672ec2fb22Sdrh sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); 18682ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 1869b89aeb6aSdrh sqlite3VdbeChangeP5(v, p5); 187061441c34Sdan VdbeComment((v, "%s", pIdx->zName)); 1871b89aeb6aSdrh } 18726a53499aSdrh } 187326198bb4Sdrh if( iBase>pParse->nTab ) pParse->nTab = iBase; 187426198bb4Sdrh return i; 1875cd44690aSdrh } 18769d9cf229Sdrh 187791c58e23Sdrh 187891c58e23Sdrh #ifdef SQLITE_TEST 187991c58e23Sdrh /* 188091c58e23Sdrh ** The following global variable is incremented whenever the 188191c58e23Sdrh ** transfer optimization is used. This is used for testing 188291c58e23Sdrh ** purposes only - to make sure the transfer optimization really 188360ec914cSpeter.d.reid ** is happening when it is supposed to. 188491c58e23Sdrh */ 188591c58e23Sdrh int sqlite3_xferopt_count; 188691c58e23Sdrh #endif /* SQLITE_TEST */ 188791c58e23Sdrh 188891c58e23Sdrh 18899d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 18909d9cf229Sdrh /* 18919d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data 18929d9cf229Sdrh ** for index pDest in an insert transfer optimization. The rules 18939d9cf229Sdrh ** for a compatible index: 18949d9cf229Sdrh ** 18959d9cf229Sdrh ** * The index is over the same set of columns 18969d9cf229Sdrh ** * The same DESC and ASC markings occurs on all columns 18979d9cf229Sdrh ** * The same onError processing (OE_Abort, OE_Ignore, etc) 18989d9cf229Sdrh ** * The same collating sequence on each column 1899b2b9d3d7Sdrh ** * The index has the exact same WHERE clause 19009d9cf229Sdrh */ 19019d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 19029d9cf229Sdrh int i; 19039d9cf229Sdrh assert( pDest && pSrc ); 19049d9cf229Sdrh assert( pDest->pTable!=pSrc->pTable ); 1905bbbdc83bSdrh if( pDest->nKeyCol!=pSrc->nKeyCol ){ 19069d9cf229Sdrh return 0; /* Different number of columns */ 19079d9cf229Sdrh } 19089d9cf229Sdrh if( pDest->onError!=pSrc->onError ){ 19099d9cf229Sdrh return 0; /* Different conflict resolution strategies */ 19109d9cf229Sdrh } 1911bbbdc83bSdrh for(i=0; i<pSrc->nKeyCol; i++){ 19129d9cf229Sdrh if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 19139d9cf229Sdrh return 0; /* Different columns indexed */ 19149d9cf229Sdrh } 19154b92f98cSdrh if( pSrc->aiColumn[i]==XN_EXPR ){ 19161f9ca2c8Sdrh assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); 19175aa550cfSdan if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr, 19181f9ca2c8Sdrh pDest->aColExpr->a[i].pExpr, -1)!=0 ){ 19191f9ca2c8Sdrh return 0; /* Different expressions in the index */ 19201f9ca2c8Sdrh } 19211f9ca2c8Sdrh } 19229d9cf229Sdrh if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 19239d9cf229Sdrh return 0; /* Different sort orders */ 19249d9cf229Sdrh } 19250472af91Sdrh if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){ 192660a713c6Sdrh return 0; /* Different collating sequences */ 19279d9cf229Sdrh } 19289d9cf229Sdrh } 19295aa550cfSdan if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ 1930b2b9d3d7Sdrh return 0; /* Different WHERE clauses */ 1931b2b9d3d7Sdrh } 19329d9cf229Sdrh 19339d9cf229Sdrh /* If no test above fails then the indices must be compatible */ 19349d9cf229Sdrh return 1; 19359d9cf229Sdrh } 19369d9cf229Sdrh 19379d9cf229Sdrh /* 19389d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form 19399d9cf229Sdrh ** 19409d9cf229Sdrh ** INSERT INTO tab1 SELECT * FROM tab2; 19419d9cf229Sdrh ** 1942ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1. 194360ec914cSpeter.d.reid ** Columns are not decoded and reassembled, which greatly improves 1944ccdf1baeSdrh ** performance. Raw index records are transferred in the same way. 19459d9cf229Sdrh ** 1946ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible. 1947ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments 1948ccdf1baeSdrh ** embedded in the code for details. 19499d9cf229Sdrh ** 1950ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used. 1951ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table 1952ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time. In that 1953ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also 1954ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the 1955ccdf1baeSdrh ** xfer optimization code if the test fails. In that case, this routine 1956ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate 1957ccdf1baeSdrh ** an unoptimized transfer. This routine also returns FALSE if there 1958ccdf1baeSdrh ** is no chance that the xfer optimization can be applied. 19599d9cf229Sdrh ** 1960ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster. 19619d9cf229Sdrh */ 19629d9cf229Sdrh static int xferOptimization( 19639d9cf229Sdrh Parse *pParse, /* Parser context */ 19649d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 19659d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 19669d9cf229Sdrh int onError, /* How to handle constraint errors */ 19679d9cf229Sdrh int iDbDest /* The database of pDest */ 19689d9cf229Sdrh ){ 1969e34162b1Sdan sqlite3 *db = pParse->db; 19709d9cf229Sdrh ExprList *pEList; /* The result set of the SELECT */ 19719d9cf229Sdrh Table *pSrc; /* The table in the FROM clause of SELECT */ 19729d9cf229Sdrh Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 19739d9cf229Sdrh struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 19749d9cf229Sdrh int i; /* Loop counter */ 19759d9cf229Sdrh int iDbSrc; /* The database of pSrc */ 19769d9cf229Sdrh int iSrc, iDest; /* Cursors from source and destination */ 19779d9cf229Sdrh int addr1, addr2; /* Loop addresses */ 1978da475b8dSdrh int emptyDestTest = 0; /* Address of test for empty pDest */ 1979da475b8dSdrh int emptySrcTest = 0; /* Address of test for empty pSrc */ 19809d9cf229Sdrh Vdbe *v; /* The VDBE we are building */ 19816a288a33Sdrh int regAutoinc; /* Memory register used by AUTOINC */ 1982f33c9fadSdrh int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 1983b7654111Sdrh int regData, regRowid; /* Registers holding data and rowid */ 19849d9cf229Sdrh 19859d9cf229Sdrh if( pSelect==0 ){ 19869d9cf229Sdrh return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 19879d9cf229Sdrh } 1988ebbf08a0Sdan if( pParse->pWith || pSelect->pWith ){ 1989ebbf08a0Sdan /* Do not attempt to process this query if there are an WITH clauses 1990ebbf08a0Sdan ** attached to it. Proceeding may generate a false "no such table: xxx" 1991ebbf08a0Sdan ** error if pSelect reads from a CTE named "xxx". */ 1992ebbf08a0Sdan return 0; 1993ebbf08a0Sdan } 19942f886d1dSdanielk1977 if( sqlite3TriggerList(pParse, pDest) ){ 19959d9cf229Sdrh return 0; /* tab1 must not have triggers */ 19969d9cf229Sdrh } 19979d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 199844266ec6Sdrh if( IsVirtual(pDest) ){ 19999d9cf229Sdrh return 0; /* tab1 must not be a virtual table */ 20009d9cf229Sdrh } 20019d9cf229Sdrh #endif 20029d9cf229Sdrh if( onError==OE_Default ){ 2003e7224a01Sdrh if( pDest->iPKey>=0 ) onError = pDest->keyConf; 2004e7224a01Sdrh if( onError==OE_Default ) onError = OE_Abort; 20059d9cf229Sdrh } 20065ce240a6Sdanielk1977 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 20079d9cf229Sdrh if( pSelect->pSrc->nSrc!=1 ){ 20089d9cf229Sdrh return 0; /* FROM clause must have exactly one term */ 20099d9cf229Sdrh } 20109d9cf229Sdrh if( pSelect->pSrc->a[0].pSelect ){ 20119d9cf229Sdrh return 0; /* FROM clause cannot contain a subquery */ 20129d9cf229Sdrh } 20139d9cf229Sdrh if( pSelect->pWhere ){ 20149d9cf229Sdrh return 0; /* SELECT may not have a WHERE clause */ 20159d9cf229Sdrh } 20169d9cf229Sdrh if( pSelect->pOrderBy ){ 20179d9cf229Sdrh return 0; /* SELECT may not have an ORDER BY clause */ 20189d9cf229Sdrh } 20198103b7d2Sdrh /* Do not need to test for a HAVING clause. If HAVING is present but 20208103b7d2Sdrh ** there is no ORDER BY, we will get an error. */ 20219d9cf229Sdrh if( pSelect->pGroupBy ){ 20229d9cf229Sdrh return 0; /* SELECT may not have a GROUP BY clause */ 20239d9cf229Sdrh } 20249d9cf229Sdrh if( pSelect->pLimit ){ 20259d9cf229Sdrh return 0; /* SELECT may not have a LIMIT clause */ 20269d9cf229Sdrh } 20279d9cf229Sdrh if( pSelect->pPrior ){ 20289d9cf229Sdrh return 0; /* SELECT may not be a compound query */ 20299d9cf229Sdrh } 20307d10d5a6Sdrh if( pSelect->selFlags & SF_Distinct ){ 20319d9cf229Sdrh return 0; /* SELECT may not be DISTINCT */ 20329d9cf229Sdrh } 20339d9cf229Sdrh pEList = pSelect->pEList; 20349d9cf229Sdrh assert( pEList!=0 ); 20359d9cf229Sdrh if( pEList->nExpr!=1 ){ 20369d9cf229Sdrh return 0; /* The result set must have exactly one column */ 20379d9cf229Sdrh } 20389d9cf229Sdrh assert( pEList->a[0].pExpr ); 20391a1d3cd2Sdrh if( pEList->a[0].pExpr->op!=TK_ASTERISK ){ 20409d9cf229Sdrh return 0; /* The result set must be the special operator "*" */ 20419d9cf229Sdrh } 20429d9cf229Sdrh 20439d9cf229Sdrh /* At this point we have established that the statement is of the 20449d9cf229Sdrh ** correct syntactic form to participate in this optimization. Now 20459d9cf229Sdrh ** we have to check the semantics. 20469d9cf229Sdrh */ 20479d9cf229Sdrh pItem = pSelect->pSrc->a; 204841fb5cd1Sdan pSrc = sqlite3LocateTableItem(pParse, 0, pItem); 20499d9cf229Sdrh if( pSrc==0 ){ 20509d9cf229Sdrh return 0; /* FROM clause does not contain a real table */ 20519d9cf229Sdrh } 20529d9cf229Sdrh if( pSrc==pDest ){ 20539d9cf229Sdrh return 0; /* tab1 and tab2 may not be the same table */ 20549d9cf229Sdrh } 205555548273Sdrh if( HasRowid(pDest)!=HasRowid(pSrc) ){ 205655548273Sdrh return 0; /* source and destination must both be WITHOUT ROWID or not */ 205755548273Sdrh } 20589d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 205944266ec6Sdrh if( IsVirtual(pSrc) ){ 20609d9cf229Sdrh return 0; /* tab2 must not be a virtual table */ 20619d9cf229Sdrh } 20629d9cf229Sdrh #endif 20639d9cf229Sdrh if( pSrc->pSelect ){ 20649d9cf229Sdrh return 0; /* tab2 may not be a view */ 20659d9cf229Sdrh } 20669d9cf229Sdrh if( pDest->nCol!=pSrc->nCol ){ 20679d9cf229Sdrh return 0; /* Number of columns must be the same in tab1 and tab2 */ 20689d9cf229Sdrh } 20699d9cf229Sdrh if( pDest->iPKey!=pSrc->iPKey ){ 20709d9cf229Sdrh return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 20719d9cf229Sdrh } 20729d9cf229Sdrh for(i=0; i<pDest->nCol; i++){ 20739940e2aaSdan Column *pDestCol = &pDest->aCol[i]; 20749940e2aaSdan Column *pSrcCol = &pSrc->aCol[i]; 2075ba68f8f3Sdan #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS 20768257aa8dSdrh if( (db->mDbFlags & DBFLAG_Vacuum)==0 2077aaea3143Sdan && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN 2078aaea3143Sdan ){ 2079ba68f8f3Sdan return 0; /* Neither table may have __hidden__ columns */ 2080ba68f8f3Sdan } 2081ba68f8f3Sdan #endif 20829940e2aaSdan if( pDestCol->affinity!=pSrcCol->affinity ){ 20839d9cf229Sdrh return 0; /* Affinity must be the same on all columns */ 20849d9cf229Sdrh } 20850472af91Sdrh if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){ 20869d9cf229Sdrh return 0; /* Collating sequence must be the same on all columns */ 20879d9cf229Sdrh } 20889940e2aaSdan if( pDestCol->notNull && !pSrcCol->notNull ){ 20899d9cf229Sdrh return 0; /* tab2 must be NOT NULL if tab1 is */ 20909d9cf229Sdrh } 2091453e0261Sdrh /* Default values for second and subsequent columns need to match. */ 209294fa9c41Sdrh if( i>0 ){ 209394fa9c41Sdrh assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN ); 209494fa9c41Sdrh assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN ); 209594fa9c41Sdrh if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) 209694fa9c41Sdrh || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken, 209794fa9c41Sdrh pSrcCol->pDflt->u.zToken)!=0) 20989940e2aaSdan ){ 20999940e2aaSdan return 0; /* Default values must be the same for all columns */ 21009940e2aaSdan } 21019d9cf229Sdrh } 210294fa9c41Sdrh } 21039d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 21045f1d1d9cSdrh if( IsUniqueIndex(pDestIdx) ){ 2105f33c9fadSdrh destHasUniqueIdx = 1; 2106f33c9fadSdrh } 21079d9cf229Sdrh for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 21089d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 21099d9cf229Sdrh } 21109d9cf229Sdrh if( pSrcIdx==0 ){ 21119d9cf229Sdrh return 0; /* pDestIdx has no corresponding index in pSrc */ 21129d9cf229Sdrh } 21139d9cf229Sdrh } 21147fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK 2115619a1305Sdrh if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ 21168103b7d2Sdrh return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 21178103b7d2Sdrh } 21187fc2f41bSdrh #endif 2119713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY 2120713de341Sdrh /* Disallow the transfer optimization if the destination table constains 2121713de341Sdrh ** any foreign key constraints. This is more restrictive than necessary. 2122713de341Sdrh ** But the main beneficiary of the transfer optimization is the VACUUM 2123713de341Sdrh ** command, and the VACUUM command disables foreign key constraints. So 2124713de341Sdrh ** the extra complication to make this rule less restrictive is probably 2125713de341Sdrh ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] 2126713de341Sdrh */ 2127e34162b1Sdan if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ 2128713de341Sdrh return 0; 2129713de341Sdrh } 2130713de341Sdrh #endif 2131e34162b1Sdan if( (db->flags & SQLITE_CountRows)!=0 ){ 2132ccdf1baeSdrh return 0; /* xfer opt does not play well with PRAGMA count_changes */ 21331696124dSdan } 21349d9cf229Sdrh 2135ccdf1baeSdrh /* If we get this far, it means that the xfer optimization is at 2136ccdf1baeSdrh ** least a possibility, though it might only work if the destination 2137ccdf1baeSdrh ** table (tab1) is initially empty. 21389d9cf229Sdrh */ 2139dd73521bSdrh #ifdef SQLITE_TEST 2140dd73521bSdrh sqlite3_xferopt_count++; 2141dd73521bSdrh #endif 2142e34162b1Sdan iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); 21439d9cf229Sdrh v = sqlite3GetVdbe(pParse); 2144f53e9b5aSdrh sqlite3CodeVerifySchema(pParse, iDbSrc); 21459d9cf229Sdrh iSrc = pParse->nTab++; 21469d9cf229Sdrh iDest = pParse->nTab++; 21476a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 214855548273Sdrh regData = sqlite3GetTempReg(pParse); 214955548273Sdrh regRowid = sqlite3GetTempReg(pParse); 21509d9cf229Sdrh sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 2151427ebba1Sdan assert( HasRowid(pDest) || destHasUniqueIdx ); 21528257aa8dSdrh if( (db->mDbFlags & DBFLAG_Vacuum)==0 && ( 2153e34162b1Sdan (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ 2154ccdf1baeSdrh || destHasUniqueIdx /* (2) */ 2155ccdf1baeSdrh || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ 2156e34162b1Sdan )){ 2157ccdf1baeSdrh /* In some circumstances, we are able to run the xfer optimization 2158e34162b1Sdan ** only if the destination table is initially empty. Unless the 21598257aa8dSdrh ** DBFLAG_Vacuum flag is set, this block generates code to make 21608257aa8dSdrh ** that determination. If DBFLAG_Vacuum is set, then the destination 2161e34162b1Sdan ** table is always empty. 2162e34162b1Sdan ** 2163e34162b1Sdan ** Conditions under which the destination must be empty: 2164f33c9fadSdrh ** 2165ccdf1baeSdrh ** (1) There is no INTEGER PRIMARY KEY but there are indices. 2166ccdf1baeSdrh ** (If the destination is not initially empty, the rowid fields 2167ccdf1baeSdrh ** of index entries might need to change.) 2168ccdf1baeSdrh ** 2169ccdf1baeSdrh ** (2) The destination has a unique index. (The xfer optimization 2170ccdf1baeSdrh ** is unable to test uniqueness.) 2171ccdf1baeSdrh ** 2172ccdf1baeSdrh ** (3) onError is something other than OE_Abort and OE_Rollback. 21739d9cf229Sdrh */ 2174688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); 21752991ba05Sdrh emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); 21769d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 21779d9cf229Sdrh } 2178427ebba1Sdan if( HasRowid(pSrc) ){ 2179c9b9deaeSdrh u8 insFlags; 21809d9cf229Sdrh sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 2181688852abSdrh emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 218242242dedSdrh if( pDest->iPKey>=0 ){ 2183b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 2184b7654111Sdrh addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 2185688852abSdrh VdbeCoverage(v); 2186f9c8ce3cSdrh sqlite3RowidConstraint(pParse, onError, pDest); 21879d9cf229Sdrh sqlite3VdbeJumpHere(v, addr2); 2188b7654111Sdrh autoIncStep(pParse, regAutoinc, regRowid); 2189bd36ba69Sdrh }else if( pDest->pIndex==0 ){ 2190b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 219195bad4c7Sdrh }else{ 2192b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 21937d10d5a6Sdrh assert( (pDest->tabFlags & TF_Autoincrement)==0 ); 219495bad4c7Sdrh } 2195e7b554d6Sdrh sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); 21968257aa8dSdrh if( db->mDbFlags & DBFLAG_Vacuum ){ 219786b40dfdSdrh sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); 2198c9b9deaeSdrh insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID| 2199c9b9deaeSdrh OPFLAG_APPEND|OPFLAG_USESEEKRESULT; 2200c9b9deaeSdrh }else{ 2201c9b9deaeSdrh insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND; 2202c9b9deaeSdrh } 22039b34abeeSdrh sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid, 220420f272c9Sdrh (char*)pDest, P4_TABLE); 2205c9b9deaeSdrh sqlite3VdbeChangeP5(v, insFlags); 2206688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); 220755548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 220855548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2209da475b8dSdrh }else{ 2210da475b8dSdrh sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); 2211da475b8dSdrh sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); 221255548273Sdrh } 22139d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 221441b9ca25Sdrh u8 idxInsFlags = 0; 22151b7ecbb4Sdrh for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ 22169d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 22179d9cf229Sdrh } 22189d9cf229Sdrh assert( pSrcIdx ); 22192ec2fb22Sdrh sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); 22202ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); 2221d4e70ebdSdrh VdbeComment((v, "%s", pSrcIdx->zName)); 22222ec2fb22Sdrh sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); 22232ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); 222459885728Sdan sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); 2225207872a4Sdanielk1977 VdbeComment((v, "%s", pDestIdx->zName)); 2226688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2227e7b554d6Sdrh sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); 22288257aa8dSdrh if( db->mDbFlags & DBFLAG_Vacuum ){ 2229e34162b1Sdan /* This INSERT command is part of a VACUUM operation, which guarantees 2230e34162b1Sdan ** that the destination table is empty. If all indexed columns use 2231e34162b1Sdan ** collation sequence BINARY, then it can also be assumed that the 2232e34162b1Sdan ** index will be populated by inserting keys in strictly sorted 2233e34162b1Sdan ** order. In this case, instead of seeking within the b-tree as part 223486b40dfdSdrh ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the 2235e34162b1Sdan ** OP_IdxInsert to seek to the point within the b-tree where each key 2236e34162b1Sdan ** should be inserted. This is faster. 2237e34162b1Sdan ** 2238e34162b1Sdan ** If any of the indexed columns use a collation sequence other than 2239e34162b1Sdan ** BINARY, this optimization is disabled. This is because the user 2240e34162b1Sdan ** might change the definition of a collation sequence and then run 2241e34162b1Sdan ** a VACUUM command. In that case keys may not be written in strictly 2242e34162b1Sdan ** sorted order. */ 2243e34162b1Sdan for(i=0; i<pSrcIdx->nColumn; i++){ 2244f19aa5faSdrh const char *zColl = pSrcIdx->azColl[i]; 2245f19aa5faSdrh if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break; 2246e34162b1Sdan } 2247e34162b1Sdan if( i==pSrcIdx->nColumn ){ 224841b9ca25Sdrh idxInsFlags = OPFLAG_USESEEKRESULT; 224986b40dfdSdrh sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); 2250e34162b1Sdan } 2251e34162b1Sdan } 225241b9ca25Sdrh if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){ 225341b9ca25Sdrh idxInsFlags |= OPFLAG_NCHANGE; 225441b9ca25Sdrh } 22559b4eaebcSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData); 22569b4eaebcSdrh sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND); 2257688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); 22589d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 225955548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 226055548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 22619d9cf229Sdrh } 2262aceb31b1Sdrh if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); 2263b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 2264b7654111Sdrh sqlite3ReleaseTempReg(pParse, regData); 22659d9cf229Sdrh if( emptyDestTest ){ 22661dd518cfSdrh sqlite3AutoincrementEnd(pParse); 226766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 22689d9cf229Sdrh sqlite3VdbeJumpHere(v, emptyDestTest); 226966a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 22709d9cf229Sdrh return 0; 22719d9cf229Sdrh }else{ 22729d9cf229Sdrh return 1; 22739d9cf229Sdrh } 22749d9cf229Sdrh } 22759d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 2276