1cce7d176Sdrh /* 2b19a2bc6Sdrh ** 2001 September 15 3cce7d176Sdrh ** 4b19a2bc6Sdrh ** The author disclaims copyright to this source code. In place of 5b19a2bc6Sdrh ** a legal notice, here is a blessing: 6cce7d176Sdrh ** 7b19a2bc6Sdrh ** May you do good and not evil. 8b19a2bc6Sdrh ** May you find forgiveness for yourself and forgive others. 9b19a2bc6Sdrh ** May you share freely, never taking more than you give. 10cce7d176Sdrh ** 11cce7d176Sdrh ************************************************************************* 12cce7d176Sdrh ** This file contains C code routines that are called by the parser 13b19a2bc6Sdrh ** to handle INSERT statements in SQLite. 14cce7d176Sdrh */ 15cce7d176Sdrh #include "sqliteInt.h" 16cce7d176Sdrh 17cce7d176Sdrh /* 1826198bb4Sdrh ** Generate code that will 19dd9930efSdrh ** 2026198bb4Sdrh ** (1) acquire a lock for table pTab then 2126198bb4Sdrh ** (2) open pTab as cursor iCur. 2226198bb4Sdrh ** 2326198bb4Sdrh ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index 2426198bb4Sdrh ** for that table that is actually opened. 25bbb5e4e0Sdrh */ 26bbb5e4e0Sdrh void sqlite3OpenTable( 272ec2fb22Sdrh Parse *pParse, /* Generate code into this VDBE */ 28bbb5e4e0Sdrh int iCur, /* The cursor number of the table */ 29bbb5e4e0Sdrh int iDb, /* The database index in sqlite3.aDb[] */ 30bbb5e4e0Sdrh Table *pTab, /* The table to be opened */ 31bbb5e4e0Sdrh int opcode /* OP_OpenRead or OP_OpenWrite */ 32bbb5e4e0Sdrh ){ 33bbb5e4e0Sdrh Vdbe *v; 345f53aac2Sdrh assert( !IsVirtual(pTab) ); 352ec2fb22Sdrh v = sqlite3GetVdbe(pParse); 36bbb5e4e0Sdrh assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); 372ec2fb22Sdrh sqlite3TableLock(pParse, iDb, pTab->tnum, 382ec2fb22Sdrh (opcode==OP_OpenWrite)?1:0, pTab->zName); 39ec95c441Sdrh if( HasRowid(pTab) ){ 400b0b3a95Sdrh sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol); 41bbb5e4e0Sdrh VdbeComment((v, "%s", pTab->zName)); 4226198bb4Sdrh }else{ 43dd9930efSdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab); 44dd9930efSdrh assert( pPk!=0 ); 45afe028a8Sdrh assert( pPk->tnum==pTab->tnum ); 462ec2fb22Sdrh sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb); 472ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pPk); 48bbb5e4e0Sdrh VdbeComment((v, "%s", pTab->zName)); 49bbb5e4e0Sdrh } 50bbb5e4e0Sdrh } 51bbb5e4e0Sdrh 52bbb5e4e0Sdrh /* 5369f8bb9cSdan ** Return a pointer to the column affinity string associated with index 5469f8bb9cSdan ** pIdx. A column affinity string has one character for each column in 5569f8bb9cSdan ** the table, according to the affinity of the column: 563d1bfeaaSdanielk1977 ** 573d1bfeaaSdanielk1977 ** Character Column affinity 583d1bfeaaSdanielk1977 ** ------------------------------ 5905883a34Sdrh ** 'A' BLOB 604583c37cSdrh ** 'B' TEXT 614583c37cSdrh ** 'C' NUMERIC 624583c37cSdrh ** 'D' INTEGER 634583c37cSdrh ** 'F' REAL 642d401ab8Sdrh ** 654583c37cSdrh ** An extra 'D' is appended to the end of the string to cover the 662d401ab8Sdrh ** rowid that appears as the last column in every index. 6769f8bb9cSdan ** 6869f8bb9cSdan ** Memory for the buffer containing the column index affinity string 6969f8bb9cSdan ** is managed along with the rest of the Index structure. It will be 7069f8bb9cSdan ** released when sqlite3DeleteIndex() is called. 713d1bfeaaSdanielk1977 */ 72e9107698Sdrh const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){ 73a37cdde0Sdanielk1977 if( !pIdx->zColAff ){ 74e014a838Sdanielk1977 /* The first time a column affinity string for a particular index is 75a37cdde0Sdanielk1977 ** required, it is allocated and populated here. It is then stored as 76e014a838Sdanielk1977 ** a member of the Index structure for subsequent use. 77a37cdde0Sdanielk1977 ** 78a37cdde0Sdanielk1977 ** The column affinity string will eventually be deleted by 79e014a838Sdanielk1977 ** sqliteDeleteIndex() when the Index structure itself is cleaned 80a37cdde0Sdanielk1977 ** up. 81a37cdde0Sdanielk1977 */ 82a37cdde0Sdanielk1977 int n; 83a37cdde0Sdanielk1977 Table *pTab = pIdx->pTable; 84ad124329Sdrh pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1); 85a37cdde0Sdanielk1977 if( !pIdx->zColAff ){ 864a642b60Sdrh sqlite3OomFault(db); 8769f8bb9cSdan return 0; 88a37cdde0Sdanielk1977 } 89a37cdde0Sdanielk1977 for(n=0; n<pIdx->nColumn; n++){ 90ad124329Sdrh i16 x = pIdx->aiColumn[n]; 916860e6faSdrh char aff; 9281506b88Sdrh if( x>=0 ){ 9381506b88Sdrh aff = pTab->aCol[x].affinity; 9481506b88Sdrh }else if( x==XN_ROWID ){ 9581506b88Sdrh aff = SQLITE_AFF_INTEGER; 9681506b88Sdrh }else{ 974b92f98cSdrh assert( x==XN_EXPR ); 981f9ca2c8Sdrh assert( pIdx->aColExpr!=0 ); 996860e6faSdrh aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr); 10081506b88Sdrh } 10196fb16eeSdrh if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB; 1027314495fSdrh if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC; 1036860e6faSdrh pIdx->zColAff[n] = aff; 1041f9ca2c8Sdrh } 1052d401ab8Sdrh pIdx->zColAff[n] = 0; 106a37cdde0Sdanielk1977 } 1073d1bfeaaSdanielk1977 10869f8bb9cSdan return pIdx->zColAff; 109a37cdde0Sdanielk1977 } 110a37cdde0Sdanielk1977 111a37cdde0Sdanielk1977 /* 11257bf4a8eSdrh ** Compute the affinity string for table pTab, if it has not already been 11305883a34Sdrh ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities. 11457bf4a8eSdrh ** 11505883a34Sdrh ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and 11657bf4a8eSdrh ** if iReg>0 then code an OP_Affinity opcode that will set the affinities 11757bf4a8eSdrh ** for register iReg and following. Or if affinities exists and iReg==0, 11857bf4a8eSdrh ** then just set the P4 operand of the previous opcode (which should be 11957bf4a8eSdrh ** an OP_MakeRecord) to the affinity string. 12057bf4a8eSdrh ** 121b6e8fd10Sdrh ** A column affinity string has one character per column: 122a37cdde0Sdanielk1977 ** 123a37cdde0Sdanielk1977 ** Character Column affinity 124a37cdde0Sdanielk1977 ** ------------------------------ 12505883a34Sdrh ** 'A' BLOB 1264583c37cSdrh ** 'B' TEXT 1274583c37cSdrh ** 'C' NUMERIC 1284583c37cSdrh ** 'D' INTEGER 1294583c37cSdrh ** 'E' REAL 130a37cdde0Sdanielk1977 */ 13157bf4a8eSdrh void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ 132ab45fc04Sdrh int i, j; 13357bf4a8eSdrh char *zColAff = pTab->zColAff; 13457bf4a8eSdrh if( zColAff==0 ){ 135abb6fcabSdrh sqlite3 *db = sqlite3VdbeDb(v); 136b975598eSdrh zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); 1373d1bfeaaSdanielk1977 if( !zColAff ){ 1384a642b60Sdrh sqlite3OomFault(db); 139a37cdde0Sdanielk1977 return; 1403d1bfeaaSdanielk1977 } 1413d1bfeaaSdanielk1977 142ab45fc04Sdrh for(i=j=0; i<pTab->nCol; i++){ 14396fb16eeSdrh assert( pTab->aCol[i].affinity!=0 ); 144ab45fc04Sdrh if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){ 145ab45fc04Sdrh zColAff[j++] = pTab->aCol[i].affinity; 146ab45fc04Sdrh } 1473d1bfeaaSdanielk1977 } 14857bf4a8eSdrh do{ 149ab45fc04Sdrh zColAff[j--] = 0; 150ab45fc04Sdrh }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB ); 1513d1bfeaaSdanielk1977 pTab->zColAff = zColAff; 1523d1bfeaaSdanielk1977 } 1537301e774Sdrh assert( zColAff!=0 ); 1547301e774Sdrh i = sqlite3Strlen30NN(zColAff); 15557bf4a8eSdrh if( i ){ 15657bf4a8eSdrh if( iReg ){ 15757bf4a8eSdrh sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i); 15857bf4a8eSdrh }else{ 15957bf4a8eSdrh sqlite3VdbeChangeP4(v, -1, zColAff, i); 16057bf4a8eSdrh } 16157bf4a8eSdrh } 1623d1bfeaaSdanielk1977 } 1633d1bfeaaSdanielk1977 1644d88778bSdanielk1977 /* 16548d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices 166b6e8fd10Sdrh ** have been opened at any point in the VDBE program. This is used to see if 16748d1178aSdrh ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can 168b6e8fd10Sdrh ** run without using a temporary table for the results of the SELECT. 1694d88778bSdanielk1977 */ 17005a86c5cSdrh static int readsTable(Parse *p, int iDb, Table *pTab){ 171595a523aSdanielk1977 Vdbe *v = sqlite3GetVdbe(p); 1724d88778bSdanielk1977 int i; 17348d1178aSdrh int iEnd = sqlite3VdbeCurrentAddr(v); 174595a523aSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE 175595a523aSdanielk1977 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; 176595a523aSdanielk1977 #endif 177595a523aSdanielk1977 17805a86c5cSdrh for(i=1; i<iEnd; i++){ 17948d1178aSdrh VdbeOp *pOp = sqlite3VdbeGetOp(v, i); 180ef0bea92Sdrh assert( pOp!=0 ); 181207872a4Sdanielk1977 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ 18248d1178aSdrh Index *pIndex; 183207872a4Sdanielk1977 int tnum = pOp->p2; 18448d1178aSdrh if( tnum==pTab->tnum ){ 18548d1178aSdrh return 1; 18648d1178aSdrh } 18748d1178aSdrh for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 18848d1178aSdrh if( tnum==pIndex->tnum ){ 18948d1178aSdrh return 1; 19048d1178aSdrh } 19148d1178aSdrh } 19248d1178aSdrh } 193543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 194595a523aSdanielk1977 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){ 1952dca4ac1Sdanielk1977 assert( pOp->p4.pVtab!=0 ); 19666a5167bSdrh assert( pOp->p4type==P4_VTAB ); 19748d1178aSdrh return 1; 1984d88778bSdanielk1977 } 199543165efSdrh #endif 2004d88778bSdanielk1977 } 2014d88778bSdanielk1977 return 0; 2024d88778bSdanielk1977 } 2033d1bfeaaSdanielk1977 204c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 205c1431144Sdrh /* 206c1431144Sdrh ** All regular columns for table pTab have been puts into registers 207c1431144Sdrh ** starting with iRegStore. The registers that correspond to STORED 208dd6cc9b5Sdrh ** or VIRTUAL columns have not yet been initialized. This routine goes 209dd6cc9b5Sdrh ** back and computes the values for those columns based on the previously 210dd6cc9b5Sdrh ** computed normal columns. 211c1431144Sdrh */ 212dd6cc9b5Sdrh void sqlite3ComputeGeneratedColumns( 213c1431144Sdrh Parse *pParse, /* Parsing context */ 214c1431144Sdrh int iRegStore, /* Register holding the first column */ 215c1431144Sdrh Table *pTab /* The table */ 216c1431144Sdrh ){ 217c1431144Sdrh int i; 218dd6cc9b5Sdrh int nv; 219dd6cc9b5Sdrh /* Because there can be multiple generated columns that refer to one another, 220dd6cc9b5Sdrh ** this is a two-pass algorithm. On the first pass, mark all generated 221dd6cc9b5Sdrh ** columns as "not available". 2229942ef0dSdrh */ 2239942ef0dSdrh for(i=0; i<pTab->nCol; i++){ 224dd6cc9b5Sdrh if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ 225427b96aeSdrh testcase( pTab->aCol[i].colflags & COLFLAG_VIRTUAL ); 226427b96aeSdrh testcase( pTab->aCol[i].colflags & COLFLAG_STORED ); 2279942ef0dSdrh pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL; 2289942ef0dSdrh } 2299942ef0dSdrh } 2309942ef0dSdrh /* On the second pass, compute the value of each NOT-AVAILABLE column. 2319942ef0dSdrh ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will 2329942ef0dSdrh ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as 2339942ef0dSdrh ** they are needed. 2349942ef0dSdrh */ 235c1431144Sdrh pParse->iSelfTab = -iRegStore; 236dd6cc9b5Sdrh for(i=nv=0; i<pTab->nCol; i++){ 237c1431144Sdrh u32 colFlags = pTab->aCol[i].colFlags; 238dd6cc9b5Sdrh if( (colFlags & COLFLAG_NOTAVAIL)!=0 ){ 239dd6cc9b5Sdrh assert( colFlags & COLFLAG_GENERATED ); 240dd6cc9b5Sdrh if( colFlags & COLFLAG_VIRTUAL ){ 241dd6cc9b5Sdrh /* Virtual columns go at the end */ 242dd6cc9b5Sdrh assert( pTab->nNVCol+nv == sqlite3TableColumnToStorage(pTab,i) ); 243*e70fa7feSdrh sqlite3ExprCodeGeneratedColumn(pParse, &pTab->aCol[i], 244dd6cc9b5Sdrh iRegStore+pTab->nNVCol+nv); 245dd6cc9b5Sdrh }else{ 246dd6cc9b5Sdrh /* Stored columns go in column order */ 247dd6cc9b5Sdrh assert( i-nv == sqlite3TableColumnToStorage(pTab,i) ); 248*e70fa7feSdrh sqlite3ExprCodeGeneratedColumn(pParse, &pTab->aCol[i], iRegStore+i-nv); 249dd6cc9b5Sdrh } 250*e70fa7feSdrh pTab->aCol[i].colFlags &= ~COLFLAG_NOTAVAIL; 251c1431144Sdrh } 252dd6cc9b5Sdrh if( (colFlags & COLFLAG_VIRTUAL)!=0 ) nv++; 253c1431144Sdrh } 254c1431144Sdrh pParse->iSelfTab = 0; 255c1431144Sdrh } 256c1431144Sdrh #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 257c1431144Sdrh 258c1431144Sdrh 2599d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 2609d9cf229Sdrh /* 2610b9f50d8Sdrh ** Locate or create an AutoincInfo structure associated with table pTab 2620b9f50d8Sdrh ** which is in database iDb. Return the register number for the register 2639ef5e770Sdrh ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT 2649ef5e770Sdrh ** table. (Also return zero when doing a VACUUM since we do not want to 2659ef5e770Sdrh ** update the AUTOINCREMENT counters during a VACUUM.) 2669d9cf229Sdrh ** 2670b9f50d8Sdrh ** There is at most one AutoincInfo structure per table even if the 2680b9f50d8Sdrh ** same table is autoincremented multiple times due to inserts within 2690b9f50d8Sdrh ** triggers. A new AutoincInfo structure is created if this is the 2700b9f50d8Sdrh ** first use of table pTab. On 2nd and subsequent uses, the original 2710b9f50d8Sdrh ** AutoincInfo structure is used. 2729d9cf229Sdrh ** 273c8abbc11Sdrh ** Four consecutive registers are allocated: 2740b9f50d8Sdrh ** 275c8abbc11Sdrh ** (1) The name of the pTab table. 276c8abbc11Sdrh ** (2) The maximum ROWID of pTab. 277c8abbc11Sdrh ** (3) The rowid in sqlite_sequence of pTab 278c8abbc11Sdrh ** (4) The original value of the max ROWID in pTab, or NULL if none 2790b9f50d8Sdrh ** 2800b9f50d8Sdrh ** The 2nd register is the one that is returned. That is all the 2810b9f50d8Sdrh ** insert routine needs to know about. 2829d9cf229Sdrh */ 2839d9cf229Sdrh static int autoIncBegin( 2849d9cf229Sdrh Parse *pParse, /* Parsing context */ 2859d9cf229Sdrh int iDb, /* Index of the database holding pTab */ 2869d9cf229Sdrh Table *pTab /* The table we are writing to */ 2879d9cf229Sdrh ){ 2886a288a33Sdrh int memId = 0; /* Register holding maximum rowid */ 289186ebd41Sdrh assert( pParse->db->aDb[iDb].pSchema!=0 ); 2909ef5e770Sdrh if( (pTab->tabFlags & TF_Autoincrement)!=0 2918257aa8dSdrh && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0 2929ef5e770Sdrh ){ 29365a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 2940b9f50d8Sdrh AutoincInfo *pInfo; 295186ebd41Sdrh Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab; 296186ebd41Sdrh 297186ebd41Sdrh /* Verify that the sqlite_sequence table exists and is an ordinary 298186ebd41Sdrh ** rowid table with exactly two columns. 299186ebd41Sdrh ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */ 300186ebd41Sdrh if( pSeqTab==0 301186ebd41Sdrh || !HasRowid(pSeqTab) 302186ebd41Sdrh || IsVirtual(pSeqTab) 303186ebd41Sdrh || pSeqTab->nCol!=2 304186ebd41Sdrh ){ 305186ebd41Sdrh pParse->nErr++; 306186ebd41Sdrh pParse->rc = SQLITE_CORRUPT_SEQUENCE; 307186ebd41Sdrh return 0; 308186ebd41Sdrh } 3090b9f50d8Sdrh 31065a7cd16Sdan pInfo = pToplevel->pAinc; 3110b9f50d8Sdrh while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } 3120b9f50d8Sdrh if( pInfo==0 ){ 313575fad65Sdrh pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo)); 3140b9f50d8Sdrh if( pInfo==0 ) return 0; 31565a7cd16Sdan pInfo->pNext = pToplevel->pAinc; 31665a7cd16Sdan pToplevel->pAinc = pInfo; 3170b9f50d8Sdrh pInfo->pTab = pTab; 3180b9f50d8Sdrh pInfo->iDb = iDb; 31965a7cd16Sdan pToplevel->nMem++; /* Register to hold name of table */ 32065a7cd16Sdan pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ 321c8abbc11Sdrh pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */ 3220b9f50d8Sdrh } 3230b9f50d8Sdrh memId = pInfo->regCtr; 3249d9cf229Sdrh } 3259d9cf229Sdrh return memId; 3269d9cf229Sdrh } 3279d9cf229Sdrh 3289d9cf229Sdrh /* 3290b9f50d8Sdrh ** This routine generates code that will initialize all of the 3300b9f50d8Sdrh ** register used by the autoincrement tracker. 3310b9f50d8Sdrh */ 3320b9f50d8Sdrh void sqlite3AutoincrementBegin(Parse *pParse){ 3330b9f50d8Sdrh AutoincInfo *p; /* Information about an AUTOINCREMENT */ 3340b9f50d8Sdrh sqlite3 *db = pParse->db; /* The database connection */ 3350b9f50d8Sdrh Db *pDb; /* Database only autoinc table */ 3360b9f50d8Sdrh int memId; /* Register holding max rowid */ 3370b9f50d8Sdrh Vdbe *v = pParse->pVdbe; /* VDBE under construction */ 3380b9f50d8Sdrh 339345ba7dbSdrh /* This routine is never called during trigger-generation. It is 340345ba7dbSdrh ** only called from the top-level */ 341345ba7dbSdrh assert( pParse->pTriggerTab==0 ); 342c149f18fSdrh assert( sqlite3IsToplevel(pParse) ); 34376d462eeSdan 3440b9f50d8Sdrh assert( v ); /* We failed long ago if this is not so */ 3450b9f50d8Sdrh for(p = pParse->pAinc; p; p = p->pNext){ 3461b32554bSdrh static const int iLn = VDBE_OFFSET_LINENO(2); 3471b32554bSdrh static const VdbeOpList autoInc[] = { 3481b32554bSdrh /* 0 */ {OP_Null, 0, 0, 0}, 349c8abbc11Sdrh /* 1 */ {OP_Rewind, 0, 10, 0}, 3501b32554bSdrh /* 2 */ {OP_Column, 0, 0, 0}, 351c8abbc11Sdrh /* 3 */ {OP_Ne, 0, 9, 0}, 3521b32554bSdrh /* 4 */ {OP_Rowid, 0, 0, 0}, 3531b32554bSdrh /* 5 */ {OP_Column, 0, 1, 0}, 354c8abbc11Sdrh /* 6 */ {OP_AddImm, 0, 0, 0}, 355c8abbc11Sdrh /* 7 */ {OP_Copy, 0, 0, 0}, 356c8abbc11Sdrh /* 8 */ {OP_Goto, 0, 11, 0}, 357c8abbc11Sdrh /* 9 */ {OP_Next, 0, 2, 0}, 358c8abbc11Sdrh /* 10 */ {OP_Integer, 0, 0, 0}, 359c8abbc11Sdrh /* 11 */ {OP_Close, 0, 0, 0} 3601b32554bSdrh }; 3611b32554bSdrh VdbeOp *aOp; 3620b9f50d8Sdrh pDb = &db->aDb[p->iDb]; 3630b9f50d8Sdrh memId = p->regCtr; 3642120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 3650b9f50d8Sdrh sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); 366076e85f5Sdrh sqlite3VdbeLoadString(v, memId-1, p->pTab->zName); 3671b32554bSdrh aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn); 3681b32554bSdrh if( aOp==0 ) break; 3691b32554bSdrh aOp[0].p2 = memId; 370c8abbc11Sdrh aOp[0].p3 = memId+2; 3711b32554bSdrh aOp[2].p3 = memId; 3721b32554bSdrh aOp[3].p1 = memId-1; 3731b32554bSdrh aOp[3].p3 = memId; 3741b32554bSdrh aOp[3].p5 = SQLITE_JUMPIFNULL; 3751b32554bSdrh aOp[4].p2 = memId+1; 3761b32554bSdrh aOp[5].p3 = memId; 377c8abbc11Sdrh aOp[6].p1 = memId; 378c8abbc11Sdrh aOp[7].p2 = memId+2; 379c8abbc11Sdrh aOp[7].p1 = memId; 380c8abbc11Sdrh aOp[10].p2 = memId; 38104ab586bSdrh if( pParse->nTab==0 ) pParse->nTab = 1; 3820b9f50d8Sdrh } 3830b9f50d8Sdrh } 3840b9f50d8Sdrh 3850b9f50d8Sdrh /* 3869d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation. 3879d9cf229Sdrh ** 3881b32554bSdrh ** This routine should be called when the regRowid register holds a 3899d9cf229Sdrh ** new rowid that is about to be inserted. If that new rowid is 3909d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the 3911b32554bSdrh ** memory cell is updated. 3929d9cf229Sdrh */ 3936a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){ 3949d9cf229Sdrh if( memId>0 ){ 3956a288a33Sdrh sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); 3969d9cf229Sdrh } 3979d9cf229Sdrh } 3989d9cf229Sdrh 3999d9cf229Sdrh /* 4000b9f50d8Sdrh ** This routine generates the code needed to write autoincrement 4010b9f50d8Sdrh ** maximum rowid values back into the sqlite_sequence register. 4020b9f50d8Sdrh ** Every statement that might do an INSERT into an autoincrement 4030b9f50d8Sdrh ** table (either directly or through triggers) needs to call this 4040b9f50d8Sdrh ** routine just before the "exit" code. 4059d9cf229Sdrh */ 4061b32554bSdrh static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ 4070b9f50d8Sdrh AutoincInfo *p; 4089d9cf229Sdrh Vdbe *v = pParse->pVdbe; 4090b9f50d8Sdrh sqlite3 *db = pParse->db; 4106a288a33Sdrh 4119d9cf229Sdrh assert( v ); 4120b9f50d8Sdrh for(p = pParse->pAinc; p; p = p->pNext){ 4131b32554bSdrh static const int iLn = VDBE_OFFSET_LINENO(2); 4141b32554bSdrh static const VdbeOpList autoIncEnd[] = { 4151b32554bSdrh /* 0 */ {OP_NotNull, 0, 2, 0}, 4161b32554bSdrh /* 1 */ {OP_NewRowid, 0, 0, 0}, 4171b32554bSdrh /* 2 */ {OP_MakeRecord, 0, 2, 0}, 4181b32554bSdrh /* 3 */ {OP_Insert, 0, 0, 0}, 4191b32554bSdrh /* 4 */ {OP_Close, 0, 0, 0} 4201b32554bSdrh }; 4211b32554bSdrh VdbeOp *aOp; 4220b9f50d8Sdrh Db *pDb = &db->aDb[p->iDb]; 4230b9f50d8Sdrh int iRec; 4240b9f50d8Sdrh int memId = p->regCtr; 4250b9f50d8Sdrh 4260b9f50d8Sdrh iRec = sqlite3GetTempReg(pParse); 4272120608eSdrh assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); 428c8abbc11Sdrh sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId); 429c8abbc11Sdrh VdbeCoverage(v); 4300b9f50d8Sdrh sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); 4311b32554bSdrh aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn); 4321b32554bSdrh if( aOp==0 ) break; 4331b32554bSdrh aOp[0].p1 = memId+1; 4341b32554bSdrh aOp[1].p2 = memId+1; 4351b32554bSdrh aOp[2].p1 = memId-1; 4361b32554bSdrh aOp[2].p3 = iRec; 4371b32554bSdrh aOp[3].p2 = iRec; 4381b32554bSdrh aOp[3].p3 = memId+1; 4391b32554bSdrh aOp[3].p5 = OPFLAG_APPEND; 4400b9f50d8Sdrh sqlite3ReleaseTempReg(pParse, iRec); 4419d9cf229Sdrh } 4429d9cf229Sdrh } 4431b32554bSdrh void sqlite3AutoincrementEnd(Parse *pParse){ 4441b32554bSdrh if( pParse->pAinc ) autoIncrementEnd(pParse); 4451b32554bSdrh } 4469d9cf229Sdrh #else 4479d9cf229Sdrh /* 4489d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines 4499d9cf229Sdrh ** above are all no-ops 4509d9cf229Sdrh */ 4519d9cf229Sdrh # define autoIncBegin(A,B,C) (0) 452287fb61cSdanielk1977 # define autoIncStep(A,B,C) 4539d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */ 4549d9cf229Sdrh 4559d9cf229Sdrh 4569d9cf229Sdrh /* Forward declaration */ 4579d9cf229Sdrh static int xferOptimization( 4589d9cf229Sdrh Parse *pParse, /* Parser context */ 4599d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 4609d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 4619d9cf229Sdrh int onError, /* How to handle constraint errors */ 4629d9cf229Sdrh int iDbDest /* The database of pDest */ 4639d9cf229Sdrh ); 4649d9cf229Sdrh 4653d1bfeaaSdanielk1977 /* 466d82b5021Sdrh ** This routine is called to handle SQL of the following forms: 467cce7d176Sdrh ** 468a21f78b9Sdrh ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),... 4691ccde15dSdrh ** insert into TABLE (IDLIST) select 470a21f78b9Sdrh ** insert into TABLE (IDLIST) default values 471cce7d176Sdrh ** 4721ccde15dSdrh ** The IDLIST following the table name is always optional. If omitted, 473a21f78b9Sdrh ** then a list of all (non-hidden) columns for the table is substituted. 474a21f78b9Sdrh ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST 475a21f78b9Sdrh ** is omitted. 4761ccde15dSdrh ** 477a21f78b9Sdrh ** For the pSelect parameter holds the values to be inserted for the 478a21f78b9Sdrh ** first two forms shown above. A VALUES clause is really just short-hand 479a21f78b9Sdrh ** for a SELECT statement that omits the FROM clause and everything else 480a21f78b9Sdrh ** that follows. If the pSelect parameter is NULL, that means that the 481a21f78b9Sdrh ** DEFAULT VALUES form of the INSERT statement is intended. 482142e30dfSdrh ** 4839d9cf229Sdrh ** The code generated follows one of four templates. For a simple 484a21f78b9Sdrh ** insert with data coming from a single-row VALUES clause, the code executes 485e00ee6ebSdrh ** once straight down through. Pseudo-code follows (we call this 486e00ee6ebSdrh ** the "1st template"): 487142e30dfSdrh ** 488142e30dfSdrh ** open write cursor to <table> and its indices 489ec95c441Sdrh ** put VALUES clause expressions into registers 490142e30dfSdrh ** write the resulting record into <table> 491142e30dfSdrh ** cleanup 492142e30dfSdrh ** 4939d9cf229Sdrh ** The three remaining templates assume the statement is of the form 494142e30dfSdrh ** 495142e30dfSdrh ** INSERT INTO <table> SELECT ... 496142e30dfSdrh ** 4979d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - 4989d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table 4999d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and 5009d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical 5019d9cf229Sdrh ** schemas, including all the same indices, then a special optimization 5029d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>. 5039d9cf229Sdrh ** See the xferOptimization() function for the implementation of this 504e00ee6ebSdrh ** template. This is the 2nd template. 5059d9cf229Sdrh ** 5069d9cf229Sdrh ** open a write cursor to <table> 5079d9cf229Sdrh ** open read cursor on <table2> 5089d9cf229Sdrh ** transfer all records in <table2> over to <table> 5099d9cf229Sdrh ** close cursors 5109d9cf229Sdrh ** foreach index on <table> 5119d9cf229Sdrh ** open a write cursor on the <table> index 5129d9cf229Sdrh ** open a read cursor on the corresponding <table2> index 5139d9cf229Sdrh ** transfer all records from the read to the write cursors 5149d9cf229Sdrh ** close cursors 5159d9cf229Sdrh ** end foreach 5169d9cf229Sdrh ** 517e00ee6ebSdrh ** The 3rd template is for when the second template does not apply 5189d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time. 5199d9cf229Sdrh ** The generated code follows this template: 520142e30dfSdrh ** 521e00ee6ebSdrh ** X <- A 522142e30dfSdrh ** goto B 523142e30dfSdrh ** A: setup for the SELECT 5249d9cf229Sdrh ** loop over the rows in the SELECT 525e00ee6ebSdrh ** load values into registers R..R+n 526e00ee6ebSdrh ** yield X 527142e30dfSdrh ** end loop 528142e30dfSdrh ** cleanup after the SELECT 52981cf13ecSdrh ** end-coroutine X 530e00ee6ebSdrh ** B: open write cursor to <table> and its indices 53181cf13ecSdrh ** C: yield X, at EOF goto D 532e00ee6ebSdrh ** insert the select result into <table> from R..R+n 533e00ee6ebSdrh ** goto C 534142e30dfSdrh ** D: cleanup 535142e30dfSdrh ** 536e00ee6ebSdrh ** The 4th template is used if the insert statement takes its 537142e30dfSdrh ** values from a SELECT but the data is being inserted into a table 538142e30dfSdrh ** that is also read as part of the SELECT. In the third form, 53960ec914cSpeter.d.reid ** we have to use an intermediate table to store the results of 540142e30dfSdrh ** the select. The template is like this: 541142e30dfSdrh ** 542e00ee6ebSdrh ** X <- A 543142e30dfSdrh ** goto B 544142e30dfSdrh ** A: setup for the SELECT 545142e30dfSdrh ** loop over the tables in the SELECT 546e00ee6ebSdrh ** load value into register R..R+n 547e00ee6ebSdrh ** yield X 548142e30dfSdrh ** end loop 549142e30dfSdrh ** cleanup after the SELECT 55081cf13ecSdrh ** end co-routine R 551e00ee6ebSdrh ** B: open temp table 55281cf13ecSdrh ** L: yield X, at EOF goto M 553e00ee6ebSdrh ** insert row from R..R+n into temp table 554e00ee6ebSdrh ** goto L 555e00ee6ebSdrh ** M: open write cursor to <table> and its indices 556e00ee6ebSdrh ** rewind temp table 557e00ee6ebSdrh ** C: loop over rows of intermediate table 558142e30dfSdrh ** transfer values form intermediate table into <table> 559e00ee6ebSdrh ** end loop 560e00ee6ebSdrh ** D: cleanup 561cce7d176Sdrh */ 5624adee20fSdanielk1977 void sqlite3Insert( 563cce7d176Sdrh Parse *pParse, /* Parser context */ 564113088ecSdrh SrcList *pTabList, /* Name of table into which we are inserting */ 5655974a30fSdrh Select *pSelect, /* A SELECT statement to use as the data source */ 566f5f1915dSdrh IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */ 5672c2e844aSdrh int onError, /* How to handle constraint errors */ 56846d2e5c3Sdrh Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */ 569cce7d176Sdrh ){ 5706a288a33Sdrh sqlite3 *db; /* The main database structure */ 5716a288a33Sdrh Table *pTab; /* The table to insert into. aka TABLE */ 57260ffc807Sdrh int i, j; /* Loop counters */ 5735974a30fSdrh Vdbe *v; /* Generate code into this virtual machine */ 5745974a30fSdrh Index *pIdx; /* For looping over indices of the table */ 575967e8b73Sdrh int nColumn; /* Number of columns in the data */ 5766a288a33Sdrh int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ 57726198bb4Sdrh int iDataCur = 0; /* VDBE cursor that is the main data repository */ 57826198bb4Sdrh int iIdxCur = 0; /* First index cursor */ 579d82b5021Sdrh int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ 5800ca3e24bSdrh int endOfLoop; /* Label for the end of the insertion loop */ 581cfe9a69fSdanielk1977 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ 582e00ee6ebSdrh int addrInsTop = 0; /* Jump to label "D" */ 583e00ee6ebSdrh int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ 5842eb95377Sdrh SelectDest dest; /* Destination for SELECT on rhs of INSERT */ 5856a288a33Sdrh int iDb; /* Index of database holding TABLE */ 58605a86c5cSdrh u8 useTempTable = 0; /* Store SELECT results in intermediate table */ 58705a86c5cSdrh u8 appendFlag = 0; /* True if the insert is likely to be an append */ 58805a86c5cSdrh u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ 589a21f78b9Sdrh u8 bIdListInOrder; /* True if IDLIST is in table order */ 59075593d96Sdrh ExprList *pList = 0; /* List of VALUES() to be inserted */ 591c27ea2aeSdrh int iRegStore; /* Register in which to store next column */ 592cce7d176Sdrh 5936a288a33Sdrh /* Register allocations */ 5941bd10f8aSdrh int regFromSelect = 0;/* Base register for data coming from SELECT */ 5956a288a33Sdrh int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ 5966a288a33Sdrh int regRowCount = 0; /* Memory cell used for the row counter */ 5976a288a33Sdrh int regIns; /* Block of regs holding rowid+data being inserted */ 5986a288a33Sdrh int regRowid; /* registers holding insert rowid */ 5996a288a33Sdrh int regData; /* register holding first column to insert */ 600aa9b8963Sdrh int *aRegIdx = 0; /* One register allocated to each index */ 6016a288a33Sdrh 602798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER 603798da52cSdrh int isView; /* True if attempting to insert into a view */ 6042f886d1dSdanielk1977 Trigger *pTrigger; /* List of triggers on pTab, if required */ 6052f886d1dSdanielk1977 int tmask; /* Mask of trigger times */ 606798da52cSdrh #endif 607c3f9bad2Sdanielk1977 60817435752Sdrh db = pParse->db; 60917435752Sdrh if( pParse->nErr || db->mallocFailed ){ 6106f7adc8aSdrh goto insert_cleanup; 6116f7adc8aSdrh } 6124c883487Sdrh dest.iSDParm = 0; /* Suppress a harmless compiler warning */ 613daffd0e5Sdrh 61475593d96Sdrh /* If the Select object is really just a simple VALUES() list with a 615a21f78b9Sdrh ** single row (the common case) then keep that one row of values 616a21f78b9Sdrh ** and discard the other (unused) parts of the pSelect object 61775593d96Sdrh */ 61875593d96Sdrh if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){ 61975593d96Sdrh pList = pSelect->pEList; 62075593d96Sdrh pSelect->pEList = 0; 62175593d96Sdrh sqlite3SelectDelete(db, pSelect); 62275593d96Sdrh pSelect = 0; 62375593d96Sdrh } 62475593d96Sdrh 6251ccde15dSdrh /* Locate the table into which we will be inserting new information. 6261ccde15dSdrh */ 627113088ecSdrh assert( pTabList->nSrc==1 ); 6284adee20fSdanielk1977 pTab = sqlite3SrcListLookup(pParse, pTabList); 629c3f9bad2Sdanielk1977 if( pTab==0 ){ 630c3f9bad2Sdanielk1977 goto insert_cleanup; 631c3f9bad2Sdanielk1977 } 632da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 633da184236Sdanielk1977 assert( iDb<db->nDb ); 634a0daa751Sdrh if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, 635a0daa751Sdrh db->aDb[iDb].zDbSName) ){ 6361962bda7Sdrh goto insert_cleanup; 6371962bda7Sdrh } 638ec95c441Sdrh withoutRowid = !HasRowid(pTab); 639c3f9bad2Sdanielk1977 640b7f9164eSdrh /* Figure out if we have any triggers and if the table being 641b7f9164eSdrh ** inserted into is a view 642b7f9164eSdrh */ 643b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER 6442f886d1dSdanielk1977 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); 645b7f9164eSdrh isView = pTab->pSelect!=0; 646b7f9164eSdrh #else 6472f886d1dSdanielk1977 # define pTrigger 0 6482f886d1dSdanielk1977 # define tmask 0 649b7f9164eSdrh # define isView 0 650b7f9164eSdrh #endif 651b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW 652b7f9164eSdrh # undef isView 653b7f9164eSdrh # define isView 0 654b7f9164eSdrh #endif 6552f886d1dSdanielk1977 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); 656b7f9164eSdrh 657f573c99bSdrh /* If pTab is really a view, make sure it has been initialized. 658d82b5021Sdrh ** ViewGetColumnNames() is a no-op if pTab is not a view. 659f573c99bSdrh */ 660b3d24bf8Sdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 661f573c99bSdrh goto insert_cleanup; 662f573c99bSdrh } 663f573c99bSdrh 664d82b5021Sdrh /* Cannot insert into a read-only table. 665595a523aSdanielk1977 */ 666595a523aSdanielk1977 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ 667595a523aSdanielk1977 goto insert_cleanup; 668595a523aSdanielk1977 } 669595a523aSdanielk1977 6701ccde15dSdrh /* Allocate a VDBE 6711ccde15dSdrh */ 6724adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 6735974a30fSdrh if( v==0 ) goto insert_cleanup; 6744794f735Sdrh if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 6752f886d1dSdanielk1977 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); 6761ccde15dSdrh 6779d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 6789d9cf229Sdrh /* If the statement is of the form 6799d9cf229Sdrh ** 6809d9cf229Sdrh ** INSERT INTO <table1> SELECT * FROM <table2>; 6819d9cf229Sdrh ** 6829d9cf229Sdrh ** Then special optimizations can be applied that make the transfer 6839d9cf229Sdrh ** very fast and which reduce fragmentation of indices. 684e00ee6ebSdrh ** 685e00ee6ebSdrh ** This is the 2nd template. 6869d9cf229Sdrh */ 6879d9cf229Sdrh if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ 6882f886d1dSdanielk1977 assert( !pTrigger ); 6899d9cf229Sdrh assert( pList==0 ); 6900b9f50d8Sdrh goto insert_end; 6919d9cf229Sdrh } 6929d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 6939d9cf229Sdrh 6942958a4e6Sdrh /* If this is an AUTOINCREMENT table, look up the sequence number in the 6956a288a33Sdrh ** sqlite_sequence table and store it in memory cell regAutoinc. 6962958a4e6Sdrh */ 6976a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDb, pTab); 6982958a4e6Sdrh 699f5f1915dSdrh /* Allocate a block registers to hold the rowid and the values 700f5f1915dSdrh ** for all columns of the new row. 7011ccde15dSdrh */ 70205a86c5cSdrh regRowid = regIns = pParse->nMem+1; 70305a86c5cSdrh pParse->nMem += pTab->nCol + 1; 704034ca14fSdanielk1977 if( IsVirtual(pTab) ){ 70505a86c5cSdrh regRowid++; 70605a86c5cSdrh pParse->nMem++; 707034ca14fSdanielk1977 } 70805a86c5cSdrh regData = regRowid+1; 7091ccde15dSdrh 7101ccde15dSdrh /* If the INSERT statement included an IDLIST term, then make sure 7111ccde15dSdrh ** all elements of the IDLIST really are columns of the table and 7121ccde15dSdrh ** remember the column indices. 713c8392586Sdrh ** 714c8392586Sdrh ** If the table has an INTEGER PRIMARY KEY column and that column 715d82b5021Sdrh ** is named in the IDLIST, then record in the ipkColumn variable 716d82b5021Sdrh ** the index into IDLIST of the primary key column. ipkColumn is 717c8392586Sdrh ** the index of the primary key as it appears in IDLIST, not as 718d82b5021Sdrh ** is appears in the original table. (The index of the INTEGER 719f5f1915dSdrh ** PRIMARY KEY in the original table is pTab->iPKey.) After this 720f5f1915dSdrh ** loop, if ipkColumn==(-1), that means that integer primary key 721f5f1915dSdrh ** is unspecified, and hence the table is either WITHOUT ROWID or 722f5f1915dSdrh ** it will automatically generated an integer primary key. 723f5f1915dSdrh ** 724f5f1915dSdrh ** bIdListInOrder is true if the columns in IDLIST are in storage 725f5f1915dSdrh ** order. This enables an optimization that avoids shuffling the 726f5f1915dSdrh ** columns into storage order. False negatives are harmless, 727f5f1915dSdrh ** but false positives will cause database corruption. 7281ccde15dSdrh */ 729d4cd292cSdrh bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0; 730967e8b73Sdrh if( pColumn ){ 731967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 732967e8b73Sdrh pColumn->a[i].idx = -1; 733cce7d176Sdrh } 734967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 735cce7d176Sdrh for(j=0; j<pTab->nCol; j++){ 7364adee20fSdanielk1977 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ 737967e8b73Sdrh pColumn->a[i].idx = j; 73805a86c5cSdrh if( i!=j ) bIdListInOrder = 0; 7394a32431cSdrh if( j==pTab->iPKey ){ 740d82b5021Sdrh ipkColumn = i; assert( !withoutRowid ); 7414a32431cSdrh } 7427e508f1eSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 7437e508f1eSdrh if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){ 7447e508f1eSdrh sqlite3ErrorMsg(pParse, 7457e508f1eSdrh "cannot INSERT into generated column \"%s\"", 7467e508f1eSdrh pTab->aCol[j].zName); 7477e508f1eSdrh goto insert_cleanup; 7487e508f1eSdrh } 7497e508f1eSdrh #endif 750cce7d176Sdrh break; 751cce7d176Sdrh } 752cce7d176Sdrh } 753cce7d176Sdrh if( j>=pTab->nCol ){ 754ec95c441Sdrh if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ 755d82b5021Sdrh ipkColumn = i; 756e48ae715Sdrh bIdListInOrder = 0; 757a0217ba7Sdrh }else{ 7584adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %S has no column named %s", 759da93d238Sdrh pTabList, 0, pColumn->a[i].zName); 7601db95106Sdan pParse->checkSchema = 1; 761cce7d176Sdrh goto insert_cleanup; 762cce7d176Sdrh } 763cce7d176Sdrh } 764cce7d176Sdrh } 765a0217ba7Sdrh } 7661ccde15dSdrh 767cce7d176Sdrh /* Figure out how many columns of data are supplied. If the data 768cce7d176Sdrh ** is coming from a SELECT statement, then generate a co-routine that 769cce7d176Sdrh ** produces a single row of the SELECT on each invocation. The 770cce7d176Sdrh ** co-routine is the common header to the 3rd and 4th templates. 771cce7d176Sdrh */ 7725f085269Sdrh if( pSelect ){ 773a21f78b9Sdrh /* Data is coming from a SELECT or from a multi-row VALUES clause. 774a21f78b9Sdrh ** Generate a co-routine to run the SELECT. */ 77505a86c5cSdrh int regYield; /* Register holding co-routine entry-point */ 77605a86c5cSdrh int addrTop; /* Top of the co-routine */ 77705a86c5cSdrh int rc; /* Result code */ 778cce7d176Sdrh 77905a86c5cSdrh regYield = ++pParse->nMem; 78005a86c5cSdrh addrTop = sqlite3VdbeCurrentAddr(v) + 1; 78105a86c5cSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 78205a86c5cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 78305a86c5cSdrh dest.iSdst = bIdListInOrder ? regData : 0; 78405a86c5cSdrh dest.nSdst = pTab->nCol; 78505a86c5cSdrh rc = sqlite3Select(pParse, pSelect, &dest); 7862b596da8Sdrh regFromSelect = dest.iSdst; 787992590beSdrh if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup; 7882fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regYield); 78905a86c5cSdrh sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ 790cce7d176Sdrh assert( pSelect->pEList ); 791cce7d176Sdrh nColumn = pSelect->pEList->nExpr; 792cce7d176Sdrh 793cce7d176Sdrh /* Set useTempTable to TRUE if the result of the SELECT statement 794cce7d176Sdrh ** should be written into a temporary table (template 4). Set to 795cce7d176Sdrh ** FALSE if each output row of the SELECT can be written directly into 796cce7d176Sdrh ** the destination table (template 3). 797cce7d176Sdrh ** 798cce7d176Sdrh ** A temp table must be used if the table being updated is also one 799cce7d176Sdrh ** of the tables being read by the SELECT statement. Also use a 800cce7d176Sdrh ** temp table in the case of row triggers. 801cce7d176Sdrh */ 80205a86c5cSdrh if( pTrigger || readsTable(pParse, iDb, pTab) ){ 803cce7d176Sdrh useTempTable = 1; 804cce7d176Sdrh } 805cce7d176Sdrh 806cce7d176Sdrh if( useTempTable ){ 807cce7d176Sdrh /* Invoke the coroutine to extract information from the SELECT 808cce7d176Sdrh ** and add it to a transient table srcTab. The code generated 809cce7d176Sdrh ** here is from the 4th template: 810cce7d176Sdrh ** 811cce7d176Sdrh ** B: open temp table 81281cf13ecSdrh ** L: yield X, goto M at EOF 813cce7d176Sdrh ** insert row from R..R+n into temp table 814cce7d176Sdrh ** goto L 815cce7d176Sdrh ** M: ... 816cce7d176Sdrh */ 817cce7d176Sdrh int regRec; /* Register to hold packed record */ 818cce7d176Sdrh int regTempRowid; /* Register to hold temp table ROWID */ 81906280ee5Sdrh int addrL; /* Label "L" */ 820cce7d176Sdrh 821cce7d176Sdrh srcTab = pParse->nTab++; 822cce7d176Sdrh regRec = sqlite3GetTempReg(pParse); 823cce7d176Sdrh regTempRowid = sqlite3GetTempReg(pParse); 824cce7d176Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); 82506280ee5Sdrh addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); 826cce7d176Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); 827cce7d176Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); 828cce7d176Sdrh sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); 829076e85f5Sdrh sqlite3VdbeGoto(v, addrL); 83006280ee5Sdrh sqlite3VdbeJumpHere(v, addrL); 831cce7d176Sdrh sqlite3ReleaseTempReg(pParse, regRec); 832cce7d176Sdrh sqlite3ReleaseTempReg(pParse, regTempRowid); 833cce7d176Sdrh } 834cce7d176Sdrh }else{ 835a21f78b9Sdrh /* This is the case if the data for the INSERT is coming from a 836a21f78b9Sdrh ** single-row VALUES clause 837cce7d176Sdrh */ 838cce7d176Sdrh NameContext sNC; 839cce7d176Sdrh memset(&sNC, 0, sizeof(sNC)); 840cce7d176Sdrh sNC.pParse = pParse; 841cce7d176Sdrh srcTab = -1; 842cce7d176Sdrh assert( useTempTable==0 ); 843fea870beSdrh if( pList ){ 844fea870beSdrh nColumn = pList->nExpr; 845fea870beSdrh if( sqlite3ResolveExprListNames(&sNC, pList) ){ 846cce7d176Sdrh goto insert_cleanup; 847cce7d176Sdrh } 848fea870beSdrh }else{ 849fea870beSdrh nColumn = 0; 850cce7d176Sdrh } 851cce7d176Sdrh } 852cce7d176Sdrh 853aacc543eSdrh /* If there is no IDLIST term but the table has an integer primary 854d82b5021Sdrh ** key, the set the ipkColumn variable to the integer primary key 855d82b5021Sdrh ** column index in the original table definition. 8564a32431cSdrh */ 857147d0cccSdrh if( pColumn==0 && nColumn>0 ){ 858d82b5021Sdrh ipkColumn = pTab->iPKey; 859427b96aeSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 860427b96aeSdrh if( pTab->tabFlags & TF_HasGenerated ){ 861427b96aeSdrh testcase( pTab->tabFlags & TF_HasVirtual ); 862427b96aeSdrh testcase( pTab->tabFlags & TF_HasGenerated ); 863427b96aeSdrh for(i=ipkColumn-1; i>=0; i--){ 864427b96aeSdrh if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ 865427b96aeSdrh testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ); 866427b96aeSdrh testcase( pTab->aCol[i].colFlags & COLFLAG_GENERATED ); 867427b96aeSdrh ipkColumn--; 868427b96aeSdrh } 869427b96aeSdrh } 870427b96aeSdrh } 871427b96aeSdrh #endif 8724a32431cSdrh } 8734a32431cSdrh 874cce7d176Sdrh /* Make sure the number of columns in the source data matches the number 875cce7d176Sdrh ** of columns to be inserted into the table. 876cce7d176Sdrh */ 877cce7d176Sdrh for(i=0; i<pTab->nCol; i++){ 8787e508f1eSdrh if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++; 879cce7d176Sdrh } 880cce7d176Sdrh if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ 881cce7d176Sdrh sqlite3ErrorMsg(pParse, 882cce7d176Sdrh "table %S has %d columns but %d values were supplied", 883cce7d176Sdrh pTabList, 0, pTab->nCol-nHidden, nColumn); 884cce7d176Sdrh goto insert_cleanup; 885cce7d176Sdrh } 886cce7d176Sdrh if( pColumn!=0 && nColumn!=pColumn->nId ){ 887cce7d176Sdrh sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 888cce7d176Sdrh goto insert_cleanup; 889cce7d176Sdrh } 890cce7d176Sdrh 891c3f9bad2Sdanielk1977 /* Initialize the count of rows to be inserted 8921ccde15dSdrh */ 89379636913Sdrh if( (db->flags & SQLITE_CountRows)!=0 89479636913Sdrh && !pParse->nested 89579636913Sdrh && !pParse->pTriggerTab 89679636913Sdrh ){ 8976a288a33Sdrh regRowCount = ++pParse->nMem; 8986a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 899c3f9bad2Sdanielk1977 } 900c3f9bad2Sdanielk1977 901e448dc4aSdanielk1977 /* If this is not a view, open the table and and all indices */ 902e448dc4aSdanielk1977 if( !isView ){ 903aa9b8963Sdrh int nIdx; 904fd261ec6Sdan nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0, 90526198bb4Sdrh &iDataCur, &iIdxCur); 906a7c3b93fSdrh aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2)); 907aa9b8963Sdrh if( aRegIdx==0 ){ 908aa9b8963Sdrh goto insert_cleanup; 909aa9b8963Sdrh } 9102c4dfc30Sdrh for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){ 9112c4dfc30Sdrh assert( pIdx ); 912aa9b8963Sdrh aRegIdx[i] = ++pParse->nMem; 9132c4dfc30Sdrh pParse->nMem += pIdx->nColumn; 914aa9b8963Sdrh } 915a7c3b93fSdrh aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */ 916feeb1394Sdrh } 917788d55aaSdrh #ifndef SQLITE_OMIT_UPSERT 9180b30a116Sdrh if( pUpsert ){ 919b042d921Sdrh if( IsVirtual(pTab) ){ 920b042d921Sdrh sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"", 921b042d921Sdrh pTab->zName); 922b042d921Sdrh goto insert_cleanup; 923b042d921Sdrh } 9249105fd51Sdan if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){ 9259105fd51Sdan goto insert_cleanup; 9269105fd51Sdan } 927788d55aaSdrh pTabList->a[0].iCursor = iDataCur; 9280b30a116Sdrh pUpsert->pUpsertSrc = pTabList; 929eac9fabbSdrh pUpsert->regData = regData; 9307fc3aba8Sdrh pUpsert->iDataCur = iDataCur; 9317fc3aba8Sdrh pUpsert->iIdxCur = iIdxCur; 9320b30a116Sdrh if( pUpsert->pUpsertTarget ){ 933e9c2e772Sdrh sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert); 934788d55aaSdrh } 9350b30a116Sdrh } 936788d55aaSdrh #endif 937788d55aaSdrh 938feeb1394Sdrh 939e00ee6ebSdrh /* This is the top of the main insertion loop */ 940142e30dfSdrh if( useTempTable ){ 941e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 942e00ee6ebSdrh ** following pseudocode (template 4): 943e00ee6ebSdrh ** 94481cf13ecSdrh ** rewind temp table, if empty goto D 945e00ee6ebSdrh ** C: loop over rows of intermediate table 946e00ee6ebSdrh ** transfer values form intermediate table into <table> 947e00ee6ebSdrh ** end loop 948e00ee6ebSdrh ** D: ... 949e00ee6ebSdrh */ 950688852abSdrh addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); 951e00ee6ebSdrh addrCont = sqlite3VdbeCurrentAddr(v); 952142e30dfSdrh }else if( pSelect ){ 953e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 954e00ee6ebSdrh ** following pseudocode (template 3): 955e00ee6ebSdrh ** 95681cf13ecSdrh ** C: yield X, at EOF goto D 957e00ee6ebSdrh ** insert the select result into <table> from R..R+n 958e00ee6ebSdrh ** goto C 959e00ee6ebSdrh ** D: ... 960e00ee6ebSdrh */ 96181cf13ecSdrh addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 962688852abSdrh VdbeCoverage(v); 963f5f1915dSdrh if( ipkColumn>=0 ){ 964f5f1915dSdrh /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the 965f5f1915dSdrh ** SELECT, go ahead and copy the value into the rowid slot now, so that 966f5f1915dSdrh ** the value does not get overwritten by a NULL at tag-20191021-002. */ 967f5f1915dSdrh sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); 968bed8690fSdrh } 969f5f1915dSdrh } 970f5f1915dSdrh 971f5f1915dSdrh /* Compute data for ordinary columns of the new entry. Values 972f5f1915dSdrh ** are written in storage order into registers starting with regData. 973f5f1915dSdrh ** Only ordinary columns are computed in this loop. The rowid 974f5f1915dSdrh ** (if there is one) is computed later and generated columns are 975f5f1915dSdrh ** computed after the rowid since they might depend on the value 976f5f1915dSdrh ** of the rowid. 977f5f1915dSdrh */ 978f5f1915dSdrh nHidden = 0; 979f5f1915dSdrh iRegStore = regData; assert( regData==regRowid+1 ); 980f5f1915dSdrh for(i=0; i<pTab->nCol; i++, iRegStore++){ 981f5f1915dSdrh int k; 982f5f1915dSdrh u32 colFlags; 983f5f1915dSdrh assert( i>=nHidden ); 984f5f1915dSdrh if( i==pTab->iPKey ){ 985f5f1915dSdrh /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled 986f5f1915dSdrh ** using the rowid. So put a NULL in the IPK slot of the record to avoid 987f5f1915dSdrh ** using excess space. The file format definition requires this extra 988f5f1915dSdrh ** NULL - we cannot optimize further by skipping the column completely */ 989f5f1915dSdrh sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); 990f5f1915dSdrh continue; 991f5f1915dSdrh } 992f5f1915dSdrh if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){ 993f5f1915dSdrh nHidden++; 994f5f1915dSdrh if( (colFlags & COLFLAG_VIRTUAL)!=0 ){ 995f5f1915dSdrh /* Virtual columns do not participate in OP_MakeRecord. So back up 996f5f1915dSdrh ** iRegStore by one slot to compensate for the iRegStore++ in the 997f5f1915dSdrh ** outer for() loop */ 998f5f1915dSdrh iRegStore--; 999f5f1915dSdrh continue; 1000f5f1915dSdrh }else if( (colFlags & COLFLAG_STORED)!=0 ){ 1001f5f1915dSdrh /* Stored columns are computed later. But if there are BEFORE 1002f5f1915dSdrh ** triggers, the slots used for stored columns will be OP_Copy-ed 1003f5f1915dSdrh ** to a second block of registers, so the register needs to be 1004f5f1915dSdrh ** initialized to NULL to avoid an uninitialized register read */ 1005f5f1915dSdrh if( tmask & TRIGGER_BEFORE ){ 1006f5f1915dSdrh sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); 1007f5f1915dSdrh } 1008f5f1915dSdrh continue; 1009f5f1915dSdrh }else if( pColumn==0 ){ 1010f5f1915dSdrh /* Hidden columns that are not explicitly named in the INSERT 1011f5f1915dSdrh ** get there default value */ 1012f5f1915dSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 1013f5f1915dSdrh continue; 1014f5f1915dSdrh } 1015f5f1915dSdrh } 1016f5f1915dSdrh if( pColumn ){ 1017f5f1915dSdrh for(j=0; j<pColumn->nId && pColumn->a[j].idx!=i; j++){} 1018f5f1915dSdrh if( j>=pColumn->nId ){ 1019f5f1915dSdrh /* A column not named in the insert column list gets its 1020f5f1915dSdrh ** default value */ 1021f5f1915dSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 1022f5f1915dSdrh continue; 1023f5f1915dSdrh } 1024f5f1915dSdrh k = j; 1025f5f1915dSdrh }else if( nColumn==0 ){ 1026f5f1915dSdrh /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */ 1027f5f1915dSdrh sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); 1028f5f1915dSdrh continue; 1029f5f1915dSdrh }else{ 1030f5f1915dSdrh k = i - nHidden; 1031f5f1915dSdrh } 1032f5f1915dSdrh 1033f5f1915dSdrh if( useTempTable ){ 1034f5f1915dSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore); 1035f5f1915dSdrh }else if( pSelect ){ 1036f5f1915dSdrh if( regFromSelect!=regData ){ 1037f5f1915dSdrh sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore); 1038f5f1915dSdrh } 1039f5f1915dSdrh }else{ 1040f5f1915dSdrh sqlite3ExprCode(pParse, pList->a[k].pExpr, iRegStore); 1041f5f1915dSdrh } 1042f5f1915dSdrh } 1043f5f1915dSdrh 10441ccde15dSdrh 10455cf590c1Sdrh /* Run the BEFORE and INSTEAD OF triggers, if there are any 104670ce3f0cSdrh */ 1047ec4ccdbcSdrh endOfLoop = sqlite3VdbeMakeLabel(pParse); 10482f886d1dSdanielk1977 if( tmask & TRIGGER_BEFORE ){ 104976d462eeSdan int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); 1050c3f9bad2Sdanielk1977 105170ce3f0cSdrh /* build the NEW.* reference row. Note that if there is an INTEGER 105270ce3f0cSdrh ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 105370ce3f0cSdrh ** translated into a unique ID for the row. But on a BEFORE trigger, 105470ce3f0cSdrh ** we do not know what the unique ID will be (because the insert has 105570ce3f0cSdrh ** not happened yet) so we substitute a rowid of -1 105670ce3f0cSdrh */ 1057d82b5021Sdrh if( ipkColumn<0 ){ 105876d462eeSdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 105970ce3f0cSdrh }else{ 1060728e0f91Sdrh int addr1; 1061ec95c441Sdrh assert( !withoutRowid ); 10627fe45908Sdrh if( useTempTable ){ 1063d82b5021Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); 10647fe45908Sdrh }else{ 1065d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 1066d82b5021Sdrh sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); 10677fe45908Sdrh } 1068728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); 106976d462eeSdan sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); 1070728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 1071688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); 107270ce3f0cSdrh } 107370ce3f0cSdrh 1074034ca14fSdanielk1977 /* Cannot have triggers on a virtual table. If it were possible, 1075034ca14fSdanielk1977 ** this block would have to account for hidden column. 1076034ca14fSdanielk1977 */ 1077034ca14fSdanielk1977 assert( !IsVirtual(pTab) ); 1078034ca14fSdanielk1977 1079f5f1915dSdrh /* Copy the new data already generated. */ 1080f5f1915dSdrh assert( pTab->nNVCol>0 ); 1081f5f1915dSdrh sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1); 1082f5f1915dSdrh 1083f5f1915dSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1084f5f1915dSdrh /* Compute the new value for generated columns after all other 1085f5f1915dSdrh ** columns have already been computed. This must be done after 1086f5f1915dSdrh ** computing the ROWID in case one of the generated columns 1087f5f1915dSdrh ** refers to the ROWID. */ 1088427b96aeSdrh if( pTab->tabFlags & TF_HasGenerated ){ 1089427b96aeSdrh testcase( pTab->tabFlags & TF_HasVirtual ); 1090427b96aeSdrh testcase( pTab->tabFlags & TF_HasStored ); 1091f5f1915dSdrh sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab); 1092c3f9bad2Sdanielk1977 } 1093f5f1915dSdrh #endif 1094a37cdde0Sdanielk1977 1095a37cdde0Sdanielk1977 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 1096a37cdde0Sdanielk1977 ** do not attempt any conversions before assembling the record. 1097a37cdde0Sdanielk1977 ** If this is a real table, attempt conversions as required by the 1098a37cdde0Sdanielk1977 ** table column affinities. 1099a37cdde0Sdanielk1977 */ 1100a37cdde0Sdanielk1977 if( !isView ){ 110157bf4a8eSdrh sqlite3TableAffinity(v, pTab, regCols+1); 1102a37cdde0Sdanielk1977 } 1103c3f9bad2Sdanielk1977 11045cf590c1Sdrh /* Fire BEFORE or INSTEAD OF triggers */ 1105165921a7Sdan sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 110694d7f50aSdan pTab, regCols-pTab->nCol-1, onError, endOfLoop); 1107165921a7Sdan 110876d462eeSdan sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); 110970ce3f0cSdrh } 1110c3f9bad2Sdanielk1977 11115cf590c1Sdrh if( !isView ){ 11124cbdda9eSdrh if( IsVirtual(pTab) ){ 11134cbdda9eSdrh /* The row that the VUpdate opcode will delete: none */ 11146a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); 11154cbdda9eSdrh } 1116d82b5021Sdrh if( ipkColumn>=0 ){ 1117f5f1915dSdrh /* Compute the new rowid */ 1118142e30dfSdrh if( useTempTable ){ 1119d82b5021Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); 1120142e30dfSdrh }else if( pSelect ){ 1121f5f1915dSdrh /* Rowid already initialized at tag-20191021-001 */ 11224a32431cSdrh }else{ 112304fcef00Sdrh Expr *pIpk = pList->a[ipkColumn].pExpr; 112404fcef00Sdrh if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){ 112504fcef00Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 1126e4d90813Sdrh appendFlag = 1; 112704fcef00Sdrh }else{ 112804fcef00Sdrh sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); 1129e4d90813Sdrh } 113027a32783Sdrh } 1131f0863fe5Sdrh /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 1132e1e68f49Sdrh ** to generate a unique primary key value. 1133e1e68f49Sdrh */ 1134e4d90813Sdrh if( !appendFlag ){ 1135728e0f91Sdrh int addr1; 1136bb50e7adSdanielk1977 if( !IsVirtual(pTab) ){ 1137728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); 113826198bb4Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 1139728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 1140bb50e7adSdanielk1977 }else{ 1141728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 1142728e0f91Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); 1143bb50e7adSdanielk1977 } 1144688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); 1145e4d90813Sdrh } 1146ec95c441Sdrh }else if( IsVirtual(pTab) || withoutRowid ){ 11476a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); 11484a32431cSdrh }else{ 114926198bb4Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); 1150e4d90813Sdrh appendFlag = 1; 11514a32431cSdrh } 11526a288a33Sdrh autoIncStep(pParse, regAutoinc, regRowid); 11534a32431cSdrh 1154c1431144Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1155dd6cc9b5Sdrh /* Compute the new value for generated columns after all other 1156f5f1915dSdrh ** columns have already been computed. This must be done after 1157f5f1915dSdrh ** computing the ROWID in case one of the generated columns 1158f5f1915dSdrh ** refers to the ROWID. */ 1159427b96aeSdrh if( pTab->tabFlags & TF_HasGenerated ){ 1160427b96aeSdrh testcase( pTab->tabFlags & TF_HasVirtual ); 1161427b96aeSdrh testcase( pTab->tabFlags & TF_HasStored ); 1162dd6cc9b5Sdrh sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab); 1163c1431144Sdrh } 1164c1431144Sdrh #endif 1165c1431144Sdrh 11660ca3e24bSdrh /* Generate code to check constraints and generate index keys and 11670ca3e24bSdrh ** do the insertion. 11684a32431cSdrh */ 11694cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 11704cbdda9eSdrh if( IsVirtual(pTab) ){ 1171595a523aSdanielk1977 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 11724f3dd150Sdrh sqlite3VtabMakeWritable(pParse, pTab); 1173595a523aSdanielk1977 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); 1174b061d058Sdan sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); 1175e0af83acSdan sqlite3MayAbort(pParse); 11764cbdda9eSdrh }else 11774cbdda9eSdrh #endif 11784cbdda9eSdrh { 1179de630353Sdanielk1977 int isReplace; /* Set to true if constraints may cause a replace */ 11803b908d41Sdan int bUseSeek; /* True to use OPFLAG_SEEKRESULT */ 1181f8ffb278Sdrh sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, 1182788d55aaSdrh regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert 118304adf416Sdrh ); 11848ff2d956Sdan sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); 11853b908d41Sdan 11863b908d41Sdan /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE 11873b908d41Sdan ** constraints or (b) there are no triggers and this table is not a 11883b908d41Sdan ** parent table in a foreign key constraint. It is safe to set the 11893b908d41Sdan ** flag in the second case as if any REPLACE constraint is hit, an 11903b908d41Sdan ** OP_Delete or OP_IdxDelete instruction will be executed on each 11913b908d41Sdan ** cursor that is disturbed. And these instructions both clear the 11923b908d41Sdan ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT 11933b908d41Sdan ** functionality. */ 11943b908d41Sdan bUseSeek = (isReplace==0 || (pTrigger==0 && 11953b908d41Sdan ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0) 11963b908d41Sdan )); 119726198bb4Sdrh sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, 11983b908d41Sdan regIns, aRegIdx, 0, appendFlag, bUseSeek 11993b908d41Sdan ); 12005cf590c1Sdrh } 12014cbdda9eSdrh } 12021bee3d7bSdrh 1203feeb1394Sdrh /* Update the count of rows that are inserted 12041bee3d7bSdrh */ 120579636913Sdrh if( regRowCount ){ 12066a288a33Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 12071bee3d7bSdrh } 1208c3f9bad2Sdanielk1977 12092f886d1dSdanielk1977 if( pTrigger ){ 1210c3f9bad2Sdanielk1977 /* Code AFTER triggers */ 1211165921a7Sdan sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 121294d7f50aSdan pTab, regData-2-pTab->nCol, onError, endOfLoop); 1213c3f9bad2Sdanielk1977 } 12141bee3d7bSdrh 1215e00ee6ebSdrh /* The bottom of the main insertion loop, if the data source 1216e00ee6ebSdrh ** is a SELECT statement. 12171ccde15dSdrh */ 12184adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, endOfLoop); 1219142e30dfSdrh if( useTempTable ){ 1220688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); 1221e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 12222eb95377Sdrh sqlite3VdbeAddOp1(v, OP_Close, srcTab); 1223142e30dfSdrh }else if( pSelect ){ 1224076e85f5Sdrh sqlite3VdbeGoto(v, addrCont); 1225e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 12266b56344dSdrh } 1227c3f9bad2Sdanielk1977 12280b9f50d8Sdrh insert_end: 1229f3388144Sdrh /* Update the sqlite_sequence table by storing the content of the 12300b9f50d8Sdrh ** maximum rowid counter values recorded while inserting into 12310b9f50d8Sdrh ** autoincrement tables. 12322958a4e6Sdrh */ 1233165921a7Sdan if( pParse->nested==0 && pParse->pTriggerTab==0 ){ 12340b9f50d8Sdrh sqlite3AutoincrementEnd(pParse); 12350b9f50d8Sdrh } 12362958a4e6Sdrh 12371bee3d7bSdrh /* 1238e7de6f25Sdanielk1977 ** Return the number of rows inserted. If this routine is 1239e7de6f25Sdanielk1977 ** generating code because of a call to sqlite3NestedParse(), do not 1240e7de6f25Sdanielk1977 ** invoke the callback function. 12411bee3d7bSdrh */ 124279636913Sdrh if( regRowCount ){ 12436a288a33Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); 124422322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, 1); 124510fb749bSdanielk1977 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); 12461bee3d7bSdrh } 1247cce7d176Sdrh 1248cce7d176Sdrh insert_cleanup: 1249633e6d57Sdrh sqlite3SrcListDelete(db, pTabList); 1250633e6d57Sdrh sqlite3ExprListDelete(db, pList); 125146d2e5c3Sdrh sqlite3UpsertDelete(db, pUpsert); 1252633e6d57Sdrh sqlite3SelectDelete(db, pSelect); 1253633e6d57Sdrh sqlite3IdListDelete(db, pColumn); 1254633e6d57Sdrh sqlite3DbFree(db, aRegIdx); 1255cce7d176Sdrh } 12569cfcf5d4Sdrh 125775cbd984Sdan /* Make sure "isView" and other macros defined above are undefined. Otherwise 125860ec914cSpeter.d.reid ** they may interfere with compilation of other functions in this file 125975cbd984Sdan ** (or in another file, if this file becomes part of the amalgamation). */ 126075cbd984Sdan #ifdef isView 126175cbd984Sdan #undef isView 126275cbd984Sdan #endif 126375cbd984Sdan #ifdef pTrigger 126475cbd984Sdan #undef pTrigger 126575cbd984Sdan #endif 126675cbd984Sdan #ifdef tmask 126775cbd984Sdan #undef tmask 126875cbd984Sdan #endif 126975cbd984Sdan 12709cfcf5d4Sdrh /* 1271e9816d82Sdrh ** Meanings of bits in of pWalker->eCode for 1272e9816d82Sdrh ** sqlite3ExprReferencesUpdatedColumn() 127398bfa16dSdrh */ 127498bfa16dSdrh #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */ 127598bfa16dSdrh #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */ 127698bfa16dSdrh 1277e9816d82Sdrh /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn(). 1278e9816d82Sdrh * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this 1279e9816d82Sdrh ** expression node references any of the 12802a0b527bSdrh ** columns that are being modifed by an UPDATE statement. 12812a0b527bSdrh */ 12822a0b527bSdrh static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){ 128398bfa16dSdrh if( pExpr->op==TK_COLUMN ){ 128498bfa16dSdrh assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 ); 128598bfa16dSdrh if( pExpr->iColumn>=0 ){ 128698bfa16dSdrh if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){ 128798bfa16dSdrh pWalker->eCode |= CKCNSTRNT_COLUMN; 128898bfa16dSdrh } 128998bfa16dSdrh }else{ 129098bfa16dSdrh pWalker->eCode |= CKCNSTRNT_ROWID; 129198bfa16dSdrh } 12922a0b527bSdrh } 12932a0b527bSdrh return WRC_Continue; 12942a0b527bSdrh } 12952a0b527bSdrh 12962a0b527bSdrh /* 12972a0b527bSdrh ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The 12982a0b527bSdrh ** only columns that are modified by the UPDATE are those for which 129998bfa16dSdrh ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true. 130098bfa16dSdrh ** 1301e9816d82Sdrh ** Return true if CHECK constraint pExpr uses any of the 130298bfa16dSdrh ** changing columns (or the rowid if it is changing). In other words, 1303e9816d82Sdrh ** return true if this CHECK constraint must be validated for 130498bfa16dSdrh ** the new row in the UPDATE statement. 1305e9816d82Sdrh ** 1306e9816d82Sdrh ** 2018-09-15: pExpr might also be an expression for an index-on-expressions. 1307e9816d82Sdrh ** The operation of this routine is the same - return true if an only if 1308e9816d82Sdrh ** the expression uses one or more of columns identified by the second and 1309e9816d82Sdrh ** third arguments. 13102a0b527bSdrh */ 1311e9816d82Sdrh int sqlite3ExprReferencesUpdatedColumn( 1312e9816d82Sdrh Expr *pExpr, /* The expression to be checked */ 1313e9816d82Sdrh int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */ 1314e9816d82Sdrh int chngRowid /* True if UPDATE changes the rowid */ 1315e9816d82Sdrh ){ 13162a0b527bSdrh Walker w; 13172a0b527bSdrh memset(&w, 0, sizeof(w)); 131898bfa16dSdrh w.eCode = 0; 13192a0b527bSdrh w.xExprCallback = checkConstraintExprNode; 13202a0b527bSdrh w.u.aiCol = aiChng; 13212a0b527bSdrh sqlite3WalkExpr(&w, pExpr); 132205723a9eSdrh if( !chngRowid ){ 132305723a9eSdrh testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 ); 132405723a9eSdrh w.eCode &= ~CKCNSTRNT_ROWID; 132505723a9eSdrh } 132605723a9eSdrh testcase( w.eCode==0 ); 132705723a9eSdrh testcase( w.eCode==CKCNSTRNT_COLUMN ); 132805723a9eSdrh testcase( w.eCode==CKCNSTRNT_ROWID ); 132905723a9eSdrh testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) ); 1330e9816d82Sdrh return w.eCode!=0; 13312a0b527bSdrh } 13322a0b527bSdrh 133311e85273Sdrh /* 13346934fc7bSdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE 13356934fc7bSdrh ** on table pTab. 13369cfcf5d4Sdrh ** 13376934fc7bSdrh ** The regNewData parameter is the first register in a range that contains 13386934fc7bSdrh ** the data to be inserted or the data after the update. There will be 13396934fc7bSdrh ** pTab->nCol+1 registers in this range. The first register (the one 13406934fc7bSdrh ** that regNewData points to) will contain the new rowid, or NULL in the 13416934fc7bSdrh ** case of a WITHOUT ROWID table. The second register in the range will 13426934fc7bSdrh ** contain the content of the first table column. The third register will 13436934fc7bSdrh ** contain the content of the second table column. And so forth. 13440ca3e24bSdrh ** 1345f8ffb278Sdrh ** The regOldData parameter is similar to regNewData except that it contains 1346f8ffb278Sdrh ** the data prior to an UPDATE rather than afterwards. regOldData is zero 1347f8ffb278Sdrh ** for an INSERT. This routine can distinguish between UPDATE and INSERT by 1348f8ffb278Sdrh ** checking regOldData for zero. 13490ca3e24bSdrh ** 1350f8ffb278Sdrh ** For an UPDATE, the pkChng boolean is true if the true primary key (the 1351f8ffb278Sdrh ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) 1352f8ffb278Sdrh ** might be modified by the UPDATE. If pkChng is false, then the key of 1353f8ffb278Sdrh ** the iDataCur content table is guaranteed to be unchanged by the UPDATE. 13540ca3e24bSdrh ** 1355f8ffb278Sdrh ** For an INSERT, the pkChng boolean indicates whether or not the rowid 1356f8ffb278Sdrh ** was explicitly specified as part of the INSERT statement. If pkChng 1357f8ffb278Sdrh ** is zero, it means that the either rowid is computed automatically or 1358f8ffb278Sdrh ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, 1359f8ffb278Sdrh ** pkChng will only be true if the INSERT statement provides an integer 1360f8ffb278Sdrh ** value for either the rowid column or its INTEGER PRIMARY KEY alias. 13610ca3e24bSdrh ** 13626934fc7bSdrh ** The code generated by this routine will store new index entries into 1363aa9b8963Sdrh ** registers identified by aRegIdx[]. No index entry is created for 1364aa9b8963Sdrh ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is 1365aa9b8963Sdrh ** the same as the order of indices on the linked list of indices 13666934fc7bSdrh ** at pTab->pIndex. 13676934fc7bSdrh ** 1368a7c3b93fSdrh ** (2019-05-07) The generated code also creates a new record for the 1369a7c3b93fSdrh ** main table, if pTab is a rowid table, and stores that record in the 1370a7c3b93fSdrh ** register identified by aRegIdx[nIdx] - in other words in the first 1371a7c3b93fSdrh ** entry of aRegIdx[] past the last index. It is important that the 1372a7c3b93fSdrh ** record be generated during constraint checks to avoid affinity changes 1373a7c3b93fSdrh ** to the register content that occur after constraint checks but before 1374a7c3b93fSdrh ** the new record is inserted. 1375a7c3b93fSdrh ** 13766934fc7bSdrh ** The caller must have already opened writeable cursors on the main 13776934fc7bSdrh ** table and all applicable indices (that is to say, all indices for which 13786934fc7bSdrh ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when 13796934fc7bSdrh ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY 13806934fc7bSdrh ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor 13816934fc7bSdrh ** for the first index in the pTab->pIndex list. Cursors for other indices 13826934fc7bSdrh ** are at iIdxCur+N for the N-th element of the pTab->pIndex list. 13839cfcf5d4Sdrh ** 13849cfcf5d4Sdrh ** This routine also generates code to check constraints. NOT NULL, 13859cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 13861c92853dSdrh ** then the appropriate action is performed. There are five possible 13871c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 13889cfcf5d4Sdrh ** 13899cfcf5d4Sdrh ** Constraint type Action What Happens 13909cfcf5d4Sdrh ** --------------- ---------- ---------------------------------------- 13911c92853dSdrh ** any ROLLBACK The current transaction is rolled back and 13926934fc7bSdrh ** sqlite3_step() returns immediately with a 13939cfcf5d4Sdrh ** return code of SQLITE_CONSTRAINT. 13949cfcf5d4Sdrh ** 13951c92853dSdrh ** any ABORT Back out changes from the current command 13961c92853dSdrh ** only (do not do a complete rollback) then 13976934fc7bSdrh ** cause sqlite3_step() to return immediately 13981c92853dSdrh ** with SQLITE_CONSTRAINT. 13991c92853dSdrh ** 14006934fc7bSdrh ** any FAIL Sqlite3_step() returns immediately with a 14011c92853dSdrh ** return code of SQLITE_CONSTRAINT. The 14021c92853dSdrh ** transaction is not rolled back and any 14036934fc7bSdrh ** changes to prior rows are retained. 14041c92853dSdrh ** 14056934fc7bSdrh ** any IGNORE The attempt in insert or update the current 14066934fc7bSdrh ** row is skipped, without throwing an error. 14076934fc7bSdrh ** Processing continues with the next row. 14086934fc7bSdrh ** (There is an immediate jump to ignoreDest.) 14099cfcf5d4Sdrh ** 14109cfcf5d4Sdrh ** NOT NULL REPLACE The NULL value is replace by the default 14119cfcf5d4Sdrh ** value for that column. If the default value 14129cfcf5d4Sdrh ** is NULL, the action is the same as ABORT. 14139cfcf5d4Sdrh ** 14149cfcf5d4Sdrh ** UNIQUE REPLACE The other row that conflicts with the row 14159cfcf5d4Sdrh ** being inserted is removed. 14169cfcf5d4Sdrh ** 14179cfcf5d4Sdrh ** CHECK REPLACE Illegal. The results in an exception. 14189cfcf5d4Sdrh ** 14191c92853dSdrh ** Which action to take is determined by the overrideError parameter. 14201c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter 14211c92853dSdrh ** is used. Or if pParse->onError==OE_Default then the onError value 14221c92853dSdrh ** for the constraint is used. 14239cfcf5d4Sdrh */ 14244adee20fSdanielk1977 void sqlite3GenerateConstraintChecks( 14259cfcf5d4Sdrh Parse *pParse, /* The parser context */ 14266934fc7bSdrh Table *pTab, /* The table being inserted or updated */ 1427f8ffb278Sdrh int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ 14286934fc7bSdrh int iDataCur, /* Canonical data cursor (main table or PK index) */ 142926198bb4Sdrh int iIdxCur, /* First index cursor */ 14306934fc7bSdrh int regNewData, /* First register in a range holding values to insert */ 1431f8ffb278Sdrh int regOldData, /* Previous content. 0 for INSERTs */ 1432f8ffb278Sdrh u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ 1433f8ffb278Sdrh u8 overrideError, /* Override onError to this if not OE_Default */ 1434de630353Sdanielk1977 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ 1435bdb00225Sdrh int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */ 1436788d55aaSdrh int *aiChng, /* column i is unchanged if aiChng[i]<0 */ 1437788d55aaSdrh Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */ 14389cfcf5d4Sdrh ){ 14391b7ecbb4Sdrh Vdbe *v; /* VDBE under constrution */ 14401b7ecbb4Sdrh Index *pIdx; /* Pointer to one of the indices */ 144111e85273Sdrh Index *pPk = 0; /* The PRIMARY KEY index */ 14422938f924Sdrh sqlite3 *db; /* Database connection */ 1443f8ffb278Sdrh int i; /* loop counter */ 1444f8ffb278Sdrh int ix; /* Index loop counter */ 14459cfcf5d4Sdrh int nCol; /* Number of columns */ 14469cfcf5d4Sdrh int onError; /* Conflict resolution strategy */ 1447728e0f91Sdrh int addr1; /* Address of jump instruction */ 14481b7ecbb4Sdrh int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ 14496fbe41acSdrh int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ 1450096fd476Sdrh Index *pUpIdx = 0; /* Index to which to apply the upsert */ 14518d1b82e4Sdrh u8 isUpdate; /* True if this is an UPDATE operation */ 145257bf4a8eSdrh u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ 1453096fd476Sdrh int upsertBypass = 0; /* Address of Goto to bypass upsert subroutine */ 145484304506Sdrh int upsertJump = 0; /* Address of Goto that jumps into upsert subroutine */ 145584304506Sdrh int ipkTop = 0; /* Top of the IPK uniqueness check */ 145684304506Sdrh int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */ 14579cfcf5d4Sdrh 1458f8ffb278Sdrh isUpdate = regOldData!=0; 14592938f924Sdrh db = pParse->db; 14604adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 14619cfcf5d4Sdrh assert( v!=0 ); 1462417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 14639cfcf5d4Sdrh nCol = pTab->nCol; 1464aa9b8963Sdrh 14656934fc7bSdrh /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for 14666934fc7bSdrh ** normal rowid tables. nPkField is the number of key fields in the 14676934fc7bSdrh ** pPk index or 1 for a rowid table. In other words, nPkField is the 14686934fc7bSdrh ** number of fields in the true primary key of the table. */ 146926198bb4Sdrh if( HasRowid(pTab) ){ 147026198bb4Sdrh pPk = 0; 147126198bb4Sdrh nPkField = 1; 147226198bb4Sdrh }else{ 147326198bb4Sdrh pPk = sqlite3PrimaryKeyIndex(pTab); 147426198bb4Sdrh nPkField = pPk->nKeyCol; 147526198bb4Sdrh } 14766fbe41acSdrh 14776fbe41acSdrh /* Record that this module has started */ 14786fbe41acSdrh VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", 14796934fc7bSdrh iDataCur, iIdxCur, regNewData, regOldData, pkChng)); 14809cfcf5d4Sdrh 14819cfcf5d4Sdrh /* Test all NOT NULL constraints. 14829cfcf5d4Sdrh */ 14839cfcf5d4Sdrh for(i=0; i<nCol; i++){ 14848e10d74bSdrh int iReg; 14850ca3e24bSdrh if( i==pTab->iPKey ){ 1486bdb00225Sdrh continue; /* ROWID is never NULL */ 1487bdb00225Sdrh } 1488bdb00225Sdrh if( aiChng && aiChng[i]<0 ){ 1489bdb00225Sdrh /* Don't bother checking for NOT NULL on columns that do not change */ 14900ca3e24bSdrh continue; 14910ca3e24bSdrh } 14929cfcf5d4Sdrh onError = pTab->aCol[i].notNull; 1493bdb00225Sdrh if( onError==OE_None ) continue; /* This column is allowed to be NULL */ 14949cfcf5d4Sdrh if( overrideError!=OE_Default ){ 14959cfcf5d4Sdrh onError = overrideError; 1496a996e477Sdrh }else if( onError==OE_Default ){ 1497a996e477Sdrh onError = OE_Abort; 14989cfcf5d4Sdrh } 14997977a17fSdanielk1977 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ 15009cfcf5d4Sdrh onError = OE_Abort; 15019cfcf5d4Sdrh } 1502b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1503b84f96f8Sdanielk1977 || onError==OE_Ignore || onError==OE_Replace ); 15049bfb0794Sdrh addr1 = 0; 1505c5f808d8Sdrh testcase( i!=sqlite3TableColumnToStorage(pTab, i) ); 1506dd6cc9b5Sdrh testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ); 1507dd6cc9b5Sdrh testcase( pTab->aCol[i].colFlags & COLFLAG_STORED ); 1508b9bcf7caSdrh iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1; 15099cfcf5d4Sdrh switch( onError ){ 15109bfb0794Sdrh case OE_Replace: { 15119bfb0794Sdrh assert( onError==OE_Replace ); 1512ec4ccdbcSdrh addr1 = sqlite3VdbeMakeLabel(pParse); 15138e10d74bSdrh sqlite3VdbeAddOp2(v, OP_NotNull, iReg, addr1); 15149bfb0794Sdrh VdbeCoverage(v); 15159bfb0794Sdrh sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); 15168e10d74bSdrh sqlite3VdbeAddOp2(v, OP_NotNull, iReg, addr1); 15179bfb0794Sdrh VdbeCoverage(v); 15189bfb0794Sdrh onError = OE_Abort; 15199bfb0794Sdrh /* Fall through into the OE_Abort case to generate code that runs 15209bfb0794Sdrh ** if both the input and the default value are NULL */ 15219bfb0794Sdrh } 15221c92853dSdrh case OE_Abort: 1523e0af83acSdan sqlite3MayAbort(pParse); 15240978d4ffSdrh /* Fall through */ 1525e0af83acSdan case OE_Rollback: 15261c92853dSdrh case OE_Fail: { 1527f9c8ce3cSdrh char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, 1528f9c8ce3cSdrh pTab->aCol[i].zName); 15292700acaaSdrh sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError, 15308e10d74bSdrh iReg); 15312700acaaSdrh sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC); 1532f9c8ce3cSdrh sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); 1533688852abSdrh VdbeCoverage(v); 15349bfb0794Sdrh if( addr1 ) sqlite3VdbeResolveLabel(v, addr1); 15359cfcf5d4Sdrh break; 15369cfcf5d4Sdrh } 1537098d1684Sdrh default: { 15389bfb0794Sdrh assert( onError==OE_Ignore ); 15398e10d74bSdrh sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest); 1540728e0f91Sdrh VdbeCoverage(v); 15419cfcf5d4Sdrh break; 15429cfcf5d4Sdrh } 15439cfcf5d4Sdrh } 15449cfcf5d4Sdrh } 15459cfcf5d4Sdrh 15469cfcf5d4Sdrh /* Test all CHECK constraints 15479cfcf5d4Sdrh */ 1548ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 15492938f924Sdrh if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ 15502938f924Sdrh ExprList *pCheck = pTab->pCheck; 15516e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 1552aa01c7e2Sdrh onError = overrideError!=OE_Default ? overrideError : OE_Abort; 15532938f924Sdrh for(i=0; i<pCheck->nExpr; i++){ 155405723a9eSdrh int allOk; 15552a0b527bSdrh Expr *pExpr = pCheck->a[i].pExpr; 1556e9816d82Sdrh if( aiChng 1557e9816d82Sdrh && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng) 1558e9816d82Sdrh ){ 1559e9816d82Sdrh /* The check constraints do not reference any of the columns being 1560e9816d82Sdrh ** updated so there is no point it verifying the check constraint */ 1561e9816d82Sdrh continue; 1562e9816d82Sdrh } 1563ec4ccdbcSdrh allOk = sqlite3VdbeMakeLabel(pParse); 15644031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 15652a0b527bSdrh sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL); 15662e06c67cSdrh if( onError==OE_Ignore ){ 1567076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 1568aa01c7e2Sdrh }else{ 1569f9c8ce3cSdrh char *zName = pCheck->a[i].zName; 1570f9c8ce3cSdrh if( zName==0 ) zName = pTab->zName; 15710ce974d1Sdrh if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */ 1572d91c1a17Sdrh sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, 1573f9c8ce3cSdrh onError, zName, P4_TRANSIENT, 1574f9c8ce3cSdrh P5_ConstraintCheck); 1575aa01c7e2Sdrh } 1576ffe07b2dSdrh sqlite3VdbeResolveLabel(v, allOk); 1577ffe07b2dSdrh } 15786e97f8ecSdrh pParse->iSelfTab = 0; 15792938f924Sdrh } 1580ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */ 15819cfcf5d4Sdrh 1582096fd476Sdrh /* UNIQUE and PRIMARY KEY constraints should be handled in the following 1583096fd476Sdrh ** order: 1584096fd476Sdrh ** 158584304506Sdrh ** (1) OE_Update 158684304506Sdrh ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore 1587096fd476Sdrh ** (3) OE_Replace 1588096fd476Sdrh ** 1589096fd476Sdrh ** OE_Fail and OE_Ignore must happen before any changes are made. 1590096fd476Sdrh ** OE_Update guarantees that only a single row will change, so it 1591096fd476Sdrh ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback 1592096fd476Sdrh ** could happen in any order, but they are grouped up front for 1593096fd476Sdrh ** convenience. 1594096fd476Sdrh ** 159584304506Sdrh ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43 159684304506Sdrh ** The order of constraints used to have OE_Update as (2) and OE_Abort 159784304506Sdrh ** and so forth as (1). But apparently PostgreSQL checks the OE_Update 159884304506Sdrh ** constraint before any others, so it had to be moved. 159984304506Sdrh ** 1600096fd476Sdrh ** Constraint checking code is generated in this order: 1601096fd476Sdrh ** (A) The rowid constraint 1602096fd476Sdrh ** (B) Unique index constraints that do not have OE_Replace as their 1603096fd476Sdrh ** default conflict resolution strategy 1604096fd476Sdrh ** (C) Unique index that do use OE_Replace by default. 1605096fd476Sdrh ** 1606096fd476Sdrh ** The ordering of (2) and (3) is accomplished by making sure the linked 1607096fd476Sdrh ** list of indexes attached to a table puts all OE_Replace indexes last 1608096fd476Sdrh ** in the list. See sqlite3CreateIndex() for where that happens. 1609096fd476Sdrh */ 1610096fd476Sdrh 1611096fd476Sdrh if( pUpsert ){ 1612096fd476Sdrh if( pUpsert->pUpsertTarget==0 ){ 1613096fd476Sdrh /* An ON CONFLICT DO NOTHING clause, without a constraint-target. 1614096fd476Sdrh ** Make all unique constraint resolution be OE_Ignore */ 1615dedbc508Sdrh assert( pUpsert->pUpsertSet==0 ); 1616096fd476Sdrh overrideError = OE_Ignore; 1617096fd476Sdrh pUpsert = 0; 1618096fd476Sdrh }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){ 161984304506Sdrh /* If the constraint-target uniqueness check must be run first. 162084304506Sdrh ** Jump to that uniqueness check now */ 162184304506Sdrh upsertJump = sqlite3VdbeAddOp0(v, OP_Goto); 162284304506Sdrh VdbeComment((v, "UPSERT constraint goes first")); 1623096fd476Sdrh } 1624096fd476Sdrh } 1625096fd476Sdrh 1626f8ffb278Sdrh /* If rowid is changing, make sure the new rowid does not previously 1627f8ffb278Sdrh ** exist in the table. 16289cfcf5d4Sdrh */ 16296fbe41acSdrh if( pkChng && pPk==0 ){ 1630ec4ccdbcSdrh int addrRowidOk = sqlite3VdbeMakeLabel(pParse); 163111e85273Sdrh 1632f8ffb278Sdrh /* Figure out what action to take in case of a rowid collision */ 16330ca3e24bSdrh onError = pTab->keyConf; 16340ca3e24bSdrh if( overrideError!=OE_Default ){ 16350ca3e24bSdrh onError = overrideError; 1636a996e477Sdrh }else if( onError==OE_Default ){ 1637a996e477Sdrh onError = OE_Abort; 16380ca3e24bSdrh } 1639a0217ba7Sdrh 1640c8a0c90bSdrh /* figure out whether or not upsert applies in this case */ 1641096fd476Sdrh if( pUpsert && pUpsert->pUpsertIdx==0 ){ 1642c8a0c90bSdrh if( pUpsert->pUpsertSet==0 ){ 1643c8a0c90bSdrh onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */ 1644c8a0c90bSdrh }else{ 1645c8a0c90bSdrh onError = OE_Update; /* DO UPDATE */ 1646c8a0c90bSdrh } 1647c8a0c90bSdrh } 1648c8a0c90bSdrh 16498d1b82e4Sdrh /* If the response to a rowid conflict is REPLACE but the response 16508d1b82e4Sdrh ** to some other UNIQUE constraint is FAIL or IGNORE, then we need 16518d1b82e4Sdrh ** to defer the running of the rowid conflict checking until after 16528d1b82e4Sdrh ** the UNIQUE constraints have run. 16538d1b82e4Sdrh */ 165484304506Sdrh if( onError==OE_Replace /* IPK rule is REPLACE */ 165584304506Sdrh && onError!=overrideError /* Rules for other contraints are different */ 165684304506Sdrh && pTab->pIndex /* There exist other constraints */ 1657096fd476Sdrh ){ 165884304506Sdrh ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1; 165984304506Sdrh VdbeComment((v, "defer IPK REPLACE until last")); 16608d1b82e4Sdrh } 16618d1b82e4Sdrh 1662bb6b1ca7Sdrh if( isUpdate ){ 1663bb6b1ca7Sdrh /* pkChng!=0 does not mean that the rowid has changed, only that 1664bb6b1ca7Sdrh ** it might have changed. Skip the conflict logic below if the rowid 1665bb6b1ca7Sdrh ** is unchanged. */ 1666bb6b1ca7Sdrh sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); 1667bb6b1ca7Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1668bb6b1ca7Sdrh VdbeCoverage(v); 1669bb6b1ca7Sdrh } 1670bb6b1ca7Sdrh 1671f8ffb278Sdrh /* Check to see if the new rowid already exists in the table. Skip 1672f8ffb278Sdrh ** the following conflict logic if it does not. */ 16737f5f306bSdrh VdbeNoopComment((v, "uniqueness check for ROWID")); 16744031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 16756934fc7bSdrh sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); 1676688852abSdrh VdbeCoverage(v); 1677f8ffb278Sdrh 16780ca3e24bSdrh switch( onError ){ 1679a0217ba7Sdrh default: { 1680a0217ba7Sdrh onError = OE_Abort; 1681a0217ba7Sdrh /* Fall thru into the next case */ 1682a0217ba7Sdrh } 16831c92853dSdrh case OE_Rollback: 16841c92853dSdrh case OE_Abort: 16851c92853dSdrh case OE_Fail: { 16869916048bSdrh testcase( onError==OE_Rollback ); 16879916048bSdrh testcase( onError==OE_Abort ); 16889916048bSdrh testcase( onError==OE_Fail ); 1689f9c8ce3cSdrh sqlite3RowidConstraint(pParse, onError, pTab); 16900ca3e24bSdrh break; 16910ca3e24bSdrh } 16925383ae5cSdrh case OE_Replace: { 16932283d46cSdan /* If there are DELETE triggers on this table and the 16942283d46cSdan ** recursive-triggers flag is set, call GenerateRowDelete() to 1695d5578433Smistachkin ** remove the conflicting row from the table. This will fire 16962283d46cSdan ** the triggers and remove both the table and index b-tree entries. 16972283d46cSdan ** 16982283d46cSdan ** Otherwise, if there are no triggers or the recursive-triggers 1699da730f6eSdan ** flag is not set, but the table has one or more indexes, call 1700da730f6eSdan ** GenerateRowIndexDelete(). This removes the index b-tree entries 1701da730f6eSdan ** only. The table b-tree entry will be replaced by the new entry 1702da730f6eSdan ** when it is inserted. 1703da730f6eSdan ** 1704da730f6eSdan ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, 1705da730f6eSdan ** also invoke MultiWrite() to indicate that this VDBE may require 1706da730f6eSdan ** statement rollback (if the statement is aborted after the delete 1707da730f6eSdan ** takes place). Earlier versions called sqlite3MultiWrite() regardless, 1708da730f6eSdan ** but being more selective here allows statements like: 1709da730f6eSdan ** 1710da730f6eSdan ** REPLACE INTO t(rowid) VALUES($newrowid) 1711da730f6eSdan ** 1712da730f6eSdan ** to run without a statement journal if there are no indexes on the 1713da730f6eSdan ** table. 1714da730f6eSdan */ 17152283d46cSdan Trigger *pTrigger = 0; 17162938f924Sdrh if( db->flags&SQLITE_RecTriggers ){ 17172283d46cSdan pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 17182283d46cSdan } 1719e7a94d81Sdan if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ 1720da730f6eSdan sqlite3MultiWrite(pParse); 172126198bb4Sdrh sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1722438b8815Sdan regNewData, 1, 0, OE_Replace, 1, -1); 17232da8d6feSdrh sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); 17242c3de90dSdrh VdbeCoverage(v); 17252da8d6feSdrh sqlite3RowidConstraint(pParse, OE_Abort, pTab); 172646c47d46Sdan }else{ 17279b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 172854f2cd90Sdrh assert( HasRowid(pTab) ); 172946c47d46Sdan /* This OP_Delete opcode fires the pre-update-hook only. It does 173046c47d46Sdan ** not modify the b-tree. It is more efficient to let the coming 173146c47d46Sdan ** OP_Insert replace the existing entry than it is to delete the 173246c47d46Sdan ** existing entry and then insert a new one. */ 1733cbf1b8efSdrh sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP); 1734f14b7fb7Sdrh sqlite3VdbeAppendP4(v, pTab, P4_TABLE); 17359b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ 173646c47d46Sdan if( pTab->pIndex ){ 1737da730f6eSdan sqlite3MultiWrite(pParse); 1738f0ee1d3cSdan sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); 17392283d46cSdan } 174046c47d46Sdan } 17415383ae5cSdrh seenReplace = 1; 17425383ae5cSdrh break; 17435383ae5cSdrh } 17449eddacadSdrh #ifndef SQLITE_OMIT_UPSERT 17459eddacadSdrh case OE_Update: { 17462cc00423Sdan sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur); 17479eddacadSdrh /* Fall through */ 17489eddacadSdrh } 17499eddacadSdrh #endif 17500ca3e24bSdrh case OE_Ignore: { 17519916048bSdrh testcase( onError==OE_Ignore ); 1752076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 17530ca3e24bSdrh break; 17540ca3e24bSdrh } 17550ca3e24bSdrh } 175611e85273Sdrh sqlite3VdbeResolveLabel(v, addrRowidOk); 175784304506Sdrh if( ipkTop ){ 175884304506Sdrh ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); 175984304506Sdrh sqlite3VdbeJumpHere(v, ipkTop-1); 1760a05a722fSdrh } 17610ca3e24bSdrh } 17620bd1f4eaSdrh 17630bd1f4eaSdrh /* Test all UNIQUE constraints by creating entries for each UNIQUE 17640bd1f4eaSdrh ** index and making sure that duplicate entries do not already exist. 176511e85273Sdrh ** Compute the revised record entries for indices as we go. 1766f8ffb278Sdrh ** 1767f8ffb278Sdrh ** This loop also handles the case of the PRIMARY KEY index for a 1768f8ffb278Sdrh ** WITHOUT ROWID table. 17690bd1f4eaSdrh */ 177026198bb4Sdrh for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ 17716934fc7bSdrh int regIdx; /* Range of registers hold conent for pIdx */ 17726934fc7bSdrh int regR; /* Range of registers holding conflicting PK */ 17736934fc7bSdrh int iThisCur; /* Cursor for this UNIQUE index */ 17746934fc7bSdrh int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ 17752184fc75Sdrh 177626198bb4Sdrh if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ 17777f5f306bSdrh if( pUpIdx==pIdx ){ 177884304506Sdrh addrUniqueOk = upsertJump+1; 17797f5f306bSdrh upsertBypass = sqlite3VdbeGoto(v, 0); 17807f5f306bSdrh VdbeComment((v, "Skip upsert subroutine")); 178184304506Sdrh sqlite3VdbeJumpHere(v, upsertJump); 17827f5f306bSdrh }else{ 1783ec4ccdbcSdrh addrUniqueOk = sqlite3VdbeMakeLabel(pParse); 17847f5f306bSdrh } 178584304506Sdrh if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){ 178684304506Sdrh sqlite3TableAffinity(v, pTab, regNewData+1); 178784304506Sdrh bAffinityDone = 1; 178884304506Sdrh } 17897f5f306bSdrh VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName)); 17906934fc7bSdrh iThisCur = iIdxCur+ix; 17917f5f306bSdrh 1792b2fe7d8cSdrh 1793f8ffb278Sdrh /* Skip partial indices for which the WHERE clause is not true */ 1794b2b9d3d7Sdrh if( pIdx->pPartIdxWhere ){ 179526198bb4Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); 17966e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 179772bc8208Sdrh sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, 1798b2b9d3d7Sdrh SQLITE_JUMPIFNULL); 17996e97f8ecSdrh pParse->iSelfTab = 0; 1800b2b9d3d7Sdrh } 1801b2b9d3d7Sdrh 18026934fc7bSdrh /* Create a record for this index entry as it should appear after 1803f8ffb278Sdrh ** the insert or update. Store that record in the aRegIdx[ix] register 1804f8ffb278Sdrh */ 1805bf2f5739Sdrh regIdx = aRegIdx[ix]+1; 18069cfcf5d4Sdrh for(i=0; i<pIdx->nColumn; i++){ 18076934fc7bSdrh int iField = pIdx->aiColumn[i]; 1808f82b9afcSdrh int x; 18094b92f98cSdrh if( iField==XN_EXPR ){ 18106e97f8ecSdrh pParse->iSelfTab = -(regNewData+1); 18111c75c9d7Sdrh sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); 18126e97f8ecSdrh pParse->iSelfTab = 0; 18131f9ca2c8Sdrh VdbeComment((v, "%s column %d", pIdx->zName, i)); 1814463e76ffSdrh }else if( iField==XN_ROWID || iField==pTab->iPKey ){ 1815f82b9afcSdrh x = regNewData; 1816463e76ffSdrh sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i); 1817463e76ffSdrh VdbeComment((v, "rowid")); 1818463e76ffSdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1819463e76ffSdrh }else if( pTab->aCol[iField].colFlags & COLFLAG_VIRTUAL ){ 1820463e76ffSdrh pParse->iSelfTab = -(regNewData+1); 1821463e76ffSdrh sqlite3ExprCodeCopy(pParse, pTab->aCol[iField].pDflt, regIdx+i); 1822463e76ffSdrh pParse->iSelfTab = 0; 1823463e76ffSdrh VdbeComment((v, "%s column %d", pIdx->zName, i)); 1824463e76ffSdrh #endif 18259cfcf5d4Sdrh }else{ 1826c5f808d8Sdrh testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField ); 1827b9bcf7caSdrh x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1; 1828463e76ffSdrh sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i); 1829463e76ffSdrh VdbeComment((v, "%s", pTab->aCol[iField].zName)); 18309cfcf5d4Sdrh } 18311f9ca2c8Sdrh } 183226198bb4Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); 183326198bb4Sdrh VdbeComment((v, "for %s", pIdx->zName)); 18347e4acf7bSdrh #ifdef SQLITE_ENABLE_NULL_TRIM 18359df385ecSdrh if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){ 18369df385ecSdrh sqlite3SetMakeRecordP5(v, pIdx->pTable); 18379df385ecSdrh } 18387e4acf7bSdrh #endif 1839b2fe7d8cSdrh 1840f8ffb278Sdrh /* In an UPDATE operation, if this index is the PRIMARY KEY index 1841f8ffb278Sdrh ** of a WITHOUT ROWID table and there has been no change the 1842f8ffb278Sdrh ** primary key, then no collision is possible. The collision detection 1843f8ffb278Sdrh ** logic below can all be skipped. */ 184400012df4Sdrh if( isUpdate && pPk==pIdx && pkChng==0 ){ 1845da475b8dSdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1846da475b8dSdrh continue; 1847da475b8dSdrh } 1848f8ffb278Sdrh 18496934fc7bSdrh /* Find out what action to take in case there is a uniqueness conflict */ 18509cfcf5d4Sdrh onError = pIdx->onError; 1851de630353Sdanielk1977 if( onError==OE_None ){ 185211e85273Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1853de630353Sdanielk1977 continue; /* pIdx is not a UNIQUE index */ 1854de630353Sdanielk1977 } 18559cfcf5d4Sdrh if( overrideError!=OE_Default ){ 18569cfcf5d4Sdrh onError = overrideError; 1857a996e477Sdrh }else if( onError==OE_Default ){ 1858a996e477Sdrh onError = OE_Abort; 18599cfcf5d4Sdrh } 18605383ae5cSdrh 1861c8a0c90bSdrh /* Figure out if the upsert clause applies to this index */ 1862096fd476Sdrh if( pUpIdx==pIdx ){ 1863c8a0c90bSdrh if( pUpsert->pUpsertSet==0 ){ 1864c8a0c90bSdrh onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */ 1865c8a0c90bSdrh }else{ 1866c8a0c90bSdrh onError = OE_Update; /* DO UPDATE */ 1867c8a0c90bSdrh } 1868c8a0c90bSdrh } 1869c8a0c90bSdrh 1870801f55d8Sdrh /* Collision detection may be omitted if all of the following are true: 1871801f55d8Sdrh ** (1) The conflict resolution algorithm is REPLACE 1872801f55d8Sdrh ** (2) The table is a WITHOUT ROWID table 1873801f55d8Sdrh ** (3) There are no secondary indexes on the table 1874801f55d8Sdrh ** (4) No delete triggers need to be fired if there is a conflict 1875f9a12a10Sdan ** (5) No FK constraint counters need to be updated if a conflict occurs. 1876418454c6Sdan ** 1877418454c6Sdan ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row 1878418454c6Sdan ** must be explicitly deleted in order to ensure any pre-update hook 1879418454c6Sdan ** is invoked. */ 1880418454c6Sdan #ifndef SQLITE_ENABLE_PREUPDATE_HOOK 1881801f55d8Sdrh if( (ix==0 && pIdx->pNext==0) /* Condition 3 */ 1882801f55d8Sdrh && pPk==pIdx /* Condition 2 */ 1883801f55d8Sdrh && onError==OE_Replace /* Condition 1 */ 1884801f55d8Sdrh && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */ 1885801f55d8Sdrh 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0)) 1886f9a12a10Sdan && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */ 1887f9a12a10Sdan (0==pTab->pFKey && 0==sqlite3FkReferences(pTab))) 18884e1f0efbSdan ){ 1889c6c9e158Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 1890c6c9e158Sdrh continue; 1891c6c9e158Sdrh } 1892418454c6Sdan #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */ 1893c6c9e158Sdrh 1894b2fe7d8cSdrh /* Check to see if the new index entry will be unique */ 18954031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 189626198bb4Sdrh sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, 1897688852abSdrh regIdx, pIdx->nKeyCol); VdbeCoverage(v); 1898f8ffb278Sdrh 1899f8ffb278Sdrh /* Generate code to handle collisions */ 1900392ee21dSdrh regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); 190146d03fcbSdrh if( isUpdate || onError==OE_Replace ){ 190211e85273Sdrh if( HasRowid(pTab) ){ 19036934fc7bSdrh sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); 19040978d4ffSdrh /* Conflict only if the rowid of the existing index entry 19050978d4ffSdrh ** is different from old-rowid */ 1906f8ffb278Sdrh if( isUpdate ){ 19076934fc7bSdrh sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); 19083d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 1909688852abSdrh VdbeCoverage(v); 1910f8ffb278Sdrh } 191126198bb4Sdrh }else{ 1912ccc79f02Sdrh int x; 191326198bb4Sdrh /* Extract the PRIMARY KEY from the end of the index entry and 1914da475b8dSdrh ** store it in registers regR..regR+nPk-1 */ 1915a021f121Sdrh if( pIdx!=pPk ){ 191626198bb4Sdrh for(i=0; i<pPk->nKeyCol; i++){ 19174b92f98cSdrh assert( pPk->aiColumn[i]>=0 ); 1918b9bcf7caSdrh x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]); 191926198bb4Sdrh sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); 192026198bb4Sdrh VdbeComment((v, "%s.%s", pTab->zName, 192126198bb4Sdrh pTab->aCol[pPk->aiColumn[i]].zName)); 192226198bb4Sdrh } 1923da475b8dSdrh } 1924da475b8dSdrh if( isUpdate ){ 1925e83267daSdan /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 1926e83267daSdan ** table, only conflict if the new PRIMARY KEY values are actually 1927e83267daSdan ** different from the old. 1928e83267daSdan ** 1929e83267daSdan ** For a UNIQUE index, only conflict if the PRIMARY KEY values 1930e83267daSdan ** of the matched index row are different from the original PRIMARY 1931e83267daSdan ** KEY values of this row before the update. */ 1932e83267daSdan int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; 1933e83267daSdan int op = OP_Ne; 193448dd1d8eSdrh int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); 1935e83267daSdan 1936e83267daSdan for(i=0; i<pPk->nKeyCol; i++){ 1937e83267daSdan char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); 1938ccc79f02Sdrh x = pPk->aiColumn[i]; 19394b92f98cSdrh assert( x>=0 ); 1940e83267daSdan if( i==(pPk->nKeyCol-1) ){ 1941e83267daSdan addrJump = addrUniqueOk; 1942e83267daSdan op = OP_Eq; 194311e85273Sdrh } 1944e83267daSdan sqlite3VdbeAddOp4(v, op, 1945e83267daSdan regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ 1946e83267daSdan ); 19473d77dee9Sdrh sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); 19483d77dee9Sdrh VdbeCoverageIf(v, op==OP_Eq); 19493d77dee9Sdrh VdbeCoverageIf(v, op==OP_Ne); 1950da475b8dSdrh } 195111e85273Sdrh } 195226198bb4Sdrh } 195346d03fcbSdrh } 1954b2fe7d8cSdrh 1955b2fe7d8cSdrh /* Generate code that executes if the new index entry is not unique */ 1956b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 19579eddacadSdrh || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update ); 19589cfcf5d4Sdrh switch( onError ){ 19591c92853dSdrh case OE_Rollback: 19601c92853dSdrh case OE_Abort: 19611c92853dSdrh case OE_Fail: { 19629916048bSdrh testcase( onError==OE_Rollback ); 19639916048bSdrh testcase( onError==OE_Abort ); 19649916048bSdrh testcase( onError==OE_Fail ); 1965f9c8ce3cSdrh sqlite3UniqueConstraint(pParse, onError, pIdx); 19669cfcf5d4Sdrh break; 19679cfcf5d4Sdrh } 19689eddacadSdrh #ifndef SQLITE_OMIT_UPSERT 19699eddacadSdrh case OE_Update: { 19702cc00423Sdan sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix); 19719eddacadSdrh /* Fall through */ 19729eddacadSdrh } 19739eddacadSdrh #endif 19749cfcf5d4Sdrh case OE_Ignore: { 19759916048bSdrh testcase( onError==OE_Ignore ); 1976076e85f5Sdrh sqlite3VdbeGoto(v, ignoreDest); 19779cfcf5d4Sdrh break; 19789cfcf5d4Sdrh } 1979098d1684Sdrh default: { 19802283d46cSdan Trigger *pTrigger = 0; 19812da8d6feSdrh int bRetryConstraintCheck = 0; 1982098d1684Sdrh assert( onError==OE_Replace ); 19832938f924Sdrh if( db->flags&SQLITE_RecTriggers ){ 19842283d46cSdan pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); 19852283d46cSdan } 1986fecfb318Sdan if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ 1987fecfb318Sdan sqlite3MultiWrite(pParse); 19882da8d6feSdrh bRetryConstraintCheck = 1; 1989fecfb318Sdan } 199026198bb4Sdrh sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, 1991b0264eecSdrh regR, nPkField, 0, OE_Replace, 199268116939Sdrh (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur); 19932da8d6feSdrh if( bRetryConstraintCheck ){ 19942da8d6feSdrh sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, 19952da8d6feSdrh regIdx, pIdx->nKeyCol); VdbeCoverage(v); 19962da8d6feSdrh sqlite3UniqueConstraint(pParse, OE_Abort, pIdx); 19972da8d6feSdrh } 19980ca3e24bSdrh seenReplace = 1; 19999cfcf5d4Sdrh break; 20009cfcf5d4Sdrh } 20019cfcf5d4Sdrh } 20027f5f306bSdrh if( pUpIdx==pIdx ){ 200384304506Sdrh sqlite3VdbeGoto(v, upsertJump+1); 20047f5f306bSdrh sqlite3VdbeJumpHere(v, upsertBypass); 20057f5f306bSdrh }else{ 200611e85273Sdrh sqlite3VdbeResolveLabel(v, addrUniqueOk); 20077f5f306bSdrh } 2008392ee21dSdrh if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); 20099cfcf5d4Sdrh } 201084304506Sdrh 201184304506Sdrh /* If the IPK constraint is a REPLACE, run it last */ 201284304506Sdrh if( ipkTop ){ 20136214d939Sdrh sqlite3VdbeGoto(v, ipkTop); 201484304506Sdrh VdbeComment((v, "Do IPK REPLACE")); 201584304506Sdrh sqlite3VdbeJumpHere(v, ipkBottom); 201684304506Sdrh } 2017de630353Sdanielk1977 2018a7c3b93fSdrh /* Generate the table record */ 2019a7c3b93fSdrh if( HasRowid(pTab) ){ 2020a7c3b93fSdrh int regRec = aRegIdx[ix]; 20210b0b3a95Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec); 2022a7c3b93fSdrh sqlite3SetMakeRecordP5(v, pTab); 2023a7c3b93fSdrh if( !bAffinityDone ){ 2024a7c3b93fSdrh sqlite3TableAffinity(v, pTab, 0); 2025a7c3b93fSdrh } 2026a7c3b93fSdrh } 2027a7c3b93fSdrh 2028de630353Sdanielk1977 *pbMayReplace = seenReplace; 2029ce60aa46Sdrh VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); 20309cfcf5d4Sdrh } 20310ca3e24bSdrh 2032d447dcedSdrh #ifdef SQLITE_ENABLE_NULL_TRIM 20330ca3e24bSdrh /* 2034585ce192Sdrh ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord) 2035585ce192Sdrh ** to be the number of columns in table pTab that must not be NULL-trimmed. 2036585ce192Sdrh ** 2037585ce192Sdrh ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero. 2038585ce192Sdrh */ 2039585ce192Sdrh void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){ 2040585ce192Sdrh u16 i; 2041585ce192Sdrh 2042585ce192Sdrh /* Records with omitted columns are only allowed for schema format 2043585ce192Sdrh ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */ 2044585ce192Sdrh if( pTab->pSchema->file_format<2 ) return; 2045585ce192Sdrh 20467e4acf7bSdrh for(i=pTab->nCol-1; i>0; i--){ 20477e4acf7bSdrh if( pTab->aCol[i].pDflt!=0 ) break; 20487e4acf7bSdrh if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break; 20497e4acf7bSdrh } 20507e4acf7bSdrh sqlite3VdbeChangeP5(v, i+1); 2051585ce192Sdrh } 2052d447dcedSdrh #endif 2053585ce192Sdrh 20540ca3e24bSdrh /* 20550ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation 20564adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 20576934fc7bSdrh ** A consecutive range of registers starting at regNewData contains the 205804adf416Sdrh ** rowid and the content to be inserted. 20590ca3e24bSdrh ** 2060b419a926Sdrh ** The arguments to this routine should be the same as the first six 20614adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks. 20620ca3e24bSdrh */ 20634adee20fSdanielk1977 void sqlite3CompleteInsertion( 20640ca3e24bSdrh Parse *pParse, /* The parser context */ 20650ca3e24bSdrh Table *pTab, /* the table into which we are inserting */ 206626198bb4Sdrh int iDataCur, /* Cursor of the canonical data source */ 206726198bb4Sdrh int iIdxCur, /* First index cursor */ 20686934fc7bSdrh int regNewData, /* Range of content */ 2069aa9b8963Sdrh int *aRegIdx, /* Register used by each index. 0 for unused indices */ 2070f91c1318Sdan int update_flags, /* True for UPDATE, False for INSERT */ 2071de630353Sdanielk1977 int appendBias, /* True if this is likely to be an append */ 2072de630353Sdanielk1977 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ 20730ca3e24bSdrh ){ 20746934fc7bSdrh Vdbe *v; /* Prepared statements under construction */ 20756934fc7bSdrh Index *pIdx; /* An index being inserted or updated */ 20766934fc7bSdrh u8 pik_flags; /* flag values passed to the btree insert */ 20776934fc7bSdrh int i; /* Loop counter */ 20780ca3e24bSdrh 2079f91c1318Sdan assert( update_flags==0 2080f91c1318Sdan || update_flags==OPFLAG_ISUPDATE 2081f91c1318Sdan || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION) 2082f91c1318Sdan ); 2083f91c1318Sdan 20844adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 20850ca3e24bSdrh assert( v!=0 ); 2086417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 2087b2b9d3d7Sdrh for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 2088aa9b8963Sdrh if( aRegIdx[i]==0 ) continue; 2089b2b9d3d7Sdrh if( pIdx->pPartIdxWhere ){ 2090b2b9d3d7Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); 2091688852abSdrh VdbeCoverage(v); 2092b2b9d3d7Sdrh } 2093cb9a3643Sdan pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0); 209448dd1d8eSdrh if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 20954308e348Sdrh assert( pParse->nested==0 ); 20966546af14Sdrh pik_flags |= OPFLAG_NCHANGE; 2097f91c1318Sdan pik_flags |= (update_flags & OPFLAG_SAVEPOSITION); 2098cb9a3643Sdan #ifdef SQLITE_ENABLE_PREUPDATE_HOOK 2099cb9a3643Sdan if( update_flags==0 ){ 210050ef6716Sdrh int r = sqlite3GetTempReg(pParse); 210150ef6716Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, r); 210250ef6716Sdrh sqlite3VdbeAddOp4(v, OP_Insert, 210350ef6716Sdrh iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE 2104cb9a3643Sdan ); 2105cb9a3643Sdan sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP); 210650ef6716Sdrh sqlite3ReleaseTempReg(pParse, r); 2107de630353Sdanielk1977 } 2108cb9a3643Sdan #endif 2109cb9a3643Sdan } 2110cb9a3643Sdan sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i], 2111cb9a3643Sdan aRegIdx[i]+1, 2112cb9a3643Sdan pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn); 21139b34abeeSdrh sqlite3VdbeChangeP5(v, pik_flags); 21140ca3e24bSdrh } 2115ec95c441Sdrh if( !HasRowid(pTab) ) return; 21164794f735Sdrh if( pParse->nested ){ 21174794f735Sdrh pik_flags = 0; 21184794f735Sdrh }else{ 211994eb6a14Sdanielk1977 pik_flags = OPFLAG_NCHANGE; 2120f91c1318Sdan pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID); 21214794f735Sdrh } 2122e4d90813Sdrh if( appendBias ){ 2123e4d90813Sdrh pik_flags |= OPFLAG_APPEND; 2124e4d90813Sdrh } 2125de630353Sdanielk1977 if( useSeekResult ){ 2126de630353Sdanielk1977 pik_flags |= OPFLAG_USESEEKRESULT; 2127de630353Sdanielk1977 } 2128a7c3b93fSdrh sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData); 212994eb6a14Sdanielk1977 if( !pParse->nested ){ 2130f14b7fb7Sdrh sqlite3VdbeAppendP4(v, pTab, P4_TABLE); 213194eb6a14Sdanielk1977 } 2132b7654111Sdrh sqlite3VdbeChangeP5(v, pik_flags); 21330ca3e24bSdrh } 2134cd44690aSdrh 2135cd44690aSdrh /* 213626198bb4Sdrh ** Allocate cursors for the pTab table and all its indices and generate 213726198bb4Sdrh ** code to open and initialized those cursors. 2138aa9b8963Sdrh ** 213926198bb4Sdrh ** The cursor for the object that contains the complete data (normally 214026198bb4Sdrh ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT 214126198bb4Sdrh ** ROWID table) is returned in *piDataCur. The first index cursor is 214226198bb4Sdrh ** returned in *piIdxCur. The number of indices is returned. 214326198bb4Sdrh ** 214426198bb4Sdrh ** Use iBase as the first cursor (either the *piDataCur for rowid tables 214526198bb4Sdrh ** or the first index for WITHOUT ROWID tables) if it is non-negative. 214626198bb4Sdrh ** If iBase is negative, then allocate the next available cursor. 214726198bb4Sdrh ** 214826198bb4Sdrh ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. 214926198bb4Sdrh ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range 215026198bb4Sdrh ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the 215126198bb4Sdrh ** pTab->pIndex list. 2152b6b4b79fSdrh ** 2153b6b4b79fSdrh ** If pTab is a virtual table, then this routine is a no-op and the 2154b6b4b79fSdrh ** *piDataCur and *piIdxCur values are left uninitialized. 2155cd44690aSdrh */ 2156aa9b8963Sdrh int sqlite3OpenTableAndIndices( 2157290c1948Sdrh Parse *pParse, /* Parsing context */ 2158290c1948Sdrh Table *pTab, /* Table to be opened */ 215926198bb4Sdrh int op, /* OP_OpenRead or OP_OpenWrite */ 2160b89aeb6aSdrh u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */ 216126198bb4Sdrh int iBase, /* Use this for the table cursor, if there is one */ 21626a53499aSdrh u8 *aToOpen, /* If not NULL: boolean for each table and index */ 216326198bb4Sdrh int *piDataCur, /* Write the database source cursor number here */ 216426198bb4Sdrh int *piIdxCur /* Write the first index cursor number here */ 2165290c1948Sdrh ){ 2166cd44690aSdrh int i; 21674cbdda9eSdrh int iDb; 21686a53499aSdrh int iDataCur; 2169cd44690aSdrh Index *pIdx; 21704cbdda9eSdrh Vdbe *v; 21714cbdda9eSdrh 217226198bb4Sdrh assert( op==OP_OpenRead || op==OP_OpenWrite ); 2173fd261ec6Sdan assert( op==OP_OpenWrite || p5==0 ); 217426198bb4Sdrh if( IsVirtual(pTab) ){ 2175b6b4b79fSdrh /* This routine is a no-op for virtual tables. Leave the output 2176b6b4b79fSdrh ** variables *piDataCur and *piIdxCur uninitialized so that valgrind 2177b6b4b79fSdrh ** can detect if they are used by mistake in the caller. */ 217826198bb4Sdrh return 0; 217926198bb4Sdrh } 21804cbdda9eSdrh iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 21814cbdda9eSdrh v = sqlite3GetVdbe(pParse); 2182cd44690aSdrh assert( v!=0 ); 218326198bb4Sdrh if( iBase<0 ) iBase = pParse->nTab; 21846a53499aSdrh iDataCur = iBase++; 21856a53499aSdrh if( piDataCur ) *piDataCur = iDataCur; 21866a53499aSdrh if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ 21876a53499aSdrh sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); 21886fbe41acSdrh }else{ 218926198bb4Sdrh sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); 21906fbe41acSdrh } 21916a53499aSdrh if( piIdxCur ) *piIdxCur = iBase; 219226198bb4Sdrh for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 219326198bb4Sdrh int iIdxCur = iBase++; 2194da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 219561441c34Sdan if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ 219661441c34Sdan if( piDataCur ) *piDataCur = iIdxCur; 219761441c34Sdan p5 = 0; 219861441c34Sdan } 21996a53499aSdrh if( aToOpen==0 || aToOpen[i+1] ){ 22002ec2fb22Sdrh sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); 22012ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 2202b89aeb6aSdrh sqlite3VdbeChangeP5(v, p5); 220361441c34Sdan VdbeComment((v, "%s", pIdx->zName)); 2204b89aeb6aSdrh } 22056a53499aSdrh } 220626198bb4Sdrh if( iBase>pParse->nTab ) pParse->nTab = iBase; 220726198bb4Sdrh return i; 2208cd44690aSdrh } 22099d9cf229Sdrh 221091c58e23Sdrh 221191c58e23Sdrh #ifdef SQLITE_TEST 221291c58e23Sdrh /* 221391c58e23Sdrh ** The following global variable is incremented whenever the 221491c58e23Sdrh ** transfer optimization is used. This is used for testing 221591c58e23Sdrh ** purposes only - to make sure the transfer optimization really 221660ec914cSpeter.d.reid ** is happening when it is supposed to. 221791c58e23Sdrh */ 221891c58e23Sdrh int sqlite3_xferopt_count; 221991c58e23Sdrh #endif /* SQLITE_TEST */ 222091c58e23Sdrh 222191c58e23Sdrh 22229d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 22239d9cf229Sdrh /* 22249d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data 22259d9cf229Sdrh ** for index pDest in an insert transfer optimization. The rules 22269d9cf229Sdrh ** for a compatible index: 22279d9cf229Sdrh ** 22289d9cf229Sdrh ** * The index is over the same set of columns 22299d9cf229Sdrh ** * The same DESC and ASC markings occurs on all columns 22309d9cf229Sdrh ** * The same onError processing (OE_Abort, OE_Ignore, etc) 22319d9cf229Sdrh ** * The same collating sequence on each column 2232b2b9d3d7Sdrh ** * The index has the exact same WHERE clause 22339d9cf229Sdrh */ 22349d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 22359d9cf229Sdrh int i; 22369d9cf229Sdrh assert( pDest && pSrc ); 22379d9cf229Sdrh assert( pDest->pTable!=pSrc->pTable ); 2238bbbdc83bSdrh if( pDest->nKeyCol!=pSrc->nKeyCol ){ 22399d9cf229Sdrh return 0; /* Different number of columns */ 22409d9cf229Sdrh } 22419d9cf229Sdrh if( pDest->onError!=pSrc->onError ){ 22429d9cf229Sdrh return 0; /* Different conflict resolution strategies */ 22439d9cf229Sdrh } 2244bbbdc83bSdrh for(i=0; i<pSrc->nKeyCol; i++){ 22459d9cf229Sdrh if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 22469d9cf229Sdrh return 0; /* Different columns indexed */ 22479d9cf229Sdrh } 22484b92f98cSdrh if( pSrc->aiColumn[i]==XN_EXPR ){ 22491f9ca2c8Sdrh assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); 22505aa550cfSdan if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr, 22511f9ca2c8Sdrh pDest->aColExpr->a[i].pExpr, -1)!=0 ){ 22521f9ca2c8Sdrh return 0; /* Different expressions in the index */ 22531f9ca2c8Sdrh } 22541f9ca2c8Sdrh } 22559d9cf229Sdrh if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 22569d9cf229Sdrh return 0; /* Different sort orders */ 22579d9cf229Sdrh } 22580472af91Sdrh if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){ 225960a713c6Sdrh return 0; /* Different collating sequences */ 22609d9cf229Sdrh } 22619d9cf229Sdrh } 22625aa550cfSdan if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ 2263b2b9d3d7Sdrh return 0; /* Different WHERE clauses */ 2264b2b9d3d7Sdrh } 22659d9cf229Sdrh 22669d9cf229Sdrh /* If no test above fails then the indices must be compatible */ 22679d9cf229Sdrh return 1; 22689d9cf229Sdrh } 22699d9cf229Sdrh 22709d9cf229Sdrh /* 22719d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form 22729d9cf229Sdrh ** 22739d9cf229Sdrh ** INSERT INTO tab1 SELECT * FROM tab2; 22749d9cf229Sdrh ** 2275ccdf1baeSdrh ** The xfer optimization transfers raw records from tab2 over to tab1. 227660ec914cSpeter.d.reid ** Columns are not decoded and reassembled, which greatly improves 2277ccdf1baeSdrh ** performance. Raw index records are transferred in the same way. 22789d9cf229Sdrh ** 2279ccdf1baeSdrh ** The xfer optimization is only attempted if tab1 and tab2 are compatible. 2280ccdf1baeSdrh ** There are lots of rules for determining compatibility - see comments 2281ccdf1baeSdrh ** embedded in the code for details. 22829d9cf229Sdrh ** 2283ccdf1baeSdrh ** This routine returns TRUE if the optimization is guaranteed to be used. 2284ccdf1baeSdrh ** Sometimes the xfer optimization will only work if the destination table 2285ccdf1baeSdrh ** is empty - a factor that can only be determined at run-time. In that 2286ccdf1baeSdrh ** case, this routine generates code for the xfer optimization but also 2287ccdf1baeSdrh ** does a test to see if the destination table is empty and jumps over the 2288ccdf1baeSdrh ** xfer optimization code if the test fails. In that case, this routine 2289ccdf1baeSdrh ** returns FALSE so that the caller will know to go ahead and generate 2290ccdf1baeSdrh ** an unoptimized transfer. This routine also returns FALSE if there 2291ccdf1baeSdrh ** is no chance that the xfer optimization can be applied. 22929d9cf229Sdrh ** 2293ccdf1baeSdrh ** This optimization is particularly useful at making VACUUM run faster. 22949d9cf229Sdrh */ 22959d9cf229Sdrh static int xferOptimization( 22969d9cf229Sdrh Parse *pParse, /* Parser context */ 22979d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 22989d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 22999d9cf229Sdrh int onError, /* How to handle constraint errors */ 23009d9cf229Sdrh int iDbDest /* The database of pDest */ 23019d9cf229Sdrh ){ 2302e34162b1Sdan sqlite3 *db = pParse->db; 23039d9cf229Sdrh ExprList *pEList; /* The result set of the SELECT */ 23049d9cf229Sdrh Table *pSrc; /* The table in the FROM clause of SELECT */ 23059d9cf229Sdrh Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 23069d9cf229Sdrh struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 23079d9cf229Sdrh int i; /* Loop counter */ 23089d9cf229Sdrh int iDbSrc; /* The database of pSrc */ 23099d9cf229Sdrh int iSrc, iDest; /* Cursors from source and destination */ 23109d9cf229Sdrh int addr1, addr2; /* Loop addresses */ 2311da475b8dSdrh int emptyDestTest = 0; /* Address of test for empty pDest */ 2312da475b8dSdrh int emptySrcTest = 0; /* Address of test for empty pSrc */ 23139d9cf229Sdrh Vdbe *v; /* The VDBE we are building */ 23146a288a33Sdrh int regAutoinc; /* Memory register used by AUTOINC */ 2315f33c9fadSdrh int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 2316b7654111Sdrh int regData, regRowid; /* Registers holding data and rowid */ 23179d9cf229Sdrh 23189d9cf229Sdrh if( pSelect==0 ){ 23199d9cf229Sdrh return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 23209d9cf229Sdrh } 2321ebbf08a0Sdan if( pParse->pWith || pSelect->pWith ){ 2322ebbf08a0Sdan /* Do not attempt to process this query if there are an WITH clauses 2323ebbf08a0Sdan ** attached to it. Proceeding may generate a false "no such table: xxx" 2324ebbf08a0Sdan ** error if pSelect reads from a CTE named "xxx". */ 2325ebbf08a0Sdan return 0; 2326ebbf08a0Sdan } 23272f886d1dSdanielk1977 if( sqlite3TriggerList(pParse, pDest) ){ 23289d9cf229Sdrh return 0; /* tab1 must not have triggers */ 23299d9cf229Sdrh } 23309d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 233144266ec6Sdrh if( IsVirtual(pDest) ){ 23329d9cf229Sdrh return 0; /* tab1 must not be a virtual table */ 23339d9cf229Sdrh } 23349d9cf229Sdrh #endif 23359d9cf229Sdrh if( onError==OE_Default ){ 2336e7224a01Sdrh if( pDest->iPKey>=0 ) onError = pDest->keyConf; 2337e7224a01Sdrh if( onError==OE_Default ) onError = OE_Abort; 23389d9cf229Sdrh } 23395ce240a6Sdanielk1977 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 23409d9cf229Sdrh if( pSelect->pSrc->nSrc!=1 ){ 23419d9cf229Sdrh return 0; /* FROM clause must have exactly one term */ 23429d9cf229Sdrh } 23439d9cf229Sdrh if( pSelect->pSrc->a[0].pSelect ){ 23449d9cf229Sdrh return 0; /* FROM clause cannot contain a subquery */ 23459d9cf229Sdrh } 23469d9cf229Sdrh if( pSelect->pWhere ){ 23479d9cf229Sdrh return 0; /* SELECT may not have a WHERE clause */ 23489d9cf229Sdrh } 23499d9cf229Sdrh if( pSelect->pOrderBy ){ 23509d9cf229Sdrh return 0; /* SELECT may not have an ORDER BY clause */ 23519d9cf229Sdrh } 23528103b7d2Sdrh /* Do not need to test for a HAVING clause. If HAVING is present but 23538103b7d2Sdrh ** there is no ORDER BY, we will get an error. */ 23549d9cf229Sdrh if( pSelect->pGroupBy ){ 23559d9cf229Sdrh return 0; /* SELECT may not have a GROUP BY clause */ 23569d9cf229Sdrh } 23579d9cf229Sdrh if( pSelect->pLimit ){ 23589d9cf229Sdrh return 0; /* SELECT may not have a LIMIT clause */ 23599d9cf229Sdrh } 23609d9cf229Sdrh if( pSelect->pPrior ){ 23619d9cf229Sdrh return 0; /* SELECT may not be a compound query */ 23629d9cf229Sdrh } 23637d10d5a6Sdrh if( pSelect->selFlags & SF_Distinct ){ 23649d9cf229Sdrh return 0; /* SELECT may not be DISTINCT */ 23659d9cf229Sdrh } 23669d9cf229Sdrh pEList = pSelect->pEList; 23679d9cf229Sdrh assert( pEList!=0 ); 23689d9cf229Sdrh if( pEList->nExpr!=1 ){ 23699d9cf229Sdrh return 0; /* The result set must have exactly one column */ 23709d9cf229Sdrh } 23719d9cf229Sdrh assert( pEList->a[0].pExpr ); 23721a1d3cd2Sdrh if( pEList->a[0].pExpr->op!=TK_ASTERISK ){ 23739d9cf229Sdrh return 0; /* The result set must be the special operator "*" */ 23749d9cf229Sdrh } 23759d9cf229Sdrh 23769d9cf229Sdrh /* At this point we have established that the statement is of the 23779d9cf229Sdrh ** correct syntactic form to participate in this optimization. Now 23789d9cf229Sdrh ** we have to check the semantics. 23799d9cf229Sdrh */ 23809d9cf229Sdrh pItem = pSelect->pSrc->a; 238141fb5cd1Sdan pSrc = sqlite3LocateTableItem(pParse, 0, pItem); 23829d9cf229Sdrh if( pSrc==0 ){ 23839d9cf229Sdrh return 0; /* FROM clause does not contain a real table */ 23849d9cf229Sdrh } 238521908b21Sdrh if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){ 238621908b21Sdrh testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */ 23879d9cf229Sdrh return 0; /* tab1 and tab2 may not be the same table */ 23889d9cf229Sdrh } 238955548273Sdrh if( HasRowid(pDest)!=HasRowid(pSrc) ){ 239055548273Sdrh return 0; /* source and destination must both be WITHOUT ROWID or not */ 239155548273Sdrh } 23929d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 239344266ec6Sdrh if( IsVirtual(pSrc) ){ 23949d9cf229Sdrh return 0; /* tab2 must not be a virtual table */ 23959d9cf229Sdrh } 23969d9cf229Sdrh #endif 23979d9cf229Sdrh if( pSrc->pSelect ){ 23989d9cf229Sdrh return 0; /* tab2 may not be a view */ 23999d9cf229Sdrh } 24009d9cf229Sdrh if( pDest->nCol!=pSrc->nCol ){ 24019d9cf229Sdrh return 0; /* Number of columns must be the same in tab1 and tab2 */ 24029d9cf229Sdrh } 24039d9cf229Sdrh if( pDest->iPKey!=pSrc->iPKey ){ 24049d9cf229Sdrh return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 24059d9cf229Sdrh } 24069d9cf229Sdrh for(i=0; i<pDest->nCol; i++){ 24079940e2aaSdan Column *pDestCol = &pDest->aCol[i]; 24089940e2aaSdan Column *pSrcCol = &pSrc->aCol[i]; 2409ba68f8f3Sdan #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS 24108257aa8dSdrh if( (db->mDbFlags & DBFLAG_Vacuum)==0 2411aaea3143Sdan && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN 2412aaea3143Sdan ){ 2413ba68f8f3Sdan return 0; /* Neither table may have __hidden__ columns */ 2414ba68f8f3Sdan } 2415ba68f8f3Sdan #endif 2416ae3977a8Sdrh if( (pDestCol->colFlags & COLFLAG_GENERATED) != 2417ae3977a8Sdrh (pSrcCol->colFlags & COLFLAG_GENERATED) ){ 2418ae3977a8Sdrh return 0; /* Both columns have the same generated type */ 2419ae3977a8Sdrh } 24209940e2aaSdan if( pDestCol->affinity!=pSrcCol->affinity ){ 24219d9cf229Sdrh return 0; /* Affinity must be the same on all columns */ 24229d9cf229Sdrh } 24230472af91Sdrh if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){ 24249d9cf229Sdrh return 0; /* Collating sequence must be the same on all columns */ 24259d9cf229Sdrh } 24269940e2aaSdan if( pDestCol->notNull && !pSrcCol->notNull ){ 24279d9cf229Sdrh return 0; /* tab2 must be NOT NULL if tab1 is */ 24289d9cf229Sdrh } 2429453e0261Sdrh /* Default values for second and subsequent columns need to match. */ 2430ae3977a8Sdrh if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){ 243194fa9c41Sdrh assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN ); 243294fa9c41Sdrh assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN ); 243394fa9c41Sdrh if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) 243494fa9c41Sdrh || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken, 243594fa9c41Sdrh pSrcCol->pDflt->u.zToken)!=0) 24369940e2aaSdan ){ 24379940e2aaSdan return 0; /* Default values must be the same for all columns */ 24389940e2aaSdan } 24399d9cf229Sdrh } 2440ae3977a8Sdrh /* Generator expressions for generated columns must match */ 2441ae3977a8Sdrh if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){ 2442ae3977a8Sdrh if( sqlite3ExprCompare(0, pSrcCol->pDflt, pDestCol->pDflt, -1)!=0 ){ 2443427b96aeSdrh testcase( pDestCol->colflags & COLFLAG_VIRTUAL ); 2444427b96aeSdrh testcase( pDestCol->colflags & COLFLAG_STORED ); 2445ae3977a8Sdrh return 0; /* Different generator expressions */ 2446ae3977a8Sdrh } 2447ae3977a8Sdrh } 244894fa9c41Sdrh } 24499d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 24505f1d1d9cSdrh if( IsUniqueIndex(pDestIdx) ){ 2451f33c9fadSdrh destHasUniqueIdx = 1; 2452f33c9fadSdrh } 24539d9cf229Sdrh for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 24549d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 24559d9cf229Sdrh } 24569d9cf229Sdrh if( pSrcIdx==0 ){ 24579d9cf229Sdrh return 0; /* pDestIdx has no corresponding index in pSrc */ 24589d9cf229Sdrh } 2459e3bd232eSdrh if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema 2460e3bd232eSdrh && sqlite3FaultSim(411)==SQLITE_OK ){ 2461e3bd232eSdrh /* The sqlite3FaultSim() call allows this corruption test to be 2462e3bd232eSdrh ** bypassed during testing, in order to exercise other corruption tests 2463e3bd232eSdrh ** further downstream. */ 246486223e8dSdrh return 0; /* Corrupt schema - two indexes on the same btree */ 246586223e8dSdrh } 24669d9cf229Sdrh } 24677fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK 2468619a1305Sdrh if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ 24698103b7d2Sdrh return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 24708103b7d2Sdrh } 24717fc2f41bSdrh #endif 2472713de341Sdrh #ifndef SQLITE_OMIT_FOREIGN_KEY 2473713de341Sdrh /* Disallow the transfer optimization if the destination table constains 2474713de341Sdrh ** any foreign key constraints. This is more restrictive than necessary. 2475713de341Sdrh ** But the main beneficiary of the transfer optimization is the VACUUM 2476713de341Sdrh ** command, and the VACUUM command disables foreign key constraints. So 2477713de341Sdrh ** the extra complication to make this rule less restrictive is probably 2478713de341Sdrh ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] 2479713de341Sdrh */ 2480e34162b1Sdan if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ 2481713de341Sdrh return 0; 2482713de341Sdrh } 2483713de341Sdrh #endif 2484e34162b1Sdan if( (db->flags & SQLITE_CountRows)!=0 ){ 2485ccdf1baeSdrh return 0; /* xfer opt does not play well with PRAGMA count_changes */ 24861696124dSdan } 24879d9cf229Sdrh 2488ccdf1baeSdrh /* If we get this far, it means that the xfer optimization is at 2489ccdf1baeSdrh ** least a possibility, though it might only work if the destination 2490ccdf1baeSdrh ** table (tab1) is initially empty. 24919d9cf229Sdrh */ 2492dd73521bSdrh #ifdef SQLITE_TEST 2493dd73521bSdrh sqlite3_xferopt_count++; 2494dd73521bSdrh #endif 2495e34162b1Sdan iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); 24969d9cf229Sdrh v = sqlite3GetVdbe(pParse); 2497f53e9b5aSdrh sqlite3CodeVerifySchema(pParse, iDbSrc); 24989d9cf229Sdrh iSrc = pParse->nTab++; 24999d9cf229Sdrh iDest = pParse->nTab++; 25006a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 250155548273Sdrh regData = sqlite3GetTempReg(pParse); 250255548273Sdrh regRowid = sqlite3GetTempReg(pParse); 25039d9cf229Sdrh sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 2504427ebba1Sdan assert( HasRowid(pDest) || destHasUniqueIdx ); 25058257aa8dSdrh if( (db->mDbFlags & DBFLAG_Vacuum)==0 && ( 2506e34162b1Sdan (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ 2507ccdf1baeSdrh || destHasUniqueIdx /* (2) */ 2508ccdf1baeSdrh || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ 2509e34162b1Sdan )){ 2510ccdf1baeSdrh /* In some circumstances, we are able to run the xfer optimization 2511e34162b1Sdan ** only if the destination table is initially empty. Unless the 25128257aa8dSdrh ** DBFLAG_Vacuum flag is set, this block generates code to make 25138257aa8dSdrh ** that determination. If DBFLAG_Vacuum is set, then the destination 2514e34162b1Sdan ** table is always empty. 2515e34162b1Sdan ** 2516e34162b1Sdan ** Conditions under which the destination must be empty: 2517f33c9fadSdrh ** 2518ccdf1baeSdrh ** (1) There is no INTEGER PRIMARY KEY but there are indices. 2519ccdf1baeSdrh ** (If the destination is not initially empty, the rowid fields 2520ccdf1baeSdrh ** of index entries might need to change.) 2521ccdf1baeSdrh ** 2522ccdf1baeSdrh ** (2) The destination has a unique index. (The xfer optimization 2523ccdf1baeSdrh ** is unable to test uniqueness.) 2524ccdf1baeSdrh ** 2525ccdf1baeSdrh ** (3) onError is something other than OE_Abort and OE_Rollback. 25269d9cf229Sdrh */ 2527688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); 25282991ba05Sdrh emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); 25299d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 25309d9cf229Sdrh } 2531427ebba1Sdan if( HasRowid(pSrc) ){ 2532c9b9deaeSdrh u8 insFlags; 25339d9cf229Sdrh sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 2534688852abSdrh emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 253542242dedSdrh if( pDest->iPKey>=0 ){ 2536b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 25374031bafaSdrh sqlite3VdbeVerifyAbortable(v, onError); 2538b7654111Sdrh addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 2539688852abSdrh VdbeCoverage(v); 2540f9c8ce3cSdrh sqlite3RowidConstraint(pParse, onError, pDest); 25419d9cf229Sdrh sqlite3VdbeJumpHere(v, addr2); 2542b7654111Sdrh autoIncStep(pParse, regAutoinc, regRowid); 25434e61e883Sdrh }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){ 2544b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 254595bad4c7Sdrh }else{ 2546b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 25477d10d5a6Sdrh assert( (pDest->tabFlags & TF_Autoincrement)==0 ); 254895bad4c7Sdrh } 2549e7b554d6Sdrh sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); 25508257aa8dSdrh if( db->mDbFlags & DBFLAG_Vacuum ){ 255186b40dfdSdrh sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); 2552c9b9deaeSdrh insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID| 2553c9b9deaeSdrh OPFLAG_APPEND|OPFLAG_USESEEKRESULT; 2554c9b9deaeSdrh }else{ 2555c9b9deaeSdrh insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND; 2556c9b9deaeSdrh } 25579b34abeeSdrh sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid, 255820f272c9Sdrh (char*)pDest, P4_TABLE); 2559c9b9deaeSdrh sqlite3VdbeChangeP5(v, insFlags); 2560688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); 256155548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 256255548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 2563da475b8dSdrh }else{ 2564da475b8dSdrh sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); 2565da475b8dSdrh sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); 256655548273Sdrh } 25679d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 256841b9ca25Sdrh u8 idxInsFlags = 0; 25691b7ecbb4Sdrh for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ 25709d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 25719d9cf229Sdrh } 25729d9cf229Sdrh assert( pSrcIdx ); 25732ec2fb22Sdrh sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); 25742ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); 2575d4e70ebdSdrh VdbeComment((v, "%s", pSrcIdx->zName)); 25762ec2fb22Sdrh sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); 25772ec2fb22Sdrh sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); 257859885728Sdan sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); 2579207872a4Sdanielk1977 VdbeComment((v, "%s", pDestIdx->zName)); 2580688852abSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); 2581e7b554d6Sdrh sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); 25828257aa8dSdrh if( db->mDbFlags & DBFLAG_Vacuum ){ 2583e34162b1Sdan /* This INSERT command is part of a VACUUM operation, which guarantees 2584e34162b1Sdan ** that the destination table is empty. If all indexed columns use 2585e34162b1Sdan ** collation sequence BINARY, then it can also be assumed that the 2586e34162b1Sdan ** index will be populated by inserting keys in strictly sorted 2587e34162b1Sdan ** order. In this case, instead of seeking within the b-tree as part 258886b40dfdSdrh ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the 2589e34162b1Sdan ** OP_IdxInsert to seek to the point within the b-tree where each key 2590e34162b1Sdan ** should be inserted. This is faster. 2591e34162b1Sdan ** 2592e34162b1Sdan ** If any of the indexed columns use a collation sequence other than 2593e34162b1Sdan ** BINARY, this optimization is disabled. This is because the user 2594e34162b1Sdan ** might change the definition of a collation sequence and then run 2595e34162b1Sdan ** a VACUUM command. In that case keys may not be written in strictly 2596e34162b1Sdan ** sorted order. */ 2597e34162b1Sdan for(i=0; i<pSrcIdx->nColumn; i++){ 2598f19aa5faSdrh const char *zColl = pSrcIdx->azColl[i]; 2599f19aa5faSdrh if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break; 2600e34162b1Sdan } 2601e34162b1Sdan if( i==pSrcIdx->nColumn ){ 260241b9ca25Sdrh idxInsFlags = OPFLAG_USESEEKRESULT; 260386b40dfdSdrh sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); 2604e34162b1Sdan } 2605e34162b1Sdan } 26069df385ecSdrh if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){ 260741b9ca25Sdrh idxInsFlags |= OPFLAG_NCHANGE; 260841b9ca25Sdrh } 26099b4eaebcSdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData); 26109b4eaebcSdrh sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND); 2611688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); 26129d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 261355548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 261455548273Sdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 26159d9cf229Sdrh } 2616aceb31b1Sdrh if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); 2617b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 2618b7654111Sdrh sqlite3ReleaseTempReg(pParse, regData); 26199d9cf229Sdrh if( emptyDestTest ){ 26201dd518cfSdrh sqlite3AutoincrementEnd(pParse); 262166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 26229d9cf229Sdrh sqlite3VdbeJumpHere(v, emptyDestTest); 262366a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 26249d9cf229Sdrh return 0; 26259d9cf229Sdrh }else{ 26269d9cf229Sdrh return 1; 26279d9cf229Sdrh } 26289d9cf229Sdrh } 26299d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 2630