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) ){ 407e508f1eSdrh sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, 417e508f1eSdrh pTab->nCol - pTab->nVCol); 42bbb5e4e0Sdrh VdbeComment((v, "%s", pTab->zName)); 4326198bb4Sdrh }else{ 44dd9930efSdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab); 45dd9930efSdrh assert( pPk!=0 ); 46afe028a8Sdrh assert( pPk->tnum==pTab->tnum ); 472ec2fb22Sdrh sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb); 482ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pPk); 49bbb5e4e0Sdrh VdbeComment((v, "%s", pTab->zName)); 50bbb5e4e0Sdrh } 51bbb5e4e0Sdrh } 52bbb5e4e0Sdrh 53bbb5e4e0Sdrh /* 5469f8bb9cSdan ** Return a pointer to the column affinity string associated with index 5569f8bb9cSdan ** pIdx. A column affinity string has one character for each column in 5669f8bb9cSdan ** the table, according to the affinity of the column: 573d1bfeaaSdanielk1977 ** 583d1bfeaaSdanielk1977 ** Character Column affinity 593d1bfeaaSdanielk1977 ** ------------------------------ 6005883a34Sdrh ** 'A' BLOB 614583c37cSdrh ** 'B' TEXT 624583c37cSdrh ** 'C' NUMERIC 634583c37cSdrh ** 'D' INTEGER 644583c37cSdrh ** 'F' REAL 652d401ab8Sdrh ** 664583c37cSdrh ** An extra 'D' is appended to the end of the string to cover the 672d401ab8Sdrh ** rowid that appears as the last column in every index. 6869f8bb9cSdan ** 6969f8bb9cSdan ** Memory for the buffer containing the column index affinity string 7069f8bb9cSdan ** is managed along with the rest of the Index structure. It will be 7169f8bb9cSdan ** released when sqlite3DeleteIndex() is called. 723d1bfeaaSdanielk1977 */ 73e9107698Sdrh const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){ 74a37cdde0Sdanielk1977 if( !pIdx->zColAff ){ 75e014a838Sdanielk1977 /* The first time a column affinity string for a particular index is 76a37cdde0Sdanielk1977 ** required, it is allocated and populated here. It is then stored as 77e014a838Sdanielk1977 ** a member of the Index structure for subsequent use. 78a37cdde0Sdanielk1977 ** 79a37cdde0Sdanielk1977 ** The column affinity string will eventually be deleted by 80e014a838Sdanielk1977 ** sqliteDeleteIndex() when the Index structure itself is cleaned 81a37cdde0Sdanielk1977 ** up. 82a37cdde0Sdanielk1977 */ 83a37cdde0Sdanielk1977 int n; 84a37cdde0Sdanielk1977 Table *pTab = pIdx->pTable; 85ad124329Sdrh pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1); 86a37cdde0Sdanielk1977 if( !pIdx->zColAff ){ 874a642b60Sdrh sqlite3OomFault(db); 8869f8bb9cSdan return 0; 89a37cdde0Sdanielk1977 } 90a37cdde0Sdanielk1977 for(n=0; n<pIdx->nColumn; n++){ 91ad124329Sdrh i16 x = pIdx->aiColumn[n]; 926860e6faSdrh char aff; 9381506b88Sdrh if( x>=0 ){ 9481506b88Sdrh aff = pTab->aCol[x].affinity; 9581506b88Sdrh }else if( x==XN_ROWID ){ 9681506b88Sdrh aff = SQLITE_AFF_INTEGER; 9781506b88Sdrh }else{ 984b92f98cSdrh assert( x==XN_EXPR ); 991f9ca2c8Sdrh assert( pIdx->aColExpr!=0 ); 1006860e6faSdrh aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr); 10181506b88Sdrh } 10296fb16eeSdrh if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB; 1037314495fSdrh if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC; 1046860e6faSdrh pIdx->zColAff[n] = aff; 1051f9ca2c8Sdrh } 1062d401ab8Sdrh pIdx->zColAff[n] = 0; 107a37cdde0Sdanielk1977 } 1083d1bfeaaSdanielk1977 10969f8bb9cSdan return pIdx->zColAff; 110a37cdde0Sdanielk1977 } 111a37cdde0Sdanielk1977 112a37cdde0Sdanielk1977 /* 11357bf4a8eSdrh ** Compute the affinity string for table pTab, if it has not already been 11405883a34Sdrh ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities. 11557bf4a8eSdrh ** 11605883a34Sdrh ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and 11757bf4a8eSdrh ** if iReg>0 then code an OP_Affinity opcode that will set the affinities 11857bf4a8eSdrh ** for register iReg and following. Or if affinities exists and iReg==0, 11957bf4a8eSdrh ** then just set the P4 operand of the previous opcode (which should be 12057bf4a8eSdrh ** an OP_MakeRecord) to the affinity string. 12157bf4a8eSdrh ** 122b6e8fd10Sdrh ** A column affinity string has one character per column: 123a37cdde0Sdanielk1977 ** 124a37cdde0Sdanielk1977 ** Character Column affinity 125a37cdde0Sdanielk1977 ** ------------------------------ 12605883a34Sdrh ** 'A' BLOB 1274583c37cSdrh ** 'B' TEXT 1284583c37cSdrh ** 'C' NUMERIC 1294583c37cSdrh ** 'D' INTEGER 1304583c37cSdrh ** 'E' REAL 131a37cdde0Sdanielk1977 */ 13257bf4a8eSdrh void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ 133ab45fc04Sdrh int i, j; 13457bf4a8eSdrh char *zColAff = pTab->zColAff; 13557bf4a8eSdrh if( zColAff==0 ){ 136abb6fcabSdrh sqlite3 *db = sqlite3VdbeDb(v); 137b975598eSdrh zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); 1383d1bfeaaSdanielk1977 if( !zColAff ){ 1394a642b60Sdrh sqlite3OomFault(db); 140a37cdde0Sdanielk1977 return; 1413d1bfeaaSdanielk1977 } 1423d1bfeaaSdanielk1977 143ab45fc04Sdrh for(i=j=0; i<pTab->nCol; i++){ 14496fb16eeSdrh assert( pTab->aCol[i].affinity!=0 ); 145ab45fc04Sdrh if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){ 146ab45fc04Sdrh zColAff[j++] = pTab->aCol[i].affinity; 147ab45fc04Sdrh } 1483d1bfeaaSdanielk1977 } 14957bf4a8eSdrh do{ 150ab45fc04Sdrh zColAff[j--] = 0; 151ab45fc04Sdrh }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB ); 1523d1bfeaaSdanielk1977 pTab->zColAff = zColAff; 1533d1bfeaaSdanielk1977 } 1547301e774Sdrh assert( zColAff!=0 ); 1557301e774Sdrh i = sqlite3Strlen30NN(zColAff); 15657bf4a8eSdrh if( i ){ 15757bf4a8eSdrh if( iReg ){ 15857bf4a8eSdrh sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i); 15957bf4a8eSdrh }else{ 16057bf4a8eSdrh sqlite3VdbeChangeP4(v, -1, zColAff, i); 16157bf4a8eSdrh } 16257bf4a8eSdrh } 1633d1bfeaaSdanielk1977 } 1643d1bfeaaSdanielk1977 1654d88778bSdanielk1977 /* 16648d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices 167b6e8fd10Sdrh ** have been opened at any point in the VDBE program. This is used to see if 16848d1178aSdrh ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can 169b6e8fd10Sdrh ** run without using a temporary table for the results of the SELECT. 1704d88778bSdanielk1977 */ 17105a86c5cSdrh static int readsTable(Parse *p, int iDb, Table *pTab){ 172595a523aSdanielk1977 Vdbe *v = sqlite3GetVdbe(p); 1734d88778bSdanielk1977 int i; 17448d1178aSdrh int iEnd = sqlite3VdbeCurrentAddr(v); 175595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 176595a523aSdanielk1977 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; 177595a523aSdanielk1977 #endif 178595a523aSdanielk1977 17905a86c5cSdrh for(i=1; i<iEnd; i++){ 18048d1178aSdrh VdbeOp *pOp = sqlite3VdbeGetOp(v, i); 181ef0bea92Sdrh assert( pOp!=0 ); 182207872a4Sdanielk1977 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ 18348d1178aSdrh Index *pIndex; 184207872a4Sdanielk1977 int tnum = pOp->p2; 18548d1178aSdrh if( tnum==pTab->tnum ){ 18648d1178aSdrh return 1; 18748d1178aSdrh } 18848d1178aSdrh for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 18948d1178aSdrh if( tnum==pIndex->tnum ){ 19048d1178aSdrh return 1; 19148d1178aSdrh } 19248d1178aSdrh } 19348d1178aSdrh } 194543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 195595a523aSdanielk1977 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){ 1962dca4ac1Sdanielk1977 assert( pOp->p4.pVtab!=0 ); 19766a5167bSdrh assert( pOp->p4type==P4_VTAB ); 19848d1178aSdrh return 1; 1994d88778bSdanielk1977 } 200543165efSdrh #endif 2014d88778bSdanielk1977 } 2024d88778bSdanielk1977 return 0; 2034d88778bSdanielk1977 } 2043d1bfeaaSdanielk1977 205c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 206c1431144Sdrh /* 207c1431144Sdrh ** All regular columns for table pTab have been puts into registers 208c1431144Sdrh ** starting with iRegStore. The registers that correspond to STORED 209c1431144Sdrh ** columns have not been initialized. This routine goes back and computes 210c1431144Sdrh ** the values for STORED columns based on the previously computed normal 211c1431144Sdrh ** columns. 212c1431144Sdrh */ 213c1431144Sdrh void sqlite3ComputeStoredColumns( 214c1431144Sdrh Parse *pParse, /* Parsing context */ 215c1431144Sdrh int iRegStore, /* Register holding the first column */ 216c1431144Sdrh Table *pTab /* The table */ 217c1431144Sdrh ){ 218c1431144Sdrh int i; 219c1431144Sdrh pParse->iSelfTab = -iRegStore; 220c1431144Sdrh for(i=0; i<pTab->nCol; i++, iRegStore++){ 221c1431144Sdrh u32 colFlags = pTab->aCol[i].colFlags; 222c1431144Sdrh if( (colFlags & COLFLAG_VIRTUAL)!=0 ){ 223*d4cd292cSdrh /* Virtual columns are not stored */ 224c1431144Sdrh iRegStore--; 225c1431144Sdrh }else if( (colFlags & COLFLAG_STORED)!=0 ){ 226c1431144Sdrh /* Stored columns are handled on the second pass */ 227c1431144Sdrh sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore); 228c1431144Sdrh } 229c1431144Sdrh } 230c1431144Sdrh pParse->iSelfTab = 0; 231c1431144Sdrh } 232c1431144Sdrh #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 233c1431144Sdrh 234c1431144Sdrh 2359d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 2369d9cf229Sdrh /* 2370b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab 2380b9f50d8Sdrh ** which is in database iDb. Return the register number for the register 2399ef5e770Sdrh ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT 2409ef5e770Sdrh ** table. (Also return zero when doing a VACUUM since we do not want to 2419ef5e770Sdrh ** update the AUTOINCREMENT counters during a VACUUM.) 2429d9cf229Sdrh ** 2430b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the 2440b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within 2450b9f50d8Sdrh ** triggers. A new AutoincInfo structure is created if this is the 2460b9f50d8Sdrh ** first use of table pTab. On 2nd and subsequent uses, the original 2470b9f50d8Sdrh ** AutoincInfo structure is used. 2489d9cf229Sdrh ** 249c8abbc11Sdrh ** Four consecutive registers are allocated: 2500b9f50d8Sdrh ** 251c8abbc11Sdrh ** (1) The name of the pTab table. 252c8abbc11Sdrh ** (2) The maximum ROWID of pTab. 253c8abbc11Sdrh ** (3) The rowid in sqlite_sequence of pTab 254c8abbc11Sdrh ** (4) The original value of the max ROWID in pTab, or NULL if none 2550b9f50d8Sdrh ** 2560b9f50d8Sdrh ** The 2nd register is the one that is returned. That is all the 2570b9f50d8Sdrh ** insert routine needs to know about. 2589d9cf229Sdrh */ 2599d9cf229Sdrh static int autoIncBegin( 2609d9cf229Sdrh Parse *pParse, /* Parsing context */ 2619d9cf229Sdrh int iDb, /* Index of the database holding pTab */ 2629d9cf229Sdrh Table *pTab /* The table we are writing to */ 2639d9cf229Sdrh ){ 2646a288a33Sdrh int memId = 0; /* Register holding maximum rowid */ 265186ebd41Sdrh assert( pParse->db->aDb[iDb].pSchema!=0 ); 2669ef5e770Sdrh if( (pTab->tabFlags & TF_Autoincrement)!=0 2678257aa8dSdrh && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0 2689ef5e770Sdrh ){ 26965a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 2700b9f50d8Sdrh AutoincInfo *pInfo; 271186ebd41Sdrh Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab; 272186ebd41Sdrh 273186ebd41Sdrh /* Verify that the sqlite_sequence table exists and is an ordinary 274186ebd41Sdrh ** rowid table with exactly two columns. 275186ebd41Sdrh ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */ 276186ebd41Sdrh if( pSeqTab==0 277186ebd41Sdrh || !HasRowid(pSeqTab) 278186ebd41Sdrh || IsVirtual(pSeqTab) 279186ebd41Sdrh || pSeqTab->nCol!=2 280186ebd41Sdrh ){ 281186ebd41Sdrh pParse->nErr++; 282186ebd41Sdrh pParse->rc = SQLITE_CORRUPT_SEQUENCE; 283186ebd41Sdrh return 0; 284186ebd41Sdrh } 2850b9f50d8Sdrh 28665a7cd16Sdan pInfo = pToplevel->pAinc; 2870b9f50d8Sdrh while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } 2880b9f50d8Sdrh if( pInfo==0 ){ 289575fad65Sdrh pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo)); 2900b9f50d8Sdrh if( pInfo==0 ) return 0; 29165a7cd16Sdan pInfo->pNext = pToplevel->pAinc; 29265a7cd16Sdan pToplevel->pAinc = pInfo; 2930b9f50d8Sdrh pInfo->pTab = pTab; 2940b9f50d8Sdrh pInfo->iDb = iDb; 29565a7cd16Sdan pToplevel->nMem++; /* Register to hold name of table */ 29665a7cd16Sdan pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ 297c8abbc11Sdrh pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */ 2980b9f50d8Sdrh } 2990b9f50d8Sdrh memId = pInfo->regCtr; 3009d9cf229Sdrh } 3019d9cf229Sdrh return memId; 3029d9cf229Sdrh } 3039d9cf229Sdrh 3049d9cf229Sdrh /* 3050b9f50d8Sdrh ** This routine generates code that will initialize all of the 3060b9f50d8Sdrh ** register used by the autoincrement tracker. 3070b9f50d8Sdrh */ 3080b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){ 3090b9f50d8Sdrh AutoincInfo *p; /* Information about an AUTOINCREMENT */ 3100b9f50d8Sdrh sqlite3 *db = pParse->db; /* The database connection */ 3110b9f50d8Sdrh Db *pDb; /* Database only autoinc table */ 3120b9f50d8Sdrh int memId; /* Register holding max rowid */ 3130b9f50d8Sdrh Vdbe *v = pParse->pVdbe; /* VDBE under construction */ 3140b9f50d8Sdrh 315345ba7dbSdrh /* This routine is never called during trigger-generation. It is 316345ba7dbSdrh ** only called from the top-level */ 317345ba7dbSdrh assert( pParse->pTriggerTab==0 ); 318c149f18fSdrh assert( sqlite3IsToplevel(pParse) ); 31976d462eeSdan 3200b9f50d8Sdrh assert( v ); /* We failed long ago if this is not so */ 3210b9f50d8Sdrh for(p = pParse->pAinc; p; p = p->pNext){ 3221b32554bSdrh static const int iLn = VDBE_OFFSET_LINENO(2); 3231b32554bSdrh static const VdbeOpList autoInc[] = { 3241b32554bSdrh /* 0 */ {OP_Null, 0, 0, 0}, 325c8abbc11Sdrh /* 1 */ {OP_Rewind, 0, 10, 0}, 3261b32554bSdrh /* 2 */ {OP_Column, 0, 0, 0}, 327c8abbc11Sdrh /* 3 */ {OP_Ne, 0, 9, 0}, 3281b32554bSdrh /* 4 */ {OP_Rowid, 0, 0, 0}, 3291b32554bSdrh /* 5 */ {OP_Column, 0, 1, 0}, 330c8abbc11Sdrh /* 6 */ {OP_AddImm, 0, 0, 0}, 331c8abbc11Sdrh /* 7 */ {OP_Copy, 0, 0, 0}, 332c8abbc11Sdrh /* 8 */ {OP_Goto, 0, 11, 0}, 333c8abbc11Sdrh /* 9 */ {OP_Next, 0, 2, 0}, 334c8abbc11Sdrh /* 10 */ {OP_Integer, 0, 0, 0}, 335c8abbc11Sdrh /* 11 */ {OP_Close, 0, 0, 0} 3361b32554bSdrh }; 3371b32554bSdrh VdbeOp *aOp; 3380b9f50d8Sdrh pDb = &db->aDb[p->iDb]; 3390b9f50d8Sdrh memId = p->regCtr; 3402120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 3410b9f50d8Sdrh sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); 342076e85f5Sdrh sqlite3VdbeLoadString(v, memId-1, p->pTab->zName); 3431b32554bSdrh aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn); 3441b32554bSdrh if( aOp==0 ) break; 3451b32554bSdrh aOp[0].p2 = memId; 346c8abbc11Sdrh aOp[0].p3 = memId+2; 3471b32554bSdrh aOp[2].p3 = memId; 3481b32554bSdrh aOp[3].p1 = memId-1; 3491b32554bSdrh aOp[3].p3 = memId; 3501b32554bSdrh aOp[3].p5 = SQLITE_JUMPIFNULL; 3511b32554bSdrh aOp[4].p2 = memId+1; 3521b32554bSdrh aOp[5].p3 = memId; 353c8abbc11Sdrh aOp[6].p1 = memId; 354c8abbc11Sdrh aOp[7].p2 = memId+2; 355c8abbc11Sdrh aOp[7].p1 = memId; 356c8abbc11Sdrh aOp[10].p2 = memId; 35704ab586bSdrh if( pParse->nTab==0 ) pParse->nTab = 1; 3580b9f50d8Sdrh } 3590b9f50d8Sdrh } 3600b9f50d8Sdrh 3610b9f50d8Sdrh /* 3629d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation. 3639d9cf229Sdrh ** 3641b32554bSdrh ** This routine should be called when the regRowid register holds a 3659d9cf229Sdrh ** new rowid that is about to be inserted. If that new rowid is 3669d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the 3671b32554bSdrh ** memory cell is updated. 3689d9cf229Sdrh */ 3696a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){ 3709d9cf229Sdrh if( memId>0 ){ 3716a288a33Sdrh sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); 3729d9cf229Sdrh } 3739d9cf229Sdrh } 3749d9cf229Sdrh 3759d9cf229Sdrh /* 3760b9f50d8Sdrh ** This routine generates the code needed to write autoincrement 3770b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register. 3780b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement 3790b9f50d8Sdrh ** table (either directly or through triggers) needs to call this 3800b9f50d8Sdrh ** routine just before the "exit" code. 3819d9cf229Sdrh */ 3821b32554bSdrh static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ 3830b9f50d8Sdrh AutoincInfo *p; 3849d9cf229Sdrh Vdbe *v = pParse->pVdbe; 3850b9f50d8Sdrh sqlite3 *db = pParse->db; 3866a288a33Sdrh 3879d9cf229Sdrh assert( v ); 3880b9f50d8Sdrh for(p = pParse->pAinc; p; p = p->pNext){ 3891b32554bSdrh static const int iLn = VDBE_OFFSET_LINENO(2); 3901b32554bSdrh static const VdbeOpList autoIncEnd[] = { 3911b32554bSdrh /* 0 */ {OP_NotNull, 0, 2, 0}, 3921b32554bSdrh /* 1 */ {OP_NewRowid, 0, 0, 0}, 3931b32554bSdrh /* 2 */ {OP_MakeRecord, 0, 2, 0}, 3941b32554bSdrh /* 3 */ {OP_Insert, 0, 0, 0}, 3951b32554bSdrh /* 4 */ {OP_Close, 0, 0, 0} 3961b32554bSdrh }; 3971b32554bSdrh VdbeOp *aOp; 3980b9f50d8Sdrh Db *pDb = &db->aDb[p->iDb]; 3990b9f50d8Sdrh int iRec; 4000b9f50d8Sdrh int memId = p->regCtr; 4010b9f50d8Sdrh 4020b9f50d8Sdrh iRec = sqlite3GetTempReg(pParse); 4032120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 404c8abbc11Sdrh sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId); 405c8abbc11Sdrh VdbeCoverage(v); 4060b9f50d8Sdrh sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); 4071b32554bSdrh aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn); 4081b32554bSdrh if( aOp==0 ) break; 4091b32554bSdrh aOp[0].p1 = memId+1; 4101b32554bSdrh aOp[1].p2 = memId+1; 4111b32554bSdrh aOp[2].p1 = memId-1; 4121b32554bSdrh aOp[2].p3 = iRec; 4131b32554bSdrh aOp[3].p2 = iRec; 4141b32554bSdrh aOp[3].p3 = memId+1; 4151b32554bSdrh aOp[3].p5 = OPFLAG_APPEND; 4160b9f50d8Sdrh sqlite3ReleaseTempReg(pParse, iRec); 4179d9cf229Sdrh } 4189d9cf229Sdrh } 4191b32554bSdrh void sqlite3AutoincrementEnd(Parse *pParse){ 4201b32554bSdrh if( pParse->pAinc ) autoIncrementEnd(pParse); 4211b32554bSdrh } 4229d9cf229Sdrh #else 4239d9cf229Sdrh /* 4249d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines 4259d9cf229Sdrh ** above are all no-ops 4269d9cf229Sdrh */ 4279d9cf229Sdrh # define autoIncBegin(A,B,C) (0) 428287fb61cSdanielk1977 # define autoIncStep(A,B,C) 4299d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */ 4309d9cf229Sdrh 4319d9cf229Sdrh 4329d9cf229Sdrh /* Forward declaration */ 4339d9cf229Sdrh static int xferOptimization( 4349d9cf229Sdrh Parse *pParse, /* Parser context */ 4359d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 4369d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 4379d9cf229Sdrh int onError, /* How to handle constraint errors */ 4389d9cf229Sdrh int iDbDest /* The database of pDest */ 4399d9cf229Sdrh ); 4409d9cf229Sdrh 4413d1bfeaaSdanielk1977 /* 442d82b5021Sdrh ** This routine is called to handle SQL of the following forms: 443cce7d176Sdrh ** 444a21f78b9Sdrh ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),... 4451ccde15dSdrh ** insert into TABLE (IDLIST) select 446a21f78b9Sdrh ** insert into TABLE (IDLIST) default values 447cce7d176Sdrh ** 4481ccde15dSdrh ** The IDLIST following the table name is always optional. If omitted, 449a21f78b9Sdrh ** then a list of all (non-hidden) columns for the table is substituted. 450a21f78b9Sdrh ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST 451a21f78b9Sdrh ** is omitted. 4521ccde15dSdrh ** 453a21f78b9Sdrh ** For the pSelect parameter holds the values to be inserted for the 454a21f78b9Sdrh ** first two forms shown above. A VALUES clause is really just short-hand 455a21f78b9Sdrh ** for a SELECT statement that omits the FROM clause and everything else 456a21f78b9Sdrh ** that follows. If the pSelect parameter is NULL, that means that the 457a21f78b9Sdrh ** DEFAULT VALUES form of the INSERT statement is intended. 458142e30dfSdrh ** 4599d9cf229Sdrh ** The code generated follows one of four templates. For a simple 460a21f78b9Sdrh ** insert with data coming from a single-row VALUES clause, the code executes 461e00ee6ebSdrh ** once straight down through. Pseudo-code follows (we call this 462e00ee6ebSdrh ** the "1st template"): 463142e30dfSdrh ** 464142e30dfSdrh ** open write cursor to <table> and its indices 465ec95c441Sdrh ** put VALUES clause expressions into registers 466142e30dfSdrh ** write the resulting record into <table> 467142e30dfSdrh ** cleanup 468142e30dfSdrh ** 4699d9cf229Sdrh ** The three remaining templates assume the statement is of the form 470142e30dfSdrh ** 471142e30dfSdrh ** INSERT INTO <table> SELECT ... 472142e30dfSdrh ** 4739d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - 4749d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table 4759d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and 4769d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical 4779d9cf229Sdrh ** schemas, including all the same indices, then a special optimization 4789d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>. 4799d9cf229Sdrh ** See the xferOptimization() function for the implementation of this 480e00ee6ebSdrh ** template. This is the 2nd template. 4819d9cf229Sdrh ** 4829d9cf229Sdrh ** open a write cursor to <table> 4839d9cf229Sdrh ** open read cursor on <table2> 4849d9cf229Sdrh ** transfer all records in <table2> over to <table> 4859d9cf229Sdrh ** close cursors 4869d9cf229Sdrh ** foreach index on <table> 4879d9cf229Sdrh ** open a write cursor on the <table> index 4889d9cf229Sdrh ** open a read cursor on the corresponding <table2> index 4899d9cf229Sdrh ** transfer all records from the read to the write cursors 4909d9cf229Sdrh ** close cursors 4919d9cf229Sdrh ** end foreach 4929d9cf229Sdrh ** 493e00ee6ebSdrh ** The 3rd template is for when the second template does not apply 4949d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time. 4959d9cf229Sdrh ** The generated code follows this template: 496142e30dfSdrh ** 497e00ee6ebSdrh ** X <- A 498142e30dfSdrh ** goto B 499142e30dfSdrh ** A: setup for the SELECT 5009d9cf229Sdrh ** loop over the rows in the SELECT 501e00ee6ebSdrh ** load values into registers R..R+n 502e00ee6ebSdrh ** yield X 503142e30dfSdrh ** end loop 504142e30dfSdrh ** cleanup after the SELECT 50581cf13ecSdrh ** end-coroutine X 506e00ee6ebSdrh ** B: open write cursor to <table> and its indices 50781cf13ecSdrh ** C: yield X, at EOF goto D 508e00ee6ebSdrh ** insert the select result into <table> from R..R+n 509e00ee6ebSdrh ** goto C 510142e30dfSdrh ** D: cleanup 511142e30dfSdrh ** 512e00ee6ebSdrh ** The 4th template is used if the insert statement takes its 513142e30dfSdrh ** values from a SELECT but the data is being inserted into a table 514142e30dfSdrh ** that is also read as part of the SELECT. In the third form, 51560ec914cSpeter.d.reid ** we have to use an intermediate table to store the results of 516142e30dfSdrh ** the select. The template is like this: 517142e30dfSdrh ** 518e00ee6ebSdrh ** X <- A 519142e30dfSdrh ** goto B 520142e30dfSdrh ** A: setup for the SELECT 521142e30dfSdrh ** loop over the tables in the SELECT 522e00ee6ebSdrh ** load value into register R..R+n 523e00ee6ebSdrh ** yield X 524142e30dfSdrh ** end loop 525142e30dfSdrh ** cleanup after the SELECT 52681cf13ecSdrh ** end co-routine R 527e00ee6ebSdrh ** B: open temp table 52881cf13ecSdrh ** L: yield X, at EOF goto M 529e00ee6ebSdrh ** insert row from R..R+n into temp table 530e00ee6ebSdrh ** goto L 531e00ee6ebSdrh ** M: open write cursor to <table> and its indices 532e00ee6ebSdrh ** rewind temp table 533e00ee6ebSdrh ** C: loop over rows of intermediate table 534142e30dfSdrh ** transfer values form intermediate table into <table> 535e00ee6ebSdrh ** end loop 536e00ee6ebSdrh ** D: cleanup 537cce7d176Sdrh */ 5384adee20fSdanielk1977 void sqlite3Insert( 539cce7d176Sdrh Parse *pParse, /* Parser context */ 540113088ecSdrh SrcList *pTabList, /* Name of table into which we are inserting */ 5415974a30fSdrh Select *pSelect, /* A SELECT statement to use as the data source */ 5429cfcf5d4Sdrh IdList *pColumn, /* Column names corresponding to IDLIST. */ 5432c2e844aSdrh int onError, /* How to handle constraint errors */ 54446d2e5c3Sdrh Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */ 545cce7d176Sdrh ){ 5466a288a33Sdrh sqlite3 *db; /* The main database structure */ 5476a288a33Sdrh Table *pTab; /* The table to insert into. aka TABLE */ 54860ffc807Sdrh int i, j; /* Loop counters */ 5495974a30fSdrh Vdbe *v; /* Generate code into this virtual machine */ 5505974a30fSdrh Index *pIdx; /* For looping over indices of the table */ 551967e8b73Sdrh int nColumn; /* Number of columns in the data */ 5526a288a33Sdrh int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ 55326198bb4Sdrh int iDataCur = 0; /* VDBE cursor that is the main data repository */ 55426198bb4Sdrh int iIdxCur = 0; /* First index cursor */ 555d82b5021Sdrh int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ 5560ca3e24bSdrh int endOfLoop; /* Label for the end of the insertion loop */ 557cfe9a69fSdanielk1977 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ 558e00ee6ebSdrh int addrInsTop = 0; /* Jump to label "D" */ 559e00ee6ebSdrh int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ 5602eb95377Sdrh SelectDest dest; /* Destination for SELECT on rhs of INSERT */ 5616a288a33Sdrh int iDb; /* Index of database holding TABLE */ 56205a86c5cSdrh u8 useTempTable = 0; /* Store SELECT results in intermediate table */ 56305a86c5cSdrh u8 appendFlag = 0; /* True if the insert is likely to be an append */ 56405a86c5cSdrh u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ 565a21f78b9Sdrh u8 bIdListInOrder; /* True if IDLIST is in table order */ 56675593d96Sdrh ExprList *pList = 0; /* List of VALUES() to be inserted */ 567c27ea2aeSdrh int iRegStore; /* Register in which to store next column */ 568cce7d176Sdrh 5696a288a33Sdrh /* Register allocations */ 5701bd10f8aSdrh int regFromSelect = 0;/* Base register for data coming from SELECT */ 5716a288a33Sdrh int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ 5726a288a33Sdrh int regRowCount = 0; /* Memory cell used for the row counter */ 5736a288a33Sdrh int regIns; /* Block of regs holding rowid+data being inserted */ 5746a288a33Sdrh int regRowid; /* registers holding insert rowid */ 5756a288a33Sdrh int regData; /* register holding first column to insert */ 576aa9b8963Sdrh int *aRegIdx = 0; /* One register allocated to each index */ 5776a288a33Sdrh 578798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER 579798da52cSdrh int isView; /* True if attempting to insert into a view */ 5802f886d1dSdanielk1977 Trigger *pTrigger; /* List of triggers on pTab, if required */ 5812f886d1dSdanielk1977 int tmask; /* Mask of trigger times */ 582798da52cSdrh #endif 583c3f9bad2Sdanielk1977 58417435752Sdrh db = pParse->db; 58517435752Sdrh if( pParse->nErr || db->mallocFailed ){ 5866f7adc8aSdrh goto insert_cleanup; 5876f7adc8aSdrh } 5884c883487Sdrh dest.iSDParm = 0; /* Suppress a harmless compiler warning */ 589daffd0e5Sdrh 59075593d96Sdrh /* If the Select object is really just a simple VALUES() list with a 591a21f78b9Sdrh ** single row (the common case) then keep that one row of values 592a21f78b9Sdrh ** and discard the other (unused) parts of the pSelect object 59375593d96Sdrh */ 59475593d96Sdrh if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){ 59575593d96Sdrh pList = pSelect->pEList; 59675593d96Sdrh pSelect->pEList = 0; 59775593d96Sdrh sqlite3SelectDelete(db, pSelect); 59875593d96Sdrh pSelect = 0; 59975593d96Sdrh } 60075593d96Sdrh 6011ccde15dSdrh /* Locate the table into which we will be inserting new information. 6021ccde15dSdrh */ 603113088ecSdrh assert( pTabList->nSrc==1 ); 6044adee20fSdanielk1977 pTab = sqlite3SrcListLookup(pParse, pTabList); 605c3f9bad2Sdanielk1977 if( pTab==0 ){ 606c3f9bad2Sdanielk1977 goto insert_cleanup; 607c3f9bad2Sdanielk1977 } 608da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 609da184236Sdanielk1977 assert( iDb<db->nDb ); 610a0daa751Sdrh if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, 611a0daa751Sdrh db->aDb[iDb].zDbSName) ){ 6121962bda7Sdrh goto insert_cleanup; 6131962bda7Sdrh } 614ec95c441Sdrh withoutRowid = !HasRowid(pTab); 615c3f9bad2Sdanielk1977 616b7f9164eSdrh /* Figure out if we have any triggers and if the table being 617b7f9164eSdrh ** inserted into is a view 618b7f9164eSdrh */ 619b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER 6202f886d1dSdanielk1977 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); 621b7f9164eSdrh isView = pTab->pSelect!=0; 622b7f9164eSdrh #else 6232f886d1dSdanielk1977 # define pTrigger 0 6242f886d1dSdanielk1977 # define tmask 0 625b7f9164eSdrh # define isView 0 626b7f9164eSdrh #endif 627b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW 628b7f9164eSdrh # undef isView 629b7f9164eSdrh # define isView 0 630b7f9164eSdrh #endif 6312f886d1dSdanielk1977 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); 632b7f9164eSdrh 633f573c99bSdrh /* If pTab is really a view, make sure it has been initialized. 634d82b5021Sdrh ** ViewGetColumnNames() is a no-op if pTab is not a view. 635f573c99bSdrh */ 636b3d24bf8Sdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 637f573c99bSdrh goto insert_cleanup; 638f573c99bSdrh } 639f573c99bSdrh 640d82b5021Sdrh /* Cannot insert into a read-only table. 641595a523aSdanielk1977 */ 642595a523aSdanielk1977 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ 643595a523aSdanielk1977 goto insert_cleanup; 644595a523aSdanielk1977 } 645595a523aSdanielk1977 6461ccde15dSdrh /* Allocate a VDBE 6471ccde15dSdrh */ 6484adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 6495974a30fSdrh if( v==0 ) goto insert_cleanup; 6504794f735Sdrh if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 6512f886d1dSdanielk1977 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); 6521ccde15dSdrh 6539d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 6549d9cf229Sdrh /* If the statement is of the form 6559d9cf229Sdrh ** 6569d9cf229Sdrh ** INSERT INTO <table1> SELECT * FROM <table2>; 6579d9cf229Sdrh ** 6589d9cf229Sdrh ** Then special optimizations can be applied that make the transfer 6599d9cf229Sdrh ** very fast and which reduce fragmentation of indices. 660e00ee6ebSdrh ** 661e00ee6ebSdrh ** This is the 2nd template. 6629d9cf229Sdrh */ 6639d9cf229Sdrh if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ 6642f886d1dSdanielk1977 assert( !pTrigger ); 6659d9cf229Sdrh assert( pList==0 ); 6660b9f50d8Sdrh goto insert_end; 6679d9cf229Sdrh } 6689d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 6699d9cf229Sdrh 6702958a4e6Sdrh /* If this is an AUTOINCREMENT table, look up the sequence number in the 6716a288a33Sdrh ** sqlite_sequence table and store it in memory cell regAutoinc. 6722958a4e6Sdrh */ 6736a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDb, pTab); 6742958a4e6Sdrh 67505a86c5cSdrh /* Allocate registers for holding the rowid of the new row, 67660ec914cSpeter.d.reid ** the content of the new row, and the assembled row record. 6771ccde15dSdrh */ 67805a86c5cSdrh regRowid = regIns = pParse->nMem+1; 67905a86c5cSdrh pParse->nMem += pTab->nCol + 1; 680034ca14fSdanielk1977 if( IsVirtual(pTab) ){ 68105a86c5cSdrh regRowid++; 68205a86c5cSdrh pParse->nMem++; 683034ca14fSdanielk1977 } 68405a86c5cSdrh regData = regRowid+1; 6851ccde15dSdrh 6861ccde15dSdrh /* If the INSERT statement included an IDLIST term, then make sure 6871ccde15dSdrh ** all elements of the IDLIST really are columns of the table and 6881ccde15dSdrh ** remember the column indices. 689c8392586Sdrh ** 690c8392586Sdrh ** If the table has an INTEGER PRIMARY KEY column and that column 691d82b5021Sdrh ** is named in the IDLIST, then record in the ipkColumn variable 692d82b5021Sdrh ** the index into IDLIST of the primary key column. ipkColumn is 693c8392586Sdrh ** the index of the primary key as it appears in IDLIST, not as 694d82b5021Sdrh ** is appears in the original table. (The index of the INTEGER 695d82b5021Sdrh ** PRIMARY KEY in the original table is pTab->iPKey.) 6961ccde15dSdrh */ 697*d4cd292cSdrh bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0; 698967e8b73Sdrh if( pColumn ){ 699967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 700967e8b73Sdrh pColumn->a[i].idx = -1; 701cce7d176Sdrh } 702967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 703cce7d176Sdrh for(j=0; j<pTab->nCol; j++){ 7044adee20fSdanielk1977 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ 705967e8b73Sdrh pColumn->a[i].idx = j; 70605a86c5cSdrh if( i!=j ) bIdListInOrder = 0; 7074a32431cSdrh if( j==pTab->iPKey ){ 708d82b5021Sdrh ipkColumn = i; assert( !withoutRowid ); 7094a32431cSdrh } 7107e508f1eSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 7117e508f1eSdrh if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){ 7127e508f1eSdrh sqlite3ErrorMsg(pParse, 7137e508f1eSdrh "cannot INSERT into generated column \"%s\"", 7147e508f1eSdrh pTab->aCol[j].zName); 7157e508f1eSdrh goto insert_cleanup; 7167e508f1eSdrh } 7177e508f1eSdrh #endif 718cce7d176Sdrh break; 719cce7d176Sdrh } 720cce7d176Sdrh } 721cce7d176Sdrh if( j>=pTab->nCol ){ 722ec95c441Sdrh if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ 723d82b5021Sdrh ipkColumn = i; 724e48ae715Sdrh bIdListInOrder = 0; 725a0217ba7Sdrh }else{ 7264adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %S has no column named %s", 727da93d238Sdrh pTabList, 0, pColumn->a[i].zName); 7281db95106Sdan pParse->checkSchema = 1; 729cce7d176Sdrh goto insert_cleanup; 730cce7d176Sdrh } 731cce7d176Sdrh } 732cce7d176Sdrh } 733a0217ba7Sdrh } 7341ccde15dSdrh 735cce7d176Sdrh /* Figure out how many columns of data are supplied. If the data 736cce7d176Sdrh ** is coming from a SELECT statement, then generate a co-routine that 737cce7d176Sdrh ** produces a single row of the SELECT on each invocation. The 738cce7d176Sdrh ** co-routine is the common header to the 3rd and 4th templates. 739cce7d176Sdrh */ 7405f085269Sdrh if( pSelect ){ 741a21f78b9Sdrh /* Data is coming from a SELECT or from a multi-row VALUES clause. 742a21f78b9Sdrh ** Generate a co-routine to run the SELECT. */ 74305a86c5cSdrh int regYield; /* Register holding co-routine entry-point */ 74405a86c5cSdrh int addrTop; /* Top of the co-routine */ 74505a86c5cSdrh int rc; /* Result code */ 746cce7d176Sdrh 74705a86c5cSdrh regYield = ++pParse->nMem; 74805a86c5cSdrh addrTop = sqlite3VdbeCurrentAddr(v) + 1; 74905a86c5cSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 75005a86c5cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 75105a86c5cSdrh dest.iSdst = bIdListInOrder ? regData : 0; 75205a86c5cSdrh dest.nSdst = pTab->nCol; 75305a86c5cSdrh rc = sqlite3Select(pParse, pSelect, &dest); 7542b596da8Sdrh regFromSelect = dest.iSdst; 755992590beSdrh if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup; 7562fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regYield); 75705a86c5cSdrh sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ 758cce7d176Sdrh assert( pSelect->pEList ); 759cce7d176Sdrh nColumn = pSelect->pEList->nExpr; 760cce7d176Sdrh 761cce7d176Sdrh /* Set useTempTable to TRUE if the result of the SELECT statement 762cce7d176Sdrh ** should be written into a temporary table (template 4). Set to 763cce7d176Sdrh ** FALSE if each output row of the SELECT can be written directly into 764cce7d176Sdrh ** the destination table (template 3). 765cce7d176Sdrh ** 766cce7d176Sdrh ** A temp table must be used if the table being updated is also one 767cce7d176Sdrh ** of the tables being read by the SELECT statement. Also use a 768cce7d176Sdrh ** temp table in the case of row triggers. 769cce7d176Sdrh */ 77005a86c5cSdrh if( pTrigger || readsTable(pParse, iDb, pTab) ){ 771cce7d176Sdrh useTempTable = 1; 772cce7d176Sdrh } 773cce7d176Sdrh 774cce7d176Sdrh if( useTempTable ){ 775cce7d176Sdrh /* Invoke the coroutine to extract information from the SELECT 776cce7d176Sdrh ** and add it to a transient table srcTab. The code generated 777cce7d176Sdrh ** here is from the 4th template: 778cce7d176Sdrh ** 779cce7d176Sdrh ** B: open temp table 78081cf13ecSdrh ** L: yield X, goto M at EOF 781cce7d176Sdrh ** insert row from R..R+n into temp table 782cce7d176Sdrh ** goto L 783cce7d176Sdrh ** M: ... 784cce7d176Sdrh */ 785cce7d176Sdrh int regRec; /* Register to hold packed record */ 786cce7d176Sdrh int regTempRowid; /* Register to hold temp table ROWID */ 78706280ee5Sdrh int addrL; /* Label "L" */ 788cce7d176Sdrh 789cce7d176Sdrh srcTab = pParse->nTab++; 790cce7d176Sdrh regRec = sqlite3GetTempReg(pParse); 791cce7d176Sdrh regTempRowid = sqlite3GetTempReg(pParse); 792cce7d176Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); 79306280ee5Sdrh addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); 794cce7d176Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); 795cce7d176Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); 796cce7d176Sdrh sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); 797076e85f5Sdrh sqlite3VdbeGoto(v, addrL); 79806280ee5Sdrh sqlite3VdbeJumpHere(v, addrL); 799cce7d176Sdrh sqlite3ReleaseTempReg(pParse, regRec); 800cce7d176Sdrh sqlite3ReleaseTempReg(pParse, regTempRowid); 801cce7d176Sdrh } 802cce7d176Sdrh }else{ 803a21f78b9Sdrh /* This is the case if the data for the INSERT is coming from a 804a21f78b9Sdrh ** single-row VALUES clause 805cce7d176Sdrh */ 806cce7d176Sdrh NameContext sNC; 807cce7d176Sdrh memset(&sNC, 0, sizeof(sNC)); 808cce7d176Sdrh sNC.pParse = pParse; 809cce7d176Sdrh srcTab = -1; 810cce7d176Sdrh assert( useTempTable==0 ); 811fea870beSdrh if( pList ){ 812fea870beSdrh nColumn = pList->nExpr; 813fea870beSdrh if( sqlite3ResolveExprListNames(&sNC, pList) ){ 814cce7d176Sdrh goto insert_cleanup; 815cce7d176Sdrh } 816fea870beSdrh }else{ 817fea870beSdrh nColumn = 0; 818cce7d176Sdrh } 819cce7d176Sdrh } 820cce7d176Sdrh 821aacc543eSdrh /* If there is no IDLIST term but the table has an integer primary 822d82b5021Sdrh ** key, the set the ipkColumn variable to the integer primary key 823d82b5021Sdrh ** column index in the original table definition. 8244a32431cSdrh */ 825147d0cccSdrh if( pColumn==0 && nColumn>0 ){ 826d82b5021Sdrh ipkColumn = pTab->iPKey; 8274a32431cSdrh } 8284a32431cSdrh 829cce7d176Sdrh /* Make sure the number of columns in the source data matches the number 830cce7d176Sdrh ** of columns to be inserted into the table. 831cce7d176Sdrh */ 832cce7d176Sdrh for(i=0; i<pTab->nCol; i++){ 8337e508f1eSdrh if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++; 834cce7d176Sdrh } 835cce7d176Sdrh if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ 836cce7d176Sdrh sqlite3ErrorMsg(pParse, 837cce7d176Sdrh "table %S has %d columns but %d values were supplied", 838cce7d176Sdrh pTabList, 0, pTab->nCol-nHidden, nColumn); 839cce7d176Sdrh goto insert_cleanup; 840cce7d176Sdrh } 841cce7d176Sdrh if( pColumn!=0 && nColumn!=pColumn->nId ){ 842cce7d176Sdrh sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 843cce7d176Sdrh goto insert_cleanup; 844cce7d176Sdrh } 845cce7d176Sdrh 846c3f9bad2Sdanielk1977 /* Initialize the count of rows to be inserted 8471ccde15dSdrh */ 84879636913Sdrh if( (db->flags & SQLITE_CountRows)!=0 84979636913Sdrh && !pParse->nested 85079636913Sdrh && !pParse->pTriggerTab 85179636913Sdrh ){ 8526a288a33Sdrh regRowCount = ++pParse->nMem; 8536a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 854c3f9bad2Sdanielk1977 } 855c3f9bad2Sdanielk1977 856e448dc4aSdanielk1977 /* If this is not a view, open the table and and all indices */ 857e448dc4aSdanielk1977 if( !isView ){ 858aa9b8963Sdrh int nIdx; 859fd261ec6Sdan nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0, 86026198bb4Sdrh &iDataCur, &iIdxCur); 861a7c3b93fSdrh aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2)); 862aa9b8963Sdrh if( aRegIdx==0 ){ 863aa9b8963Sdrh goto insert_cleanup; 864aa9b8963Sdrh } 8652c4dfc30Sdrh for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){ 8662c4dfc30Sdrh assert( pIdx ); 867aa9b8963Sdrh aRegIdx[i] = ++pParse->nMem; 8682c4dfc30Sdrh pParse->nMem += pIdx->nColumn; 869aa9b8963Sdrh } 870a7c3b93fSdrh aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */ 871feeb1394Sdrh } 872788d55aaSdrh #ifndef SQLITE_OMIT_UPSERT 8730b30a116Sdrh if( pUpsert ){ 874b042d921Sdrh if( IsVirtual(pTab) ){ 875b042d921Sdrh sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"", 876b042d921Sdrh pTab->zName); 877b042d921Sdrh goto insert_cleanup; 878b042d921Sdrh } 8799105fd51Sdan if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){ 8809105fd51Sdan goto insert_cleanup; 8819105fd51Sdan } 882788d55aaSdrh pTabList->a[0].iCursor = iDataCur; 8830b30a116Sdrh pUpsert->pUpsertSrc = pTabList; 884eac9fabbSdrh pUpsert->regData = regData; 8857fc3aba8Sdrh pUpsert->iDataCur = iDataCur; 8867fc3aba8Sdrh pUpsert->iIdxCur = iIdxCur; 8870b30a116Sdrh if( pUpsert->pUpsertTarget ){ 888e9c2e772Sdrh sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert); 889788d55aaSdrh } 8900b30a116Sdrh } 891788d55aaSdrh #endif 892788d55aaSdrh 893feeb1394Sdrh 894e00ee6ebSdrh /* This is the top of the main insertion loop */ 895142e30dfSdrh if( useTempTable ){ 896e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 897e00ee6ebSdrh ** following pseudocode (template 4): 898e00ee6ebSdrh ** 89981cf13ecSdrh ** rewind temp table, if empty goto D 900e00ee6ebSdrh ** C: loop over rows of intermediate table 901e00ee6ebSdrh ** transfer values form intermediate table into <table> 902e00ee6ebSdrh ** end loop 903e00ee6ebSdrh ** D: ... 904e00ee6ebSdrh */ 905688852abSdrh addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); 906e00ee6ebSdrh addrCont = sqlite3VdbeCurrentAddr(v); 907142e30dfSdrh }else if( pSelect ){ 908e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 909e00ee6ebSdrh ** following pseudocode (template 3): 910e00ee6ebSdrh ** 91181cf13ecSdrh ** C: yield X, at EOF goto D 912e00ee6ebSdrh ** insert the select result into <table> from R..R+n 913e00ee6ebSdrh ** goto C 914e00ee6ebSdrh ** D: ... 915e00ee6ebSdrh */ 91681cf13ecSdrh addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 917688852abSdrh VdbeCoverage(v); 918bed8690fSdrh } 9191ccde15dSdrh 9205cf590c1Sdrh /* Run the BEFORE and INSTEAD OF triggers, if there are any 92170ce3f0cSdrh */ 922ec4ccdbcSdrh endOfLoop = sqlite3VdbeMakeLabel(pParse); 9232f886d1dSdanielk1977 if( tmask & TRIGGER_BEFORE ){ 92476d462eeSdan int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); 925c3f9bad2Sdanielk1977 92670ce3f0cSdrh /* build the NEW.* reference row. Note that if there is an INTEGER 92770ce3f0cSdrh ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 92870ce3f0cSdrh ** translated into a unique ID for the row. But on a BEFORE trigger, 92970ce3f0cSdrh ** we do not know what the unique ID will be (because the insert has 93070ce3f0cSdrh ** not happened yet) so we substitute a rowid of -1 93170ce3f0cSdrh */ 932d82b5021Sdrh if( ipkColumn<0 ){ 93376d462eeSdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 93470ce3f0cSdrh }else{ 935728e0f91Sdrh int addr1; 936ec95c441Sdrh assert( !withoutRowid ); 9377fe45908Sdrh if( useTempTable ){ 938d82b5021Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); 9397fe45908Sdrh }else{ 940d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 941d82b5021Sdrh sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); 9427fe45908Sdrh } 943728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); 94476d462eeSdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 945728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 946688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); 94770ce3f0cSdrh } 94870ce3f0cSdrh 949034ca14fSdanielk1977 /* Cannot have triggers on a virtual table. If it were possible, 950034ca14fSdanielk1977 ** this block would have to account for hidden column. 951034ca14fSdanielk1977 */ 952034ca14fSdanielk1977 assert( !IsVirtual(pTab) ); 953034ca14fSdanielk1977 95470ce3f0cSdrh /* Create the new column data 95570ce3f0cSdrh */ 956b1daa3f4Sdrh for(i=j=0; i<pTab->nCol; i++){ 957b1daa3f4Sdrh if( pColumn ){ 958c3f9bad2Sdanielk1977 for(j=0; j<pColumn->nId; j++){ 959c3f9bad2Sdanielk1977 if( pColumn->a[j].idx==i ) break; 960c3f9bad2Sdanielk1977 } 961c3f9bad2Sdanielk1977 } 962b1daa3f4Sdrh if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) 96303d69a68Sdrh || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){ 96476d462eeSdan sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1); 965142e30dfSdrh }else if( useTempTable ){ 96676d462eeSdan sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 967c3f9bad2Sdanielk1977 }else{ 968d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 96976d462eeSdan sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); 970c3f9bad2Sdanielk1977 } 97103d69a68Sdrh if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++; 972c3f9bad2Sdanielk1977 } 973a37cdde0Sdanielk1977 974a37cdde0Sdanielk1977 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 975a37cdde0Sdanielk1977 ** do not attempt any conversions before assembling the record. 976a37cdde0Sdanielk1977 ** If this is a real table, attempt conversions as required by the 977a37cdde0Sdanielk1977 ** table column affinities. 978a37cdde0Sdanielk1977 */ 979a37cdde0Sdanielk1977 if( !isView ){ 98057bf4a8eSdrh sqlite3TableAffinity(v, pTab, regCols+1); 981a37cdde0Sdanielk1977 } 982c3f9bad2Sdanielk1977 9835cf590c1Sdrh /* Fire BEFORE or INSTEAD OF triggers */ 984165921a7Sdan sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 98594d7f50aSdan pTab, regCols-pTab->nCol-1, onError, endOfLoop); 986165921a7Sdan 98776d462eeSdan sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); 98870ce3f0cSdrh } 989c3f9bad2Sdanielk1977 990d82b5021Sdrh /* Compute the content of the next row to insert into a range of 991d82b5021Sdrh ** registers beginning at regIns. 9921ccde15dSdrh */ 9935cf590c1Sdrh if( !isView ){ 9944cbdda9eSdrh if( IsVirtual(pTab) ){ 9954cbdda9eSdrh /* The row that the VUpdate opcode will delete: none */ 9966a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); 9974cbdda9eSdrh } 998d82b5021Sdrh if( ipkColumn>=0 ){ 999142e30dfSdrh if( useTempTable ){ 1000d82b5021Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); 1001142e30dfSdrh }else if( pSelect ){ 100205a86c5cSdrh sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); 10034a32431cSdrh }else{ 100404fcef00Sdrh Expr *pIpk = pList->a[ipkColumn].pExpr; 100504fcef00Sdrh if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){ 100604fcef00Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 1007e4d90813Sdrh appendFlag = 1; 100804fcef00Sdrh }else{ 100904fcef00Sdrh sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); 1010e4d90813Sdrh } 101127a32783Sdrh } 1012f0863fe5Sdrh /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 1013e1e68f49Sdrh ** to generate a unique primary key value. 1014e1e68f49Sdrh */ 1015e4d90813Sdrh if( !appendFlag ){ 1016728e0f91Sdrh int addr1; 1017bb50e7adSdanielk1977 if( !IsVirtual(pTab) ){ 1018728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); 101926198bb4Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 1020728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 1021bb50e7adSdanielk1977 }else{ 1022728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 1023728e0f91Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); 1024bb50e7adSdanielk1977 } 1025688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); 1026e4d90813Sdrh } 1027ec95c441Sdrh }else if( IsVirtual(pTab) || withoutRowid ){ 10286a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); 10294a32431cSdrh }else{ 103026198bb4Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 1031e4d90813Sdrh appendFlag = 1; 10324a32431cSdrh } 10336a288a33Sdrh autoIncStep(pParse, regAutoinc, regRowid); 10344a32431cSdrh 1035d82b5021Sdrh /* Compute data for all columns of the new entry, beginning 10364a32431cSdrh ** with the first column. 10374a32431cSdrh */ 1038034ca14fSdanielk1977 nHidden = 0; 1039c27ea2aeSdrh iRegStore = regRowid+1; 1040c27ea2aeSdrh for(i=0; i<pTab->nCol; i++, iRegStore++){ 1041ab45fc04Sdrh int k; 1042676fa25aSdrh u32 colFlags; 1043ab45fc04Sdrh assert( i>=nHidden ); 1044ab45fc04Sdrh assert( iRegStore==sqlite3ColumnOfTable(pTab,i)+regRowid+1 ); 10454a32431cSdrh if( i==pTab->iPKey ){ 10464a32431cSdrh /* The value of the INTEGER PRIMARY KEY column is always a NULL. 1047d82b5021Sdrh ** Whenever this column is read, the rowid will be substituted 1048d82b5021Sdrh ** in its place. Hence, fill this column with a NULL to avoid 104905a86c5cSdrh ** taking up data space with information that will never be used. 105005a86c5cSdrh ** As there may be shallow copies of this value, make it a soft-NULL */ 105105a86c5cSdrh sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); 10524a32431cSdrh continue; 10534a32431cSdrh } 1054676fa25aSdrh if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){ 1055034ca14fSdanielk1977 nHidden++; 1056676fa25aSdrh if( (colFlags & COLFLAG_VIRTUAL)!=0 ){ 1057ab45fc04Sdrh /* Virtual columns are no stored */ 1058c27ea2aeSdrh iRegStore--; 10597e508f1eSdrh continue; 1060c1431144Sdrh }else if( (colFlags & COLFLAG_STORED)!=0 ){ 1061c1431144Sdrh /* Stored columns are handled on the second pass */ 1062c1431144Sdrh continue; 1063c1431144Sdrh }else if( pColumn==0 ){ 1064c1431144Sdrh /* Hidden columns that are not explicitly named in the INSERT */ 1065676fa25aSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 1066676fa25aSdrh continue; 1067676fa25aSdrh } 10687e508f1eSdrh } 1069ab45fc04Sdrh if( pColumn ){ 1070ab45fc04Sdrh for(j=0; j<pColumn->nId && pColumn->a[j].idx!=i; j++){} 1071ab45fc04Sdrh if( j>=pColumn->nId ){ 1072ab45fc04Sdrh /* A column not named in the insert column list gets its 1073ab45fc04Sdrh ** default value */ 107405a86c5cSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 1075ab45fc04Sdrh continue; 1076ab45fc04Sdrh } 1077ab45fc04Sdrh k = j; 1078ab45fc04Sdrh }else if( nColumn==0 ){ 1079ab45fc04Sdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 1080ab45fc04Sdrh continue; 1081ab45fc04Sdrh }else{ 1082ab45fc04Sdrh k = i - nHidden; 1083ab45fc04Sdrh } 1084ab45fc04Sdrh 1085ab45fc04Sdrh if( useTempTable ){ 1086ab45fc04Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore); 1087142e30dfSdrh }else if( pSelect ){ 108805a86c5cSdrh if( regFromSelect!=regData ){ 1089ab45fc04Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore); 109005a86c5cSdrh } 1091cce7d176Sdrh }else{ 1092ab45fc04Sdrh sqlite3ExprCode(pParse, pList->a[k].pExpr, iRegStore); 1093cce7d176Sdrh } 1094cce7d176Sdrh } 10951ccde15dSdrh 1096c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1097c1431144Sdrh /* Compute the new value for STORED columns after all other 1098c1431144Sdrh ** columns have already been computed */ 1099c1431144Sdrh if( pTab->tabFlags & TF_HasStored ){ 1100c1431144Sdrh sqlite3ComputeStoredColumns(pParse, regRowid+1, pTab); 1101c1431144Sdrh } 1102c1431144Sdrh #endif 1103c1431144Sdrh 11040ca3e24bSdrh /* Generate code to check constraints and generate index keys and 11050ca3e24bSdrh ** do the insertion. 11064a32431cSdrh */ 11074cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 11084cbdda9eSdrh if( IsVirtual(pTab) ){ 1109595a523aSdanielk1977 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 11104f3dd150Sdrh sqlite3VtabMakeWritable(pParse, pTab); 1111595a523aSdanielk1977 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); 1112b061d058Sdan sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); 1113e0af83acSdan sqlite3MayAbort(pParse); 11144cbdda9eSdrh }else 11154cbdda9eSdrh #endif 11164cbdda9eSdrh { 1117de630353Sdanielk1977 int isReplace; /* Set to true if constraints may cause a replace */ 11183b908d41Sdan int bUseSeek; /* True to use OPFLAG_SEEKRESULT */ 1119f8ffb278Sdrh sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, 1120788d55aaSdrh regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert 112104adf416Sdrh ); 11228ff2d956Sdan sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); 11233b908d41Sdan 11243b908d41Sdan /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE 11253b908d41Sdan ** constraints or (b) there are no triggers and this table is not a 11263b908d41Sdan ** parent table in a foreign key constraint. It is safe to set the 11273b908d41Sdan ** flag in the second case as if any REPLACE constraint is hit, an 11283b908d41Sdan ** OP_Delete or OP_IdxDelete instruction will be executed on each 11293b908d41Sdan ** cursor that is disturbed. And these instructions both clear the 11303b908d41Sdan ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT 11313b908d41Sdan ** functionality. */ 11323b908d41Sdan bUseSeek = (isReplace==0 || (pTrigger==0 && 11333b908d41Sdan ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0) 11343b908d41Sdan )); 113526198bb4Sdrh sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, 11363b908d41Sdan regIns, aRegIdx, 0, appendFlag, bUseSeek 11373b908d41Sdan ); 11385cf590c1Sdrh } 11394cbdda9eSdrh } 11401bee3d7bSdrh 1141feeb1394Sdrh /* Update the count of rows that are inserted 11421bee3d7bSdrh */ 114379636913Sdrh if( regRowCount ){ 11446a288a33Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 11451bee3d7bSdrh } 1146c3f9bad2Sdanielk1977 11472f886d1dSdanielk1977 if( pTrigger ){ 1148c3f9bad2Sdanielk1977 /* Code AFTER triggers */ 1149165921a7Sdan sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 115094d7f50aSdan pTab, regData-2-pTab->nCol, onError, endOfLoop); 1151c3f9bad2Sdanielk1977 } 11521bee3d7bSdrh 1153e00ee6ebSdrh /* The bottom of the main insertion loop, if the data source 1154e00ee6ebSdrh ** is a SELECT statement. 11551ccde15dSdrh */ 11564adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, endOfLoop); 1157142e30dfSdrh if( useTempTable ){ 1158688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); 1159e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 11602eb95377Sdrh sqlite3VdbeAddOp1(v, OP_Close, srcTab); 1161142e30dfSdrh }else if( pSelect ){ 1162076e85f5Sdrh sqlite3VdbeGoto(v, addrCont); 1163e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 11646b56344dSdrh } 1165c3f9bad2Sdanielk1977 11660b9f50d8Sdrh insert_end: 1167f3388144Sdrh /* Update the sqlite_sequence table by storing the content of the 11680b9f50d8Sdrh ** maximum rowid counter values recorded while inserting into 11690b9f50d8Sdrh ** autoincrement tables. 11702958a4e6Sdrh */ 1171165921a7Sdan if( pParse->nested==0 && pParse->pTriggerTab==0 ){ 11720b9f50d8Sdrh sqlite3AutoincrementEnd(pParse); 11730b9f50d8Sdrh } 11742958a4e6Sdrh 11751bee3d7bSdrh /* 1176e7de6f25Sdanielk1977 ** Return the number of rows inserted. If this routine is 1177e7de6f25Sdanielk1977 ** generating code because of a call to sqlite3NestedParse(), do not 1178e7de6f25Sdanielk1977 ** invoke the callback function. 11791bee3d7bSdrh */ 118079636913Sdrh if( regRowCount ){ 11816a288a33Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); 118222322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, 1); 118310fb749bSdanielk1977 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); 11841bee3d7bSdrh } 1185cce7d176Sdrh 1186cce7d176Sdrh insert_cleanup: 1187633e6d57Sdrh sqlite3SrcListDelete(db, pTabList); 1188633e6d57Sdrh sqlite3ExprListDelete(db, pList); 118946d2e5c3Sdrh sqlite3UpsertDelete(db, pUpsert); 1190633e6d57Sdrh sqlite3SelectDelete(db, pSelect); 1191633e6d57Sdrh sqlite3IdListDelete(db, pColumn); 1192633e6d57Sdrh sqlite3DbFree(db, aRegIdx); 1193cce7d176Sdrh } 11949cfcf5d4Sdrh 119575cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise 119660ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file 119775cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation). */ 119875cbd984Sdan #ifdef isView 119975cbd984Sdan #undef isView 120075cbd984Sdan #endif 120175cbd984Sdan #ifdef pTrigger 120275cbd984Sdan #undef pTrigger 120375cbd984Sdan #endif 120475cbd984Sdan #ifdef tmask 120575cbd984Sdan #undef tmask 120675cbd984Sdan #endif 120775cbd984Sdan 12089cfcf5d4Sdrh /* 1209e9816d82Sdrh ** Meanings of bits in of pWalker->eCode for 1210e9816d82Sdrh ** sqlite3ExprReferencesUpdatedColumn() 121198bfa16dSdrh */ 121298bfa16dSdrh #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */ 121398bfa16dSdrh #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */ 121498bfa16dSdrh 1215e9816d82Sdrh /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn(). 1216e9816d82Sdrh * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this 1217e9816d82Sdrh ** expression node references any of the 12182a0b527bSdrh ** columns that are being modifed by an UPDATE statement. 12192a0b527bSdrh */ 12202a0b527bSdrh static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){ 122198bfa16dSdrh if( pExpr->op==TK_COLUMN ){ 122298bfa16dSdrh assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 ); 122398bfa16dSdrh if( pExpr->iColumn>=0 ){ 122498bfa16dSdrh if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){ 122598bfa16dSdrh pWalker->eCode |= CKCNSTRNT_COLUMN; 122698bfa16dSdrh } 122798bfa16dSdrh }else{ 122898bfa16dSdrh pWalker->eCode |= CKCNSTRNT_ROWID; 122998bfa16dSdrh } 12302a0b527bSdrh } 12312a0b527bSdrh return WRC_Continue; 12322a0b527bSdrh } 12332a0b527bSdrh 12342a0b527bSdrh /* 12352a0b527bSdrh ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The 12362a0b527bSdrh ** only columns that are modified by the UPDATE are those for which 123798bfa16dSdrh ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true. 123898bfa16dSdrh ** 1239e9816d82Sdrh ** Return true if CHECK constraint pExpr uses any of the 124098bfa16dSdrh ** changing columns (or the rowid if it is changing). In other words, 1241e9816d82Sdrh ** return true if this CHECK constraint must be validated for 124298bfa16dSdrh ** the new row in the UPDATE statement. 1243e9816d82Sdrh ** 1244e9816d82Sdrh ** 2018-09-15: pExpr might also be an expression for an index-on-expressions. 1245e9816d82Sdrh ** The operation of this routine is the same - return true if an only if 1246e9816d82Sdrh ** the expression uses one or more of columns identified by the second and 1247e9816d82Sdrh ** third arguments. 12482a0b527bSdrh */ 1249e9816d82Sdrh int sqlite3ExprReferencesUpdatedColumn( 1250e9816d82Sdrh Expr *pExpr, /* The expression to be checked */ 1251e9816d82Sdrh int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */ 1252e9816d82Sdrh int chngRowid /* True if UPDATE changes the rowid */ 1253e9816d82Sdrh ){ 12542a0b527bSdrh Walker w; 12552a0b527bSdrh memset(&w, 0, sizeof(w)); 125698bfa16dSdrh w.eCode = 0; 12572a0b527bSdrh w.xExprCallback = checkConstraintExprNode; 12582a0b527bSdrh w.u.aiCol = aiChng; 12592a0b527bSdrh sqlite3WalkExpr(&w, pExpr); 126005723a9eSdrh if( !chngRowid ){ 126105723a9eSdrh testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 ); 126205723a9eSdrh w.eCode &= ~CKCNSTRNT_ROWID; 126305723a9eSdrh } 126405723a9eSdrh testcase( w.eCode==0 ); 126505723a9eSdrh testcase( w.eCode==CKCNSTRNT_COLUMN ); 126605723a9eSdrh testcase( w.eCode==CKCNSTRNT_ROWID ); 126705723a9eSdrh testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) ); 1268e9816d82Sdrh return w.eCode!=0; 12692a0b527bSdrh } 12702a0b527bSdrh 127111e85273Sdrh /* 12726934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE 12736934fc7bSdrh ** on table pTab. 12749cfcf5d4Sdrh ** 12756934fc7bSdrh ** The regNewData parameter is the first register in a range that contains 12766934fc7bSdrh ** the data to be inserted or the data after the update. There will be 12776934fc7bSdrh ** pTab->nCol+1 registers in this range. The first register (the one 12786934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the 12796934fc7bSdrh ** case of a WITHOUT ROWID table. The second register in the range will 12806934fc7bSdrh ** contain the content of the first table column. The third register will 12816934fc7bSdrh ** contain the content of the second table column. And so forth. 12820ca3e24bSdrh ** 1283f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains 1284f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards. regOldData is zero 1285f8ffb278Sdrh ** for an INSERT. This routine can distinguish between UPDATE and INSERT by 1286f8ffb278Sdrh ** checking regOldData for zero. 12870ca3e24bSdrh ** 1288f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the 1289f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) 1290f8ffb278Sdrh ** might be modified by the UPDATE. If pkChng is false, then the key of 1291f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE. 12920ca3e24bSdrh ** 1293f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid 1294f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement. If pkChng 1295f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or 1296f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, 1297f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer 1298f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias. 12990ca3e24bSdrh ** 13006934fc7bSdrh ** The code generated by this routine will store new index entries into 1301aa9b8963Sdrh ** registers identified by aRegIdx[]. No index entry is created for 1302aa9b8963Sdrh ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is 1303aa9b8963Sdrh ** the same as the order of indices on the linked list of indices 13046934fc7bSdrh ** at pTab->pIndex. 13056934fc7bSdrh ** 1306a7c3b93fSdrh ** (2019-05-07) The generated code also creates a new record for the 1307a7c3b93fSdrh ** main table, if pTab is a rowid table, and stores that record in the 1308a7c3b93fSdrh ** register identified by aRegIdx[nIdx] - in other words in the first 1309a7c3b93fSdrh ** entry of aRegIdx[] past the last index. It is important that the 1310a7c3b93fSdrh ** record be generated during constraint checks to avoid affinity changes 1311a7c3b93fSdrh ** to the register content that occur after constraint checks but before 1312a7c3b93fSdrh ** the new record is inserted. 1313a7c3b93fSdrh ** 13146934fc7bSdrh ** The caller must have already opened writeable cursors on the main 13156934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which 13166934fc7bSdrh ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when 13176934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY 13186934fc7bSdrh ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor 13196934fc7bSdrh ** for the first index in the pTab->pIndex list. Cursors for other indices 13206934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list. 13219cfcf5d4Sdrh ** 13229cfcf5d4Sdrh ** This routine also generates code to check constraints. NOT NULL, 13239cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 13241c92853dSdrh ** then the appropriate action is performed. There are five possible 13251c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 13269cfcf5d4Sdrh ** 13279cfcf5d4Sdrh ** Constraint type Action What Happens 13289cfcf5d4Sdrh ** --------------- ---------- ---------------------------------------- 13291c92853dSdrh ** any ROLLBACK The current transaction is rolled back and 13306934fc7bSdrh ** sqlite3_step() returns immediately with a 13319cfcf5d4Sdrh ** return code of SQLITE_CONSTRAINT. 13329cfcf5d4Sdrh ** 13331c92853dSdrh ** any ABORT Back out changes from the current command 13341c92853dSdrh ** only (do not do a complete rollback) then 13356934fc7bSdrh ** cause sqlite3_step() to return immediately 13361c92853dSdrh ** with SQLITE_CONSTRAINT. 13371c92853dSdrh ** 13386934fc7bSdrh ** any FAIL Sqlite3_step() returns immediately with a 13391c92853dSdrh ** return code of SQLITE_CONSTRAINT. The 13401c92853dSdrh ** transaction is not rolled back and any 13416934fc7bSdrh ** changes to prior rows are retained. 13421c92853dSdrh ** 13436934fc7bSdrh ** any IGNORE The attempt in insert or update the current 13446934fc7bSdrh ** row is skipped, without throwing an error. 13456934fc7bSdrh ** Processing continues with the next row. 13466934fc7bSdrh ** (There is an immediate jump to ignoreDest.) 13479cfcf5d4Sdrh ** 13489cfcf5d4Sdrh ** NOT NULL REPLACE The NULL value is replace by the default 13499cfcf5d4Sdrh ** value for that column. If the default value 13509cfcf5d4Sdrh ** is NULL, the action is the same as ABORT. 13519cfcf5d4Sdrh ** 13529cfcf5d4Sdrh ** UNIQUE REPLACE The other row that conflicts with the row 13539cfcf5d4Sdrh ** being inserted is removed. 13549cfcf5d4Sdrh ** 13559cfcf5d4Sdrh ** CHECK REPLACE Illegal. The results in an exception. 13569cfcf5d4Sdrh ** 13571c92853dSdrh ** Which action to take is determined by the overrideError parameter. 13581c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter 13591c92853dSdrh ** is used. Or if pParse->onError==OE_Default then the onError value 13601c92853dSdrh ** for the constraint is used. 13619cfcf5d4Sdrh */ 13624adee20fSdanielk1977 void sqlite3GenerateConstraintChecks( 13639cfcf5d4Sdrh Parse *pParse, /* The parser context */ 13646934fc7bSdrh Table *pTab, /* The table being inserted or updated */ 1365f8ffb278Sdrh int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ 13666934fc7bSdrh int iDataCur, /* Canonical data cursor (main table or PK index) */ 136726198bb4Sdrh int iIdxCur, /* First index cursor */ 13686934fc7bSdrh int regNewData, /* First register in a range holding values to insert */ 1369f8ffb278Sdrh int regOldData, /* Previous content. 0 for INSERTs */ 1370f8ffb278Sdrh u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ 1371f8ffb278Sdrh u8 overrideError, /* Override onError to this if not OE_Default */ 1372de630353Sdanielk1977 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ 1373bdb00225Sdrh int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */ 1374788d55aaSdrh int *aiChng, /* column i is unchanged if aiChng[i]<0 */ 1375788d55aaSdrh Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */ 13769cfcf5d4Sdrh ){ 13771b7ecbb4Sdrh Vdbe *v; /* VDBE under constrution */ 13781b7ecbb4Sdrh Index *pIdx; /* Pointer to one of the indices */ 137911e85273Sdrh Index *pPk = 0; /* The PRIMARY KEY index */ 13802938f924Sdrh sqlite3 *db; /* Database connection */ 1381f8ffb278Sdrh int i; /* loop counter */ 1382f8ffb278Sdrh int ix; /* Index loop counter */ 13839cfcf5d4Sdrh int nCol; /* Number of columns */ 13849cfcf5d4Sdrh int onError; /* Conflict resolution strategy */ 1385728e0f91Sdrh int addr1; /* Address of jump instruction */ 13861b7ecbb4Sdrh int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ 13876fbe41acSdrh int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ 1388096fd476Sdrh Index *pUpIdx = 0; /* Index to which to apply the upsert */ 13898d1b82e4Sdrh u8 isUpdate; /* True if this is an UPDATE operation */ 139057bf4a8eSdrh u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ 1391096fd476Sdrh int upsertBypass = 0; /* Address of Goto to bypass upsert subroutine */ 139284304506Sdrh int upsertJump = 0; /* Address of Goto that jumps into upsert subroutine */ 139384304506Sdrh int ipkTop = 0; /* Top of the IPK uniqueness check */ 139484304506Sdrh int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */ 13959cfcf5d4Sdrh 1396f8ffb278Sdrh isUpdate = regOldData!=0; 13972938f924Sdrh db = pParse->db; 13984adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 13999cfcf5d4Sdrh assert( v!=0 ); 1400417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 14019cfcf5d4Sdrh nCol = pTab->nCol; 1402aa9b8963Sdrh 14036934fc7bSdrh /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for 14046934fc7bSdrh ** normal rowid tables. nPkField is the number of key fields in the 14056934fc7bSdrh ** pPk index or 1 for a rowid table. In other words, nPkField is the 14066934fc7bSdrh ** number of fields in the true primary key of the table. */ 140726198bb4Sdrh if( HasRowid(pTab) ){ 140826198bb4Sdrh pPk = 0; 140926198bb4Sdrh nPkField = 1; 141026198bb4Sdrh }else{ 141126198bb4Sdrh pPk = sqlite3PrimaryKeyIndex(pTab); 141226198bb4Sdrh nPkField = pPk->nKeyCol; 141326198bb4Sdrh } 14146fbe41acSdrh 14156fbe41acSdrh /* Record that this module has started */ 14166fbe41acSdrh VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", 14176934fc7bSdrh iDataCur, iIdxCur, regNewData, regOldData, pkChng)); 14189cfcf5d4Sdrh 14199cfcf5d4Sdrh /* Test all NOT NULL constraints. 14209cfcf5d4Sdrh */ 14219cfcf5d4Sdrh for(i=0; i<nCol; i++){ 14220ca3e24bSdrh if( i==pTab->iPKey ){ 1423bdb00225Sdrh continue; /* ROWID is never NULL */ 1424bdb00225Sdrh } 1425bdb00225Sdrh if( aiChng && aiChng[i]<0 ){ 1426bdb00225Sdrh /* Don't bother checking for NOT NULL on columns that do not change */ 14270ca3e24bSdrh continue; 14280ca3e24bSdrh } 14299cfcf5d4Sdrh onError = pTab->aCol[i].notNull; 1430bdb00225Sdrh if( onError==OE_None ) continue; /* This column is allowed to be NULL */ 14319cfcf5d4Sdrh if( overrideError!=OE_Default ){ 14329cfcf5d4Sdrh onError = overrideError; 1433a996e477Sdrh }else if( onError==OE_Default ){ 1434a996e477Sdrh onError = OE_Abort; 14359cfcf5d4Sdrh } 14367977a17fSdanielk1977 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ 14379cfcf5d4Sdrh onError = OE_Abort; 14389cfcf5d4Sdrh } 1439b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1440b84f96f8Sdanielk1977 || onError==OE_Ignore || onError==OE_Replace ); 14419bfb0794Sdrh addr1 = 0; 14429cfcf5d4Sdrh switch( onError ){ 14439bfb0794Sdrh case OE_Replace: { 14449bfb0794Sdrh assert( onError==OE_Replace ); 1445ec4ccdbcSdrh addr1 = sqlite3VdbeMakeLabel(pParse); 14469bfb0794Sdrh sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1); 14479bfb0794Sdrh VdbeCoverage(v); 14489bfb0794Sdrh sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); 14499bfb0794Sdrh sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1); 14509bfb0794Sdrh VdbeCoverage(v); 14519bfb0794Sdrh onError = OE_Abort; 14529bfb0794Sdrh /* Fall through into the OE_Abort case to generate code that runs 14539bfb0794Sdrh ** if both the input and the default value are NULL */ 14549bfb0794Sdrh } 14551c92853dSdrh case OE_Abort: 1456e0af83acSdan sqlite3MayAbort(pParse); 14570978d4ffSdrh /* Fall through */ 1458e0af83acSdan case OE_Rollback: 14591c92853dSdrh case OE_Fail: { 1460f9c8ce3cSdrh char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, 1461f9c8ce3cSdrh pTab->aCol[i].zName); 14622700acaaSdrh sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError, 14632700acaaSdrh regNewData+1+i); 14642700acaaSdrh sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC); 1465f9c8ce3cSdrh sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); 1466688852abSdrh VdbeCoverage(v); 14679bfb0794Sdrh if( addr1 ) sqlite3VdbeResolveLabel(v, addr1); 14689cfcf5d4Sdrh break; 14699cfcf5d4Sdrh } 1470098d1684Sdrh default: { 14719bfb0794Sdrh assert( onError==OE_Ignore ); 14729bfb0794Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest); 1473728e0f91Sdrh VdbeCoverage(v); 14749cfcf5d4Sdrh break; 14759cfcf5d4Sdrh } 14769cfcf5d4Sdrh } 14779cfcf5d4Sdrh } 14789cfcf5d4Sdrh 14799cfcf5d4Sdrh /* Test all CHECK constraints 14809cfcf5d4Sdrh */ 1481ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 14822938f924Sdrh if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ 14832938f924Sdrh ExprList *pCheck = pTab->pCheck; 14846e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 1485aa01c7e2Sdrh onError = overrideError!=OE_Default ? overrideError : OE_Abort; 14862938f924Sdrh for(i=0; i<pCheck->nExpr; i++){ 148705723a9eSdrh int allOk; 14882a0b527bSdrh Expr *pExpr = pCheck->a[i].pExpr; 1489e9816d82Sdrh if( aiChng 1490e9816d82Sdrh && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng) 1491e9816d82Sdrh ){ 1492e9816d82Sdrh /* The check constraints do not reference any of the columns being 1493e9816d82Sdrh ** updated so there is no point it verifying the check constraint */ 1494e9816d82Sdrh continue; 1495e9816d82Sdrh } 1496ec4ccdbcSdrh allOk = sqlite3VdbeMakeLabel(pParse); 14974031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 14982a0b527bSdrh sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL); 14992e06c67cSdrh if( onError==OE_Ignore ){ 1500076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 1501aa01c7e2Sdrh }else{ 1502f9c8ce3cSdrh char *zName = pCheck->a[i].zName; 1503f9c8ce3cSdrh if( zName==0 ) zName = pTab->zName; 15040ce974d1Sdrh if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */ 1505d91c1a17Sdrh sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, 1506f9c8ce3cSdrh onError, zName, P4_TRANSIENT, 1507f9c8ce3cSdrh P5_ConstraintCheck); 1508aa01c7e2Sdrh } 1509ffe07b2dSdrh sqlite3VdbeResolveLabel(v, allOk); 1510ffe07b2dSdrh } 15116e97f8ecSdrh pParse->iSelfTab = 0; 15122938f924Sdrh } 1513ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */ 15149cfcf5d4Sdrh 1515096fd476Sdrh /* UNIQUE and PRIMARY KEY constraints should be handled in the following 1516096fd476Sdrh ** order: 1517096fd476Sdrh ** 151884304506Sdrh ** (1) OE_Update 151984304506Sdrh ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore 1520096fd476Sdrh ** (3) OE_Replace 1521096fd476Sdrh ** 1522096fd476Sdrh ** OE_Fail and OE_Ignore must happen before any changes are made. 1523096fd476Sdrh ** OE_Update guarantees that only a single row will change, so it 1524096fd476Sdrh ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback 1525096fd476Sdrh ** could happen in any order, but they are grouped up front for 1526096fd476Sdrh ** convenience. 1527096fd476Sdrh ** 152884304506Sdrh ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43 152984304506Sdrh ** The order of constraints used to have OE_Update as (2) and OE_Abort 153084304506Sdrh ** and so forth as (1). But apparently PostgreSQL checks the OE_Update 153184304506Sdrh ** constraint before any others, so it had to be moved. 153284304506Sdrh ** 1533096fd476Sdrh ** Constraint checking code is generated in this order: 1534096fd476Sdrh ** (A) The rowid constraint 1535096fd476Sdrh ** (B) Unique index constraints that do not have OE_Replace as their 1536096fd476Sdrh ** default conflict resolution strategy 1537096fd476Sdrh ** (C) Unique index that do use OE_Replace by default. 1538096fd476Sdrh ** 1539096fd476Sdrh ** The ordering of (2) and (3) is accomplished by making sure the linked 1540096fd476Sdrh ** list of indexes attached to a table puts all OE_Replace indexes last 1541096fd476Sdrh ** in the list. See sqlite3CreateIndex() for where that happens. 1542096fd476Sdrh */ 1543096fd476Sdrh 1544096fd476Sdrh if( pUpsert ){ 1545096fd476Sdrh if( pUpsert->pUpsertTarget==0 ){ 1546096fd476Sdrh /* An ON CONFLICT DO NOTHING clause, without a constraint-target. 1547096fd476Sdrh ** Make all unique constraint resolution be OE_Ignore */ 1548dedbc508Sdrh assert( pUpsert->pUpsertSet==0 ); 1549096fd476Sdrh overrideError = OE_Ignore; 1550096fd476Sdrh pUpsert = 0; 1551096fd476Sdrh }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){ 155284304506Sdrh /* If the constraint-target uniqueness check must be run first. 155384304506Sdrh ** Jump to that uniqueness check now */ 155484304506Sdrh upsertJump = sqlite3VdbeAddOp0(v, OP_Goto); 155584304506Sdrh VdbeComment((v, "UPSERT constraint goes first")); 1556096fd476Sdrh } 1557096fd476Sdrh } 1558096fd476Sdrh 1559f8ffb278Sdrh /* If rowid is changing, make sure the new rowid does not previously 1560f8ffb278Sdrh ** exist in the table. 15619cfcf5d4Sdrh */ 15626fbe41acSdrh if( pkChng && pPk==0 ){ 1563ec4ccdbcSdrh int addrRowidOk = sqlite3VdbeMakeLabel(pParse); 156411e85273Sdrh 1565f8ffb278Sdrh /* Figure out what action to take in case of a rowid collision */ 15660ca3e24bSdrh onError = pTab->keyConf; 15670ca3e24bSdrh if( overrideError!=OE_Default ){ 15680ca3e24bSdrh onError = overrideError; 1569a996e477Sdrh }else if( onError==OE_Default ){ 1570a996e477Sdrh onError = OE_Abort; 15710ca3e24bSdrh } 1572a0217ba7Sdrh 1573c8a0c90bSdrh /* figure out whether or not upsert applies in this case */ 1574096fd476Sdrh if( pUpsert && pUpsert->pUpsertIdx==0 ){ 1575c8a0c90bSdrh if( pUpsert->pUpsertSet==0 ){ 1576c8a0c90bSdrh onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */ 1577c8a0c90bSdrh }else{ 1578c8a0c90bSdrh onError = OE_Update; /* DO UPDATE */ 1579c8a0c90bSdrh } 1580c8a0c90bSdrh } 1581c8a0c90bSdrh 15828d1b82e4Sdrh /* If the response to a rowid conflict is REPLACE but the response 15838d1b82e4Sdrh ** to some other UNIQUE constraint is FAIL or IGNORE, then we need 15848d1b82e4Sdrh ** to defer the running of the rowid conflict checking until after 15858d1b82e4Sdrh ** the UNIQUE constraints have run. 15868d1b82e4Sdrh */ 158784304506Sdrh if( onError==OE_Replace /* IPK rule is REPLACE */ 158884304506Sdrh && onError!=overrideError /* Rules for other contraints are different */ 158984304506Sdrh && pTab->pIndex /* There exist other constraints */ 1590096fd476Sdrh ){ 159184304506Sdrh ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1; 159284304506Sdrh VdbeComment((v, "defer IPK REPLACE until last")); 15938d1b82e4Sdrh } 15948d1b82e4Sdrh 1595bb6b1ca7Sdrh if( isUpdate ){ 1596bb6b1ca7Sdrh /* pkChng!=0 does not mean that the rowid has changed, only that 1597bb6b1ca7Sdrh ** it might have changed. Skip the conflict logic below if the rowid 1598bb6b1ca7Sdrh ** is unchanged. */ 1599bb6b1ca7Sdrh sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); 1600bb6b1ca7Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1601bb6b1ca7Sdrh VdbeCoverage(v); 1602bb6b1ca7Sdrh } 1603bb6b1ca7Sdrh 1604f8ffb278Sdrh /* Check to see if the new rowid already exists in the table. Skip 1605f8ffb278Sdrh ** the following conflict logic if it does not. */ 16067f5f306bSdrh VdbeNoopComment((v, "uniqueness check for ROWID")); 16074031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 16086934fc7bSdrh sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); 1609688852abSdrh VdbeCoverage(v); 1610f8ffb278Sdrh 16110ca3e24bSdrh switch( onError ){ 1612a0217ba7Sdrh default: { 1613a0217ba7Sdrh onError = OE_Abort; 1614a0217ba7Sdrh /* Fall thru into the next case */ 1615a0217ba7Sdrh } 16161c92853dSdrh case OE_Rollback: 16171c92853dSdrh case OE_Abort: 16181c92853dSdrh case OE_Fail: { 16199916048bSdrh testcase( onError==OE_Rollback ); 16209916048bSdrh testcase( onError==OE_Abort ); 16219916048bSdrh testcase( onError==OE_Fail ); 1622f9c8ce3cSdrh sqlite3RowidConstraint(pParse, onError, pTab); 16230ca3e24bSdrh break; 16240ca3e24bSdrh } 16255383ae5cSdrh case OE_Replace: { 16262283d46cSdan /* If there are DELETE triggers on this table and the 16272283d46cSdan ** recursive-triggers flag is set, call GenerateRowDelete() to 1628d5578433Smistachkin ** remove the conflicting row from the table. This will fire 16292283d46cSdan ** the triggers and remove both the table and index b-tree entries. 16302283d46cSdan ** 16312283d46cSdan ** Otherwise, if there are no triggers or the recursive-triggers 1632da730f6eSdan ** flag is not set, but the table has one or more indexes, call 1633da730f6eSdan ** GenerateRowIndexDelete(). This removes the index b-tree entries 1634da730f6eSdan ** only. The table b-tree entry will be replaced by the new entry 1635da730f6eSdan ** when it is inserted. 1636da730f6eSdan ** 1637da730f6eSdan ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, 1638da730f6eSdan ** also invoke MultiWrite() to indicate that this VDBE may require 1639da730f6eSdan ** statement rollback (if the statement is aborted after the delete 1640da730f6eSdan ** takes place). Earlier versions called sqlite3MultiWrite() regardless, 1641da730f6eSdan ** but being more selective here allows statements like: 1642da730f6eSdan ** 1643da730f6eSdan ** REPLACE INTO t(rowid) VALUES($newrowid) 1644da730f6eSdan ** 1645da730f6eSdan ** to run without a statement journal if there are no indexes on the 1646da730f6eSdan ** table. 1647da730f6eSdan */ 16482283d46cSdan Trigger *pTrigger = 0; 16492938f924Sdrh if( db->flags&SQLITE_RecTriggers ){ 16502283d46cSdan pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 16512283d46cSdan } 1652e7a94d81Sdan if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ 1653da730f6eSdan sqlite3MultiWrite(pParse); 165426198bb4Sdrh sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1655438b8815Sdan regNewData, 1, 0, OE_Replace, 1, -1); 165646c47d46Sdan }else{ 16579b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 165854f2cd90Sdrh assert( HasRowid(pTab) ); 165946c47d46Sdan /* This OP_Delete opcode fires the pre-update-hook only. It does 166046c47d46Sdan ** not modify the b-tree. It is more efficient to let the coming 166146c47d46Sdan ** OP_Insert replace the existing entry than it is to delete the 166246c47d46Sdan ** existing entry and then insert a new one. */ 1663cbf1b8efSdrh sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP); 1664f14b7fb7Sdrh sqlite3VdbeAppendP4(v, pTab, P4_TABLE); 16659b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ 166646c47d46Sdan if( pTab->pIndex ){ 1667da730f6eSdan sqlite3MultiWrite(pParse); 1668f0ee1d3cSdan sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); 16692283d46cSdan } 167046c47d46Sdan } 16715383ae5cSdrh seenReplace = 1; 16725383ae5cSdrh break; 16735383ae5cSdrh } 16749eddacadSdrh #ifndef SQLITE_OMIT_UPSERT 16759eddacadSdrh case OE_Update: { 16762cc00423Sdan sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur); 16779eddacadSdrh /* Fall through */ 16789eddacadSdrh } 16799eddacadSdrh #endif 16800ca3e24bSdrh case OE_Ignore: { 16819916048bSdrh testcase( onError==OE_Ignore ); 1682076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 16830ca3e24bSdrh break; 16840ca3e24bSdrh } 16850ca3e24bSdrh } 168611e85273Sdrh sqlite3VdbeResolveLabel(v, addrRowidOk); 168784304506Sdrh if( ipkTop ){ 168884304506Sdrh ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); 168984304506Sdrh sqlite3VdbeJumpHere(v, ipkTop-1); 1690a05a722fSdrh } 16910ca3e24bSdrh } 16920bd1f4eaSdrh 16930bd1f4eaSdrh /* Test all UNIQUE constraints by creating entries for each UNIQUE 16940bd1f4eaSdrh ** index and making sure that duplicate entries do not already exist. 169511e85273Sdrh ** Compute the revised record entries for indices as we go. 1696f8ffb278Sdrh ** 1697f8ffb278Sdrh ** This loop also handles the case of the PRIMARY KEY index for a 1698f8ffb278Sdrh ** WITHOUT ROWID table. 16990bd1f4eaSdrh */ 170026198bb4Sdrh for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ 17016934fc7bSdrh int regIdx; /* Range of registers hold conent for pIdx */ 17026934fc7bSdrh int regR; /* Range of registers holding conflicting PK */ 17036934fc7bSdrh int iThisCur; /* Cursor for this UNIQUE index */ 17046934fc7bSdrh int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ 17052184fc75Sdrh 170626198bb4Sdrh if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ 17077f5f306bSdrh if( pUpIdx==pIdx ){ 170884304506Sdrh addrUniqueOk = upsertJump+1; 17097f5f306bSdrh upsertBypass = sqlite3VdbeGoto(v, 0); 17107f5f306bSdrh VdbeComment((v, "Skip upsert subroutine")); 171184304506Sdrh sqlite3VdbeJumpHere(v, upsertJump); 17127f5f306bSdrh }else{ 1713ec4ccdbcSdrh addrUniqueOk = sqlite3VdbeMakeLabel(pParse); 17147f5f306bSdrh } 171584304506Sdrh if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){ 171684304506Sdrh sqlite3TableAffinity(v, pTab, regNewData+1); 171784304506Sdrh bAffinityDone = 1; 171884304506Sdrh } 17197f5f306bSdrh VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName)); 17206934fc7bSdrh iThisCur = iIdxCur+ix; 17217f5f306bSdrh 1722b2fe7d8cSdrh 1723f8ffb278Sdrh /* Skip partial indices for which the WHERE clause is not true */ 1724b2b9d3d7Sdrh if( pIdx->pPartIdxWhere ){ 172526198bb4Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); 17266e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 172772bc8208Sdrh sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, 1728b2b9d3d7Sdrh SQLITE_JUMPIFNULL); 17296e97f8ecSdrh pParse->iSelfTab = 0; 1730b2b9d3d7Sdrh } 1731b2b9d3d7Sdrh 17326934fc7bSdrh /* Create a record for this index entry as it should appear after 1733f8ffb278Sdrh ** the insert or update. Store that record in the aRegIdx[ix] register 1734f8ffb278Sdrh */ 1735bf2f5739Sdrh regIdx = aRegIdx[ix]+1; 17369cfcf5d4Sdrh for(i=0; i<pIdx->nColumn; i++){ 17376934fc7bSdrh int iField = pIdx->aiColumn[i]; 1738f82b9afcSdrh int x; 17394b92f98cSdrh if( iField==XN_EXPR ){ 17406e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 17411c75c9d7Sdrh sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); 17426e97f8ecSdrh pParse->iSelfTab = 0; 17431f9ca2c8Sdrh VdbeComment((v, "%s column %d", pIdx->zName, i)); 17441f9ca2c8Sdrh }else{ 17454b92f98cSdrh if( iField==XN_ROWID || iField==pTab->iPKey ){ 1746f82b9afcSdrh x = regNewData; 17479cfcf5d4Sdrh }else{ 1748f82b9afcSdrh x = iField + regNewData + 1; 17499cfcf5d4Sdrh } 1750fed7ac6fSdrh sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i); 1751f82b9afcSdrh VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName)); 17529cfcf5d4Sdrh } 17531f9ca2c8Sdrh } 175426198bb4Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); 175526198bb4Sdrh VdbeComment((v, "for %s", pIdx->zName)); 17567e4acf7bSdrh #ifdef SQLITE_ENABLE_NULL_TRIM 17579df385ecSdrh if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){ 17589df385ecSdrh sqlite3SetMakeRecordP5(v, pIdx->pTable); 17599df385ecSdrh } 17607e4acf7bSdrh #endif 1761b2fe7d8cSdrh 1762f8ffb278Sdrh /* In an UPDATE operation, if this index is the PRIMARY KEY index 1763f8ffb278Sdrh ** of a WITHOUT ROWID table and there has been no change the 1764f8ffb278Sdrh ** primary key, then no collision is possible. The collision detection 1765f8ffb278Sdrh ** logic below can all be skipped. */ 176600012df4Sdrh if( isUpdate && pPk==pIdx && pkChng==0 ){ 1767da475b8dSdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1768da475b8dSdrh continue; 1769da475b8dSdrh } 1770f8ffb278Sdrh 17716934fc7bSdrh /* Find out what action to take in case there is a uniqueness conflict */ 17729cfcf5d4Sdrh onError = pIdx->onError; 1773de630353Sdanielk1977 if( onError==OE_None ){ 177411e85273Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1775de630353Sdanielk1977 continue; /* pIdx is not a UNIQUE index */ 1776de630353Sdanielk1977 } 17779cfcf5d4Sdrh if( overrideError!=OE_Default ){ 17789cfcf5d4Sdrh onError = overrideError; 1779a996e477Sdrh }else if( onError==OE_Default ){ 1780a996e477Sdrh onError = OE_Abort; 17819cfcf5d4Sdrh } 17825383ae5cSdrh 1783c8a0c90bSdrh /* Figure out if the upsert clause applies to this index */ 1784096fd476Sdrh if( pUpIdx==pIdx ){ 1785c8a0c90bSdrh if( pUpsert->pUpsertSet==0 ){ 1786c8a0c90bSdrh onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */ 1787c8a0c90bSdrh }else{ 1788c8a0c90bSdrh onError = OE_Update; /* DO UPDATE */ 1789c8a0c90bSdrh } 1790c8a0c90bSdrh } 1791c8a0c90bSdrh 1792801f55d8Sdrh /* Collision detection may be omitted if all of the following are true: 1793801f55d8Sdrh ** (1) The conflict resolution algorithm is REPLACE 1794801f55d8Sdrh ** (2) The table is a WITHOUT ROWID table 1795801f55d8Sdrh ** (3) There are no secondary indexes on the table 1796801f55d8Sdrh ** (4) No delete triggers need to be fired if there is a conflict 1797f9a12a10Sdan ** (5) No FK constraint counters need to be updated if a conflict occurs. 1798418454c6Sdan ** 1799418454c6Sdan ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row 1800418454c6Sdan ** must be explicitly deleted in order to ensure any pre-update hook 1801418454c6Sdan ** is invoked. */ 1802418454c6Sdan #ifndef SQLITE_ENABLE_PREUPDATE_HOOK 1803801f55d8Sdrh if( (ix==0 && pIdx->pNext==0) /* Condition 3 */ 1804801f55d8Sdrh && pPk==pIdx /* Condition 2 */ 1805801f55d8Sdrh && onError==OE_Replace /* Condition 1 */ 1806801f55d8Sdrh && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */ 1807801f55d8Sdrh 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0)) 1808f9a12a10Sdan && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */ 1809f9a12a10Sdan (0==pTab->pFKey && 0==sqlite3FkReferences(pTab))) 18104e1f0efbSdan ){ 1811c6c9e158Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1812c6c9e158Sdrh continue; 1813c6c9e158Sdrh } 1814418454c6Sdan #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */ 1815c6c9e158Sdrh 1816b2fe7d8cSdrh /* Check to see if the new index entry will be unique */ 18174031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 181826198bb4Sdrh sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, 1819688852abSdrh regIdx, pIdx->nKeyCol); VdbeCoverage(v); 1820f8ffb278Sdrh 1821f8ffb278Sdrh /* Generate code to handle collisions */ 1822392ee21dSdrh regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); 182346d03fcbSdrh if( isUpdate || onError==OE_Replace ){ 182411e85273Sdrh if( HasRowid(pTab) ){ 18256934fc7bSdrh sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); 18260978d4ffSdrh /* Conflict only if the rowid of the existing index entry 18270978d4ffSdrh ** is different from old-rowid */ 1828f8ffb278Sdrh if( isUpdate ){ 18296934fc7bSdrh sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); 18303d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1831688852abSdrh VdbeCoverage(v); 1832f8ffb278Sdrh } 183326198bb4Sdrh }else{ 1834ccc79f02Sdrh int x; 183526198bb4Sdrh /* Extract the PRIMARY KEY from the end of the index entry and 1836da475b8dSdrh ** store it in registers regR..regR+nPk-1 */ 1837a021f121Sdrh if( pIdx!=pPk ){ 183826198bb4Sdrh for(i=0; i<pPk->nKeyCol; i++){ 18394b92f98cSdrh assert( pPk->aiColumn[i]>=0 ); 1840ccc79f02Sdrh x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]); 184126198bb4Sdrh sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); 184226198bb4Sdrh VdbeComment((v, "%s.%s", pTab->zName, 184326198bb4Sdrh pTab->aCol[pPk->aiColumn[i]].zName)); 184426198bb4Sdrh } 1845da475b8dSdrh } 1846da475b8dSdrh if( isUpdate ){ 1847e83267daSdan /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 1848e83267daSdan ** table, only conflict if the new PRIMARY KEY values are actually 1849e83267daSdan ** different from the old. 1850e83267daSdan ** 1851e83267daSdan ** For a UNIQUE index, only conflict if the PRIMARY KEY values 1852e83267daSdan ** of the matched index row are different from the original PRIMARY 1853e83267daSdan ** KEY values of this row before the update. */ 1854e83267daSdan int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; 1855e83267daSdan int op = OP_Ne; 185648dd1d8eSdrh int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); 1857e83267daSdan 1858e83267daSdan for(i=0; i<pPk->nKeyCol; i++){ 1859e83267daSdan char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); 1860ccc79f02Sdrh x = pPk->aiColumn[i]; 18614b92f98cSdrh assert( x>=0 ); 1862e83267daSdan if( i==(pPk->nKeyCol-1) ){ 1863e83267daSdan addrJump = addrUniqueOk; 1864e83267daSdan op = OP_Eq; 186511e85273Sdrh } 1866e83267daSdan sqlite3VdbeAddOp4(v, op, 1867e83267daSdan regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ 1868e83267daSdan ); 18693d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 18703d77dee9Sdrh VdbeCoverageIf(v, op==OP_Eq); 18713d77dee9Sdrh VdbeCoverageIf(v, op==OP_Ne); 1872da475b8dSdrh } 187311e85273Sdrh } 187426198bb4Sdrh } 187546d03fcbSdrh } 1876b2fe7d8cSdrh 1877b2fe7d8cSdrh /* Generate code that executes if the new index entry is not unique */ 1878b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 18799eddacadSdrh || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update ); 18809cfcf5d4Sdrh switch( onError ){ 18811c92853dSdrh case OE_Rollback: 18821c92853dSdrh case OE_Abort: 18831c92853dSdrh case OE_Fail: { 18849916048bSdrh testcase( onError==OE_Rollback ); 18859916048bSdrh testcase( onError==OE_Abort ); 18869916048bSdrh testcase( onError==OE_Fail ); 1887f9c8ce3cSdrh sqlite3UniqueConstraint(pParse, onError, pIdx); 18889cfcf5d4Sdrh break; 18899cfcf5d4Sdrh } 18909eddacadSdrh #ifndef SQLITE_OMIT_UPSERT 18919eddacadSdrh case OE_Update: { 18922cc00423Sdan sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix); 18939eddacadSdrh /* Fall through */ 18949eddacadSdrh } 18959eddacadSdrh #endif 18969cfcf5d4Sdrh case OE_Ignore: { 18979916048bSdrh testcase( onError==OE_Ignore ); 1898076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 18999cfcf5d4Sdrh break; 19009cfcf5d4Sdrh } 1901098d1684Sdrh default: { 19022283d46cSdan Trigger *pTrigger = 0; 1903098d1684Sdrh assert( onError==OE_Replace ); 19042938f924Sdrh if( db->flags&SQLITE_RecTriggers ){ 19052283d46cSdan pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 19062283d46cSdan } 1907fecfb318Sdan if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ 1908fecfb318Sdan sqlite3MultiWrite(pParse); 1909fecfb318Sdan } 191026198bb4Sdrh sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1911b0264eecSdrh regR, nPkField, 0, OE_Replace, 191268116939Sdrh (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur); 19130ca3e24bSdrh seenReplace = 1; 19149cfcf5d4Sdrh break; 19159cfcf5d4Sdrh } 19169cfcf5d4Sdrh } 19177f5f306bSdrh if( pUpIdx==pIdx ){ 191884304506Sdrh sqlite3VdbeGoto(v, upsertJump+1); 19197f5f306bSdrh sqlite3VdbeJumpHere(v, upsertBypass); 19207f5f306bSdrh }else{ 192111e85273Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 19227f5f306bSdrh } 1923392ee21dSdrh if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); 19249cfcf5d4Sdrh } 192584304506Sdrh 192684304506Sdrh /* If the IPK constraint is a REPLACE, run it last */ 192784304506Sdrh if( ipkTop ){ 19286214d939Sdrh sqlite3VdbeGoto(v, ipkTop); 192984304506Sdrh VdbeComment((v, "Do IPK REPLACE")); 193084304506Sdrh sqlite3VdbeJumpHere(v, ipkBottom); 193184304506Sdrh } 1932de630353Sdanielk1977 1933a7c3b93fSdrh /* Generate the table record */ 1934a7c3b93fSdrh if( HasRowid(pTab) ){ 1935a7c3b93fSdrh int regRec = aRegIdx[ix]; 19367e508f1eSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, 19377e508f1eSdrh pTab->nCol-pTab->nVCol, regRec); 1938a7c3b93fSdrh sqlite3SetMakeRecordP5(v, pTab); 1939a7c3b93fSdrh if( !bAffinityDone ){ 1940a7c3b93fSdrh sqlite3TableAffinity(v, pTab, 0); 1941a7c3b93fSdrh } 1942a7c3b93fSdrh } 1943a7c3b93fSdrh 1944de630353Sdanielk1977 *pbMayReplace = seenReplace; 1945ce60aa46Sdrh VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); 19469cfcf5d4Sdrh } 19470ca3e24bSdrh 1948d447dcedSdrh #ifdef SQLITE_ENABLE_NULL_TRIM 19490ca3e24bSdrh /* 1950585ce192Sdrh ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord) 1951585ce192Sdrh ** to be the number of columns in table pTab that must not be NULL-trimmed. 1952585ce192Sdrh ** 1953585ce192Sdrh ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero. 1954585ce192Sdrh */ 1955585ce192Sdrh void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){ 1956585ce192Sdrh u16 i; 1957585ce192Sdrh 1958585ce192Sdrh /* Records with omitted columns are only allowed for schema format 1959585ce192Sdrh ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */ 1960585ce192Sdrh if( pTab->pSchema->file_format<2 ) return; 1961585ce192Sdrh 19627e4acf7bSdrh for(i=pTab->nCol-1; i>0; i--){ 19637e4acf7bSdrh if( pTab->aCol[i].pDflt!=0 ) break; 19647e4acf7bSdrh if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break; 19657e4acf7bSdrh } 19667e4acf7bSdrh sqlite3VdbeChangeP5(v, i+1); 1967585ce192Sdrh } 1968d447dcedSdrh #endif 1969585ce192Sdrh 19700ca3e24bSdrh /* 19710ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation 19724adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 19736934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the 197404adf416Sdrh ** rowid and the content to be inserted. 19750ca3e24bSdrh ** 1976b419a926Sdrh ** The arguments to this routine should be the same as the first six 19774adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks. 19780ca3e24bSdrh */ 19794adee20fSdanielk1977 void sqlite3CompleteInsertion( 19800ca3e24bSdrh Parse *pParse, /* The parser context */ 19810ca3e24bSdrh Table *pTab, /* the table into which we are inserting */ 198226198bb4Sdrh int iDataCur, /* Cursor of the canonical data source */ 198326198bb4Sdrh int iIdxCur, /* First index cursor */ 19846934fc7bSdrh int regNewData, /* Range of content */ 1985aa9b8963Sdrh int *aRegIdx, /* Register used by each index. 0 for unused indices */ 1986f91c1318Sdan int update_flags, /* True for UPDATE, False for INSERT */ 1987de630353Sdanielk1977 int appendBias, /* True if this is likely to be an append */ 1988de630353Sdanielk1977 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ 19890ca3e24bSdrh ){ 19906934fc7bSdrh Vdbe *v; /* Prepared statements under construction */ 19916934fc7bSdrh Index *pIdx; /* An index being inserted or updated */ 19926934fc7bSdrh u8 pik_flags; /* flag values passed to the btree insert */ 19936934fc7bSdrh int i; /* Loop counter */ 19940ca3e24bSdrh 1995f91c1318Sdan assert( update_flags==0 1996f91c1318Sdan || update_flags==OPFLAG_ISUPDATE 1997f91c1318Sdan || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION) 1998f91c1318Sdan ); 1999f91c1318Sdan 20004adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 20010ca3e24bSdrh assert( v!=0 ); 2002417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 2003b2b9d3d7Sdrh for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 2004aa9b8963Sdrh if( aRegIdx[i]==0 ) continue; 2005b2b9d3d7Sdrh if( pIdx->pPartIdxWhere ){ 2006b2b9d3d7Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); 2007688852abSdrh VdbeCoverage(v); 2008b2b9d3d7Sdrh } 2009cb9a3643Sdan pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0); 201048dd1d8eSdrh if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 20114308e348Sdrh assert( pParse->nested==0 ); 20126546af14Sdrh pik_flags |= OPFLAG_NCHANGE; 2013f91c1318Sdan pik_flags |= (update_flags & OPFLAG_SAVEPOSITION); 2014cb9a3643Sdan #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 2015cb9a3643Sdan if( update_flags==0 ){ 201650ef6716Sdrh int r = sqlite3GetTempReg(pParse); 201750ef6716Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, r); 201850ef6716Sdrh sqlite3VdbeAddOp4(v, OP_Insert, 201950ef6716Sdrh iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE 2020cb9a3643Sdan ); 2021cb9a3643Sdan sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP); 202250ef6716Sdrh sqlite3ReleaseTempReg(pParse, r); 2023de630353Sdanielk1977 } 2024cb9a3643Sdan #endif 2025cb9a3643Sdan } 2026cb9a3643Sdan sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i], 2027cb9a3643Sdan aRegIdx[i]+1, 2028cb9a3643Sdan pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn); 20299b34abeeSdrh sqlite3VdbeChangeP5(v, pik_flags); 20300ca3e24bSdrh } 2031ec95c441Sdrh if( !HasRowid(pTab) ) return; 20324794f735Sdrh if( pParse->nested ){ 20334794f735Sdrh pik_flags = 0; 20344794f735Sdrh }else{ 203594eb6a14Sdanielk1977 pik_flags = OPFLAG_NCHANGE; 2036f91c1318Sdan pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID); 20374794f735Sdrh } 2038e4d90813Sdrh if( appendBias ){ 2039e4d90813Sdrh pik_flags |= OPFLAG_APPEND; 2040e4d90813Sdrh } 2041de630353Sdanielk1977 if( useSeekResult ){ 2042de630353Sdanielk1977 pik_flags |= OPFLAG_USESEEKRESULT; 2043de630353Sdanielk1977 } 2044a7c3b93fSdrh sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData); 204594eb6a14Sdanielk1977 if( !pParse->nested ){ 2046f14b7fb7Sdrh sqlite3VdbeAppendP4(v, pTab, P4_TABLE); 204794eb6a14Sdanielk1977 } 2048b7654111Sdrh sqlite3VdbeChangeP5(v, pik_flags); 20490ca3e24bSdrh } 2050cd44690aSdrh 2051cd44690aSdrh /* 205226198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate 205326198bb4Sdrh ** code to open and initialized those cursors. 2054aa9b8963Sdrh ** 205526198bb4Sdrh ** The cursor for the object that contains the complete data (normally 205626198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT 205726198bb4Sdrh ** ROWID table) is returned in *piDataCur. The first index cursor is 205826198bb4Sdrh ** returned in *piIdxCur. The number of indices is returned. 205926198bb4Sdrh ** 206026198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables 206126198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative. 206226198bb4Sdrh ** If iBase is negative, then allocate the next available cursor. 206326198bb4Sdrh ** 206426198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. 206526198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range 206626198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the 206726198bb4Sdrh ** pTab->pIndex list. 2068b6b4b79fSdrh ** 2069b6b4b79fSdrh ** If pTab is a virtual table, then this routine is a no-op and the 2070b6b4b79fSdrh ** *piDataCur and *piIdxCur values are left uninitialized. 2071cd44690aSdrh */ 2072aa9b8963Sdrh int sqlite3OpenTableAndIndices( 2073290c1948Sdrh Parse *pParse, /* Parsing context */ 2074290c1948Sdrh Table *pTab, /* Table to be opened */ 207526198bb4Sdrh int op, /* OP_OpenRead or OP_OpenWrite */ 2076b89aeb6aSdrh u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */ 207726198bb4Sdrh int iBase, /* Use this for the table cursor, if there is one */ 20786a53499aSdrh u8 *aToOpen, /* If not NULL: boolean for each table and index */ 207926198bb4Sdrh int *piDataCur, /* Write the database source cursor number here */ 208026198bb4Sdrh int *piIdxCur /* Write the first index cursor number here */ 2081290c1948Sdrh ){ 2082cd44690aSdrh int i; 20834cbdda9eSdrh int iDb; 20846a53499aSdrh int iDataCur; 2085cd44690aSdrh Index *pIdx; 20864cbdda9eSdrh Vdbe *v; 20874cbdda9eSdrh 208826198bb4Sdrh assert( op==OP_OpenRead || op==OP_OpenWrite ); 2089fd261ec6Sdan assert( op==OP_OpenWrite || p5==0 ); 209026198bb4Sdrh if( IsVirtual(pTab) ){ 2091b6b4b79fSdrh /* This routine is a no-op for virtual tables. Leave the output 2092b6b4b79fSdrh ** variables *piDataCur and *piIdxCur uninitialized so that valgrind 2093b6b4b79fSdrh ** can detect if they are used by mistake in the caller. */ 209426198bb4Sdrh return 0; 209526198bb4Sdrh } 20964cbdda9eSdrh iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 20974cbdda9eSdrh v = sqlite3GetVdbe(pParse); 2098cd44690aSdrh assert( v!=0 ); 209926198bb4Sdrh if( iBase<0 ) iBase = pParse->nTab; 21006a53499aSdrh iDataCur = iBase++; 21016a53499aSdrh if( piDataCur ) *piDataCur = iDataCur; 21026a53499aSdrh if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ 21036a53499aSdrh sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); 21046fbe41acSdrh }else{ 210526198bb4Sdrh sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); 21066fbe41acSdrh } 21076a53499aSdrh if( piIdxCur ) *piIdxCur = iBase; 210826198bb4Sdrh for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 210926198bb4Sdrh int iIdxCur = iBase++; 2110da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 211161441c34Sdan if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 211261441c34Sdan if( piDataCur ) *piDataCur = iIdxCur; 211361441c34Sdan p5 = 0; 211461441c34Sdan } 21156a53499aSdrh if( aToOpen==0 || aToOpen[i+1] ){ 21162ec2fb22Sdrh sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); 21172ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 2118b89aeb6aSdrh sqlite3VdbeChangeP5(v, p5); 211961441c34Sdan VdbeComment((v, "%s", pIdx->zName)); 2120b89aeb6aSdrh } 21216a53499aSdrh } 212226198bb4Sdrh if( iBase>pParse->nTab ) pParse->nTab = iBase; 212326198bb4Sdrh return i; 2124cd44690aSdrh } 21259d9cf229Sdrh 212691c58e23Sdrh 212791c58e23Sdrh #ifdef SQLITE_TEST 212891c58e23Sdrh /* 212991c58e23Sdrh ** The following global variable is incremented whenever the 213091c58e23Sdrh ** transfer optimization is used. This is used for testing 213191c58e23Sdrh ** purposes only - to make sure the transfer optimization really 213260ec914cSpeter.d.reid ** is happening when it is supposed to. 213391c58e23Sdrh */ 213491c58e23Sdrh int sqlite3_xferopt_count; 213591c58e23Sdrh #endif /* SQLITE_TEST */ 213691c58e23Sdrh 213791c58e23Sdrh 21389d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 21399d9cf229Sdrh /* 21409d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data 21419d9cf229Sdrh ** for index pDest in an insert transfer optimization. The rules 21429d9cf229Sdrh ** for a compatible index: 21439d9cf229Sdrh ** 21449d9cf229Sdrh ** * The index is over the same set of columns 21459d9cf229Sdrh ** * The same DESC and ASC markings occurs on all columns 21469d9cf229Sdrh ** * The same onError processing (OE_Abort, OE_Ignore, etc) 21479d9cf229Sdrh ** * The same collating sequence on each column 2148b2b9d3d7Sdrh ** * The index has the exact same WHERE clause 21499d9cf229Sdrh */ 21509d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 21519d9cf229Sdrh int i; 21529d9cf229Sdrh assert( pDest && pSrc ); 21539d9cf229Sdrh assert( pDest->pTable!=pSrc->pTable ); 2154bbbdc83bSdrh if( pDest->nKeyCol!=pSrc->nKeyCol ){ 21559d9cf229Sdrh return 0; /* Different number of columns */ 21569d9cf229Sdrh } 21579d9cf229Sdrh if( pDest->onError!=pSrc->onError ){ 21589d9cf229Sdrh return 0; /* Different conflict resolution strategies */ 21599d9cf229Sdrh } 2160bbbdc83bSdrh for(i=0; i<pSrc->nKeyCol; i++){ 21619d9cf229Sdrh if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 21629d9cf229Sdrh return 0; /* Different columns indexed */ 21639d9cf229Sdrh } 21644b92f98cSdrh if( pSrc->aiColumn[i]==XN_EXPR ){ 21651f9ca2c8Sdrh assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); 21665aa550cfSdan if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr, 21671f9ca2c8Sdrh pDest->aColExpr->a[i].pExpr, -1)!=0 ){ 21681f9ca2c8Sdrh return 0; /* Different expressions in the index */ 21691f9ca2c8Sdrh } 21701f9ca2c8Sdrh } 21719d9cf229Sdrh if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 21729d9cf229Sdrh return 0; /* Different sort orders */ 21739d9cf229Sdrh } 21740472af91Sdrh if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){ 217560a713c6Sdrh return 0; /* Different collating sequences */ 21769d9cf229Sdrh } 21779d9cf229Sdrh } 21785aa550cfSdan if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ 2179b2b9d3d7Sdrh return 0; /* Different WHERE clauses */ 2180b2b9d3d7Sdrh } 21819d9cf229Sdrh 21829d9cf229Sdrh /* If no test above fails then the indices must be compatible */ 21839d9cf229Sdrh return 1; 21849d9cf229Sdrh } 21859d9cf229Sdrh 21869d9cf229Sdrh /* 21879d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form 21889d9cf229Sdrh ** 21899d9cf229Sdrh ** INSERT INTO tab1 SELECT * FROM tab2; 21909d9cf229Sdrh ** 2191ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1. 219260ec914cSpeter.d.reid ** Columns are not decoded and reassembled, which greatly improves 2193ccdf1baeSdrh ** performance. Raw index records are transferred in the same way. 21949d9cf229Sdrh ** 2195ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible. 2196ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments 2197ccdf1baeSdrh ** embedded in the code for details. 21989d9cf229Sdrh ** 2199ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used. 2200ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table 2201ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time. In that 2202ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also 2203ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the 2204ccdf1baeSdrh ** xfer optimization code if the test fails. In that case, this routine 2205ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate 2206ccdf1baeSdrh ** an unoptimized transfer. This routine also returns FALSE if there 2207ccdf1baeSdrh ** is no chance that the xfer optimization can be applied. 22089d9cf229Sdrh ** 2209ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster. 22109d9cf229Sdrh */ 22119d9cf229Sdrh static int xferOptimization( 22129d9cf229Sdrh Parse *pParse, /* Parser context */ 22139d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 22149d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 22159d9cf229Sdrh int onError, /* How to handle constraint errors */ 22169d9cf229Sdrh int iDbDest /* The database of pDest */ 22179d9cf229Sdrh ){ 2218e34162b1Sdan sqlite3 *db = pParse->db; 22199d9cf229Sdrh ExprList *pEList; /* The result set of the SELECT */ 22209d9cf229Sdrh Table *pSrc; /* The table in the FROM clause of SELECT */ 22219d9cf229Sdrh Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 22229d9cf229Sdrh struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 22239d9cf229Sdrh int i; /* Loop counter */ 22249d9cf229Sdrh int iDbSrc; /* The database of pSrc */ 22259d9cf229Sdrh int iSrc, iDest; /* Cursors from source and destination */ 22269d9cf229Sdrh int addr1, addr2; /* Loop addresses */ 2227da475b8dSdrh int emptyDestTest = 0; /* Address of test for empty pDest */ 2228da475b8dSdrh int emptySrcTest = 0; /* Address of test for empty pSrc */ 22299d9cf229Sdrh Vdbe *v; /* The VDBE we are building */ 22306a288a33Sdrh int regAutoinc; /* Memory register used by AUTOINC */ 2231f33c9fadSdrh int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 2232b7654111Sdrh int regData, regRowid; /* Registers holding data and rowid */ 22339d9cf229Sdrh 22349d9cf229Sdrh if( pSelect==0 ){ 22359d9cf229Sdrh return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 22369d9cf229Sdrh } 2237ebbf08a0Sdan if( pParse->pWith || pSelect->pWith ){ 2238ebbf08a0Sdan /* Do not attempt to process this query if there are an WITH clauses 2239ebbf08a0Sdan ** attached to it. Proceeding may generate a false "no such table: xxx" 2240ebbf08a0Sdan ** error if pSelect reads from a CTE named "xxx". */ 2241ebbf08a0Sdan return 0; 2242ebbf08a0Sdan } 22432f886d1dSdanielk1977 if( sqlite3TriggerList(pParse, pDest) ){ 22449d9cf229Sdrh return 0; /* tab1 must not have triggers */ 22459d9cf229Sdrh } 22469d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 224744266ec6Sdrh if( IsVirtual(pDest) ){ 22489d9cf229Sdrh return 0; /* tab1 must not be a virtual table */ 22499d9cf229Sdrh } 22509d9cf229Sdrh #endif 22519d9cf229Sdrh if( onError==OE_Default ){ 2252e7224a01Sdrh if( pDest->iPKey>=0 ) onError = pDest->keyConf; 2253e7224a01Sdrh if( onError==OE_Default ) onError = OE_Abort; 22549d9cf229Sdrh } 22555ce240a6Sdanielk1977 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 22569d9cf229Sdrh if( pSelect->pSrc->nSrc!=1 ){ 22579d9cf229Sdrh return 0; /* FROM clause must have exactly one term */ 22589d9cf229Sdrh } 22599d9cf229Sdrh if( pSelect->pSrc->a[0].pSelect ){ 22609d9cf229Sdrh return 0; /* FROM clause cannot contain a subquery */ 22619d9cf229Sdrh } 22629d9cf229Sdrh if( pSelect->pWhere ){ 22639d9cf229Sdrh return 0; /* SELECT may not have a WHERE clause */ 22649d9cf229Sdrh } 22659d9cf229Sdrh if( pSelect->pOrderBy ){ 22669d9cf229Sdrh return 0; /* SELECT may not have an ORDER BY clause */ 22679d9cf229Sdrh } 22688103b7d2Sdrh /* Do not need to test for a HAVING clause. If HAVING is present but 22698103b7d2Sdrh ** there is no ORDER BY, we will get an error. */ 22709d9cf229Sdrh if( pSelect->pGroupBy ){ 22719d9cf229Sdrh return 0; /* SELECT may not have a GROUP BY clause */ 22729d9cf229Sdrh } 22739d9cf229Sdrh if( pSelect->pLimit ){ 22749d9cf229Sdrh return 0; /* SELECT may not have a LIMIT clause */ 22759d9cf229Sdrh } 22769d9cf229Sdrh if( pSelect->pPrior ){ 22779d9cf229Sdrh return 0; /* SELECT may not be a compound query */ 22789d9cf229Sdrh } 22797d10d5a6Sdrh if( pSelect->selFlags & SF_Distinct ){ 22809d9cf229Sdrh return 0; /* SELECT may not be DISTINCT */ 22819d9cf229Sdrh } 22829d9cf229Sdrh pEList = pSelect->pEList; 22839d9cf229Sdrh assert( pEList!=0 ); 22849d9cf229Sdrh if( pEList->nExpr!=1 ){ 22859d9cf229Sdrh return 0; /* The result set must have exactly one column */ 22869d9cf229Sdrh } 22879d9cf229Sdrh assert( pEList->a[0].pExpr ); 22881a1d3cd2Sdrh if( pEList->a[0].pExpr->op!=TK_ASTERISK ){ 22899d9cf229Sdrh return 0; /* The result set must be the special operator "*" */ 22909d9cf229Sdrh } 22919d9cf229Sdrh 22929d9cf229Sdrh /* At this point we have established that the statement is of the 22939d9cf229Sdrh ** correct syntactic form to participate in this optimization. Now 22949d9cf229Sdrh ** we have to check the semantics. 22959d9cf229Sdrh */ 22969d9cf229Sdrh pItem = pSelect->pSrc->a; 229741fb5cd1Sdan pSrc = sqlite3LocateTableItem(pParse, 0, pItem); 22989d9cf229Sdrh if( pSrc==0 ){ 22999d9cf229Sdrh return 0; /* FROM clause does not contain a real table */ 23009d9cf229Sdrh } 230121908b21Sdrh if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){ 230221908b21Sdrh testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */ 23039d9cf229Sdrh return 0; /* tab1 and tab2 may not be the same table */ 23049d9cf229Sdrh } 230555548273Sdrh if( HasRowid(pDest)!=HasRowid(pSrc) ){ 230655548273Sdrh return 0; /* source and destination must both be WITHOUT ROWID or not */ 230755548273Sdrh } 23089d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 230944266ec6Sdrh if( IsVirtual(pSrc) ){ 23109d9cf229Sdrh return 0; /* tab2 must not be a virtual table */ 23119d9cf229Sdrh } 23129d9cf229Sdrh #endif 23139d9cf229Sdrh if( pSrc->pSelect ){ 23149d9cf229Sdrh return 0; /* tab2 may not be a view */ 23159d9cf229Sdrh } 23169d9cf229Sdrh if( pDest->nCol!=pSrc->nCol ){ 23179d9cf229Sdrh return 0; /* Number of columns must be the same in tab1 and tab2 */ 23189d9cf229Sdrh } 23199d9cf229Sdrh if( pDest->iPKey!=pSrc->iPKey ){ 23209d9cf229Sdrh return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 23219d9cf229Sdrh } 23229d9cf229Sdrh for(i=0; i<pDest->nCol; i++){ 23239940e2aaSdan Column *pDestCol = &pDest->aCol[i]; 23249940e2aaSdan Column *pSrcCol = &pSrc->aCol[i]; 2325ba68f8f3Sdan #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS 23268257aa8dSdrh if( (db->mDbFlags & DBFLAG_Vacuum)==0 2327aaea3143Sdan && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN 2328aaea3143Sdan ){ 2329ba68f8f3Sdan return 0; /* Neither table may have __hidden__ columns */ 2330ba68f8f3Sdan } 2331ba68f8f3Sdan #endif 2332ae3977a8Sdrh if( (pDestCol->colFlags & COLFLAG_GENERATED) != 2333ae3977a8Sdrh (pSrcCol->colFlags & COLFLAG_GENERATED) ){ 2334ae3977a8Sdrh return 0; /* Both columns have the same generated type */ 2335ae3977a8Sdrh } 23369940e2aaSdan if( pDestCol->affinity!=pSrcCol->affinity ){ 23379d9cf229Sdrh return 0; /* Affinity must be the same on all columns */ 23389d9cf229Sdrh } 23390472af91Sdrh if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){ 23409d9cf229Sdrh return 0; /* Collating sequence must be the same on all columns */ 23419d9cf229Sdrh } 23429940e2aaSdan if( pDestCol->notNull && !pSrcCol->notNull ){ 23439d9cf229Sdrh return 0; /* tab2 must be NOT NULL if tab1 is */ 23449d9cf229Sdrh } 2345453e0261Sdrh /* Default values for second and subsequent columns need to match. */ 2346ae3977a8Sdrh if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){ 234794fa9c41Sdrh assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN ); 234894fa9c41Sdrh assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN ); 234994fa9c41Sdrh if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) 235094fa9c41Sdrh || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken, 235194fa9c41Sdrh pSrcCol->pDflt->u.zToken)!=0) 23529940e2aaSdan ){ 23539940e2aaSdan return 0; /* Default values must be the same for all columns */ 23549940e2aaSdan } 23559d9cf229Sdrh } 2356ae3977a8Sdrh /* Generator expressions for generated columns must match */ 2357ae3977a8Sdrh if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){ 2358ae3977a8Sdrh if( sqlite3ExprCompare(0, pSrcCol->pDflt, pDestCol->pDflt, -1)!=0 ){ 2359ae3977a8Sdrh return 0; /* Different generator expressions */ 2360ae3977a8Sdrh } 2361ae3977a8Sdrh } 236294fa9c41Sdrh } 23639d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 23645f1d1d9cSdrh if( IsUniqueIndex(pDestIdx) ){ 2365f33c9fadSdrh destHasUniqueIdx = 1; 2366f33c9fadSdrh } 23679d9cf229Sdrh for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 23689d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 23699d9cf229Sdrh } 23709d9cf229Sdrh if( pSrcIdx==0 ){ 23719d9cf229Sdrh return 0; /* pDestIdx has no corresponding index in pSrc */ 23729d9cf229Sdrh } 2373e3bd232eSdrh if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema 2374e3bd232eSdrh && sqlite3FaultSim(411)==SQLITE_OK ){ 2375e3bd232eSdrh /* The sqlite3FaultSim() call allows this corruption test to be 2376e3bd232eSdrh ** bypassed during testing, in order to exercise other corruption tests 2377e3bd232eSdrh ** further downstream. */ 237886223e8dSdrh return 0; /* Corrupt schema - two indexes on the same btree */ 237986223e8dSdrh } 23809d9cf229Sdrh } 23817fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK 2382619a1305Sdrh if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ 23838103b7d2Sdrh return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 23848103b7d2Sdrh } 23857fc2f41bSdrh #endif 2386713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY 2387713de341Sdrh /* Disallow the transfer optimization if the destination table constains 2388713de341Sdrh ** any foreign key constraints. This is more restrictive than necessary. 2389713de341Sdrh ** But the main beneficiary of the transfer optimization is the VACUUM 2390713de341Sdrh ** command, and the VACUUM command disables foreign key constraints. So 2391713de341Sdrh ** the extra complication to make this rule less restrictive is probably 2392713de341Sdrh ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] 2393713de341Sdrh */ 2394e34162b1Sdan if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ 2395713de341Sdrh return 0; 2396713de341Sdrh } 2397713de341Sdrh #endif 2398e34162b1Sdan if( (db->flags & SQLITE_CountRows)!=0 ){ 2399ccdf1baeSdrh return 0; /* xfer opt does not play well with PRAGMA count_changes */ 24001696124dSdan } 24019d9cf229Sdrh 2402ccdf1baeSdrh /* If we get this far, it means that the xfer optimization is at 2403ccdf1baeSdrh ** least a possibility, though it might only work if the destination 2404ccdf1baeSdrh ** table (tab1) is initially empty. 24059d9cf229Sdrh */ 2406dd73521bSdrh #ifdef SQLITE_TEST 2407dd73521bSdrh sqlite3_xferopt_count++; 2408dd73521bSdrh #endif 2409e34162b1Sdan iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); 24109d9cf229Sdrh v = sqlite3GetVdbe(pParse); 2411f53e9b5aSdrh sqlite3CodeVerifySchema(pParse, iDbSrc); 24129d9cf229Sdrh iSrc = pParse->nTab++; 24139d9cf229Sdrh iDest = pParse->nTab++; 24146a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 241555548273Sdrh regData = sqlite3GetTempReg(pParse); 241655548273Sdrh regRowid = sqlite3GetTempReg(pParse); 24179d9cf229Sdrh sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 2418427ebba1Sdan assert( HasRowid(pDest) || destHasUniqueIdx ); 24198257aa8dSdrh if( (db->mDbFlags & DBFLAG_Vacuum)==0 && ( 2420e34162b1Sdan (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ 2421ccdf1baeSdrh || destHasUniqueIdx /* (2) */ 2422ccdf1baeSdrh || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ 2423e34162b1Sdan )){ 2424ccdf1baeSdrh /* In some circumstances, we are able to run the xfer optimization 2425e34162b1Sdan ** only if the destination table is initially empty. Unless the 24268257aa8dSdrh ** DBFLAG_Vacuum flag is set, this block generates code to make 24278257aa8dSdrh ** that determination. If DBFLAG_Vacuum is set, then the destination 2428e34162b1Sdan ** table is always empty. 2429e34162b1Sdan ** 2430e34162b1Sdan ** Conditions under which the destination must be empty: 2431f33c9fadSdrh ** 2432ccdf1baeSdrh ** (1) There is no INTEGER PRIMARY KEY but there are indices. 2433ccdf1baeSdrh ** (If the destination is not initially empty, the rowid fields 2434ccdf1baeSdrh ** of index entries might need to change.) 2435ccdf1baeSdrh ** 2436ccdf1baeSdrh ** (2) The destination has a unique index. (The xfer optimization 2437ccdf1baeSdrh ** is unable to test uniqueness.) 2438ccdf1baeSdrh ** 2439ccdf1baeSdrh ** (3) onError is something other than OE_Abort and OE_Rollback. 24409d9cf229Sdrh */ 2441688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); 24422991ba05Sdrh emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); 24439d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 24449d9cf229Sdrh } 2445427ebba1Sdan if( HasRowid(pSrc) ){ 2446c9b9deaeSdrh u8 insFlags; 24479d9cf229Sdrh sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 2448688852abSdrh emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 244942242dedSdrh if( pDest->iPKey>=0 ){ 2450b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 24514031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 2452b7654111Sdrh addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 2453688852abSdrh VdbeCoverage(v); 2454f9c8ce3cSdrh sqlite3RowidConstraint(pParse, onError, pDest); 24559d9cf229Sdrh sqlite3VdbeJumpHere(v, addr2); 2456b7654111Sdrh autoIncStep(pParse, regAutoinc, regRowid); 24574e61e883Sdrh }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){ 2458b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 245995bad4c7Sdrh }else{ 2460b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 24617d10d5a6Sdrh assert( (pDest->tabFlags & TF_Autoincrement)==0 ); 246295bad4c7Sdrh } 2463e7b554d6Sdrh sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); 24648257aa8dSdrh if( db->mDbFlags & DBFLAG_Vacuum ){ 246586b40dfdSdrh sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); 2466c9b9deaeSdrh insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID| 2467c9b9deaeSdrh OPFLAG_APPEND|OPFLAG_USESEEKRESULT; 2468c9b9deaeSdrh }else{ 2469c9b9deaeSdrh insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND; 2470c9b9deaeSdrh } 24719b34abeeSdrh sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid, 247220f272c9Sdrh (char*)pDest, P4_TABLE); 2473c9b9deaeSdrh sqlite3VdbeChangeP5(v, insFlags); 2474688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); 247555548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 247655548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2477da475b8dSdrh }else{ 2478da475b8dSdrh sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); 2479da475b8dSdrh sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); 248055548273Sdrh } 24819d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 248241b9ca25Sdrh u8 idxInsFlags = 0; 24831b7ecbb4Sdrh for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ 24849d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 24859d9cf229Sdrh } 24869d9cf229Sdrh assert( pSrcIdx ); 24872ec2fb22Sdrh sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); 24882ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); 2489d4e70ebdSdrh VdbeComment((v, "%s", pSrcIdx->zName)); 24902ec2fb22Sdrh sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); 24912ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); 249259885728Sdan sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); 2493207872a4Sdanielk1977 VdbeComment((v, "%s", pDestIdx->zName)); 2494688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2495e7b554d6Sdrh sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); 24968257aa8dSdrh if( db->mDbFlags & DBFLAG_Vacuum ){ 2497e34162b1Sdan /* This INSERT command is part of a VACUUM operation, which guarantees 2498e34162b1Sdan ** that the destination table is empty. If all indexed columns use 2499e34162b1Sdan ** collation sequence BINARY, then it can also be assumed that the 2500e34162b1Sdan ** index will be populated by inserting keys in strictly sorted 2501e34162b1Sdan ** order. In this case, instead of seeking within the b-tree as part 250286b40dfdSdrh ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the 2503e34162b1Sdan ** OP_IdxInsert to seek to the point within the b-tree where each key 2504e34162b1Sdan ** should be inserted. This is faster. 2505e34162b1Sdan ** 2506e34162b1Sdan ** If any of the indexed columns use a collation sequence other than 2507e34162b1Sdan ** BINARY, this optimization is disabled. This is because the user 2508e34162b1Sdan ** might change the definition of a collation sequence and then run 2509e34162b1Sdan ** a VACUUM command. In that case keys may not be written in strictly 2510e34162b1Sdan ** sorted order. */ 2511e34162b1Sdan for(i=0; i<pSrcIdx->nColumn; i++){ 2512f19aa5faSdrh const char *zColl = pSrcIdx->azColl[i]; 2513f19aa5faSdrh if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break; 2514e34162b1Sdan } 2515e34162b1Sdan if( i==pSrcIdx->nColumn ){ 251641b9ca25Sdrh idxInsFlags = OPFLAG_USESEEKRESULT; 251786b40dfdSdrh sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); 2518e34162b1Sdan } 2519e34162b1Sdan } 25209df385ecSdrh if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){ 252141b9ca25Sdrh idxInsFlags |= OPFLAG_NCHANGE; 252241b9ca25Sdrh } 25239b4eaebcSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData); 25249b4eaebcSdrh sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND); 2525688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); 25269d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 252755548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 252855548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 25299d9cf229Sdrh } 2530aceb31b1Sdrh if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); 2531b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 2532b7654111Sdrh sqlite3ReleaseTempReg(pParse, regData); 25339d9cf229Sdrh if( emptyDestTest ){ 25341dd518cfSdrh sqlite3AutoincrementEnd(pParse); 253566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 25369d9cf229Sdrh sqlite3VdbeJumpHere(v, emptyDestTest); 253766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 25389d9cf229Sdrh return 0; 25399d9cf229Sdrh }else{ 25409d9cf229Sdrh return 1; 25419d9cf229Sdrh } 25429d9cf229Sdrh } 25439d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 2544