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); 41dd9930efSdrh 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 } 50ec95c441Sdrh } 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 ){ 86633e6d57Sdrh db->mallocFailed = 1; 8769f8bb9cSdan return 0; 88a37cdde0Sdanielk1977 } 89ad124329Sdrh 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 ){ 137633e6d57Sdrh db->mallocFailed = 1; 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 2030b9f50d8Sdrh ** that holds the maximum rowid. 2049d9cf229Sdrh ** 2050b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the 2060b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within 2070b9f50d8Sdrh ** triggers. A new AutoincInfo structure is created if this is the 2080b9f50d8Sdrh ** first use of table pTab. On 2nd and subsequent uses, the original 2090b9f50d8Sdrh ** AutoincInfo structure is used. 2109d9cf229Sdrh ** 2110b9f50d8Sdrh ** Three memory locations are allocated: 2120b9f50d8Sdrh ** 2130b9f50d8Sdrh ** (1) Register to hold the name of the pTab table. 2140b9f50d8Sdrh ** (2) Register to hold the maximum ROWID of pTab. 2150b9f50d8Sdrh ** (3) Register to hold the rowid in sqlite_sequence of pTab 2160b9f50d8Sdrh ** 2170b9f50d8Sdrh ** The 2nd register is the one that is returned. That is all the 2180b9f50d8Sdrh ** insert routine needs to know about. 2199d9cf229Sdrh */ 2209d9cf229Sdrh static int autoIncBegin( 2219d9cf229Sdrh Parse *pParse, /* Parsing context */ 2229d9cf229Sdrh int iDb, /* Index of the database holding pTab */ 2239d9cf229Sdrh Table *pTab /* The table we are writing to */ 2249d9cf229Sdrh ){ 2256a288a33Sdrh int memId = 0; /* Register holding maximum rowid */ 2267d10d5a6Sdrh if( pTab->tabFlags & TF_Autoincrement ){ 22765a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 2280b9f50d8Sdrh AutoincInfo *pInfo; 2290b9f50d8Sdrh 23065a7cd16Sdan pInfo = pToplevel->pAinc; 2310b9f50d8Sdrh while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } 2320b9f50d8Sdrh if( pInfo==0 ){ 2330b9f50d8Sdrh pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo)); 2340b9f50d8Sdrh if( pInfo==0 ) return 0; 23565a7cd16Sdan pInfo->pNext = pToplevel->pAinc; 23665a7cd16Sdan pToplevel->pAinc = pInfo; 2370b9f50d8Sdrh pInfo->pTab = pTab; 2380b9f50d8Sdrh pInfo->iDb = iDb; 23965a7cd16Sdan pToplevel->nMem++; /* Register to hold name of table */ 24065a7cd16Sdan pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ 24165a7cd16Sdan pToplevel->nMem++; /* Rowid in sqlite_sequence */ 2420b9f50d8Sdrh } 2430b9f50d8Sdrh memId = pInfo->regCtr; 2449d9cf229Sdrh } 2459d9cf229Sdrh return memId; 2469d9cf229Sdrh } 2479d9cf229Sdrh 2489d9cf229Sdrh /* 2490b9f50d8Sdrh ** This routine generates code that will initialize all of the 2500b9f50d8Sdrh ** register used by the autoincrement tracker. 2510b9f50d8Sdrh */ 2520b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){ 2530b9f50d8Sdrh AutoincInfo *p; /* Information about an AUTOINCREMENT */ 2540b9f50d8Sdrh sqlite3 *db = pParse->db; /* The database connection */ 2550b9f50d8Sdrh Db *pDb; /* Database only autoinc table */ 2560b9f50d8Sdrh int memId; /* Register holding max rowid */ 2570b9f50d8Sdrh int addr; /* A VDBE address */ 2580b9f50d8Sdrh Vdbe *v = pParse->pVdbe; /* VDBE under construction */ 2590b9f50d8Sdrh 260345ba7dbSdrh /* This routine is never called during trigger-generation. It is 261345ba7dbSdrh ** only called from the top-level */ 262345ba7dbSdrh assert( pParse->pTriggerTab==0 ); 263c149f18fSdrh assert( sqlite3IsToplevel(pParse) ); 26476d462eeSdan 2650b9f50d8Sdrh assert( v ); /* We failed long ago if this is not so */ 2660b9f50d8Sdrh for(p = pParse->pAinc; p; p = p->pNext){ 2670b9f50d8Sdrh pDb = &db->aDb[p->iDb]; 2680b9f50d8Sdrh memId = p->regCtr; 2692120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 2700b9f50d8Sdrh sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); 271f4d31bcbSdrh sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1); 2720b9f50d8Sdrh addr = sqlite3VdbeCurrentAddr(v); 273076e85f5Sdrh sqlite3VdbeLoadString(v, memId-1, p->pTab->zName); 274688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v); 2750b9f50d8Sdrh sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId); 276688852abSdrh sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v); 2770b9f50d8Sdrh sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); 2780b9f50d8Sdrh sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1); 2790b9f50d8Sdrh sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId); 280076e85f5Sdrh sqlite3VdbeGoto(v, addr+9); 281688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v); 2820b9f50d8Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, memId); 2830b9f50d8Sdrh sqlite3VdbeAddOp0(v, OP_Close); 2840b9f50d8Sdrh } 2850b9f50d8Sdrh } 2860b9f50d8Sdrh 2870b9f50d8Sdrh /* 2889d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation. 2899d9cf229Sdrh ** 2909d9cf229Sdrh ** This routine should be called when the top of the stack holds a 2919d9cf229Sdrh ** new rowid that is about to be inserted. If that new rowid is 2929d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the 2939d9cf229Sdrh ** memory cell is updated. The stack is unchanged. 2949d9cf229Sdrh */ 2956a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){ 2969d9cf229Sdrh if( memId>0 ){ 2976a288a33Sdrh sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); 2989d9cf229Sdrh } 2999d9cf229Sdrh } 3009d9cf229Sdrh 3019d9cf229Sdrh /* 3020b9f50d8Sdrh ** This routine generates the code needed to write autoincrement 3030b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register. 3040b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement 3050b9f50d8Sdrh ** table (either directly or through triggers) needs to call this 3060b9f50d8Sdrh ** routine just before the "exit" code. 3079d9cf229Sdrh */ 3080b9f50d8Sdrh void sqlite3AutoincrementEnd(Parse *pParse){ 3090b9f50d8Sdrh AutoincInfo *p; 3109d9cf229Sdrh Vdbe *v = pParse->pVdbe; 3110b9f50d8Sdrh sqlite3 *db = pParse->db; 3126a288a33Sdrh 3139d9cf229Sdrh assert( v ); 3140b9f50d8Sdrh for(p = pParse->pAinc; p; p = p->pNext){ 3150b9f50d8Sdrh Db *pDb = &db->aDb[p->iDb]; 316728e0f91Sdrh int addr1; 3170b9f50d8Sdrh int iRec; 3180b9f50d8Sdrh int memId = p->regCtr; 3190b9f50d8Sdrh 3200b9f50d8Sdrh iRec = sqlite3GetTempReg(pParse); 3212120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 3220b9f50d8Sdrh sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); 323728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v); 3240b9f50d8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1); 325728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 326a7a8e14bSdanielk1977 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec); 3270b9f50d8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1); 32835573356Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 3290b9f50d8Sdrh sqlite3VdbeAddOp0(v, OP_Close); 3300b9f50d8Sdrh sqlite3ReleaseTempReg(pParse, iRec); 3319d9cf229Sdrh } 3329d9cf229Sdrh } 3339d9cf229Sdrh #else 3349d9cf229Sdrh /* 3359d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines 3369d9cf229Sdrh ** above are all no-ops 3379d9cf229Sdrh */ 3389d9cf229Sdrh # define autoIncBegin(A,B,C) (0) 339287fb61cSdanielk1977 # define autoIncStep(A,B,C) 3409d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */ 3419d9cf229Sdrh 3429d9cf229Sdrh 3439d9cf229Sdrh /* Forward declaration */ 3449d9cf229Sdrh static int xferOptimization( 3459d9cf229Sdrh Parse *pParse, /* Parser context */ 3469d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 3479d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 3489d9cf229Sdrh int onError, /* How to handle constraint errors */ 3499d9cf229Sdrh int iDbDest /* The database of pDest */ 3509d9cf229Sdrh ); 3519d9cf229Sdrh 3523d1bfeaaSdanielk1977 /* 353d82b5021Sdrh ** This routine is called to handle SQL of the following forms: 354cce7d176Sdrh ** 355a21f78b9Sdrh ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),... 3561ccde15dSdrh ** insert into TABLE (IDLIST) select 357a21f78b9Sdrh ** insert into TABLE (IDLIST) default values 358cce7d176Sdrh ** 3591ccde15dSdrh ** The IDLIST following the table name is always optional. If omitted, 360a21f78b9Sdrh ** then a list of all (non-hidden) columns for the table is substituted. 361a21f78b9Sdrh ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST 362a21f78b9Sdrh ** is omitted. 3631ccde15dSdrh ** 364a21f78b9Sdrh ** For the pSelect parameter holds the values to be inserted for the 365a21f78b9Sdrh ** first two forms shown above. A VALUES clause is really just short-hand 366a21f78b9Sdrh ** for a SELECT statement that omits the FROM clause and everything else 367a21f78b9Sdrh ** that follows. If the pSelect parameter is NULL, that means that the 368a21f78b9Sdrh ** DEFAULT VALUES form of the INSERT statement is intended. 369142e30dfSdrh ** 3709d9cf229Sdrh ** The code generated follows one of four templates. For a simple 371a21f78b9Sdrh ** insert with data coming from a single-row VALUES clause, the code executes 372e00ee6ebSdrh ** once straight down through. Pseudo-code follows (we call this 373e00ee6ebSdrh ** the "1st template"): 374142e30dfSdrh ** 375142e30dfSdrh ** open write cursor to <table> and its indices 376ec95c441Sdrh ** put VALUES clause expressions into registers 377142e30dfSdrh ** write the resulting record into <table> 378142e30dfSdrh ** cleanup 379142e30dfSdrh ** 3809d9cf229Sdrh ** The three remaining templates assume the statement is of the form 381142e30dfSdrh ** 382142e30dfSdrh ** INSERT INTO <table> SELECT ... 383142e30dfSdrh ** 3849d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - 3859d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table 3869d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and 3879d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical 3889d9cf229Sdrh ** schemas, including all the same indices, then a special optimization 3899d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>. 3909d9cf229Sdrh ** See the xferOptimization() function for the implementation of this 391e00ee6ebSdrh ** template. This is the 2nd template. 3929d9cf229Sdrh ** 3939d9cf229Sdrh ** open a write cursor to <table> 3949d9cf229Sdrh ** open read cursor on <table2> 3959d9cf229Sdrh ** transfer all records in <table2> over to <table> 3969d9cf229Sdrh ** close cursors 3979d9cf229Sdrh ** foreach index on <table> 3989d9cf229Sdrh ** open a write cursor on the <table> index 3999d9cf229Sdrh ** open a read cursor on the corresponding <table2> index 4009d9cf229Sdrh ** transfer all records from the read to the write cursors 4019d9cf229Sdrh ** close cursors 4029d9cf229Sdrh ** end foreach 4039d9cf229Sdrh ** 404e00ee6ebSdrh ** The 3rd template is for when the second template does not apply 4059d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time. 4069d9cf229Sdrh ** The generated code follows this template: 407142e30dfSdrh ** 408e00ee6ebSdrh ** X <- A 409142e30dfSdrh ** goto B 410142e30dfSdrh ** A: setup for the SELECT 4119d9cf229Sdrh ** loop over the rows in the SELECT 412e00ee6ebSdrh ** load values into registers R..R+n 413e00ee6ebSdrh ** yield X 414142e30dfSdrh ** end loop 415142e30dfSdrh ** cleanup after the SELECT 41681cf13ecSdrh ** end-coroutine X 417e00ee6ebSdrh ** B: open write cursor to <table> and its indices 41881cf13ecSdrh ** C: yield X, at EOF goto D 419e00ee6ebSdrh ** insert the select result into <table> from R..R+n 420e00ee6ebSdrh ** goto C 421142e30dfSdrh ** D: cleanup 422142e30dfSdrh ** 423e00ee6ebSdrh ** The 4th template is used if the insert statement takes its 424142e30dfSdrh ** values from a SELECT but the data is being inserted into a table 425142e30dfSdrh ** that is also read as part of the SELECT. In the third form, 42660ec914cSpeter.d.reid ** we have to use an intermediate table to store the results of 427142e30dfSdrh ** the select. The template is like this: 428142e30dfSdrh ** 429e00ee6ebSdrh ** X <- A 430142e30dfSdrh ** goto B 431142e30dfSdrh ** A: setup for the SELECT 432142e30dfSdrh ** loop over the tables in the SELECT 433e00ee6ebSdrh ** load value into register R..R+n 434e00ee6ebSdrh ** yield X 435142e30dfSdrh ** end loop 436142e30dfSdrh ** cleanup after the SELECT 43781cf13ecSdrh ** end co-routine R 438e00ee6ebSdrh ** B: open temp table 43981cf13ecSdrh ** L: yield X, at EOF goto M 440e00ee6ebSdrh ** insert row from R..R+n into temp table 441e00ee6ebSdrh ** goto L 442e00ee6ebSdrh ** M: open write cursor to <table> and its indices 443e00ee6ebSdrh ** rewind temp table 444e00ee6ebSdrh ** C: loop over rows of intermediate table 445142e30dfSdrh ** transfer values form intermediate table into <table> 446e00ee6ebSdrh ** end loop 447e00ee6ebSdrh ** D: cleanup 448cce7d176Sdrh */ 4494adee20fSdanielk1977 void sqlite3Insert( 450cce7d176Sdrh Parse *pParse, /* Parser context */ 451113088ecSdrh SrcList *pTabList, /* Name of table into which we are inserting */ 4525974a30fSdrh Select *pSelect, /* A SELECT statement to use as the data source */ 4539cfcf5d4Sdrh IdList *pColumn, /* Column names corresponding to IDLIST. */ 4549cfcf5d4Sdrh int onError /* How to handle constraint errors */ 455cce7d176Sdrh ){ 4566a288a33Sdrh sqlite3 *db; /* The main database structure */ 4576a288a33Sdrh Table *pTab; /* The table to insert into. aka TABLE */ 458113088ecSdrh char *zTab; /* Name of the table into which we are inserting */ 459e22a334bSdrh const char *zDb; /* Name of the database holding this table */ 4605974a30fSdrh int i, j, idx; /* Loop counters */ 4615974a30fSdrh Vdbe *v; /* Generate code into this virtual machine */ 4625974a30fSdrh Index *pIdx; /* For looping over indices of the table */ 463967e8b73Sdrh int nColumn; /* Number of columns in the data */ 4646a288a33Sdrh int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ 46526198bb4Sdrh int iDataCur = 0; /* VDBE cursor that is the main data repository */ 46626198bb4Sdrh int iIdxCur = 0; /* First index cursor */ 467d82b5021Sdrh int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ 4680ca3e24bSdrh int endOfLoop; /* Label for the end of the insertion loop */ 469cfe9a69fSdanielk1977 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ 470e00ee6ebSdrh int addrInsTop = 0; /* Jump to label "D" */ 471e00ee6ebSdrh int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ 4722eb95377Sdrh SelectDest dest; /* Destination for SELECT on rhs of INSERT */ 4736a288a33Sdrh int iDb; /* Index of database holding TABLE */ 4742958a4e6Sdrh Db *pDb; /* The database containing table being inserted into */ 47505a86c5cSdrh u8 useTempTable = 0; /* Store SELECT results in intermediate table */ 47605a86c5cSdrh u8 appendFlag = 0; /* True if the insert is likely to be an append */ 47705a86c5cSdrh u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ 478a21f78b9Sdrh u8 bIdListInOrder; /* True if IDLIST is in table order */ 47975593d96Sdrh ExprList *pList = 0; /* List of VALUES() to be inserted */ 480cce7d176Sdrh 4816a288a33Sdrh /* Register allocations */ 4821bd10f8aSdrh int regFromSelect = 0;/* Base register for data coming from SELECT */ 4836a288a33Sdrh int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ 4846a288a33Sdrh int regRowCount = 0; /* Memory cell used for the row counter */ 4856a288a33Sdrh int regIns; /* Block of regs holding rowid+data being inserted */ 4866a288a33Sdrh int regRowid; /* registers holding insert rowid */ 4876a288a33Sdrh int regData; /* register holding first column to insert */ 488aa9b8963Sdrh int *aRegIdx = 0; /* One register allocated to each index */ 4896a288a33Sdrh 490798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER 491798da52cSdrh int isView; /* True if attempting to insert into a view */ 4922f886d1dSdanielk1977 Trigger *pTrigger; /* List of triggers on pTab, if required */ 4932f886d1dSdanielk1977 int tmask; /* Mask of trigger times */ 494798da52cSdrh #endif 495c3f9bad2Sdanielk1977 49617435752Sdrh db = pParse->db; 4971bd10f8aSdrh memset(&dest, 0, sizeof(dest)); 49817435752Sdrh if( pParse->nErr || db->mallocFailed ){ 4996f7adc8aSdrh goto insert_cleanup; 5006f7adc8aSdrh } 501daffd0e5Sdrh 50275593d96Sdrh /* If the Select object is really just a simple VALUES() list with a 503a21f78b9Sdrh ** single row (the common case) then keep that one row of values 504a21f78b9Sdrh ** and discard the other (unused) parts of the pSelect object 50575593d96Sdrh */ 50675593d96Sdrh if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){ 50775593d96Sdrh pList = pSelect->pEList; 50875593d96Sdrh pSelect->pEList = 0; 50975593d96Sdrh sqlite3SelectDelete(db, pSelect); 51075593d96Sdrh pSelect = 0; 51175593d96Sdrh } 51275593d96Sdrh 5131ccde15dSdrh /* Locate the table into which we will be inserting new information. 5141ccde15dSdrh */ 515113088ecSdrh assert( pTabList->nSrc==1 ); 516113088ecSdrh zTab = pTabList->a[0].zName; 517098d1684Sdrh if( NEVER(zTab==0) ) goto insert_cleanup; 5184adee20fSdanielk1977 pTab = sqlite3SrcListLookup(pParse, pTabList); 519c3f9bad2Sdanielk1977 if( pTab==0 ){ 520c3f9bad2Sdanielk1977 goto insert_cleanup; 521c3f9bad2Sdanielk1977 } 522da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 523da184236Sdanielk1977 assert( iDb<db->nDb ); 524da184236Sdanielk1977 pDb = &db->aDb[iDb]; 5252958a4e6Sdrh zDb = pDb->zName; 5264adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ 5271962bda7Sdrh goto insert_cleanup; 5281962bda7Sdrh } 529ec95c441Sdrh withoutRowid = !HasRowid(pTab); 530c3f9bad2Sdanielk1977 531b7f9164eSdrh /* Figure out if we have any triggers and if the table being 532b7f9164eSdrh ** inserted into is a view 533b7f9164eSdrh */ 534b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER 5352f886d1dSdanielk1977 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); 536b7f9164eSdrh isView = pTab->pSelect!=0; 537b7f9164eSdrh #else 5382f886d1dSdanielk1977 # define pTrigger 0 5392f886d1dSdanielk1977 # define tmask 0 540b7f9164eSdrh # define isView 0 541b7f9164eSdrh #endif 542b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW 543b7f9164eSdrh # undef isView 544b7f9164eSdrh # define isView 0 545b7f9164eSdrh #endif 5462f886d1dSdanielk1977 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); 547b7f9164eSdrh 548f573c99bSdrh /* If pTab is really a view, make sure it has been initialized. 549d82b5021Sdrh ** ViewGetColumnNames() is a no-op if pTab is not a view. 550f573c99bSdrh */ 551b3d24bf8Sdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 552f573c99bSdrh goto insert_cleanup; 553f573c99bSdrh } 554f573c99bSdrh 555d82b5021Sdrh /* Cannot insert into a read-only table. 556595a523aSdanielk1977 */ 557595a523aSdanielk1977 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ 558595a523aSdanielk1977 goto insert_cleanup; 559595a523aSdanielk1977 } 560595a523aSdanielk1977 5611ccde15dSdrh /* Allocate a VDBE 5621ccde15dSdrh */ 5634adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 5645974a30fSdrh if( v==0 ) goto insert_cleanup; 5654794f735Sdrh if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 5662f886d1dSdanielk1977 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); 5671ccde15dSdrh 5689d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 5699d9cf229Sdrh /* If the statement is of the form 5709d9cf229Sdrh ** 5719d9cf229Sdrh ** INSERT INTO <table1> SELECT * FROM <table2>; 5729d9cf229Sdrh ** 5739d9cf229Sdrh ** Then special optimizations can be applied that make the transfer 5749d9cf229Sdrh ** very fast and which reduce fragmentation of indices. 575e00ee6ebSdrh ** 576e00ee6ebSdrh ** This is the 2nd template. 5779d9cf229Sdrh */ 578ebbf08a0Sdan if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ 5792f886d1dSdanielk1977 assert( !pTrigger ); 5809d9cf229Sdrh assert( pList==0 ); 5810b9f50d8Sdrh goto insert_end; 5829d9cf229Sdrh } 5839d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 5849d9cf229Sdrh 5852958a4e6Sdrh /* If this is an AUTOINCREMENT table, look up the sequence number in the 5866a288a33Sdrh ** sqlite_sequence table and store it in memory cell regAutoinc. 5872958a4e6Sdrh */ 5886a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDb, pTab); 5892958a4e6Sdrh 59005a86c5cSdrh /* Allocate registers for holding the rowid of the new row, 59160ec914cSpeter.d.reid ** the content of the new row, and the assembled row record. 59205a86c5cSdrh */ 59305a86c5cSdrh regRowid = regIns = pParse->nMem+1; 59405a86c5cSdrh pParse->nMem += pTab->nCol + 1; 59505a86c5cSdrh if( IsVirtual(pTab) ){ 59605a86c5cSdrh regRowid++; 59705a86c5cSdrh pParse->nMem++; 59805a86c5cSdrh } 59905a86c5cSdrh regData = regRowid+1; 60005a86c5cSdrh 60105a86c5cSdrh /* If the INSERT statement included an IDLIST term, then make sure 60205a86c5cSdrh ** all elements of the IDLIST really are columns of the table and 60305a86c5cSdrh ** remember the column indices. 60405a86c5cSdrh ** 60505a86c5cSdrh ** If the table has an INTEGER PRIMARY KEY column and that column 60605a86c5cSdrh ** is named in the IDLIST, then record in the ipkColumn variable 60705a86c5cSdrh ** the index into IDLIST of the primary key column. ipkColumn is 60805a86c5cSdrh ** the index of the primary key as it appears in IDLIST, not as 60905a86c5cSdrh ** is appears in the original table. (The index of the INTEGER 61005a86c5cSdrh ** PRIMARY KEY in the original table is pTab->iPKey.) 61105a86c5cSdrh */ 612a21f78b9Sdrh bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0; 61305a86c5cSdrh if( pColumn ){ 61405a86c5cSdrh for(i=0; i<pColumn->nId; i++){ 61505a86c5cSdrh pColumn->a[i].idx = -1; 61605a86c5cSdrh } 61705a86c5cSdrh for(i=0; i<pColumn->nId; i++){ 61805a86c5cSdrh for(j=0; j<pTab->nCol; j++){ 61905a86c5cSdrh if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ 62005a86c5cSdrh pColumn->a[i].idx = j; 62105a86c5cSdrh if( i!=j ) bIdListInOrder = 0; 62205a86c5cSdrh if( j==pTab->iPKey ){ 62305a86c5cSdrh ipkColumn = i; assert( !withoutRowid ); 62405a86c5cSdrh } 62505a86c5cSdrh break; 62605a86c5cSdrh } 62705a86c5cSdrh } 62805a86c5cSdrh if( j>=pTab->nCol ){ 62905a86c5cSdrh if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ 63005a86c5cSdrh ipkColumn = i; 631e48ae715Sdrh bIdListInOrder = 0; 63205a86c5cSdrh }else{ 63305a86c5cSdrh sqlite3ErrorMsg(pParse, "table %S has no column named %s", 63405a86c5cSdrh pTabList, 0, pColumn->a[i].zName); 63505a86c5cSdrh pParse->checkSchema = 1; 63605a86c5cSdrh goto insert_cleanup; 63705a86c5cSdrh } 63805a86c5cSdrh } 63905a86c5cSdrh } 64005a86c5cSdrh } 64105a86c5cSdrh 6421ccde15dSdrh /* Figure out how many columns of data are supplied. If the data 643e00ee6ebSdrh ** is coming from a SELECT statement, then generate a co-routine that 644e00ee6ebSdrh ** produces a single row of the SELECT on each invocation. The 645e00ee6ebSdrh ** co-routine is the common header to the 3rd and 4th templates. 6461ccde15dSdrh */ 6475974a30fSdrh if( pSelect ){ 648a21f78b9Sdrh /* Data is coming from a SELECT or from a multi-row VALUES clause. 649a21f78b9Sdrh ** Generate a co-routine to run the SELECT. */ 65005a86c5cSdrh int regYield; /* Register holding co-routine entry-point */ 65105a86c5cSdrh int addrTop; /* Top of the co-routine */ 65205a86c5cSdrh int rc; /* Result code */ 6531013c932Sdrh 65405a86c5cSdrh regYield = ++pParse->nMem; 65505a86c5cSdrh addrTop = sqlite3VdbeCurrentAddr(v) + 1; 65605a86c5cSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 65705a86c5cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 65805a86c5cSdrh dest.iSdst = bIdListInOrder ? regData : 0; 65905a86c5cSdrh dest.nSdst = pTab->nCol; 66005a86c5cSdrh rc = sqlite3Select(pParse, pSelect, &dest); 6612b596da8Sdrh regFromSelect = dest.iSdst; 662992590beSdrh if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup; 66305a86c5cSdrh sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield); 66405a86c5cSdrh sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ 6655974a30fSdrh assert( pSelect->pEList ); 666967e8b73Sdrh nColumn = pSelect->pEList->nExpr; 667142e30dfSdrh 668142e30dfSdrh /* Set useTempTable to TRUE if the result of the SELECT statement 669e00ee6ebSdrh ** should be written into a temporary table (template 4). Set to 670d82b5021Sdrh ** FALSE if each output row of the SELECT can be written directly into 671e00ee6ebSdrh ** the destination table (template 3). 672048c530cSdrh ** 673048c530cSdrh ** A temp table must be used if the table being updated is also one 674048c530cSdrh ** of the tables being read by the SELECT statement. Also use a 675048c530cSdrh ** temp table in the case of row triggers. 676142e30dfSdrh */ 67705a86c5cSdrh if( pTrigger || readsTable(pParse, iDb, pTab) ){ 678048c530cSdrh useTempTable = 1; 679048c530cSdrh } 680142e30dfSdrh 681142e30dfSdrh if( useTempTable ){ 682e00ee6ebSdrh /* Invoke the coroutine to extract information from the SELECT 683e00ee6ebSdrh ** and add it to a transient table srcTab. The code generated 684e00ee6ebSdrh ** here is from the 4th template: 685e00ee6ebSdrh ** 686e00ee6ebSdrh ** B: open temp table 68781cf13ecSdrh ** L: yield X, goto M at EOF 688e00ee6ebSdrh ** insert row from R..R+n into temp table 689e00ee6ebSdrh ** goto L 690e00ee6ebSdrh ** M: ... 691142e30dfSdrh */ 692e00ee6ebSdrh int regRec; /* Register to hold packed record */ 693dc5ea5c7Sdrh int regTempRowid; /* Register to hold temp table ROWID */ 69406280ee5Sdrh int addrL; /* Label "L" */ 695b7654111Sdrh 696142e30dfSdrh srcTab = pParse->nTab++; 697b7654111Sdrh regRec = sqlite3GetTempReg(pParse); 698dc5ea5c7Sdrh regTempRowid = sqlite3GetTempReg(pParse); 699e00ee6ebSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); 70006280ee5Sdrh addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); 7011db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); 702dc5ea5c7Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); 703dc5ea5c7Sdrh sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); 704076e85f5Sdrh sqlite3VdbeGoto(v, addrL); 70506280ee5Sdrh sqlite3VdbeJumpHere(v, addrL); 706b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRec); 707dc5ea5c7Sdrh sqlite3ReleaseTempReg(pParse, regTempRowid); 708142e30dfSdrh } 709142e30dfSdrh }else{ 710a21f78b9Sdrh /* This is the case if the data for the INSERT is coming from a 711a21f78b9Sdrh ** single-row VALUES clause 712142e30dfSdrh */ 713b3bce662Sdanielk1977 NameContext sNC; 714b3bce662Sdanielk1977 memset(&sNC, 0, sizeof(sNC)); 715b3bce662Sdanielk1977 sNC.pParse = pParse; 7165974a30fSdrh srcTab = -1; 71748d1178aSdrh assert( useTempTable==0 ); 718fea870beSdrh if( pList ){ 719fea870beSdrh nColumn = pList->nExpr; 720fea870beSdrh if( sqlite3ResolveExprListNames(&sNC, pList) ){ 721b04a5d87Sdrh goto insert_cleanup; 722b04a5d87Sdrh } 723fea870beSdrh }else{ 724fea870beSdrh nColumn = 0; 725e64e7b20Sdrh } 7265974a30fSdrh } 7271ccde15dSdrh 72805a86c5cSdrh /* If there is no IDLIST term but the table has an integer primary 72905a86c5cSdrh ** key, the set the ipkColumn variable to the integer primary key 73005a86c5cSdrh ** column index in the original table definition. 73105a86c5cSdrh */ 73205a86c5cSdrh if( pColumn==0 && nColumn>0 ){ 73305a86c5cSdrh ipkColumn = pTab->iPKey; 73405a86c5cSdrh } 73505a86c5cSdrh 7361ccde15dSdrh /* Make sure the number of columns in the source data matches the number 7371ccde15dSdrh ** of columns to be inserted into the table. 7381ccde15dSdrh */ 739034ca14fSdanielk1977 if( IsVirtual(pTab) ){ 740034ca14fSdanielk1977 for(i=0; i<pTab->nCol; i++){ 741034ca14fSdanielk1977 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); 742034ca14fSdanielk1977 } 743034ca14fSdanielk1977 } 744034ca14fSdanielk1977 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ 7454adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 746da93d238Sdrh "table %S has %d columns but %d values were supplied", 747d51397a6Sdrh pTabList, 0, pTab->nCol-nHidden, nColumn); 748cce7d176Sdrh goto insert_cleanup; 749cce7d176Sdrh } 750967e8b73Sdrh if( pColumn!=0 && nColumn!=pColumn->nId ){ 7514adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 752cce7d176Sdrh goto insert_cleanup; 753cce7d176Sdrh } 7541ccde15dSdrh 755c3f9bad2Sdanielk1977 /* Initialize the count of rows to be inserted 7561ccde15dSdrh */ 757142e30dfSdrh if( db->flags & SQLITE_CountRows ){ 7586a288a33Sdrh regRowCount = ++pParse->nMem; 7596a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 760c3f9bad2Sdanielk1977 } 761c3f9bad2Sdanielk1977 762e448dc4aSdanielk1977 /* If this is not a view, open the table and and all indices */ 763e448dc4aSdanielk1977 if( !isView ){ 764aa9b8963Sdrh int nIdx; 765*fd261ec6Sdan nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0, 76626198bb4Sdrh &iDataCur, &iIdxCur); 7675c070538Sdrh aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); 768aa9b8963Sdrh if( aRegIdx==0 ){ 769aa9b8963Sdrh goto insert_cleanup; 770aa9b8963Sdrh } 771aa9b8963Sdrh for(i=0; i<nIdx; i++){ 772aa9b8963Sdrh aRegIdx[i] = ++pParse->nMem; 773aa9b8963Sdrh } 774feeb1394Sdrh } 775feeb1394Sdrh 776e00ee6ebSdrh /* This is the top of the main insertion loop */ 777142e30dfSdrh if( useTempTable ){ 778e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 779e00ee6ebSdrh ** following pseudocode (template 4): 780e00ee6ebSdrh ** 78181cf13ecSdrh ** rewind temp table, if empty goto D 782e00ee6ebSdrh ** C: loop over rows of intermediate table 783e00ee6ebSdrh ** transfer values form intermediate table into <table> 784e00ee6ebSdrh ** end loop 785e00ee6ebSdrh ** D: ... 786e00ee6ebSdrh */ 787688852abSdrh addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); 788e00ee6ebSdrh addrCont = sqlite3VdbeCurrentAddr(v); 789142e30dfSdrh }else if( pSelect ){ 790e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 791e00ee6ebSdrh ** following pseudocode (template 3): 792e00ee6ebSdrh ** 79381cf13ecSdrh ** C: yield X, at EOF goto D 794e00ee6ebSdrh ** insert the select result into <table> from R..R+n 795e00ee6ebSdrh ** goto C 796e00ee6ebSdrh ** D: ... 797e00ee6ebSdrh */ 79881cf13ecSdrh addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 799688852abSdrh VdbeCoverage(v); 800bed8690fSdrh } 8011ccde15dSdrh 8025cf590c1Sdrh /* Run the BEFORE and INSTEAD OF triggers, if there are any 80370ce3f0cSdrh */ 8044adee20fSdanielk1977 endOfLoop = sqlite3VdbeMakeLabel(v); 8052f886d1dSdanielk1977 if( tmask & TRIGGER_BEFORE ){ 80676d462eeSdan int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); 807c3f9bad2Sdanielk1977 80870ce3f0cSdrh /* build the NEW.* reference row. Note that if there is an INTEGER 80970ce3f0cSdrh ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 81070ce3f0cSdrh ** translated into a unique ID for the row. But on a BEFORE trigger, 81170ce3f0cSdrh ** we do not know what the unique ID will be (because the insert has 81270ce3f0cSdrh ** not happened yet) so we substitute a rowid of -1 81370ce3f0cSdrh */ 814d82b5021Sdrh if( ipkColumn<0 ){ 81576d462eeSdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 81670ce3f0cSdrh }else{ 817728e0f91Sdrh int addr1; 818ec95c441Sdrh assert( !withoutRowid ); 8197fe45908Sdrh if( useTempTable ){ 820d82b5021Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); 8217fe45908Sdrh }else{ 822d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 823d82b5021Sdrh sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); 8247fe45908Sdrh } 825728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); 82676d462eeSdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 827728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 828688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); 82970ce3f0cSdrh } 83070ce3f0cSdrh 831034ca14fSdanielk1977 /* Cannot have triggers on a virtual table. If it were possible, 832034ca14fSdanielk1977 ** this block would have to account for hidden column. 833034ca14fSdanielk1977 */ 834034ca14fSdanielk1977 assert( !IsVirtual(pTab) ); 835034ca14fSdanielk1977 83670ce3f0cSdrh /* Create the new column data 83770ce3f0cSdrh */ 838c3f9bad2Sdanielk1977 for(i=0; i<pTab->nCol; i++){ 839c3f9bad2Sdanielk1977 if( pColumn==0 ){ 840c3f9bad2Sdanielk1977 j = i; 841c3f9bad2Sdanielk1977 }else{ 842c3f9bad2Sdanielk1977 for(j=0; j<pColumn->nId; j++){ 843c3f9bad2Sdanielk1977 if( pColumn->a[j].idx==i ) break; 844c3f9bad2Sdanielk1977 } 845c3f9bad2Sdanielk1977 } 8467ba45971Sdan if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){ 84776d462eeSdan sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1); 848142e30dfSdrh }else if( useTempTable ){ 84976d462eeSdan sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 850c3f9bad2Sdanielk1977 }else{ 851d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 85276d462eeSdan sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); 853c3f9bad2Sdanielk1977 } 854c3f9bad2Sdanielk1977 } 855a37cdde0Sdanielk1977 856a37cdde0Sdanielk1977 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 857a37cdde0Sdanielk1977 ** do not attempt any conversions before assembling the record. 858a37cdde0Sdanielk1977 ** If this is a real table, attempt conversions as required by the 859a37cdde0Sdanielk1977 ** table column affinities. 860a37cdde0Sdanielk1977 */ 861a37cdde0Sdanielk1977 if( !isView ){ 86257bf4a8eSdrh sqlite3TableAffinity(v, pTab, regCols+1); 863a37cdde0Sdanielk1977 } 864c3f9bad2Sdanielk1977 8655cf590c1Sdrh /* Fire BEFORE or INSTEAD OF triggers */ 866165921a7Sdan sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 86794d7f50aSdan pTab, regCols-pTab->nCol-1, onError, endOfLoop); 868165921a7Sdan 86976d462eeSdan sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); 87070ce3f0cSdrh } 871c3f9bad2Sdanielk1977 872d82b5021Sdrh /* Compute the content of the next row to insert into a range of 873d82b5021Sdrh ** registers beginning at regIns. 8741ccde15dSdrh */ 8755cf590c1Sdrh if( !isView ){ 8764cbdda9eSdrh if( IsVirtual(pTab) ){ 8774cbdda9eSdrh /* The row that the VUpdate opcode will delete: none */ 8786a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); 8794cbdda9eSdrh } 880d82b5021Sdrh if( ipkColumn>=0 ){ 881142e30dfSdrh if( useTempTable ){ 882d82b5021Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); 883142e30dfSdrh }else if( pSelect ){ 88405a86c5cSdrh sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); 8854a32431cSdrh }else{ 886e4d90813Sdrh VdbeOp *pOp; 887d82b5021Sdrh sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); 88820411ea7Sdrh pOp = sqlite3VdbeGetOp(v, -1); 8891b7ecbb4Sdrh if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ 890e4d90813Sdrh appendFlag = 1; 891e4d90813Sdrh pOp->opcode = OP_NewRowid; 89226198bb4Sdrh pOp->p1 = iDataCur; 8936a288a33Sdrh pOp->p2 = regRowid; 8946a288a33Sdrh pOp->p3 = regAutoinc; 895e4d90813Sdrh } 89627a32783Sdrh } 897f0863fe5Sdrh /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 898e1e68f49Sdrh ** to generate a unique primary key value. 899e1e68f49Sdrh */ 900e4d90813Sdrh if( !appendFlag ){ 901728e0f91Sdrh int addr1; 902bb50e7adSdanielk1977 if( !IsVirtual(pTab) ){ 903728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); 90426198bb4Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 905728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 906bb50e7adSdanielk1977 }else{ 907728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 908728e0f91Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); 909bb50e7adSdanielk1977 } 910688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); 911e4d90813Sdrh } 912ec95c441Sdrh }else if( IsVirtual(pTab) || withoutRowid ){ 9136a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); 9144a32431cSdrh }else{ 91526198bb4Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 916e4d90813Sdrh appendFlag = 1; 9174a32431cSdrh } 9186a288a33Sdrh autoIncStep(pParse, regAutoinc, regRowid); 9194a32431cSdrh 920d82b5021Sdrh /* Compute data for all columns of the new entry, beginning 9214a32431cSdrh ** with the first column. 9224a32431cSdrh */ 923034ca14fSdanielk1977 nHidden = 0; 924cce7d176Sdrh for(i=0; i<pTab->nCol; i++){ 9256a288a33Sdrh int iRegStore = regRowid+1+i; 9264a32431cSdrh if( i==pTab->iPKey ){ 9274a32431cSdrh /* The value of the INTEGER PRIMARY KEY column is always a NULL. 928d82b5021Sdrh ** Whenever this column is read, the rowid will be substituted 929d82b5021Sdrh ** in its place. Hence, fill this column with a NULL to avoid 93005a86c5cSdrh ** taking up data space with information that will never be used. 93105a86c5cSdrh ** As there may be shallow copies of this value, make it a soft-NULL */ 93205a86c5cSdrh sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); 9334a32431cSdrh continue; 9344a32431cSdrh } 935967e8b73Sdrh if( pColumn==0 ){ 936034ca14fSdanielk1977 if( IsHiddenColumn(&pTab->aCol[i]) ){ 937034ca14fSdanielk1977 assert( IsVirtual(pTab) ); 938034ca14fSdanielk1977 j = -1; 939034ca14fSdanielk1977 nHidden++; 940034ca14fSdanielk1977 }else{ 941034ca14fSdanielk1977 j = i - nHidden; 942034ca14fSdanielk1977 } 943cce7d176Sdrh }else{ 944967e8b73Sdrh for(j=0; j<pColumn->nId; j++){ 945967e8b73Sdrh if( pColumn->a[j].idx==i ) break; 946cce7d176Sdrh } 947cce7d176Sdrh } 948034ca14fSdanielk1977 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ 94905a86c5cSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 950142e30dfSdrh }else if( useTempTable ){ 951287fb61cSdanielk1977 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 952142e30dfSdrh }else if( pSelect ){ 95305a86c5cSdrh if( regFromSelect!=regData ){ 954b7654111Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); 95505a86c5cSdrh } 956cce7d176Sdrh }else{ 957287fb61cSdanielk1977 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); 958cce7d176Sdrh } 959cce7d176Sdrh } 9601ccde15dSdrh 9610ca3e24bSdrh /* Generate code to check constraints and generate index keys and 9620ca3e24bSdrh ** do the insertion. 9634a32431cSdrh */ 9644cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 9654cbdda9eSdrh if( IsVirtual(pTab) ){ 966595a523aSdanielk1977 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 9674f3dd150Sdrh sqlite3VtabMakeWritable(pParse, pTab); 968595a523aSdanielk1977 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); 969b061d058Sdan sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); 970e0af83acSdan sqlite3MayAbort(pParse); 9714cbdda9eSdrh }else 9724cbdda9eSdrh #endif 9734cbdda9eSdrh { 974de630353Sdanielk1977 int isReplace; /* Set to true if constraints may cause a replace */ 975f8ffb278Sdrh sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, 976f8ffb278Sdrh regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace 97704adf416Sdrh ); 9788ff2d956Sdan sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); 97926198bb4Sdrh sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, 98026198bb4Sdrh regIns, aRegIdx, 0, appendFlag, isReplace==0); 9815cf590c1Sdrh } 9824cbdda9eSdrh } 9831bee3d7bSdrh 984feeb1394Sdrh /* Update the count of rows that are inserted 9851bee3d7bSdrh */ 986142e30dfSdrh if( (db->flags & SQLITE_CountRows)!=0 ){ 9876a288a33Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 9881bee3d7bSdrh } 989c3f9bad2Sdanielk1977 9902f886d1dSdanielk1977 if( pTrigger ){ 991c3f9bad2Sdanielk1977 /* Code AFTER triggers */ 992165921a7Sdan sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 99394d7f50aSdan pTab, regData-2-pTab->nCol, onError, endOfLoop); 994c3f9bad2Sdanielk1977 } 9951bee3d7bSdrh 996e00ee6ebSdrh /* The bottom of the main insertion loop, if the data source 997e00ee6ebSdrh ** is a SELECT statement. 9981ccde15dSdrh */ 9994adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, endOfLoop); 1000142e30dfSdrh if( useTempTable ){ 1001688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); 1002e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 10032eb95377Sdrh sqlite3VdbeAddOp1(v, OP_Close, srcTab); 1004142e30dfSdrh }else if( pSelect ){ 1005076e85f5Sdrh sqlite3VdbeGoto(v, addrCont); 1006e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 10076b56344dSdrh } 1008c3f9bad2Sdanielk1977 1009e448dc4aSdanielk1977 if( !IsVirtual(pTab) && !isView ){ 1010c3f9bad2Sdanielk1977 /* Close all tables opened */ 101126198bb4Sdrh if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur); 101226198bb4Sdrh for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ 101326198bb4Sdrh sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur); 1014cce7d176Sdrh } 1015c3f9bad2Sdanielk1977 } 1016c3f9bad2Sdanielk1977 10170b9f50d8Sdrh insert_end: 1018f3388144Sdrh /* Update the sqlite_sequence table by storing the content of the 10190b9f50d8Sdrh ** maximum rowid counter values recorded while inserting into 10200b9f50d8Sdrh ** autoincrement tables. 10212958a4e6Sdrh */ 1022165921a7Sdan if( pParse->nested==0 && pParse->pTriggerTab==0 ){ 10230b9f50d8Sdrh sqlite3AutoincrementEnd(pParse); 10240b9f50d8Sdrh } 10252958a4e6Sdrh 10261bee3d7bSdrh /* 1027e7de6f25Sdanielk1977 ** Return the number of rows inserted. If this routine is 1028e7de6f25Sdanielk1977 ** generating code because of a call to sqlite3NestedParse(), do not 1029e7de6f25Sdanielk1977 ** invoke the callback function. 10301bee3d7bSdrh */ 1031165921a7Sdan if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ 10326a288a33Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); 103322322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, 1); 103410fb749bSdanielk1977 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); 10351bee3d7bSdrh } 1036cce7d176Sdrh 1037cce7d176Sdrh insert_cleanup: 1038633e6d57Sdrh sqlite3SrcListDelete(db, pTabList); 1039633e6d57Sdrh sqlite3ExprListDelete(db, pList); 1040633e6d57Sdrh sqlite3SelectDelete(db, pSelect); 1041633e6d57Sdrh sqlite3IdListDelete(db, pColumn); 1042633e6d57Sdrh sqlite3DbFree(db, aRegIdx); 1043cce7d176Sdrh } 10449cfcf5d4Sdrh 104575cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise 104660ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file 104775cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation). */ 104875cbd984Sdan #ifdef isView 104975cbd984Sdan #undef isView 105075cbd984Sdan #endif 105175cbd984Sdan #ifdef pTrigger 105275cbd984Sdan #undef pTrigger 105375cbd984Sdan #endif 105475cbd984Sdan #ifdef tmask 105575cbd984Sdan #undef tmask 105675cbd984Sdan #endif 105775cbd984Sdan 105811e85273Sdrh /* 10596934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE 10606934fc7bSdrh ** on table pTab. 10619cfcf5d4Sdrh ** 10626934fc7bSdrh ** The regNewData parameter is the first register in a range that contains 10636934fc7bSdrh ** the data to be inserted or the data after the update. There will be 10646934fc7bSdrh ** pTab->nCol+1 registers in this range. The first register (the one 10656934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the 10666934fc7bSdrh ** case of a WITHOUT ROWID table. The second register in the range will 10676934fc7bSdrh ** contain the content of the first table column. The third register will 10686934fc7bSdrh ** contain the content of the second table column. And so forth. 10690ca3e24bSdrh ** 1070f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains 1071f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards. regOldData is zero 1072f8ffb278Sdrh ** for an INSERT. This routine can distinguish between UPDATE and INSERT by 1073f8ffb278Sdrh ** checking regOldData for zero. 10740ca3e24bSdrh ** 1075f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the 1076f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) 1077f8ffb278Sdrh ** might be modified by the UPDATE. If pkChng is false, then the key of 1078f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE. 1079f8ffb278Sdrh ** 1080f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid 1081f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement. If pkChng 1082f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or 1083f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, 1084f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer 1085f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias. 10860ca3e24bSdrh ** 10876934fc7bSdrh ** The code generated by this routine will store new index entries into 1088aa9b8963Sdrh ** registers identified by aRegIdx[]. No index entry is created for 1089aa9b8963Sdrh ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is 1090aa9b8963Sdrh ** the same as the order of indices on the linked list of indices 10916934fc7bSdrh ** at pTab->pIndex. 10926934fc7bSdrh ** 10936934fc7bSdrh ** The caller must have already opened writeable cursors on the main 10946934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which 10956934fc7bSdrh ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when 10966934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY 10976934fc7bSdrh ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor 10986934fc7bSdrh ** for the first index in the pTab->pIndex list. Cursors for other indices 10996934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list. 11009cfcf5d4Sdrh ** 11019cfcf5d4Sdrh ** This routine also generates code to check constraints. NOT NULL, 11029cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 11031c92853dSdrh ** then the appropriate action is performed. There are five possible 11041c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 11059cfcf5d4Sdrh ** 11069cfcf5d4Sdrh ** Constraint type Action What Happens 11079cfcf5d4Sdrh ** --------------- ---------- ---------------------------------------- 11081c92853dSdrh ** any ROLLBACK The current transaction is rolled back and 11096934fc7bSdrh ** sqlite3_step() returns immediately with a 11109cfcf5d4Sdrh ** return code of SQLITE_CONSTRAINT. 11119cfcf5d4Sdrh ** 11121c92853dSdrh ** any ABORT Back out changes from the current command 11131c92853dSdrh ** only (do not do a complete rollback) then 11146934fc7bSdrh ** cause sqlite3_step() to return immediately 11151c92853dSdrh ** with SQLITE_CONSTRAINT. 11161c92853dSdrh ** 11176934fc7bSdrh ** any FAIL Sqlite3_step() returns immediately with a 11181c92853dSdrh ** return code of SQLITE_CONSTRAINT. The 11191c92853dSdrh ** transaction is not rolled back and any 11206934fc7bSdrh ** changes to prior rows are retained. 11211c92853dSdrh ** 11226934fc7bSdrh ** any IGNORE The attempt in insert or update the current 11236934fc7bSdrh ** row is skipped, without throwing an error. 11246934fc7bSdrh ** Processing continues with the next row. 11256934fc7bSdrh ** (There is an immediate jump to ignoreDest.) 11269cfcf5d4Sdrh ** 11279cfcf5d4Sdrh ** NOT NULL REPLACE The NULL value is replace by the default 11289cfcf5d4Sdrh ** value for that column. If the default value 11299cfcf5d4Sdrh ** is NULL, the action is the same as ABORT. 11309cfcf5d4Sdrh ** 11319cfcf5d4Sdrh ** UNIQUE REPLACE The other row that conflicts with the row 11329cfcf5d4Sdrh ** being inserted is removed. 11339cfcf5d4Sdrh ** 11349cfcf5d4Sdrh ** CHECK REPLACE Illegal. The results in an exception. 11359cfcf5d4Sdrh ** 11361c92853dSdrh ** Which action to take is determined by the overrideError parameter. 11371c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter 11381c92853dSdrh ** is used. Or if pParse->onError==OE_Default then the onError value 11391c92853dSdrh ** for the constraint is used. 11409cfcf5d4Sdrh */ 11414adee20fSdanielk1977 void sqlite3GenerateConstraintChecks( 11429cfcf5d4Sdrh Parse *pParse, /* The parser context */ 11436934fc7bSdrh Table *pTab, /* The table being inserted or updated */ 1144f8ffb278Sdrh int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ 11456934fc7bSdrh int iDataCur, /* Canonical data cursor (main table or PK index) */ 114626198bb4Sdrh int iIdxCur, /* First index cursor */ 11476934fc7bSdrh int regNewData, /* First register in a range holding values to insert */ 1148f8ffb278Sdrh int regOldData, /* Previous content. 0 for INSERTs */ 1149f8ffb278Sdrh u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ 1150f8ffb278Sdrh u8 overrideError, /* Override onError to this if not OE_Default */ 1151de630353Sdanielk1977 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ 1152de630353Sdanielk1977 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */ 11539cfcf5d4Sdrh ){ 11541b7ecbb4Sdrh Vdbe *v; /* VDBE under constrution */ 11551b7ecbb4Sdrh Index *pIdx; /* Pointer to one of the indices */ 115611e85273Sdrh Index *pPk = 0; /* The PRIMARY KEY index */ 11572938f924Sdrh sqlite3 *db; /* Database connection */ 1158f8ffb278Sdrh int i; /* loop counter */ 1159f8ffb278Sdrh int ix; /* Index loop counter */ 1160f8ffb278Sdrh int nCol; /* Number of columns */ 1161f8ffb278Sdrh int onError; /* Conflict resolution strategy */ 1162728e0f91Sdrh int addr1; /* Address of jump instruction */ 11631b7ecbb4Sdrh int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ 11646fbe41acSdrh int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ 11658d1b82e4Sdrh int ipkTop = 0; /* Top of the rowid change constraint check */ 11668d1b82e4Sdrh int ipkBottom = 0; /* Bottom of the rowid change constraint check */ 11678d1b82e4Sdrh u8 isUpdate; /* True if this is an UPDATE operation */ 116857bf4a8eSdrh u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ 11695426d809Sdrh int regRowid = -1; /* Register holding ROWID value */ 11709cfcf5d4Sdrh 1171f8ffb278Sdrh isUpdate = regOldData!=0; 11722938f924Sdrh db = pParse->db; 11734adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 11749cfcf5d4Sdrh assert( v!=0 ); 1175417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 11769cfcf5d4Sdrh nCol = pTab->nCol; 1177aa9b8963Sdrh 11786934fc7bSdrh /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for 11796934fc7bSdrh ** normal rowid tables. nPkField is the number of key fields in the 11806934fc7bSdrh ** pPk index or 1 for a rowid table. In other words, nPkField is the 11816934fc7bSdrh ** number of fields in the true primary key of the table. */ 118226198bb4Sdrh if( HasRowid(pTab) ){ 118326198bb4Sdrh pPk = 0; 118426198bb4Sdrh nPkField = 1; 118526198bb4Sdrh }else{ 118626198bb4Sdrh pPk = sqlite3PrimaryKeyIndex(pTab); 118726198bb4Sdrh nPkField = pPk->nKeyCol; 118826198bb4Sdrh } 11896fbe41acSdrh 11906fbe41acSdrh /* Record that this module has started */ 11916fbe41acSdrh VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", 11926934fc7bSdrh iDataCur, iIdxCur, regNewData, regOldData, pkChng)); 119311e85273Sdrh 11949cfcf5d4Sdrh /* Test all NOT NULL constraints. 11959cfcf5d4Sdrh */ 11969cfcf5d4Sdrh for(i=0; i<nCol; i++){ 11970ca3e24bSdrh if( i==pTab->iPKey ){ 11980ca3e24bSdrh continue; 11990ca3e24bSdrh } 12009cfcf5d4Sdrh onError = pTab->aCol[i].notNull; 12010ca3e24bSdrh if( onError==OE_None ) continue; 12029cfcf5d4Sdrh if( overrideError!=OE_Default ){ 12039cfcf5d4Sdrh onError = overrideError; 1204a996e477Sdrh }else if( onError==OE_Default ){ 1205a996e477Sdrh onError = OE_Abort; 12069cfcf5d4Sdrh } 12077977a17fSdanielk1977 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ 12089cfcf5d4Sdrh onError = OE_Abort; 12099cfcf5d4Sdrh } 1210b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1211b84f96f8Sdanielk1977 || onError==OE_Ignore || onError==OE_Replace ); 12129cfcf5d4Sdrh switch( onError ){ 12131c92853dSdrh case OE_Abort: 1214e0af83acSdan sqlite3MayAbort(pParse); 12150978d4ffSdrh /* Fall through */ 1216e0af83acSdan case OE_Rollback: 12171c92853dSdrh case OE_Fail: { 1218f9c8ce3cSdrh char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, 1219f9c8ce3cSdrh pTab->aCol[i].zName); 1220f9c8ce3cSdrh sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError, 1221f9c8ce3cSdrh regNewData+1+i, zMsg, P4_DYNAMIC); 1222f9c8ce3cSdrh sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); 1223688852abSdrh VdbeCoverage(v); 12249cfcf5d4Sdrh break; 12259cfcf5d4Sdrh } 12269cfcf5d4Sdrh case OE_Ignore: { 12276934fc7bSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest); 1228688852abSdrh VdbeCoverage(v); 12299cfcf5d4Sdrh break; 12309cfcf5d4Sdrh } 1231098d1684Sdrh default: { 1232098d1684Sdrh assert( onError==OE_Replace ); 1233728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); 1234728e0f91Sdrh VdbeCoverage(v); 12356934fc7bSdrh sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); 1236728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 12379cfcf5d4Sdrh break; 12389cfcf5d4Sdrh } 12399cfcf5d4Sdrh } 12409cfcf5d4Sdrh } 12419cfcf5d4Sdrh 12429cfcf5d4Sdrh /* Test all CHECK constraints 12439cfcf5d4Sdrh */ 1244ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 12452938f924Sdrh if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ 12462938f924Sdrh ExprList *pCheck = pTab->pCheck; 12476934fc7bSdrh pParse->ckBase = regNewData+1; 1248aa01c7e2Sdrh onError = overrideError!=OE_Default ? overrideError : OE_Abort; 12492938f924Sdrh for(i=0; i<pCheck->nExpr; i++){ 12502938f924Sdrh int allOk = sqlite3VdbeMakeLabel(v); 12512d8e9203Sdrh sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL); 12522e06c67cSdrh if( onError==OE_Ignore ){ 1253076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 1254aa01c7e2Sdrh }else{ 1255f9c8ce3cSdrh char *zName = pCheck->a[i].zName; 1256f9c8ce3cSdrh if( zName==0 ) zName = pTab->zName; 12576dc84902Sdrh if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ 1258d91c1a17Sdrh sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, 1259f9c8ce3cSdrh onError, zName, P4_TRANSIENT, 1260f9c8ce3cSdrh P5_ConstraintCheck); 1261aa01c7e2Sdrh } 1262ffe07b2dSdrh sqlite3VdbeResolveLabel(v, allOk); 1263c31c7c1cSdrh } 12642938f924Sdrh } 1265ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */ 12669cfcf5d4Sdrh 1267f8ffb278Sdrh /* If rowid is changing, make sure the new rowid does not previously 1268f8ffb278Sdrh ** exist in the table. 12699cfcf5d4Sdrh */ 12706fbe41acSdrh if( pkChng && pPk==0 ){ 127111e85273Sdrh int addrRowidOk = sqlite3VdbeMakeLabel(v); 127211e85273Sdrh 1273f8ffb278Sdrh /* Figure out what action to take in case of a rowid collision */ 12740ca3e24bSdrh onError = pTab->keyConf; 12750ca3e24bSdrh if( overrideError!=OE_Default ){ 12760ca3e24bSdrh onError = overrideError; 1277a996e477Sdrh }else if( onError==OE_Default ){ 1278a996e477Sdrh onError = OE_Abort; 12790ca3e24bSdrh } 1280a0217ba7Sdrh 128179b0c956Sdrh if( isUpdate ){ 1282f8ffb278Sdrh /* pkChng!=0 does not mean that the rowid has change, only that 1283f8ffb278Sdrh ** it might have changed. Skip the conflict logic below if the rowid 1284f8ffb278Sdrh ** is unchanged. */ 12856934fc7bSdrh sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); 12863d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1287688852abSdrh VdbeCoverage(v); 128879b0c956Sdrh } 1289f8ffb278Sdrh 12908d1b82e4Sdrh /* If the response to a rowid conflict is REPLACE but the response 12918d1b82e4Sdrh ** to some other UNIQUE constraint is FAIL or IGNORE, then we need 12928d1b82e4Sdrh ** to defer the running of the rowid conflict checking until after 12938d1b82e4Sdrh ** the UNIQUE constraints have run. 12948d1b82e4Sdrh */ 12958d1b82e4Sdrh if( onError==OE_Replace && overrideError!=OE_Replace ){ 12968d1b82e4Sdrh for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 12978d1b82e4Sdrh if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){ 12988d1b82e4Sdrh ipkTop = sqlite3VdbeAddOp0(v, OP_Goto); 12998d1b82e4Sdrh break; 13008d1b82e4Sdrh } 13018d1b82e4Sdrh } 13028d1b82e4Sdrh } 13038d1b82e4Sdrh 1304f8ffb278Sdrh /* Check to see if the new rowid already exists in the table. Skip 1305f8ffb278Sdrh ** the following conflict logic if it does not. */ 13066934fc7bSdrh sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); 1307688852abSdrh VdbeCoverage(v); 1308f8ffb278Sdrh 1309f8ffb278Sdrh /* Generate code that deals with a rowid collision */ 13100ca3e24bSdrh switch( onError ){ 1311a0217ba7Sdrh default: { 1312a0217ba7Sdrh onError = OE_Abort; 1313a0217ba7Sdrh /* Fall thru into the next case */ 1314a0217ba7Sdrh } 13151c92853dSdrh case OE_Rollback: 13161c92853dSdrh case OE_Abort: 13171c92853dSdrh case OE_Fail: { 1318f9c8ce3cSdrh sqlite3RowidConstraint(pParse, onError, pTab); 13190ca3e24bSdrh break; 13200ca3e24bSdrh } 13215383ae5cSdrh case OE_Replace: { 13222283d46cSdan /* If there are DELETE triggers on this table and the 13232283d46cSdan ** recursive-triggers flag is set, call GenerateRowDelete() to 1324d5578433Smistachkin ** remove the conflicting row from the table. This will fire 13252283d46cSdan ** the triggers and remove both the table and index b-tree entries. 13262283d46cSdan ** 13272283d46cSdan ** Otherwise, if there are no triggers or the recursive-triggers 1328da730f6eSdan ** flag is not set, but the table has one or more indexes, call 1329da730f6eSdan ** GenerateRowIndexDelete(). This removes the index b-tree entries 1330da730f6eSdan ** only. The table b-tree entry will be replaced by the new entry 1331da730f6eSdan ** when it is inserted. 1332da730f6eSdan ** 1333da730f6eSdan ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, 1334da730f6eSdan ** also invoke MultiWrite() to indicate that this VDBE may require 1335da730f6eSdan ** statement rollback (if the statement is aborted after the delete 1336da730f6eSdan ** takes place). Earlier versions called sqlite3MultiWrite() regardless, 1337da730f6eSdan ** but being more selective here allows statements like: 1338da730f6eSdan ** 1339da730f6eSdan ** REPLACE INTO t(rowid) VALUES($newrowid) 1340da730f6eSdan ** 1341da730f6eSdan ** to run without a statement journal if there are no indexes on the 1342da730f6eSdan ** table. 1343da730f6eSdan */ 13442283d46cSdan Trigger *pTrigger = 0; 13452938f924Sdrh if( db->flags&SQLITE_RecTriggers ){ 13462283d46cSdan pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 13472283d46cSdan } 1348e7a94d81Sdan if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ 1349da730f6eSdan sqlite3MultiWrite(pParse); 135026198bb4Sdrh sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1351b0264eecSdrh regNewData, 1, 0, OE_Replace, 1352b0264eecSdrh ONEPASS_SINGLE, -1); 1353b77ebd82Sdrh }else{ 1354b77ebd82Sdrh if( pTab->pIndex ){ 1355da730f6eSdan sqlite3MultiWrite(pParse); 1356f0ee1d3cSdan sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); 13572283d46cSdan } 1358b77ebd82Sdrh } 13595383ae5cSdrh seenReplace = 1; 13605383ae5cSdrh break; 13615383ae5cSdrh } 13620ca3e24bSdrh case OE_Ignore: { 13638d1b82e4Sdrh /*assert( seenReplace==0 );*/ 1364076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 13650ca3e24bSdrh break; 13660ca3e24bSdrh } 13670ca3e24bSdrh } 136811e85273Sdrh sqlite3VdbeResolveLabel(v, addrRowidOk); 13698d1b82e4Sdrh if( ipkTop ){ 13708d1b82e4Sdrh ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); 13718d1b82e4Sdrh sqlite3VdbeJumpHere(v, ipkTop); 13728d1b82e4Sdrh } 13730ca3e24bSdrh } 13740bd1f4eaSdrh 13750bd1f4eaSdrh /* Test all UNIQUE constraints by creating entries for each UNIQUE 13760bd1f4eaSdrh ** index and making sure that duplicate entries do not already exist. 137711e85273Sdrh ** Compute the revised record entries for indices as we go. 1378f8ffb278Sdrh ** 1379f8ffb278Sdrh ** This loop also handles the case of the PRIMARY KEY index for a 1380f8ffb278Sdrh ** WITHOUT ROWID table. 13810bd1f4eaSdrh */ 138226198bb4Sdrh for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ 13836934fc7bSdrh int regIdx; /* Range of registers hold conent for pIdx */ 13846934fc7bSdrh int regR; /* Range of registers holding conflicting PK */ 13856934fc7bSdrh int iThisCur; /* Cursor for this UNIQUE index */ 13866934fc7bSdrh int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ 13872184fc75Sdrh 138826198bb4Sdrh if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ 138957bf4a8eSdrh if( bAffinityDone==0 ){ 139057bf4a8eSdrh sqlite3TableAffinity(v, pTab, regNewData+1); 139157bf4a8eSdrh bAffinityDone = 1; 139257bf4a8eSdrh } 13936934fc7bSdrh iThisCur = iIdxCur+ix; 13946934fc7bSdrh addrUniqueOk = sqlite3VdbeMakeLabel(v); 1395b2fe7d8cSdrh 1396f8ffb278Sdrh /* Skip partial indices for which the WHERE clause is not true */ 1397b2b9d3d7Sdrh if( pIdx->pPartIdxWhere ){ 139826198bb4Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); 13996934fc7bSdrh pParse->ckBase = regNewData+1; 140072bc8208Sdrh sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, 1401b2b9d3d7Sdrh SQLITE_JUMPIFNULL); 1402b2b9d3d7Sdrh pParse->ckBase = 0; 1403b2b9d3d7Sdrh } 1404b2b9d3d7Sdrh 14056934fc7bSdrh /* Create a record for this index entry as it should appear after 1406f8ffb278Sdrh ** the insert or update. Store that record in the aRegIdx[ix] register 1407f8ffb278Sdrh */ 140811e85273Sdrh regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn); 14099cfcf5d4Sdrh for(i=0; i<pIdx->nColumn; i++){ 14106934fc7bSdrh int iField = pIdx->aiColumn[i]; 1411f82b9afcSdrh int x; 14124b92f98cSdrh if( iField==XN_EXPR ){ 14131f9ca2c8Sdrh pParse->ckBase = regNewData+1; 14141f9ca2c8Sdrh sqlite3ExprCode(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); 14151f9ca2c8Sdrh pParse->ckBase = 0; 14161f9ca2c8Sdrh VdbeComment((v, "%s column %d", pIdx->zName, i)); 14171f9ca2c8Sdrh }else{ 14184b92f98cSdrh if( iField==XN_ROWID || iField==pTab->iPKey ){ 14195426d809Sdrh if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */ 1420f82b9afcSdrh x = regNewData; 14215426d809Sdrh regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i; 14229cfcf5d4Sdrh }else{ 1423f82b9afcSdrh x = iField + regNewData + 1; 14249cfcf5d4Sdrh } 1425fed7ac6fSdrh sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i); 1426f82b9afcSdrh VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName)); 14279cfcf5d4Sdrh } 14281f9ca2c8Sdrh } 142926198bb4Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); 143026198bb4Sdrh VdbeComment((v, "for %s", pIdx->zName)); 1431bbbdc83bSdrh sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn); 1432b2fe7d8cSdrh 1433f8ffb278Sdrh /* In an UPDATE operation, if this index is the PRIMARY KEY index 1434f8ffb278Sdrh ** of a WITHOUT ROWID table and there has been no change the 1435f8ffb278Sdrh ** primary key, then no collision is possible. The collision detection 1436f8ffb278Sdrh ** logic below can all be skipped. */ 143700012df4Sdrh if( isUpdate && pPk==pIdx && pkChng==0 ){ 1438da475b8dSdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1439da475b8dSdrh continue; 1440da475b8dSdrh } 1441f8ffb278Sdrh 14426934fc7bSdrh /* Find out what action to take in case there is a uniqueness conflict */ 14439cfcf5d4Sdrh onError = pIdx->onError; 1444de630353Sdanielk1977 if( onError==OE_None ){ 144526198bb4Sdrh sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); 144611e85273Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1447de630353Sdanielk1977 continue; /* pIdx is not a UNIQUE index */ 1448de630353Sdanielk1977 } 14499cfcf5d4Sdrh if( overrideError!=OE_Default ){ 14509cfcf5d4Sdrh onError = overrideError; 1451a996e477Sdrh }else if( onError==OE_Default ){ 1452a996e477Sdrh onError = OE_Abort; 14539cfcf5d4Sdrh } 14545383ae5cSdrh 1455b2fe7d8cSdrh /* Check to see if the new index entry will be unique */ 145626198bb4Sdrh sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, 1457688852abSdrh regIdx, pIdx->nKeyCol); VdbeCoverage(v); 1458f8ffb278Sdrh 1459f8ffb278Sdrh /* Generate code to handle collisions */ 1460392ee21dSdrh regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); 146146d03fcbSdrh if( isUpdate || onError==OE_Replace ){ 146211e85273Sdrh if( HasRowid(pTab) ){ 14636934fc7bSdrh sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); 14640978d4ffSdrh /* Conflict only if the rowid of the existing index entry 14650978d4ffSdrh ** is different from old-rowid */ 1466f8ffb278Sdrh if( isUpdate ){ 14676934fc7bSdrh sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); 14683d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1469688852abSdrh VdbeCoverage(v); 1470f8ffb278Sdrh } 147126198bb4Sdrh }else{ 1472ccc79f02Sdrh int x; 147326198bb4Sdrh /* Extract the PRIMARY KEY from the end of the index entry and 1474da475b8dSdrh ** store it in registers regR..regR+nPk-1 */ 1475a021f121Sdrh if( pIdx!=pPk ){ 147626198bb4Sdrh for(i=0; i<pPk->nKeyCol; i++){ 14774b92f98cSdrh assert( pPk->aiColumn[i]>=0 ); 1478ccc79f02Sdrh x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]); 147926198bb4Sdrh sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); 148026198bb4Sdrh VdbeComment((v, "%s.%s", pTab->zName, 148126198bb4Sdrh pTab->aCol[pPk->aiColumn[i]].zName)); 148226198bb4Sdrh } 1483da475b8dSdrh } 1484da475b8dSdrh if( isUpdate ){ 1485e83267daSdan /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 1486e83267daSdan ** table, only conflict if the new PRIMARY KEY values are actually 1487e83267daSdan ** different from the old. 1488e83267daSdan ** 1489e83267daSdan ** For a UNIQUE index, only conflict if the PRIMARY KEY values 1490e83267daSdan ** of the matched index row are different from the original PRIMARY 1491e83267daSdan ** KEY values of this row before the update. */ 1492e83267daSdan int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; 1493e83267daSdan int op = OP_Ne; 149448dd1d8eSdrh int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); 1495e83267daSdan 1496e83267daSdan for(i=0; i<pPk->nKeyCol; i++){ 1497e83267daSdan char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); 1498ccc79f02Sdrh x = pPk->aiColumn[i]; 14994b92f98cSdrh assert( x>=0 ); 1500e83267daSdan if( i==(pPk->nKeyCol-1) ){ 1501e83267daSdan addrJump = addrUniqueOk; 1502e83267daSdan op = OP_Eq; 150311e85273Sdrh } 1504e83267daSdan sqlite3VdbeAddOp4(v, op, 1505e83267daSdan regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ 15063d77dee9Sdrh ); 15073d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 15083d77dee9Sdrh VdbeCoverageIf(v, op==OP_Eq); 15093d77dee9Sdrh VdbeCoverageIf(v, op==OP_Ne); 1510da475b8dSdrh } 151111e85273Sdrh } 151226198bb4Sdrh } 151346d03fcbSdrh } 1514b2fe7d8cSdrh 1515b2fe7d8cSdrh /* Generate code that executes if the new index entry is not unique */ 1516b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1517b84f96f8Sdanielk1977 || onError==OE_Ignore || onError==OE_Replace ); 15189cfcf5d4Sdrh switch( onError ){ 15191c92853dSdrh case OE_Rollback: 15201c92853dSdrh case OE_Abort: 15211c92853dSdrh case OE_Fail: { 1522f9c8ce3cSdrh sqlite3UniqueConstraint(pParse, onError, pIdx); 15239cfcf5d4Sdrh break; 15249cfcf5d4Sdrh } 15259cfcf5d4Sdrh case OE_Ignore: { 1526076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 15279cfcf5d4Sdrh break; 15289cfcf5d4Sdrh } 1529098d1684Sdrh default: { 15302283d46cSdan Trigger *pTrigger = 0; 1531098d1684Sdrh assert( onError==OE_Replace ); 15321bea559aSdan sqlite3MultiWrite(pParse); 15332938f924Sdrh if( db->flags&SQLITE_RecTriggers ){ 15342283d46cSdan pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 15352283d46cSdan } 153626198bb4Sdrh sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1537b0264eecSdrh regR, nPkField, 0, OE_Replace, 1538b0264eecSdrh (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1); 15390ca3e24bSdrh seenReplace = 1; 15409cfcf5d4Sdrh break; 15419cfcf5d4Sdrh } 15429cfcf5d4Sdrh } 154311e85273Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1544392ee21dSdrh sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); 1545392ee21dSdrh if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); 15469cfcf5d4Sdrh } 15478d1b82e4Sdrh if( ipkTop ){ 1548076e85f5Sdrh sqlite3VdbeGoto(v, ipkTop+1); 15498d1b82e4Sdrh sqlite3VdbeJumpHere(v, ipkBottom); 15508d1b82e4Sdrh } 1551de630353Sdanielk1977 1552de630353Sdanielk1977 *pbMayReplace = seenReplace; 1553ce60aa46Sdrh VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); 15549cfcf5d4Sdrh } 15550ca3e24bSdrh 15560ca3e24bSdrh /* 15570ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation 15584adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 15596934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the 156004adf416Sdrh ** rowid and the content to be inserted. 15610ca3e24bSdrh ** 1562b419a926Sdrh ** The arguments to this routine should be the same as the first six 15634adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks. 15640ca3e24bSdrh */ 15654adee20fSdanielk1977 void sqlite3CompleteInsertion( 15660ca3e24bSdrh Parse *pParse, /* The parser context */ 15670ca3e24bSdrh Table *pTab, /* the table into which we are inserting */ 156826198bb4Sdrh int iDataCur, /* Cursor of the canonical data source */ 156926198bb4Sdrh int iIdxCur, /* First index cursor */ 15706934fc7bSdrh int regNewData, /* Range of content */ 1571aa9b8963Sdrh int *aRegIdx, /* Register used by each index. 0 for unused indices */ 157270ce3f0cSdrh int isUpdate, /* True for UPDATE, False for INSERT */ 1573de630353Sdanielk1977 int appendBias, /* True if this is likely to be an append */ 1574de630353Sdanielk1977 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ 15750ca3e24bSdrh ){ 15766934fc7bSdrh Vdbe *v; /* Prepared statements under construction */ 15776934fc7bSdrh Index *pIdx; /* An index being inserted or updated */ 15786934fc7bSdrh u8 pik_flags; /* flag values passed to the btree insert */ 15796934fc7bSdrh int regData; /* Content registers (after the rowid) */ 158060ec914cSpeter.d.reid int regRec; /* Register holding assembled record for the table */ 15816934fc7bSdrh int i; /* Loop counter */ 158257bf4a8eSdrh u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */ 15830ca3e24bSdrh 15844adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 15850ca3e24bSdrh assert( v!=0 ); 1586417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 1587b2b9d3d7Sdrh for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1588aa9b8963Sdrh if( aRegIdx[i]==0 ) continue; 158957bf4a8eSdrh bAffinityDone = 1; 1590b2b9d3d7Sdrh if( pIdx->pPartIdxWhere ){ 1591b2b9d3d7Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); 1592688852abSdrh VdbeCoverage(v); 1593b2b9d3d7Sdrh } 159426198bb4Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]); 15956546af14Sdrh pik_flags = 0; 15966546af14Sdrh if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT; 159748dd1d8eSdrh if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 15984308e348Sdrh assert( pParse->nested==0 ); 15996546af14Sdrh pik_flags |= OPFLAG_NCHANGE; 1600de630353Sdanielk1977 } 16016546af14Sdrh if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags); 16020ca3e24bSdrh } 1603ec95c441Sdrh if( !HasRowid(pTab) ) return; 16046934fc7bSdrh regData = regNewData + 1; 1605b7654111Sdrh regRec = sqlite3GetTempReg(pParse); 16061db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); 160757bf4a8eSdrh if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0); 1608da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); 16094794f735Sdrh if( pParse->nested ){ 16104794f735Sdrh pik_flags = 0; 16114794f735Sdrh }else{ 161294eb6a14Sdanielk1977 pik_flags = OPFLAG_NCHANGE; 161394eb6a14Sdanielk1977 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); 16144794f735Sdrh } 1615e4d90813Sdrh if( appendBias ){ 1616e4d90813Sdrh pik_flags |= OPFLAG_APPEND; 1617e4d90813Sdrh } 1618de630353Sdanielk1977 if( useSeekResult ){ 1619de630353Sdanielk1977 pik_flags |= OPFLAG_USESEEKRESULT; 1620de630353Sdanielk1977 } 16216934fc7bSdrh sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData); 162294eb6a14Sdanielk1977 if( !pParse->nested ){ 16238d129422Sdrh sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT); 162494eb6a14Sdanielk1977 } 1625b7654111Sdrh sqlite3VdbeChangeP5(v, pik_flags); 16260ca3e24bSdrh } 1627cd44690aSdrh 1628cd44690aSdrh /* 162926198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate 163026198bb4Sdrh ** code to open and initialized those cursors. 1631aa9b8963Sdrh ** 163226198bb4Sdrh ** The cursor for the object that contains the complete data (normally 163326198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT 163426198bb4Sdrh ** ROWID table) is returned in *piDataCur. The first index cursor is 163526198bb4Sdrh ** returned in *piIdxCur. The number of indices is returned. 163626198bb4Sdrh ** 163726198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables 163826198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative. 163926198bb4Sdrh ** If iBase is negative, then allocate the next available cursor. 164026198bb4Sdrh ** 164126198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. 164226198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range 164326198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the 164426198bb4Sdrh ** pTab->pIndex list. 1645b6b4b79fSdrh ** 1646b6b4b79fSdrh ** If pTab is a virtual table, then this routine is a no-op and the 1647b6b4b79fSdrh ** *piDataCur and *piIdxCur values are left uninitialized. 1648cd44690aSdrh */ 1649aa9b8963Sdrh int sqlite3OpenTableAndIndices( 1650290c1948Sdrh Parse *pParse, /* Parsing context */ 1651290c1948Sdrh Table *pTab, /* Table to be opened */ 165226198bb4Sdrh int op, /* OP_OpenRead or OP_OpenWrite */ 1653*fd261ec6Sdan u8 p5, /* P5 value for OP_Open* instructions */ 165426198bb4Sdrh int iBase, /* Use this for the table cursor, if there is one */ 16556a53499aSdrh u8 *aToOpen, /* If not NULL: boolean for each table and index */ 165626198bb4Sdrh int *piDataCur, /* Write the database source cursor number here */ 165726198bb4Sdrh int *piIdxCur /* Write the first index cursor number here */ 1658290c1948Sdrh ){ 1659cd44690aSdrh int i; 16604cbdda9eSdrh int iDb; 16616a53499aSdrh int iDataCur; 1662cd44690aSdrh Index *pIdx; 16634cbdda9eSdrh Vdbe *v; 16644cbdda9eSdrh 166526198bb4Sdrh assert( op==OP_OpenRead || op==OP_OpenWrite ); 1666*fd261ec6Sdan assert( op==OP_OpenWrite || p5==0 ); 166726198bb4Sdrh if( IsVirtual(pTab) ){ 1668b6b4b79fSdrh /* This routine is a no-op for virtual tables. Leave the output 1669b6b4b79fSdrh ** variables *piDataCur and *piIdxCur uninitialized so that valgrind 1670b6b4b79fSdrh ** can detect if they are used by mistake in the caller. */ 167126198bb4Sdrh return 0; 167226198bb4Sdrh } 16734cbdda9eSdrh iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 16744cbdda9eSdrh v = sqlite3GetVdbe(pParse); 1675cd44690aSdrh assert( v!=0 ); 167626198bb4Sdrh if( iBase<0 ) iBase = pParse->nTab; 16776a53499aSdrh iDataCur = iBase++; 16786a53499aSdrh if( piDataCur ) *piDataCur = iDataCur; 16796a53499aSdrh if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ 16806a53499aSdrh sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); 16816fbe41acSdrh }else{ 168226198bb4Sdrh sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); 16836fbe41acSdrh } 16846a53499aSdrh if( piIdxCur ) *piIdxCur = iBase; 168526198bb4Sdrh for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 168626198bb4Sdrh int iIdxCur = iBase++; 1687da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 168848dd1d8eSdrh if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){ 16896a53499aSdrh *piDataCur = iIdxCur; 16906a53499aSdrh } 16916a53499aSdrh if( aToOpen==0 || aToOpen[i+1] ){ 16922ec2fb22Sdrh sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); 16932ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 1694*fd261ec6Sdan sqlite3VdbeChangeP5(v, p5); 1695207872a4Sdanielk1977 VdbeComment((v, "%s", pIdx->zName)); 1696cd44690aSdrh } 16976a53499aSdrh } 169826198bb4Sdrh if( iBase>pParse->nTab ) pParse->nTab = iBase; 169926198bb4Sdrh return i; 1700cd44690aSdrh } 17019d9cf229Sdrh 170291c58e23Sdrh 170391c58e23Sdrh #ifdef SQLITE_TEST 170491c58e23Sdrh /* 170591c58e23Sdrh ** The following global variable is incremented whenever the 170691c58e23Sdrh ** transfer optimization is used. This is used for testing 170791c58e23Sdrh ** purposes only - to make sure the transfer optimization really 170860ec914cSpeter.d.reid ** is happening when it is supposed to. 170991c58e23Sdrh */ 171091c58e23Sdrh int sqlite3_xferopt_count; 171191c58e23Sdrh #endif /* SQLITE_TEST */ 171291c58e23Sdrh 171391c58e23Sdrh 17149d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 17159d9cf229Sdrh /* 17169d9cf229Sdrh ** Check to collation names to see if they are compatible. 17179d9cf229Sdrh */ 17189d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){ 17199d9cf229Sdrh if( z1==0 ){ 17209d9cf229Sdrh return z2==0; 17219d9cf229Sdrh } 17229d9cf229Sdrh if( z2==0 ){ 17239d9cf229Sdrh return 0; 17249d9cf229Sdrh } 17259d9cf229Sdrh return sqlite3StrICmp(z1, z2)==0; 17269d9cf229Sdrh } 17279d9cf229Sdrh 17289d9cf229Sdrh 17299d9cf229Sdrh /* 17309d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data 17319d9cf229Sdrh ** for index pDest in an insert transfer optimization. The rules 17329d9cf229Sdrh ** for a compatible index: 17339d9cf229Sdrh ** 17349d9cf229Sdrh ** * The index is over the same set of columns 17359d9cf229Sdrh ** * The same DESC and ASC markings occurs on all columns 17369d9cf229Sdrh ** * The same onError processing (OE_Abort, OE_Ignore, etc) 17379d9cf229Sdrh ** * The same collating sequence on each column 1738b2b9d3d7Sdrh ** * The index has the exact same WHERE clause 17399d9cf229Sdrh */ 17409d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 17419d9cf229Sdrh int i; 17429d9cf229Sdrh assert( pDest && pSrc ); 17439d9cf229Sdrh assert( pDest->pTable!=pSrc->pTable ); 1744bbbdc83bSdrh if( pDest->nKeyCol!=pSrc->nKeyCol ){ 17459d9cf229Sdrh return 0; /* Different number of columns */ 17469d9cf229Sdrh } 17479d9cf229Sdrh if( pDest->onError!=pSrc->onError ){ 17489d9cf229Sdrh return 0; /* Different conflict resolution strategies */ 17499d9cf229Sdrh } 1750bbbdc83bSdrh for(i=0; i<pSrc->nKeyCol; i++){ 17519d9cf229Sdrh if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 17529d9cf229Sdrh return 0; /* Different columns indexed */ 17539d9cf229Sdrh } 17544b92f98cSdrh if( pSrc->aiColumn[i]==XN_EXPR ){ 17551f9ca2c8Sdrh assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); 17561f9ca2c8Sdrh if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr, 17571f9ca2c8Sdrh pDest->aColExpr->a[i].pExpr, -1)!=0 ){ 17581f9ca2c8Sdrh return 0; /* Different expressions in the index */ 17591f9ca2c8Sdrh } 17601f9ca2c8Sdrh } 17619d9cf229Sdrh if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 17629d9cf229Sdrh return 0; /* Different sort orders */ 17639d9cf229Sdrh } 17643f6e781dSdrh if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){ 176560a713c6Sdrh return 0; /* Different collating sequences */ 17669d9cf229Sdrh } 17679d9cf229Sdrh } 1768619a1305Sdrh if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ 1769b2b9d3d7Sdrh return 0; /* Different WHERE clauses */ 1770b2b9d3d7Sdrh } 17719d9cf229Sdrh 17729d9cf229Sdrh /* If no test above fails then the indices must be compatible */ 17739d9cf229Sdrh return 1; 17749d9cf229Sdrh } 17759d9cf229Sdrh 17769d9cf229Sdrh /* 17779d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form 17789d9cf229Sdrh ** 17799d9cf229Sdrh ** INSERT INTO tab1 SELECT * FROM tab2; 17809d9cf229Sdrh ** 1781ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1. 178260ec914cSpeter.d.reid ** Columns are not decoded and reassembled, which greatly improves 1783ccdf1baeSdrh ** performance. Raw index records are transferred in the same way. 17849d9cf229Sdrh ** 1785ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible. 1786ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments 1787ccdf1baeSdrh ** embedded in the code for details. 17889d9cf229Sdrh ** 1789ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used. 1790ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table 1791ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time. In that 1792ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also 1793ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the 1794ccdf1baeSdrh ** xfer optimization code if the test fails. In that case, this routine 1795ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate 1796ccdf1baeSdrh ** an unoptimized transfer. This routine also returns FALSE if there 1797ccdf1baeSdrh ** is no chance that the xfer optimization can be applied. 17989d9cf229Sdrh ** 1799ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster. 18009d9cf229Sdrh */ 18019d9cf229Sdrh static int xferOptimization( 18029d9cf229Sdrh Parse *pParse, /* Parser context */ 18039d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 18049d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 18059d9cf229Sdrh int onError, /* How to handle constraint errors */ 18069d9cf229Sdrh int iDbDest /* The database of pDest */ 18079d9cf229Sdrh ){ 1808e34162b1Sdan sqlite3 *db = pParse->db; 18099d9cf229Sdrh ExprList *pEList; /* The result set of the SELECT */ 18109d9cf229Sdrh Table *pSrc; /* The table in the FROM clause of SELECT */ 18119d9cf229Sdrh Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 18129d9cf229Sdrh struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 18139d9cf229Sdrh int i; /* Loop counter */ 18149d9cf229Sdrh int iDbSrc; /* The database of pSrc */ 18159d9cf229Sdrh int iSrc, iDest; /* Cursors from source and destination */ 18169d9cf229Sdrh int addr1, addr2; /* Loop addresses */ 1817da475b8dSdrh int emptyDestTest = 0; /* Address of test for empty pDest */ 1818da475b8dSdrh int emptySrcTest = 0; /* Address of test for empty pSrc */ 18199d9cf229Sdrh Vdbe *v; /* The VDBE we are building */ 18206a288a33Sdrh int regAutoinc; /* Memory register used by AUTOINC */ 1821f33c9fadSdrh int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 1822b7654111Sdrh int regData, regRowid; /* Registers holding data and rowid */ 18239d9cf229Sdrh 18249d9cf229Sdrh if( pSelect==0 ){ 18259d9cf229Sdrh return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 18269d9cf229Sdrh } 1827ebbf08a0Sdan if( pParse->pWith || pSelect->pWith ){ 1828ebbf08a0Sdan /* Do not attempt to process this query if there are an WITH clauses 1829ebbf08a0Sdan ** attached to it. Proceeding may generate a false "no such table: xxx" 1830ebbf08a0Sdan ** error if pSelect reads from a CTE named "xxx". */ 1831ebbf08a0Sdan return 0; 1832ebbf08a0Sdan } 18332f886d1dSdanielk1977 if( sqlite3TriggerList(pParse, pDest) ){ 18349d9cf229Sdrh return 0; /* tab1 must not have triggers */ 18359d9cf229Sdrh } 18369d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 18377d10d5a6Sdrh if( pDest->tabFlags & TF_Virtual ){ 18389d9cf229Sdrh return 0; /* tab1 must not be a virtual table */ 18399d9cf229Sdrh } 18409d9cf229Sdrh #endif 18419d9cf229Sdrh if( onError==OE_Default ){ 1842e7224a01Sdrh if( pDest->iPKey>=0 ) onError = pDest->keyConf; 1843e7224a01Sdrh if( onError==OE_Default ) onError = OE_Abort; 18449d9cf229Sdrh } 18455ce240a6Sdanielk1977 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 18469d9cf229Sdrh if( pSelect->pSrc->nSrc!=1 ){ 18479d9cf229Sdrh return 0; /* FROM clause must have exactly one term */ 18489d9cf229Sdrh } 18499d9cf229Sdrh if( pSelect->pSrc->a[0].pSelect ){ 18509d9cf229Sdrh return 0; /* FROM clause cannot contain a subquery */ 18519d9cf229Sdrh } 18529d9cf229Sdrh if( pSelect->pWhere ){ 18539d9cf229Sdrh return 0; /* SELECT may not have a WHERE clause */ 18549d9cf229Sdrh } 18559d9cf229Sdrh if( pSelect->pOrderBy ){ 18569d9cf229Sdrh return 0; /* SELECT may not have an ORDER BY clause */ 18579d9cf229Sdrh } 18588103b7d2Sdrh /* Do not need to test for a HAVING clause. If HAVING is present but 18598103b7d2Sdrh ** there is no ORDER BY, we will get an error. */ 18609d9cf229Sdrh if( pSelect->pGroupBy ){ 18619d9cf229Sdrh return 0; /* SELECT may not have a GROUP BY clause */ 18629d9cf229Sdrh } 18639d9cf229Sdrh if( pSelect->pLimit ){ 18649d9cf229Sdrh return 0; /* SELECT may not have a LIMIT clause */ 18659d9cf229Sdrh } 18668103b7d2Sdrh assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ 18679d9cf229Sdrh if( pSelect->pPrior ){ 18689d9cf229Sdrh return 0; /* SELECT may not be a compound query */ 18699d9cf229Sdrh } 18707d10d5a6Sdrh if( pSelect->selFlags & SF_Distinct ){ 18719d9cf229Sdrh return 0; /* SELECT may not be DISTINCT */ 18729d9cf229Sdrh } 18739d9cf229Sdrh pEList = pSelect->pEList; 18749d9cf229Sdrh assert( pEList!=0 ); 18759d9cf229Sdrh if( pEList->nExpr!=1 ){ 18769d9cf229Sdrh return 0; /* The result set must have exactly one column */ 18779d9cf229Sdrh } 18789d9cf229Sdrh assert( pEList->a[0].pExpr ); 18799d9cf229Sdrh if( pEList->a[0].pExpr->op!=TK_ALL ){ 18809d9cf229Sdrh return 0; /* The result set must be the special operator "*" */ 18819d9cf229Sdrh } 18829d9cf229Sdrh 18839d9cf229Sdrh /* At this point we have established that the statement is of the 18849d9cf229Sdrh ** correct syntactic form to participate in this optimization. Now 18859d9cf229Sdrh ** we have to check the semantics. 18869d9cf229Sdrh */ 18879d9cf229Sdrh pItem = pSelect->pSrc->a; 188841fb5cd1Sdan pSrc = sqlite3LocateTableItem(pParse, 0, pItem); 18899d9cf229Sdrh if( pSrc==0 ){ 18909d9cf229Sdrh return 0; /* FROM clause does not contain a real table */ 18919d9cf229Sdrh } 18929d9cf229Sdrh if( pSrc==pDest ){ 18939d9cf229Sdrh return 0; /* tab1 and tab2 may not be the same table */ 18949d9cf229Sdrh } 189555548273Sdrh if( HasRowid(pDest)!=HasRowid(pSrc) ){ 189655548273Sdrh return 0; /* source and destination must both be WITHOUT ROWID or not */ 189755548273Sdrh } 18989d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 18997d10d5a6Sdrh if( pSrc->tabFlags & TF_Virtual ){ 19009d9cf229Sdrh return 0; /* tab2 must not be a virtual table */ 19019d9cf229Sdrh } 19029d9cf229Sdrh #endif 19039d9cf229Sdrh if( pSrc->pSelect ){ 19049d9cf229Sdrh return 0; /* tab2 may not be a view */ 19059d9cf229Sdrh } 19069d9cf229Sdrh if( pDest->nCol!=pSrc->nCol ){ 19079d9cf229Sdrh return 0; /* Number of columns must be the same in tab1 and tab2 */ 19089d9cf229Sdrh } 19099d9cf229Sdrh if( pDest->iPKey!=pSrc->iPKey ){ 19109d9cf229Sdrh return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 19119d9cf229Sdrh } 19129d9cf229Sdrh for(i=0; i<pDest->nCol; i++){ 19139940e2aaSdan Column *pDestCol = &pDest->aCol[i]; 19149940e2aaSdan Column *pSrcCol = &pSrc->aCol[i]; 19159940e2aaSdan if( pDestCol->affinity!=pSrcCol->affinity ){ 19169d9cf229Sdrh return 0; /* Affinity must be the same on all columns */ 19179d9cf229Sdrh } 19189940e2aaSdan if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){ 19199d9cf229Sdrh return 0; /* Collating sequence must be the same on all columns */ 19209d9cf229Sdrh } 19219940e2aaSdan if( pDestCol->notNull && !pSrcCol->notNull ){ 19229d9cf229Sdrh return 0; /* tab2 must be NOT NULL if tab1 is */ 19239d9cf229Sdrh } 1924453e0261Sdrh /* Default values for second and subsequent columns need to match. */ 1925453e0261Sdrh if( i>0 1926453e0261Sdrh && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0) 1927453e0261Sdrh || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0)) 19289940e2aaSdan ){ 19299940e2aaSdan return 0; /* Default values must be the same for all columns */ 19309940e2aaSdan } 19319d9cf229Sdrh } 19329d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 19335f1d1d9cSdrh if( IsUniqueIndex(pDestIdx) ){ 1934f33c9fadSdrh destHasUniqueIdx = 1; 1935f33c9fadSdrh } 19369d9cf229Sdrh for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 19379d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 19389d9cf229Sdrh } 19399d9cf229Sdrh if( pSrcIdx==0 ){ 19409d9cf229Sdrh return 0; /* pDestIdx has no corresponding index in pSrc */ 19419d9cf229Sdrh } 19429d9cf229Sdrh } 19437fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK 1944619a1305Sdrh if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ 19458103b7d2Sdrh return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 19468103b7d2Sdrh } 19477fc2f41bSdrh #endif 1948713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY 1949713de341Sdrh /* Disallow the transfer optimization if the destination table constains 1950713de341Sdrh ** any foreign key constraints. This is more restrictive than necessary. 1951713de341Sdrh ** But the main beneficiary of the transfer optimization is the VACUUM 1952713de341Sdrh ** command, and the VACUUM command disables foreign key constraints. So 1953713de341Sdrh ** the extra complication to make this rule less restrictive is probably 1954713de341Sdrh ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] 1955713de341Sdrh */ 1956e34162b1Sdan if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ 1957713de341Sdrh return 0; 1958713de341Sdrh } 1959713de341Sdrh #endif 1960e34162b1Sdan if( (db->flags & SQLITE_CountRows)!=0 ){ 1961ccdf1baeSdrh return 0; /* xfer opt does not play well with PRAGMA count_changes */ 19621696124dSdan } 19639d9cf229Sdrh 1964ccdf1baeSdrh /* If we get this far, it means that the xfer optimization is at 1965ccdf1baeSdrh ** least a possibility, though it might only work if the destination 1966ccdf1baeSdrh ** table (tab1) is initially empty. 19679d9cf229Sdrh */ 1968dd73521bSdrh #ifdef SQLITE_TEST 1969dd73521bSdrh sqlite3_xferopt_count++; 1970dd73521bSdrh #endif 1971e34162b1Sdan iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); 19729d9cf229Sdrh v = sqlite3GetVdbe(pParse); 1973f53e9b5aSdrh sqlite3CodeVerifySchema(pParse, iDbSrc); 19749d9cf229Sdrh iSrc = pParse->nTab++; 19759d9cf229Sdrh iDest = pParse->nTab++; 19766a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 197755548273Sdrh regData = sqlite3GetTempReg(pParse); 197855548273Sdrh regRowid = sqlite3GetTempReg(pParse); 19799d9cf229Sdrh sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 1980427ebba1Sdan assert( HasRowid(pDest) || destHasUniqueIdx ); 1981e34162b1Sdan if( (db->flags & SQLITE_Vacuum)==0 && ( 1982e34162b1Sdan (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ 1983ccdf1baeSdrh || destHasUniqueIdx /* (2) */ 1984ccdf1baeSdrh || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ 1985e34162b1Sdan )){ 1986ccdf1baeSdrh /* In some circumstances, we are able to run the xfer optimization 1987e34162b1Sdan ** only if the destination table is initially empty. Unless the 1988e34162b1Sdan ** SQLITE_Vacuum flag is set, this block generates code to make 1989e34162b1Sdan ** that determination. If SQLITE_Vacuum is set, then the destination 1990e34162b1Sdan ** table is always empty. 1991e34162b1Sdan ** 1992e34162b1Sdan ** Conditions under which the destination must be empty: 1993f33c9fadSdrh ** 1994ccdf1baeSdrh ** (1) There is no INTEGER PRIMARY KEY but there are indices. 1995ccdf1baeSdrh ** (If the destination is not initially empty, the rowid fields 1996ccdf1baeSdrh ** of index entries might need to change.) 1997ccdf1baeSdrh ** 1998ccdf1baeSdrh ** (2) The destination has a unique index. (The xfer optimization 1999ccdf1baeSdrh ** is unable to test uniqueness.) 2000ccdf1baeSdrh ** 2001ccdf1baeSdrh ** (3) onError is something other than OE_Abort and OE_Rollback. 20029d9cf229Sdrh */ 2003688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); 20042991ba05Sdrh emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); 20059d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 20069d9cf229Sdrh } 2007427ebba1Sdan if( HasRowid(pSrc) ){ 20089d9cf229Sdrh sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 2009688852abSdrh emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 201042242dedSdrh if( pDest->iPKey>=0 ){ 2011b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 2012b7654111Sdrh addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 2013688852abSdrh VdbeCoverage(v); 2014f9c8ce3cSdrh sqlite3RowidConstraint(pParse, onError, pDest); 20159d9cf229Sdrh sqlite3VdbeJumpHere(v, addr2); 2016b7654111Sdrh autoIncStep(pParse, regAutoinc, regRowid); 2017bd36ba69Sdrh }else if( pDest->pIndex==0 ){ 2018b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 201995bad4c7Sdrh }else{ 2020b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 20217d10d5a6Sdrh assert( (pDest->tabFlags & TF_Autoincrement)==0 ); 202295bad4c7Sdrh } 2023b7654111Sdrh sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); 2024b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); 2025b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); 20261f4aa337Sdanielk1977 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); 2027688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); 202855548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 202955548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2030da475b8dSdrh }else{ 2031da475b8dSdrh sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); 2032da475b8dSdrh sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); 203355548273Sdrh } 20349d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 203541b9ca25Sdrh u8 idxInsFlags = 0; 20361b7ecbb4Sdrh for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ 20379d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 20389d9cf229Sdrh } 20399d9cf229Sdrh assert( pSrcIdx ); 20402ec2fb22Sdrh sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); 20412ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); 2042d4e70ebdSdrh VdbeComment((v, "%s", pSrcIdx->zName)); 20432ec2fb22Sdrh sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); 20442ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); 204559885728Sdan sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); 2046207872a4Sdanielk1977 VdbeComment((v, "%s", pDestIdx->zName)); 2047688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2048b7654111Sdrh sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); 2049e34162b1Sdan if( db->flags & SQLITE_Vacuum ){ 2050e34162b1Sdan /* This INSERT command is part of a VACUUM operation, which guarantees 2051e34162b1Sdan ** that the destination table is empty. If all indexed columns use 2052e34162b1Sdan ** collation sequence BINARY, then it can also be assumed that the 2053e34162b1Sdan ** index will be populated by inserting keys in strictly sorted 2054e34162b1Sdan ** order. In this case, instead of seeking within the b-tree as part 2055e34162b1Sdan ** of every OP_IdxInsert opcode, an OP_Last is added before the 2056e34162b1Sdan ** OP_IdxInsert to seek to the point within the b-tree where each key 2057e34162b1Sdan ** should be inserted. This is faster. 2058e34162b1Sdan ** 2059e34162b1Sdan ** If any of the indexed columns use a collation sequence other than 2060e34162b1Sdan ** BINARY, this optimization is disabled. This is because the user 2061e34162b1Sdan ** might change the definition of a collation sequence and then run 2062e34162b1Sdan ** a VACUUM command. In that case keys may not be written in strictly 2063e34162b1Sdan ** sorted order. */ 2064e34162b1Sdan for(i=0; i<pSrcIdx->nColumn; i++){ 2065e34162b1Sdan char *zColl = pSrcIdx->azColl[i]; 2066ab06b0e5Sdrh assert( zColl!=0 ); 2067ab06b0e5Sdrh if( sqlite3_stricmp("BINARY", zColl) ) break; 2068e34162b1Sdan } 2069e34162b1Sdan if( i==pSrcIdx->nColumn ){ 207041b9ca25Sdrh idxInsFlags = OPFLAG_USESEEKRESULT; 2071e34162b1Sdan sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1); 2072e34162b1Sdan } 2073e34162b1Sdan } 207441b9ca25Sdrh if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){ 207541b9ca25Sdrh idxInsFlags |= OPFLAG_NCHANGE; 207641b9ca25Sdrh } 2077b7654111Sdrh sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); 207841b9ca25Sdrh sqlite3VdbeChangeP5(v, idxInsFlags); 2079688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); 20809d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 208155548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 208255548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 20839d9cf229Sdrh } 2084aceb31b1Sdrh if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); 2085b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 2086b7654111Sdrh sqlite3ReleaseTempReg(pParse, regData); 20879d9cf229Sdrh if( emptyDestTest ){ 208866a5167bSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 20899d9cf229Sdrh sqlite3VdbeJumpHere(v, emptyDestTest); 209066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 20919d9cf229Sdrh return 0; 20929d9cf229Sdrh }else{ 20939d9cf229Sdrh return 1; 20949d9cf229Sdrh } 20959d9cf229Sdrh } 20969d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 2097