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 ** 15*e00ee6ebSdrh ** $Id: insert.c,v 1.241 2008/06/20 15:24:02 drh Exp $ 16cce7d176Sdrh */ 17cce7d176Sdrh #include "sqliteInt.h" 18cce7d176Sdrh 19cce7d176Sdrh /* 2066a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity 21a37cdde0Sdanielk1977 ** string for index pIdx. A column affinity string has one character 223d1bfeaaSdanielk1977 ** for each column in the table, according to the affinity of the column: 233d1bfeaaSdanielk1977 ** 243d1bfeaaSdanielk1977 ** Character Column affinity 253d1bfeaaSdanielk1977 ** ------------------------------ 263eda040bSdrh ** 'a' TEXT 273eda040bSdrh ** 'b' NONE 283eda040bSdrh ** 'c' NUMERIC 293eda040bSdrh ** 'd' INTEGER 303eda040bSdrh ** 'e' REAL 312d401ab8Sdrh ** 322d401ab8Sdrh ** An extra 'b' is appended to the end of the string to cover the 332d401ab8Sdrh ** rowid that appears as the last column in every index. 343d1bfeaaSdanielk1977 */ 35a37cdde0Sdanielk1977 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ 36a37cdde0Sdanielk1977 if( !pIdx->zColAff ){ 37e014a838Sdanielk1977 /* The first time a column affinity string for a particular index is 38a37cdde0Sdanielk1977 ** required, it is allocated and populated here. It is then stored as 39e014a838Sdanielk1977 ** a member of the Index structure for subsequent use. 40a37cdde0Sdanielk1977 ** 41a37cdde0Sdanielk1977 ** The column affinity string will eventually be deleted by 42e014a838Sdanielk1977 ** sqliteDeleteIndex() when the Index structure itself is cleaned 43a37cdde0Sdanielk1977 ** up. 44a37cdde0Sdanielk1977 */ 45a37cdde0Sdanielk1977 int n; 46a37cdde0Sdanielk1977 Table *pTab = pIdx->pTable; 47abb6fcabSdrh sqlite3 *db = sqlite3VdbeDb(v); 485c070538Sdrh pIdx->zColAff = (char *)sqlite3DbMallocRaw(db, pIdx->nColumn+2); 49a37cdde0Sdanielk1977 if( !pIdx->zColAff ){ 50a37cdde0Sdanielk1977 return; 51a37cdde0Sdanielk1977 } 52a37cdde0Sdanielk1977 for(n=0; n<pIdx->nColumn; n++){ 53a37cdde0Sdanielk1977 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity; 54a37cdde0Sdanielk1977 } 552d401ab8Sdrh pIdx->zColAff[n++] = SQLITE_AFF_NONE; 562d401ab8Sdrh pIdx->zColAff[n] = 0; 57a37cdde0Sdanielk1977 } 583d1bfeaaSdanielk1977 5966a5167bSdrh sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0); 60a37cdde0Sdanielk1977 } 61a37cdde0Sdanielk1977 62a37cdde0Sdanielk1977 /* 6366a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity 64a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character 65a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the 66a37cdde0Sdanielk1977 ** column: 67a37cdde0Sdanielk1977 ** 68a37cdde0Sdanielk1977 ** Character Column affinity 69a37cdde0Sdanielk1977 ** ------------------------------ 703eda040bSdrh ** 'a' TEXT 713eda040bSdrh ** 'b' NONE 723eda040bSdrh ** 'c' NUMERIC 733eda040bSdrh ** 'd' INTEGER 743eda040bSdrh ** 'e' REAL 75a37cdde0Sdanielk1977 */ 76a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){ 773d1bfeaaSdanielk1977 /* The first time a column affinity string for a particular table 783d1bfeaaSdanielk1977 ** is required, it is allocated and populated here. It is then 793d1bfeaaSdanielk1977 ** stored as a member of the Table structure for subsequent use. 803d1bfeaaSdanielk1977 ** 813d1bfeaaSdanielk1977 ** The column affinity string will eventually be deleted by 823d1bfeaaSdanielk1977 ** sqlite3DeleteTable() when the Table structure itself is cleaned up. 833d1bfeaaSdanielk1977 */ 843d1bfeaaSdanielk1977 if( !pTab->zColAff ){ 853d1bfeaaSdanielk1977 char *zColAff; 863d1bfeaaSdanielk1977 int i; 87abb6fcabSdrh sqlite3 *db = sqlite3VdbeDb(v); 883d1bfeaaSdanielk1977 895c070538Sdrh zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1); 903d1bfeaaSdanielk1977 if( !zColAff ){ 91a37cdde0Sdanielk1977 return; 923d1bfeaaSdanielk1977 } 933d1bfeaaSdanielk1977 943d1bfeaaSdanielk1977 for(i=0; i<pTab->nCol; i++){ 95a37cdde0Sdanielk1977 zColAff[i] = pTab->aCol[i].affinity; 963d1bfeaaSdanielk1977 } 973d1bfeaaSdanielk1977 zColAff[pTab->nCol] = '\0'; 983d1bfeaaSdanielk1977 993d1bfeaaSdanielk1977 pTab->zColAff = zColAff; 1003d1bfeaaSdanielk1977 } 1013d1bfeaaSdanielk1977 10266a5167bSdrh sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0); 1033d1bfeaaSdanielk1977 } 1043d1bfeaaSdanielk1977 1054d88778bSdanielk1977 /* 10648d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices 10748d1178aSdrh ** have been opened at any point in the VDBE program beginning at location 10848d1178aSdrh ** iStartAddr throught the end of the program. This is used to see if 10948d1178aSdrh ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can 11048d1178aSdrh ** run without using temporary table for the results of the SELECT. 1114d88778bSdanielk1977 */ 11248d1178aSdrh static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){ 1134d88778bSdanielk1977 int i; 11448d1178aSdrh int iEnd = sqlite3VdbeCurrentAddr(v); 11548d1178aSdrh for(i=iStartAddr; i<iEnd; i++){ 11648d1178aSdrh VdbeOp *pOp = sqlite3VdbeGetOp(v, i); 117ef0bea92Sdrh assert( pOp!=0 ); 118207872a4Sdanielk1977 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ 11948d1178aSdrh Index *pIndex; 120207872a4Sdanielk1977 int tnum = pOp->p2; 12148d1178aSdrh if( tnum==pTab->tnum ){ 12248d1178aSdrh return 1; 12348d1178aSdrh } 12448d1178aSdrh for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 12548d1178aSdrh if( tnum==pIndex->tnum ){ 12648d1178aSdrh return 1; 12748d1178aSdrh } 12848d1178aSdrh } 12948d1178aSdrh } 130543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 1312dca4ac1Sdanielk1977 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){ 1322dca4ac1Sdanielk1977 assert( pOp->p4.pVtab!=0 ); 13366a5167bSdrh assert( pOp->p4type==P4_VTAB ); 13448d1178aSdrh return 1; 1354d88778bSdanielk1977 } 136543165efSdrh #endif 1374d88778bSdanielk1977 } 1384d88778bSdanielk1977 return 0; 1394d88778bSdanielk1977 } 1403d1bfeaaSdanielk1977 1419d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT 1429d9cf229Sdrh /* 1439d9cf229Sdrh ** Write out code to initialize the autoincrement logic. This code 1449d9cf229Sdrh ** looks up the current autoincrement value in the sqlite_sequence 1456a288a33Sdrh ** table and stores that value in a register. Code generated by 1466a288a33Sdrh ** autoIncStep() will keep that register holding the largest 1479d9cf229Sdrh ** rowid value. Code generated by autoIncEnd() will write the new 1489d9cf229Sdrh ** largest value of the counter back into the sqlite_sequence table. 1499d9cf229Sdrh ** 1509d9cf229Sdrh ** This routine returns the index of the mem[] cell that contains 1519d9cf229Sdrh ** the maximum rowid counter. 1529d9cf229Sdrh ** 1536a288a33Sdrh ** Three consecutive registers are allocated by this routine. The 1546a288a33Sdrh ** first two hold the name of the target table and the maximum rowid 1556a288a33Sdrh ** inserted into the target table, respectively. 1566a288a33Sdrh ** The third holds the rowid in sqlite_sequence where we will 1576a288a33Sdrh ** write back the revised maximum rowid. This routine returns the 1586a288a33Sdrh ** index of the second of these three registers. 1599d9cf229Sdrh */ 1609d9cf229Sdrh static int autoIncBegin( 1619d9cf229Sdrh Parse *pParse, /* Parsing context */ 1629d9cf229Sdrh int iDb, /* Index of the database holding pTab */ 1639d9cf229Sdrh Table *pTab /* The table we are writing to */ 1649d9cf229Sdrh ){ 1656a288a33Sdrh int memId = 0; /* Register holding maximum rowid */ 1669d9cf229Sdrh if( pTab->autoInc ){ 1679d9cf229Sdrh Vdbe *v = pParse->pVdbe; 1689d9cf229Sdrh Db *pDb = &pParse->db->aDb[iDb]; 1699d9cf229Sdrh int iCur = pParse->nTab; 1706a288a33Sdrh int addr; /* Address of the top of the loop */ 1719d9cf229Sdrh assert( v ); 1726a288a33Sdrh pParse->nMem++; /* Holds name of table */ 1736a288a33Sdrh memId = ++pParse->nMem; 1746a288a33Sdrh pParse->nMem++; 1759d9cf229Sdrh sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead); 1766a288a33Sdrh addr = sqlite3VdbeCurrentAddr(v); 1771db639ceSdrh sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0); 178c9ded4c6Sdrh sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9); 1791db639ceSdrh sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId); 1801db639ceSdrh sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); 18135573356Sdrh sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); 1826a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1); 1836a288a33Sdrh sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId); 184c9ded4c6Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9); 1851db639ceSdrh sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2); 186c9ded4c6Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, memId); 18766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iCur, 0); 1889d9cf229Sdrh } 1899d9cf229Sdrh return memId; 1909d9cf229Sdrh } 1919d9cf229Sdrh 1929d9cf229Sdrh /* 1939d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation. 1949d9cf229Sdrh ** 1959d9cf229Sdrh ** This routine should be called when the top of the stack holds a 1969d9cf229Sdrh ** new rowid that is about to be inserted. If that new rowid is 1979d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the 1989d9cf229Sdrh ** memory cell is updated. The stack is unchanged. 1999d9cf229Sdrh */ 2006a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){ 2019d9cf229Sdrh if( memId>0 ){ 2026a288a33Sdrh sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); 2039d9cf229Sdrh } 2049d9cf229Sdrh } 2059d9cf229Sdrh 2069d9cf229Sdrh /* 2079d9cf229Sdrh ** After doing one or more inserts, the maximum rowid is stored 2086a288a33Sdrh ** in reg[memId]. Generate code to write this value back into the 2099d9cf229Sdrh ** the sqlite_sequence table. 2109d9cf229Sdrh */ 2119d9cf229Sdrh static void autoIncEnd( 2129d9cf229Sdrh Parse *pParse, /* The parsing context */ 2139d9cf229Sdrh int iDb, /* Index of the database holding pTab */ 2149d9cf229Sdrh Table *pTab, /* Table we are inserting into */ 2159d9cf229Sdrh int memId /* Memory cell holding the maximum rowid */ 2169d9cf229Sdrh ){ 2179d9cf229Sdrh if( pTab->autoInc ){ 2189d9cf229Sdrh int iCur = pParse->nTab; 2199d9cf229Sdrh Vdbe *v = pParse->pVdbe; 2209d9cf229Sdrh Db *pDb = &pParse->db->aDb[iDb]; 2216a288a33Sdrh int j1; 222a7a8e14bSdanielk1977 int iRec = ++pParse->nMem; /* Memory cell used for record */ 2236a288a33Sdrh 2249d9cf229Sdrh assert( v ); 2259d9cf229Sdrh sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); 2266a288a33Sdrh j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); 2276a288a33Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1); 2286a288a33Sdrh sqlite3VdbeJumpHere(v, j1); 229a7a8e14bSdanielk1977 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec); 230a7a8e14bSdanielk1977 sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1); 23135573356Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 2326a288a33Sdrh sqlite3VdbeAddOp1(v, OP_Close, iCur); 2339d9cf229Sdrh } 2349d9cf229Sdrh } 2359d9cf229Sdrh #else 2369d9cf229Sdrh /* 2379d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines 2389d9cf229Sdrh ** above are all no-ops 2399d9cf229Sdrh */ 2409d9cf229Sdrh # define autoIncBegin(A,B,C) (0) 241287fb61cSdanielk1977 # define autoIncStep(A,B,C) 2429d9cf229Sdrh # define autoIncEnd(A,B,C,D) 2439d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */ 2449d9cf229Sdrh 2459d9cf229Sdrh 2469d9cf229Sdrh /* Forward declaration */ 2479d9cf229Sdrh static int xferOptimization( 2489d9cf229Sdrh Parse *pParse, /* Parser context */ 2499d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 2509d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 2519d9cf229Sdrh int onError, /* How to handle constraint errors */ 2529d9cf229Sdrh int iDbDest /* The database of pDest */ 2539d9cf229Sdrh ); 2549d9cf229Sdrh 2553d1bfeaaSdanielk1977 /* 2561ccde15dSdrh ** This routine is call to handle SQL of the following forms: 257cce7d176Sdrh ** 258cce7d176Sdrh ** insert into TABLE (IDLIST) values(EXPRLIST) 2591ccde15dSdrh ** insert into TABLE (IDLIST) select 260cce7d176Sdrh ** 2611ccde15dSdrh ** The IDLIST following the table name is always optional. If omitted, 2621ccde15dSdrh ** then a list of all columns for the table is substituted. The IDLIST 263967e8b73Sdrh ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted. 2641ccde15dSdrh ** 2651ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT 2661ccde15dSdrh ** statement above, and pSelect is NULL. For the second form, pList is 2671ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate 2681ccde15dSdrh ** data for the insert. 269142e30dfSdrh ** 2709d9cf229Sdrh ** The code generated follows one of four templates. For a simple 271142e30dfSdrh ** select with data coming from a VALUES clause, the code executes 272*e00ee6ebSdrh ** once straight down through. Pseudo-code follows (we call this 273*e00ee6ebSdrh ** the "1st template"): 274142e30dfSdrh ** 275142e30dfSdrh ** open write cursor to <table> and its indices 276142e30dfSdrh ** puts VALUES clause expressions onto the stack 277142e30dfSdrh ** write the resulting record into <table> 278142e30dfSdrh ** cleanup 279142e30dfSdrh ** 2809d9cf229Sdrh ** The three remaining templates assume the statement is of the form 281142e30dfSdrh ** 282142e30dfSdrh ** INSERT INTO <table> SELECT ... 283142e30dfSdrh ** 2849d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - 2859d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table 2869d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and 2879d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical 2889d9cf229Sdrh ** schemas, including all the same indices, then a special optimization 2899d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>. 2909d9cf229Sdrh ** See the xferOptimization() function for the implementation of this 291*e00ee6ebSdrh ** template. This is the 2nd template. 2929d9cf229Sdrh ** 2939d9cf229Sdrh ** open a write cursor to <table> 2949d9cf229Sdrh ** open read cursor on <table2> 2959d9cf229Sdrh ** transfer all records in <table2> over to <table> 2969d9cf229Sdrh ** close cursors 2979d9cf229Sdrh ** foreach index on <table> 2989d9cf229Sdrh ** open a write cursor on the <table> index 2999d9cf229Sdrh ** open a read cursor on the corresponding <table2> index 3009d9cf229Sdrh ** transfer all records from the read to the write cursors 3019d9cf229Sdrh ** close cursors 3029d9cf229Sdrh ** end foreach 3039d9cf229Sdrh ** 304*e00ee6ebSdrh ** The 3rd template is for when the second template does not apply 3059d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time. 3069d9cf229Sdrh ** The generated code follows this template: 307142e30dfSdrh ** 308*e00ee6ebSdrh ** EOF <- 0 309*e00ee6ebSdrh ** X <- A 310142e30dfSdrh ** goto B 311142e30dfSdrh ** A: setup for the SELECT 3129d9cf229Sdrh ** loop over the rows in the SELECT 313*e00ee6ebSdrh ** load values into registers R..R+n 314*e00ee6ebSdrh ** yield X 315142e30dfSdrh ** end loop 316142e30dfSdrh ** cleanup after the SELECT 317*e00ee6ebSdrh ** EOF <- 1 318*e00ee6ebSdrh ** yield X 319142e30dfSdrh ** goto A 320*e00ee6ebSdrh ** B: open write cursor to <table> and its indices 321*e00ee6ebSdrh ** C: yield X 322*e00ee6ebSdrh ** if EOF goto D 323*e00ee6ebSdrh ** insert the select result into <table> from R..R+n 324*e00ee6ebSdrh ** goto C 325142e30dfSdrh ** D: cleanup 326142e30dfSdrh ** 327*e00ee6ebSdrh ** The 4th template is used if the insert statement takes its 328142e30dfSdrh ** values from a SELECT but the data is being inserted into a table 329142e30dfSdrh ** that is also read as part of the SELECT. In the third form, 330142e30dfSdrh ** we have to use a intermediate table to store the results of 331142e30dfSdrh ** the select. The template is like this: 332142e30dfSdrh ** 333*e00ee6ebSdrh ** EOF <- 0 334*e00ee6ebSdrh ** X <- A 335142e30dfSdrh ** goto B 336142e30dfSdrh ** A: setup for the SELECT 337142e30dfSdrh ** loop over the tables in the SELECT 338*e00ee6ebSdrh ** load value into register R..R+n 339*e00ee6ebSdrh ** yield X 340142e30dfSdrh ** end loop 341142e30dfSdrh ** cleanup after the SELECT 342*e00ee6ebSdrh ** EOF <- 1 343*e00ee6ebSdrh ** yield X 344*e00ee6ebSdrh ** halt-error 345*e00ee6ebSdrh ** B: open temp table 346*e00ee6ebSdrh ** L: yield X 347*e00ee6ebSdrh ** if EOF goto M 348*e00ee6ebSdrh ** insert row from R..R+n into temp table 349*e00ee6ebSdrh ** goto L 350*e00ee6ebSdrh ** M: open write cursor to <table> and its indices 351*e00ee6ebSdrh ** rewind temp table 352*e00ee6ebSdrh ** C: loop over rows of intermediate table 353142e30dfSdrh ** transfer values form intermediate table into <table> 354*e00ee6ebSdrh ** end loop 355*e00ee6ebSdrh ** D: cleanup 356cce7d176Sdrh */ 3574adee20fSdanielk1977 void sqlite3Insert( 358cce7d176Sdrh Parse *pParse, /* Parser context */ 359113088ecSdrh SrcList *pTabList, /* Name of table into which we are inserting */ 360cce7d176Sdrh ExprList *pList, /* List of values to be inserted */ 3615974a30fSdrh Select *pSelect, /* A SELECT statement to use as the data source */ 3629cfcf5d4Sdrh IdList *pColumn, /* Column names corresponding to IDLIST. */ 3639cfcf5d4Sdrh int onError /* How to handle constraint errors */ 364cce7d176Sdrh ){ 3656a288a33Sdrh sqlite3 *db; /* The main database structure */ 3666a288a33Sdrh Table *pTab; /* The table to insert into. aka TABLE */ 367113088ecSdrh char *zTab; /* Name of the table into which we are inserting */ 368e22a334bSdrh const char *zDb; /* Name of the database holding this table */ 3695974a30fSdrh int i, j, idx; /* Loop counters */ 3705974a30fSdrh Vdbe *v; /* Generate code into this virtual machine */ 3715974a30fSdrh Index *pIdx; /* For looping over indices of the table */ 372967e8b73Sdrh int nColumn; /* Number of columns in the data */ 3736a288a33Sdrh int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ 37404adf416Sdrh int baseCur = 0; /* VDBE Cursor number for pTab */ 3754a32431cSdrh int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ 3760ca3e24bSdrh int endOfLoop; /* Label for the end of the insertion loop */ 3774d88778bSdanielk1977 int useTempTable = 0; /* Store SELECT results in intermediate table */ 378cfe9a69fSdanielk1977 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ 379*e00ee6ebSdrh int addrInsTop = 0; /* Jump to label "D" */ 380*e00ee6ebSdrh int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ 381*e00ee6ebSdrh int addrSelect = 0; /* Address of coroutine that implements the SELECT */ 3822eb95377Sdrh SelectDest dest; /* Destination for SELECT on rhs of INSERT */ 3836a288a33Sdrh int newIdx = -1; /* Cursor for the NEW pseudo-table */ 3846a288a33Sdrh int iDb; /* Index of database holding TABLE */ 3852958a4e6Sdrh Db *pDb; /* The database containing table being inserted into */ 386e4d90813Sdrh int appendFlag = 0; /* True if the insert is likely to be an append */ 387cce7d176Sdrh 3886a288a33Sdrh /* Register allocations */ 3896a288a33Sdrh int regFromSelect; /* Base register for data coming from SELECT */ 3906a288a33Sdrh int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ 3916a288a33Sdrh int regRowCount = 0; /* Memory cell used for the row counter */ 3926a288a33Sdrh int regIns; /* Block of regs holding rowid+data being inserted */ 3936a288a33Sdrh int regRowid; /* registers holding insert rowid */ 3946a288a33Sdrh int regData; /* register holding first column to insert */ 3956a288a33Sdrh int regRecord; /* Holds the assemblied row record */ 396*e00ee6ebSdrh int regEof; /* Register recording end of SELECT data */ 397aa9b8963Sdrh int *aRegIdx = 0; /* One register allocated to each index */ 3986a288a33Sdrh 399034ca14fSdanielk1977 400798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER 401798da52cSdrh int isView; /* True if attempting to insert into a view */ 402dca76841Sdrh int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */ 403798da52cSdrh #endif 404c3f9bad2Sdanielk1977 40517435752Sdrh db = pParse->db; 40617435752Sdrh if( pParse->nErr || db->mallocFailed ){ 4076f7adc8aSdrh goto insert_cleanup; 4086f7adc8aSdrh } 409daffd0e5Sdrh 4101ccde15dSdrh /* Locate the table into which we will be inserting new information. 4111ccde15dSdrh */ 412113088ecSdrh assert( pTabList->nSrc==1 ); 413113088ecSdrh zTab = pTabList->a[0].zName; 414daffd0e5Sdrh if( zTab==0 ) goto insert_cleanup; 4154adee20fSdanielk1977 pTab = sqlite3SrcListLookup(pParse, pTabList); 416c3f9bad2Sdanielk1977 if( pTab==0 ){ 417c3f9bad2Sdanielk1977 goto insert_cleanup; 418c3f9bad2Sdanielk1977 } 419da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 420da184236Sdanielk1977 assert( iDb<db->nDb ); 421da184236Sdanielk1977 pDb = &db->aDb[iDb]; 4222958a4e6Sdrh zDb = pDb->zName; 4234adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ 4241962bda7Sdrh goto insert_cleanup; 4251962bda7Sdrh } 426c3f9bad2Sdanielk1977 427b7f9164eSdrh /* Figure out if we have any triggers and if the table being 428b7f9164eSdrh ** inserted into is a view 429b7f9164eSdrh */ 430b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER 431dca76841Sdrh triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0); 432b7f9164eSdrh isView = pTab->pSelect!=0; 433b7f9164eSdrh #else 434dca76841Sdrh # define triggers_exist 0 435b7f9164eSdrh # define isView 0 436b7f9164eSdrh #endif 437b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW 438b7f9164eSdrh # undef isView 439b7f9164eSdrh # define isView 0 440b7f9164eSdrh #endif 441b7f9164eSdrh 442c3f9bad2Sdanielk1977 /* Ensure that: 443c3f9bad2Sdanielk1977 * (a) the table is not read-only, 444c3f9bad2Sdanielk1977 * (b) that if it is a view then ON INSERT triggers exist 445c3f9bad2Sdanielk1977 */ 446dca76841Sdrh if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){ 447c3f9bad2Sdanielk1977 goto insert_cleanup; 448c3f9bad2Sdanielk1977 } 44943617e9aSdrh assert( pTab!=0 ); 4501ccde15dSdrh 451f573c99bSdrh /* If pTab is really a view, make sure it has been initialized. 452b3d24bf8Sdanielk1977 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 453b3d24bf8Sdanielk1977 ** module table). 454f573c99bSdrh */ 455b3d24bf8Sdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 456f573c99bSdrh goto insert_cleanup; 457f573c99bSdrh } 458f573c99bSdrh 4591ccde15dSdrh /* Allocate a VDBE 4601ccde15dSdrh */ 4614adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 4625974a30fSdrh if( v==0 ) goto insert_cleanup; 4634794f735Sdrh if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 464da184236Sdanielk1977 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb); 4651ccde15dSdrh 466c3f9bad2Sdanielk1977 /* if there are row triggers, allocate a temp table for new.* references. */ 467dca76841Sdrh if( triggers_exist ){ 468c3f9bad2Sdanielk1977 newIdx = pParse->nTab++; 469f29ce559Sdanielk1977 } 470c3f9bad2Sdanielk1977 4719d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 4729d9cf229Sdrh /* If the statement is of the form 4739d9cf229Sdrh ** 4749d9cf229Sdrh ** INSERT INTO <table1> SELECT * FROM <table2>; 4759d9cf229Sdrh ** 4769d9cf229Sdrh ** Then special optimizations can be applied that make the transfer 4779d9cf229Sdrh ** very fast and which reduce fragmentation of indices. 478*e00ee6ebSdrh ** 479*e00ee6ebSdrh ** This is the 2nd template. 4809d9cf229Sdrh */ 4819d9cf229Sdrh if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ 4829d9cf229Sdrh assert( !triggers_exist ); 4839d9cf229Sdrh assert( pList==0 ); 4849d9cf229Sdrh goto insert_cleanup; 4859d9cf229Sdrh } 4869d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 4879d9cf229Sdrh 4882958a4e6Sdrh /* If this is an AUTOINCREMENT table, look up the sequence number in the 4896a288a33Sdrh ** sqlite_sequence table and store it in memory cell regAutoinc. 4902958a4e6Sdrh */ 4916a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDb, pTab); 4922958a4e6Sdrh 4931ccde15dSdrh /* Figure out how many columns of data are supplied. If the data 494*e00ee6ebSdrh ** is coming from a SELECT statement, then generate a co-routine that 495*e00ee6ebSdrh ** produces a single row of the SELECT on each invocation. The 496*e00ee6ebSdrh ** co-routine is the common header to the 3rd and 4th templates. 4971ccde15dSdrh */ 4985974a30fSdrh if( pSelect ){ 499142e30dfSdrh /* Data is coming from a SELECT. Generate code to implement that SELECT 500*e00ee6ebSdrh ** as a co-routine. The code is common to both the 3rd and 4th 501*e00ee6ebSdrh ** templates: 502*e00ee6ebSdrh ** 503*e00ee6ebSdrh ** EOF <- 0 504*e00ee6ebSdrh ** X <- A 505*e00ee6ebSdrh ** goto B 506*e00ee6ebSdrh ** A: setup for the SELECT 507*e00ee6ebSdrh ** loop over the tables in the SELECT 508*e00ee6ebSdrh ** load value into register R..R+n 509*e00ee6ebSdrh ** yield X 510*e00ee6ebSdrh ** end loop 511*e00ee6ebSdrh ** cleanup after the SELECT 512*e00ee6ebSdrh ** EOF <- 1 513*e00ee6ebSdrh ** yield X 514*e00ee6ebSdrh ** halt-error 515*e00ee6ebSdrh ** 516*e00ee6ebSdrh ** On each invocation of the co-routine, it puts a single row of the 517*e00ee6ebSdrh ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1. 518*e00ee6ebSdrh ** (These output registers are allocated by sqlite3Select().) When 519*e00ee6ebSdrh ** the SELECT completes, it sets the EOF flag stored in regEof. 520142e30dfSdrh */ 521*e00ee6ebSdrh int rc, j1; 5221013c932Sdrh 523*e00ee6ebSdrh regEof = ++pParse->nMem; 524*e00ee6ebSdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */ 525*e00ee6ebSdrh VdbeComment((v, "SELECT eof flag")); 526*e00ee6ebSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, 0); 527*e00ee6ebSdrh dest.regCoroutine = ++pParse->nMem; 528*e00ee6ebSdrh addrSelect = sqlite3VdbeCurrentAddr(v)+2; 529*e00ee6ebSdrh sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.regCoroutine); 530*e00ee6ebSdrh j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); 531*e00ee6ebSdrh VdbeComment((v, "Jump over SELECT coroutine")); 532b3bce662Sdanielk1977 533b3bce662Sdanielk1977 /* Resolve the expressions in the SELECT statement and execute it. */ 5346c8c8ce0Sdanielk1977 rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0); 53517435752Sdrh if( rc || pParse->nErr || db->mallocFailed ){ 5366f7adc8aSdrh goto insert_cleanup; 5376f7adc8aSdrh } 538*e00ee6ebSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */ 539*e00ee6ebSdrh sqlite3VdbeAddOp1(v, OP_Yield, dest.regCoroutine); /* yield X */ 540*e00ee6ebSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort); 541*e00ee6ebSdrh VdbeComment((v, "End of SELECT coroutine")); 542*e00ee6ebSdrh sqlite3VdbeJumpHere(v, j1); /* label B: */ 543b3bce662Sdanielk1977 5446a288a33Sdrh regFromSelect = dest.iMem; 5455974a30fSdrh assert( pSelect->pEList ); 546967e8b73Sdrh nColumn = pSelect->pEList->nExpr; 547*e00ee6ebSdrh assert( dest.nMem==nColumn ); 548142e30dfSdrh 549142e30dfSdrh /* Set useTempTable to TRUE if the result of the SELECT statement 550*e00ee6ebSdrh ** should be written into a temporary table (template 4). Set to 551*e00ee6ebSdrh ** FALSE if each* row of the SELECT can be written directly into 552*e00ee6ebSdrh ** the destination table (template 3). 553048c530cSdrh ** 554048c530cSdrh ** A temp table must be used if the table being updated is also one 555048c530cSdrh ** of the tables being read by the SELECT statement. Also use a 556048c530cSdrh ** temp table in the case of row triggers. 557142e30dfSdrh */ 558*e00ee6ebSdrh if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){ 559048c530cSdrh useTempTable = 1; 560048c530cSdrh } 561142e30dfSdrh 562142e30dfSdrh if( useTempTable ){ 563*e00ee6ebSdrh /* Invoke the coroutine to extract information from the SELECT 564*e00ee6ebSdrh ** and add it to a transient table srcTab. The code generated 565*e00ee6ebSdrh ** here is from the 4th template: 566*e00ee6ebSdrh ** 567*e00ee6ebSdrh ** B: open temp table 568*e00ee6ebSdrh ** L: yield X 569*e00ee6ebSdrh ** if EOF goto M 570*e00ee6ebSdrh ** insert row from R..R+n into temp table 571*e00ee6ebSdrh ** goto L 572*e00ee6ebSdrh ** M: ... 573142e30dfSdrh */ 574*e00ee6ebSdrh int regRec; /* Register to hold packed record */ 575*e00ee6ebSdrh int regRowid; /* Register to hold temp table ROWID */ 576*e00ee6ebSdrh int addrTop; /* Label "L" */ 577*e00ee6ebSdrh int addrIf; /* Address of jump to M */ 578b7654111Sdrh 579142e30dfSdrh srcTab = pParse->nTab++; 580b7654111Sdrh regRec = sqlite3GetTempReg(pParse); 581b7654111Sdrh regRowid = sqlite3GetTempReg(pParse); 582*e00ee6ebSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); 583*e00ee6ebSdrh addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.regCoroutine); 584*e00ee6ebSdrh addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof); 5851db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); 586b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid); 587b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid); 588*e00ee6ebSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop); 589*e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrIf); 590b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRec); 591b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 592142e30dfSdrh } 593142e30dfSdrh }else{ 594142e30dfSdrh /* This is the case if the data for the INSERT is coming from a VALUES 595142e30dfSdrh ** clause 596142e30dfSdrh */ 597b3bce662Sdanielk1977 NameContext sNC; 598b3bce662Sdanielk1977 memset(&sNC, 0, sizeof(sNC)); 599b3bce662Sdanielk1977 sNC.pParse = pParse; 6005974a30fSdrh srcTab = -1; 60148d1178aSdrh assert( useTempTable==0 ); 602147d0cccSdrh nColumn = pList ? pList->nExpr : 0; 603e64e7b20Sdrh for(i=0; i<nColumn; i++){ 604b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){ 605b04a5d87Sdrh goto insert_cleanup; 606b04a5d87Sdrh } 607e64e7b20Sdrh } 6085974a30fSdrh } 6091ccde15dSdrh 6101ccde15dSdrh /* Make sure the number of columns in the source data matches the number 6111ccde15dSdrh ** of columns to be inserted into the table. 6121ccde15dSdrh */ 613034ca14fSdanielk1977 if( IsVirtual(pTab) ){ 614034ca14fSdanielk1977 for(i=0; i<pTab->nCol; i++){ 615034ca14fSdanielk1977 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); 616034ca14fSdanielk1977 } 617034ca14fSdanielk1977 } 618034ca14fSdanielk1977 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ 6194adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 620da93d238Sdrh "table %S has %d columns but %d values were supplied", 621da93d238Sdrh pTabList, 0, pTab->nCol, nColumn); 622cce7d176Sdrh goto insert_cleanup; 623cce7d176Sdrh } 624967e8b73Sdrh if( pColumn!=0 && nColumn!=pColumn->nId ){ 6254adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 626cce7d176Sdrh goto insert_cleanup; 627cce7d176Sdrh } 6281ccde15dSdrh 6291ccde15dSdrh /* If the INSERT statement included an IDLIST term, then make sure 6301ccde15dSdrh ** all elements of the IDLIST really are columns of the table and 6311ccde15dSdrh ** remember the column indices. 632c8392586Sdrh ** 633c8392586Sdrh ** If the table has an INTEGER PRIMARY KEY column and that column 634c8392586Sdrh ** is named in the IDLIST, then record in the keyColumn variable 635c8392586Sdrh ** the index into IDLIST of the primary key column. keyColumn is 636c8392586Sdrh ** the index of the primary key as it appears in IDLIST, not as 637c8392586Sdrh ** is appears in the original table. (The index of the primary 638c8392586Sdrh ** key in the original table is pTab->iPKey.) 6391ccde15dSdrh */ 640967e8b73Sdrh if( pColumn ){ 641967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 642967e8b73Sdrh pColumn->a[i].idx = -1; 643cce7d176Sdrh } 644967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 645cce7d176Sdrh for(j=0; j<pTab->nCol; j++){ 6464adee20fSdanielk1977 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ 647967e8b73Sdrh pColumn->a[i].idx = j; 6484a32431cSdrh if( j==pTab->iPKey ){ 6499aa028daSdrh keyColumn = i; 6504a32431cSdrh } 651cce7d176Sdrh break; 652cce7d176Sdrh } 653cce7d176Sdrh } 654cce7d176Sdrh if( j>=pTab->nCol ){ 6554adee20fSdanielk1977 if( sqlite3IsRowid(pColumn->a[i].zName) ){ 656a0217ba7Sdrh keyColumn = i; 657a0217ba7Sdrh }else{ 6584adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %S has no column named %s", 659da93d238Sdrh pTabList, 0, pColumn->a[i].zName); 660cce7d176Sdrh pParse->nErr++; 661cce7d176Sdrh goto insert_cleanup; 662cce7d176Sdrh } 663cce7d176Sdrh } 664cce7d176Sdrh } 665a0217ba7Sdrh } 6661ccde15dSdrh 667aacc543eSdrh /* If there is no IDLIST term but the table has an integer primary 668c8392586Sdrh ** key, the set the keyColumn variable to the primary key column index 669c8392586Sdrh ** in the original table definition. 6704a32431cSdrh */ 671147d0cccSdrh if( pColumn==0 && nColumn>0 ){ 6724a32431cSdrh keyColumn = pTab->iPKey; 6734a32431cSdrh } 6744a32431cSdrh 675142e30dfSdrh /* Open the temp table for FOR EACH ROW triggers 676142e30dfSdrh */ 677dca76841Sdrh if( triggers_exist ){ 678cd3e8f7cSdanielk1977 sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol); 67966a5167bSdrh sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0); 680f29ce559Sdanielk1977 } 681c3f9bad2Sdanielk1977 682c3f9bad2Sdanielk1977 /* Initialize the count of rows to be inserted 6831ccde15dSdrh */ 684142e30dfSdrh if( db->flags & SQLITE_CountRows ){ 6856a288a33Sdrh regRowCount = ++pParse->nMem; 6866a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 687c3f9bad2Sdanielk1977 } 688c3f9bad2Sdanielk1977 689e448dc4aSdanielk1977 /* If this is not a view, open the table and and all indices */ 690e448dc4aSdanielk1977 if( !isView ){ 691aa9b8963Sdrh int nIdx; 692aa9b8963Sdrh int i; 693aa9b8963Sdrh 69404adf416Sdrh baseCur = pParse->nTab; 69504adf416Sdrh nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite); 6965c070538Sdrh aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); 697aa9b8963Sdrh if( aRegIdx==0 ){ 698aa9b8963Sdrh goto insert_cleanup; 699aa9b8963Sdrh } 700aa9b8963Sdrh for(i=0; i<nIdx; i++){ 701aa9b8963Sdrh aRegIdx[i] = ++pParse->nMem; 702aa9b8963Sdrh } 703feeb1394Sdrh } 704feeb1394Sdrh 705*e00ee6ebSdrh /* This is the top of the main insertion loop */ 706142e30dfSdrh if( useTempTable ){ 707*e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 708*e00ee6ebSdrh ** following pseudocode (template 4): 709*e00ee6ebSdrh ** 710*e00ee6ebSdrh ** rewind temp table 711*e00ee6ebSdrh ** C: loop over rows of intermediate table 712*e00ee6ebSdrh ** transfer values form intermediate table into <table> 713*e00ee6ebSdrh ** end loop 714*e00ee6ebSdrh ** D: ... 715*e00ee6ebSdrh */ 716*e00ee6ebSdrh addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); 717*e00ee6ebSdrh addrCont = sqlite3VdbeCurrentAddr(v); 718142e30dfSdrh }else if( pSelect ){ 719*e00ee6ebSdrh /* This block codes the top of loop only. The complete loop is the 720*e00ee6ebSdrh ** following pseudocode (template 3): 721*e00ee6ebSdrh ** 722*e00ee6ebSdrh ** C: yield X 723*e00ee6ebSdrh ** if EOF goto D 724*e00ee6ebSdrh ** insert the select result into <table> from R..R+n 725*e00ee6ebSdrh ** goto C 726*e00ee6ebSdrh ** D: ... 727*e00ee6ebSdrh */ 728*e00ee6ebSdrh addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.regCoroutine); 729*e00ee6ebSdrh addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof); 730bed8690fSdrh } 7311ccde15dSdrh 7326a288a33Sdrh /* Allocate registers for holding the rowid of the new row, 7336a288a33Sdrh ** the content of the new row, and the assemblied row record. 7346a288a33Sdrh */ 7356a288a33Sdrh regRecord = ++pParse->nMem; 7366a288a33Sdrh regRowid = regIns = pParse->nMem+1; 7376a288a33Sdrh pParse->nMem += pTab->nCol + 1; 7386a288a33Sdrh if( IsVirtual(pTab) ){ 7396a288a33Sdrh regRowid++; 7406a288a33Sdrh pParse->nMem++; 7416a288a33Sdrh } 7426a288a33Sdrh regData = regRowid+1; 7436a288a33Sdrh 7445cf590c1Sdrh /* Run the BEFORE and INSTEAD OF triggers, if there are any 74570ce3f0cSdrh */ 7464adee20fSdanielk1977 endOfLoop = sqlite3VdbeMakeLabel(v); 747dca76841Sdrh if( triggers_exist & TRIGGER_BEFORE ){ 7482d401ab8Sdrh int regRowid; 7492d401ab8Sdrh int regCols; 7502d401ab8Sdrh int regRec; 751c3f9bad2Sdanielk1977 75270ce3f0cSdrh /* build the NEW.* reference row. Note that if there is an INTEGER 75370ce3f0cSdrh ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 75470ce3f0cSdrh ** translated into a unique ID for the row. But on a BEFORE trigger, 75570ce3f0cSdrh ** we do not know what the unique ID will be (because the insert has 75670ce3f0cSdrh ** not happened yet) so we substitute a rowid of -1 75770ce3f0cSdrh */ 7582d401ab8Sdrh regRowid = sqlite3GetTempReg(pParse); 75970ce3f0cSdrh if( keyColumn<0 ){ 7602d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid); 76170ce3f0cSdrh }else if( useTempTable ){ 7622d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); 76370ce3f0cSdrh }else{ 7646a288a33Sdrh int j1; 765d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 7662d401ab8Sdrh sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); 7672d401ab8Sdrh j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); 7682d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid); 7696a288a33Sdrh sqlite3VdbeJumpHere(v, j1); 7702d401ab8Sdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); 77170ce3f0cSdrh } 77270ce3f0cSdrh 773034ca14fSdanielk1977 /* Cannot have triggers on a virtual table. If it were possible, 774034ca14fSdanielk1977 ** this block would have to account for hidden column. 775034ca14fSdanielk1977 */ 776034ca14fSdanielk1977 assert(!IsVirtual(pTab)); 777034ca14fSdanielk1977 77870ce3f0cSdrh /* Create the new column data 77970ce3f0cSdrh */ 7802d401ab8Sdrh regCols = sqlite3GetTempRange(pParse, pTab->nCol); 781c3f9bad2Sdanielk1977 for(i=0; i<pTab->nCol; i++){ 782c3f9bad2Sdanielk1977 if( pColumn==0 ){ 783c3f9bad2Sdanielk1977 j = i; 784c3f9bad2Sdanielk1977 }else{ 785c3f9bad2Sdanielk1977 for(j=0; j<pColumn->nId; j++){ 786c3f9bad2Sdanielk1977 if( pColumn->a[j].idx==i ) break; 787c3f9bad2Sdanielk1977 } 788c3f9bad2Sdanielk1977 } 789c3f9bad2Sdanielk1977 if( pColumn && j>=pColumn->nId ){ 7902d401ab8Sdrh sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i); 791142e30dfSdrh }else if( useTempTable ){ 7922d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); 793c3f9bad2Sdanielk1977 }else{ 794d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 7952d401ab8Sdrh sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i); 796c3f9bad2Sdanielk1977 } 797c3f9bad2Sdanielk1977 } 7982d401ab8Sdrh regRec = sqlite3GetTempReg(pParse); 7991db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec); 800a37cdde0Sdanielk1977 801a37cdde0Sdanielk1977 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 802a37cdde0Sdanielk1977 ** do not attempt any conversions before assembling the record. 803a37cdde0Sdanielk1977 ** If this is a real table, attempt conversions as required by the 804a37cdde0Sdanielk1977 ** table column affinities. 805a37cdde0Sdanielk1977 */ 806a37cdde0Sdanielk1977 if( !isView ){ 807a37cdde0Sdanielk1977 sqlite3TableAffinityStr(v, pTab); 808a37cdde0Sdanielk1977 } 8092d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid); 8102d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRec); 8112d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 8122d401ab8Sdrh sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol); 813c3f9bad2Sdanielk1977 8145cf590c1Sdrh /* Fire BEFORE or INSTEAD OF triggers */ 815dca76841Sdrh if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 8168f2c54e6Sdanielk1977 newIdx, -1, onError, endOfLoop, 0, 0) ){ 817f29ce559Sdanielk1977 goto insert_cleanup; 818f29ce559Sdanielk1977 } 81970ce3f0cSdrh } 820c3f9bad2Sdanielk1977 8214a32431cSdrh /* Push the record number for the new entry onto the stack. The 822f0863fe5Sdrh ** record number is a randomly generate integer created by NewRowid 8234a32431cSdrh ** except when the table has an INTEGER PRIMARY KEY column, in which 824b419a926Sdrh ** case the record number is the same as that column. 8251ccde15dSdrh */ 8265cf590c1Sdrh if( !isView ){ 8274cbdda9eSdrh if( IsVirtual(pTab) ){ 8284cbdda9eSdrh /* The row that the VUpdate opcode will delete: none */ 8296a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); 8304cbdda9eSdrh } 8314a32431cSdrh if( keyColumn>=0 ){ 832142e30dfSdrh if( useTempTable ){ 8336a288a33Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); 834142e30dfSdrh }else if( pSelect ){ 835b7654111Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid); 8364a32431cSdrh }else{ 837e4d90813Sdrh VdbeOp *pOp; 8381db639ceSdrh sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); 839e4d90813Sdrh pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1); 84001256832Sdanielk1977 if( pOp && pOp->opcode==OP_Null ){ 841e4d90813Sdrh appendFlag = 1; 842e4d90813Sdrh pOp->opcode = OP_NewRowid; 84304adf416Sdrh pOp->p1 = baseCur; 8446a288a33Sdrh pOp->p2 = regRowid; 8456a288a33Sdrh pOp->p3 = regAutoinc; 846e4d90813Sdrh } 84727a32783Sdrh } 848f0863fe5Sdrh /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 849e1e68f49Sdrh ** to generate a unique primary key value. 850e1e68f49Sdrh */ 851e4d90813Sdrh if( !appendFlag ){ 8521db639ceSdrh int j1; 8531db639ceSdrh j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); 85404adf416Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); 8551db639ceSdrh sqlite3VdbeJumpHere(v, j1); 8563c84ddffSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); 857e4d90813Sdrh } 8584cbdda9eSdrh }else if( IsVirtual(pTab) ){ 8596a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); 8604a32431cSdrh }else{ 86104adf416Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); 862e4d90813Sdrh appendFlag = 1; 8634a32431cSdrh } 8646a288a33Sdrh autoIncStep(pParse, regAutoinc, regRowid); 8654a32431cSdrh 866aacc543eSdrh /* Push onto the stack, data for all columns of the new entry, beginning 8674a32431cSdrh ** with the first column. 8684a32431cSdrh */ 869034ca14fSdanielk1977 nHidden = 0; 870cce7d176Sdrh for(i=0; i<pTab->nCol; i++){ 8716a288a33Sdrh int iRegStore = regRowid+1+i; 8724a32431cSdrh if( i==pTab->iPKey ){ 8734a32431cSdrh /* The value of the INTEGER PRIMARY KEY column is always a NULL. 874aacc543eSdrh ** Whenever this column is read, the record number will be substituted 875aacc543eSdrh ** in its place. So will fill this column with a NULL to avoid 876aacc543eSdrh ** taking up data space with information that will never be used. */ 8774c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore); 8784a32431cSdrh continue; 8794a32431cSdrh } 880967e8b73Sdrh if( pColumn==0 ){ 881034ca14fSdanielk1977 if( IsHiddenColumn(&pTab->aCol[i]) ){ 882034ca14fSdanielk1977 assert( IsVirtual(pTab) ); 883034ca14fSdanielk1977 j = -1; 884034ca14fSdanielk1977 nHidden++; 885034ca14fSdanielk1977 }else{ 886034ca14fSdanielk1977 j = i - nHidden; 887034ca14fSdanielk1977 } 888cce7d176Sdrh }else{ 889967e8b73Sdrh for(j=0; j<pColumn->nId; j++){ 890967e8b73Sdrh if( pColumn->a[j].idx==i ) break; 891cce7d176Sdrh } 892cce7d176Sdrh } 893034ca14fSdanielk1977 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ 894287fb61cSdanielk1977 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore); 895142e30dfSdrh }else if( useTempTable ){ 896287fb61cSdanielk1977 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 897142e30dfSdrh }else if( pSelect ){ 898b7654111Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); 899cce7d176Sdrh }else{ 900287fb61cSdanielk1977 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); 901cce7d176Sdrh } 902cce7d176Sdrh } 9031ccde15dSdrh 9040ca3e24bSdrh /* Generate code to check constraints and generate index keys and 9050ca3e24bSdrh ** do the insertion. 9064a32431cSdrh */ 9074cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 9084cbdda9eSdrh if( IsVirtual(pTab) ){ 9094f3dd150Sdrh sqlite3VtabMakeWritable(pParse, pTab); 9106a288a33Sdrh sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, 91166a5167bSdrh (const char*)pTab->pVtab, P4_VTAB); 9124cbdda9eSdrh }else 9134cbdda9eSdrh #endif 9144cbdda9eSdrh { 91504adf416Sdrh sqlite3GenerateConstraintChecks( 91604adf416Sdrh pParse, 91704adf416Sdrh pTab, 91804adf416Sdrh baseCur, 91904adf416Sdrh regIns, 92004adf416Sdrh aRegIdx, 92104adf416Sdrh keyColumn>=0, 92204adf416Sdrh 0, 92304adf416Sdrh onError, 92404adf416Sdrh endOfLoop 92504adf416Sdrh ); 92604adf416Sdrh sqlite3CompleteInsertion( 92704adf416Sdrh pParse, 92804adf416Sdrh pTab, 92904adf416Sdrh baseCur, 93004adf416Sdrh regIns, 93104adf416Sdrh aRegIdx, 93204adf416Sdrh 0, 93304adf416Sdrh 0, 934e4d90813Sdrh (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1, 93504adf416Sdrh appendFlag 93604adf416Sdrh ); 9375cf590c1Sdrh } 9384cbdda9eSdrh } 9391bee3d7bSdrh 940feeb1394Sdrh /* Update the count of rows that are inserted 9411bee3d7bSdrh */ 942142e30dfSdrh if( (db->flags & SQLITE_CountRows)!=0 ){ 9436a288a33Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 9441bee3d7bSdrh } 945c3f9bad2Sdanielk1977 946dca76841Sdrh if( triggers_exist ){ 947c3f9bad2Sdanielk1977 /* Code AFTER triggers */ 948dca76841Sdrh if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab, 9498f2c54e6Sdanielk1977 newIdx, -1, onError, endOfLoop, 0, 0) ){ 950f29ce559Sdanielk1977 goto insert_cleanup; 951f29ce559Sdanielk1977 } 952c3f9bad2Sdanielk1977 } 9531bee3d7bSdrh 954*e00ee6ebSdrh /* The bottom of the main insertion loop, if the data source 955*e00ee6ebSdrh ** is a SELECT statement. 9561ccde15dSdrh */ 9574adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, endOfLoop); 958142e30dfSdrh if( useTempTable ){ 959*e00ee6ebSdrh sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); 960*e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 9612eb95377Sdrh sqlite3VdbeAddOp1(v, OP_Close, srcTab); 962142e30dfSdrh }else if( pSelect ){ 963*e00ee6ebSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont); 964*e00ee6ebSdrh sqlite3VdbeJumpHere(v, addrInsTop); 9656b56344dSdrh } 966c3f9bad2Sdanielk1977 967e448dc4aSdanielk1977 if( !IsVirtual(pTab) && !isView ){ 968c3f9bad2Sdanielk1977 /* Close all tables opened */ 9692eb95377Sdrh sqlite3VdbeAddOp1(v, OP_Close, baseCur); 9706b56344dSdrh for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ 9712eb95377Sdrh sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur); 972cce7d176Sdrh } 973c3f9bad2Sdanielk1977 } 974c3f9bad2Sdanielk1977 975f3388144Sdrh /* Update the sqlite_sequence table by storing the content of the 9766a288a33Sdrh ** counter value in memory regAutoinc back into the sqlite_sequence 977f3388144Sdrh ** table. 9782958a4e6Sdrh */ 9796a288a33Sdrh autoIncEnd(pParse, iDb, pTab, regAutoinc); 9802958a4e6Sdrh 9811bee3d7bSdrh /* 982e7de6f25Sdanielk1977 ** Return the number of rows inserted. If this routine is 983e7de6f25Sdanielk1977 ** generating code because of a call to sqlite3NestedParse(), do not 984e7de6f25Sdanielk1977 ** invoke the callback function. 9851bee3d7bSdrh */ 986cc6bd383Sdanielk1977 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){ 9876a288a33Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); 98822322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, 1); 98966a5167bSdrh sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC); 9901bee3d7bSdrh } 991cce7d176Sdrh 992cce7d176Sdrh insert_cleanup: 9934adee20fSdanielk1977 sqlite3SrcListDelete(pTabList); 994d5d56523Sdanielk1977 sqlite3ExprListDelete(pList); 995d5d56523Sdanielk1977 sqlite3SelectDelete(pSelect); 9964adee20fSdanielk1977 sqlite3IdListDelete(pColumn); 997aa9b8963Sdrh sqlite3_free(aRegIdx); 998cce7d176Sdrh } 9999cfcf5d4Sdrh 10009cfcf5d4Sdrh /* 10016a288a33Sdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE. 10029cfcf5d4Sdrh ** 100304adf416Sdrh ** The input is a range of consecutive registers as follows: 10040ca3e24bSdrh ** 1005f0863fe5Sdrh ** 1. The rowid of the row to be updated before the update. This 1006b419a926Sdrh ** value is omitted unless we are doing an UPDATE that involves a 1007a05a722fSdrh ** change to the record number or writing to a virtual table. 10080ca3e24bSdrh ** 1009f0863fe5Sdrh ** 2. The rowid of the row after the update. 10100ca3e24bSdrh ** 10110ca3e24bSdrh ** 3. The data in the first column of the entry after the update. 10120ca3e24bSdrh ** 10130ca3e24bSdrh ** i. Data from middle columns... 10140ca3e24bSdrh ** 10150ca3e24bSdrh ** N. The data in the last column of the entry after the update. 10160ca3e24bSdrh ** 101704adf416Sdrh ** The regRowid parameter is the index of the register containing (2). 101804adf416Sdrh ** 1019f0863fe5Sdrh ** The old rowid shown as entry (1) above is omitted unless both isUpdate 1020f0863fe5Sdrh ** and rowidChng are 1. isUpdate is true for UPDATEs and false for 1021a05a722fSdrh ** INSERTs. RowidChng means that the new rowid is explicitly specified by 1022a05a722fSdrh ** the update or insert statement. If rowidChng is false, it means that 1023a05a722fSdrh ** the rowid is computed automatically in an insert or that the rowid value 1024a05a722fSdrh ** is not modified by the update. 10250ca3e24bSdrh ** 1026aa9b8963Sdrh ** The code generated by this routine store new index entries into 1027aa9b8963Sdrh ** registers identified by aRegIdx[]. No index entry is created for 1028aa9b8963Sdrh ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is 1029aa9b8963Sdrh ** the same as the order of indices on the linked list of indices 1030aa9b8963Sdrh ** attached to the table. 10319cfcf5d4Sdrh ** 10329cfcf5d4Sdrh ** This routine also generates code to check constraints. NOT NULL, 10339cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 10341c92853dSdrh ** then the appropriate action is performed. There are five possible 10351c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 10369cfcf5d4Sdrh ** 10379cfcf5d4Sdrh ** Constraint type Action What Happens 10389cfcf5d4Sdrh ** --------------- ---------- ---------------------------------------- 10391c92853dSdrh ** any ROLLBACK The current transaction is rolled back and 104024b03fd0Sdanielk1977 ** sqlite3_exec() returns immediately with a 10419cfcf5d4Sdrh ** return code of SQLITE_CONSTRAINT. 10429cfcf5d4Sdrh ** 10431c92853dSdrh ** any ABORT Back out changes from the current command 10441c92853dSdrh ** only (do not do a complete rollback) then 104524b03fd0Sdanielk1977 ** cause sqlite3_exec() to return immediately 10461c92853dSdrh ** with SQLITE_CONSTRAINT. 10471c92853dSdrh ** 10481c92853dSdrh ** any FAIL Sqlite_exec() returns immediately with a 10491c92853dSdrh ** return code of SQLITE_CONSTRAINT. The 10501c92853dSdrh ** transaction is not rolled back and any 10511c92853dSdrh ** prior changes are retained. 10521c92853dSdrh ** 10539cfcf5d4Sdrh ** any IGNORE The record number and data is popped from 10549cfcf5d4Sdrh ** the stack and there is an immediate jump 10559cfcf5d4Sdrh ** to label ignoreDest. 10569cfcf5d4Sdrh ** 10579cfcf5d4Sdrh ** NOT NULL REPLACE The NULL value is replace by the default 10589cfcf5d4Sdrh ** value for that column. If the default value 10599cfcf5d4Sdrh ** is NULL, the action is the same as ABORT. 10609cfcf5d4Sdrh ** 10619cfcf5d4Sdrh ** UNIQUE REPLACE The other row that conflicts with the row 10629cfcf5d4Sdrh ** being inserted is removed. 10639cfcf5d4Sdrh ** 10649cfcf5d4Sdrh ** CHECK REPLACE Illegal. The results in an exception. 10659cfcf5d4Sdrh ** 10661c92853dSdrh ** Which action to take is determined by the overrideError parameter. 10671c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter 10681c92853dSdrh ** is used. Or if pParse->onError==OE_Default then the onError value 10691c92853dSdrh ** for the constraint is used. 10709cfcf5d4Sdrh ** 1071aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with 107204adf416Sdrh ** cursor number "baseCur". All indices of pTab must also have open 107304adf416Sdrh ** read/write cursors with cursor number baseCur+i for the i-th cursor. 10749cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then 1075aa9b8963Sdrh ** cursors do not need to be open for indices where aRegIdx[i]==0. 10769cfcf5d4Sdrh */ 10774adee20fSdanielk1977 void sqlite3GenerateConstraintChecks( 10789cfcf5d4Sdrh Parse *pParse, /* The parser context */ 10799cfcf5d4Sdrh Table *pTab, /* the table into which we are inserting */ 108004adf416Sdrh int baseCur, /* Index of a read/write cursor pointing at pTab */ 108104adf416Sdrh int regRowid, /* Index of the range of input registers */ 1082aa9b8963Sdrh int *aRegIdx, /* Register used by each index. 0 for unused indices */ 1083a05a722fSdrh int rowidChng, /* True if the rowid might collide with existing entry */ 1084b419a926Sdrh int isUpdate, /* True for UPDATE, False for INSERT */ 10859cfcf5d4Sdrh int overrideError, /* Override onError to this if not OE_Default */ 1086b419a926Sdrh int ignoreDest /* Jump to this label on an OE_Ignore resolution */ 10879cfcf5d4Sdrh ){ 10889cfcf5d4Sdrh int i; 10899cfcf5d4Sdrh Vdbe *v; 10909cfcf5d4Sdrh int nCol; 10919cfcf5d4Sdrh int onError; 1092a05a722fSdrh int j1, j2, j3; /* Addresses of jump instructions */ 109304adf416Sdrh int regData; /* Register containing first data column */ 10940ca3e24bSdrh int iCur; 10950ca3e24bSdrh Index *pIdx; 10960ca3e24bSdrh int seenReplace = 0; 1097f0863fe5Sdrh int hasTwoRowids = (isUpdate && rowidChng); 10989cfcf5d4Sdrh 10994adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 11009cfcf5d4Sdrh assert( v!=0 ); 1101417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 11029cfcf5d4Sdrh nCol = pTab->nCol; 1103aa9b8963Sdrh regData = regRowid + 1; 1104aa9b8963Sdrh 110504adf416Sdrh 11069cfcf5d4Sdrh /* Test all NOT NULL constraints. 11079cfcf5d4Sdrh */ 11089cfcf5d4Sdrh for(i=0; i<nCol; i++){ 11090ca3e24bSdrh if( i==pTab->iPKey ){ 11100ca3e24bSdrh continue; 11110ca3e24bSdrh } 11129cfcf5d4Sdrh onError = pTab->aCol[i].notNull; 11130ca3e24bSdrh if( onError==OE_None ) continue; 11149cfcf5d4Sdrh if( overrideError!=OE_Default ){ 11159cfcf5d4Sdrh onError = overrideError; 1116a996e477Sdrh }else if( onError==OE_Default ){ 1117a996e477Sdrh onError = OE_Abort; 11189cfcf5d4Sdrh } 11197977a17fSdanielk1977 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ 11209cfcf5d4Sdrh onError = OE_Abort; 11219cfcf5d4Sdrh } 1122aa9b8963Sdrh j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i); 1123b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1124b84f96f8Sdanielk1977 || onError==OE_Ignore || onError==OE_Replace ); 11259cfcf5d4Sdrh switch( onError ){ 11261c92853dSdrh case OE_Rollback: 11271c92853dSdrh case OE_Abort: 11281c92853dSdrh case OE_Fail: { 1129483750baSdrh char *zMsg = 0; 113066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError); 11314adee20fSdanielk1977 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName, 113241743984Sdrh " may not be NULL", (char*)0); 113366a5167bSdrh sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC); 11349cfcf5d4Sdrh break; 11359cfcf5d4Sdrh } 11369cfcf5d4Sdrh case OE_Ignore: { 113766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 11389cfcf5d4Sdrh break; 11399cfcf5d4Sdrh } 11409cfcf5d4Sdrh case OE_Replace: { 114104adf416Sdrh sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i); 11429cfcf5d4Sdrh break; 11439cfcf5d4Sdrh } 11449cfcf5d4Sdrh } 1145aa9b8963Sdrh sqlite3VdbeJumpHere(v, j1); 11469cfcf5d4Sdrh } 11479cfcf5d4Sdrh 11489cfcf5d4Sdrh /* Test all CHECK constraints 11499cfcf5d4Sdrh */ 1150ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 11510cd2d4c9Sdrh if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){ 1152ffe07b2dSdrh int allOk = sqlite3VdbeMakeLabel(v); 1153aa9b8963Sdrh pParse->ckBase = regData; 115435573356Sdrh sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL); 1155aa01c7e2Sdrh onError = overrideError!=OE_Default ? overrideError : OE_Abort; 11562e06c67cSdrh if( onError==OE_Ignore ){ 115766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 1158aa01c7e2Sdrh }else{ 115966a5167bSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError); 1160aa01c7e2Sdrh } 1161ffe07b2dSdrh sqlite3VdbeResolveLabel(v, allOk); 1162ffe07b2dSdrh } 1163ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */ 11649cfcf5d4Sdrh 11650bd1f4eaSdrh /* If we have an INTEGER PRIMARY KEY, make sure the primary key 11660bd1f4eaSdrh ** of the new record does not previously exist. Except, if this 11670bd1f4eaSdrh ** is an UPDATE and the primary key is not changing, that is OK. 11689cfcf5d4Sdrh */ 1169f0863fe5Sdrh if( rowidChng ){ 11700ca3e24bSdrh onError = pTab->keyConf; 11710ca3e24bSdrh if( overrideError!=OE_Default ){ 11720ca3e24bSdrh onError = overrideError; 1173a996e477Sdrh }else if( onError==OE_Default ){ 1174a996e477Sdrh onError = OE_Abort; 11750ca3e24bSdrh } 1176a0217ba7Sdrh 117760a713c6Sdrh if( onError!=OE_Replace || pTab->pIndex ){ 117879b0c956Sdrh if( isUpdate ){ 1179892d3179Sdrh j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1); 118079b0c956Sdrh } 118104adf416Sdrh j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid); 11820ca3e24bSdrh switch( onError ){ 1183a0217ba7Sdrh default: { 1184a0217ba7Sdrh onError = OE_Abort; 1185a0217ba7Sdrh /* Fall thru into the next case */ 1186a0217ba7Sdrh } 11871c92853dSdrh case OE_Rollback: 11881c92853dSdrh case OE_Abort: 11891c92853dSdrh case OE_Fail: { 119066a5167bSdrh sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, 119166a5167bSdrh "PRIMARY KEY must be unique", P4_STATIC); 11920ca3e24bSdrh break; 11930ca3e24bSdrh } 11945383ae5cSdrh case OE_Replace: { 11952d401ab8Sdrh sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0); 11965383ae5cSdrh seenReplace = 1; 11975383ae5cSdrh break; 11985383ae5cSdrh } 11990ca3e24bSdrh case OE_Ignore: { 12005383ae5cSdrh assert( seenReplace==0 ); 120166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 12020ca3e24bSdrh break; 12030ca3e24bSdrh } 12040ca3e24bSdrh } 1205aa9b8963Sdrh sqlite3VdbeJumpHere(v, j3); 1206f5905aa7Sdrh if( isUpdate ){ 1207aa9b8963Sdrh sqlite3VdbeJumpHere(v, j2); 1208a05a722fSdrh } 12090ca3e24bSdrh } 12100ca3e24bSdrh } 12110bd1f4eaSdrh 12120bd1f4eaSdrh /* Test all UNIQUE constraints by creating entries for each UNIQUE 12130bd1f4eaSdrh ** index and making sure that duplicate entries do not already exist. 12140bd1f4eaSdrh ** Add the new records to the indices as we go. 12150bd1f4eaSdrh */ 1216b2fe7d8cSdrh for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){ 12172d401ab8Sdrh int regIdx; 12182d401ab8Sdrh int regR; 12192d401ab8Sdrh 1220aa9b8963Sdrh if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */ 1221b2fe7d8cSdrh 1222b2fe7d8cSdrh /* Create a key for accessing the index entry */ 12232d401ab8Sdrh regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1); 12249cfcf5d4Sdrh for(i=0; i<pIdx->nColumn; i++){ 12259cfcf5d4Sdrh int idx = pIdx->aiColumn[i]; 12269cfcf5d4Sdrh if( idx==pTab->iPKey ){ 12272d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); 12289cfcf5d4Sdrh }else{ 12292d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i); 12309cfcf5d4Sdrh } 12319cfcf5d4Sdrh } 12322d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); 12331db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]); 1234a37cdde0Sdanielk1977 sqlite3IndexAffinityStr(v, pIdx); 1235da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1); 12362d401ab8Sdrh sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); 1237b2fe7d8cSdrh 1238b2fe7d8cSdrh /* Find out what action to take in case there is an indexing conflict */ 12399cfcf5d4Sdrh onError = pIdx->onError; 1240b2fe7d8cSdrh if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */ 12419cfcf5d4Sdrh if( overrideError!=OE_Default ){ 12429cfcf5d4Sdrh onError = overrideError; 1243a996e477Sdrh }else if( onError==OE_Default ){ 1244a996e477Sdrh onError = OE_Abort; 12459cfcf5d4Sdrh } 12465383ae5cSdrh if( seenReplace ){ 12475383ae5cSdrh if( onError==OE_Ignore ) onError = OE_Replace; 12485383ae5cSdrh else if( onError==OE_Fail ) onError = OE_Abort; 12495383ae5cSdrh } 12505383ae5cSdrh 1251b2fe7d8cSdrh 1252b2fe7d8cSdrh /* Check to see if the new index entry will be unique */ 12532d401ab8Sdrh j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn); 12542d401ab8Sdrh regR = sqlite3GetTempReg(pParse); 12552d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR); 12562d401ab8Sdrh j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0, 12577209c697Sdrh regR, (char*)aRegIdx[iCur], 1258a9e852b6Smlcreech P4_INT32); 1259b2fe7d8cSdrh 1260b2fe7d8cSdrh /* Generate code that executes if the new index entry is not unique */ 1261b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1262b84f96f8Sdanielk1977 || onError==OE_Ignore || onError==OE_Replace ); 12639cfcf5d4Sdrh switch( onError ){ 12641c92853dSdrh case OE_Rollback: 12651c92853dSdrh case OE_Abort: 12661c92853dSdrh case OE_Fail: { 126737ed48edSdrh int j, n1, n2; 126837ed48edSdrh char zErrMsg[200]; 12695bb3eb9bSdrh sqlite3_snprintf(sizeof(zErrMsg), zErrMsg, 12705bb3eb9bSdrh pIdx->nColumn>1 ? "columns " : "column "); 127137ed48edSdrh n1 = strlen(zErrMsg); 127237ed48edSdrh for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){ 127337ed48edSdrh char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; 127437ed48edSdrh n2 = strlen(zCol); 127537ed48edSdrh if( j>0 ){ 12765bb3eb9bSdrh sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", "); 127737ed48edSdrh n1 += 2; 127837ed48edSdrh } 127937ed48edSdrh if( n1+n2>sizeof(zErrMsg)-30 ){ 12805bb3eb9bSdrh sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "..."); 128137ed48edSdrh n1 += 3; 128237ed48edSdrh break; 128337ed48edSdrh }else{ 12845bb3eb9bSdrh sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol); 128537ed48edSdrh n1 += n2; 128637ed48edSdrh } 128737ed48edSdrh } 12885bb3eb9bSdrh sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], 128937ed48edSdrh pIdx->nColumn>1 ? " are not unique" : " is not unique"); 129066a5167bSdrh sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0); 12919cfcf5d4Sdrh break; 12929cfcf5d4Sdrh } 12939cfcf5d4Sdrh case OE_Ignore: { 12940ca3e24bSdrh assert( seenReplace==0 ); 129566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 12969cfcf5d4Sdrh break; 12979cfcf5d4Sdrh } 12989cfcf5d4Sdrh case OE_Replace: { 12992d401ab8Sdrh sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0); 13000ca3e24bSdrh seenReplace = 1; 13019cfcf5d4Sdrh break; 13029cfcf5d4Sdrh } 13039cfcf5d4Sdrh } 1304aa9b8963Sdrh sqlite3VdbeJumpHere(v, j2); 13052d401ab8Sdrh sqlite3VdbeJumpHere(v, j3); 13062d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regR); 13079cfcf5d4Sdrh } 13089cfcf5d4Sdrh } 13090ca3e24bSdrh 13100ca3e24bSdrh /* 13110ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation 13124adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 131304adf416Sdrh ** A consecutive range of registers starting at regRowid contains the 131404adf416Sdrh ** rowid and the content to be inserted. 13150ca3e24bSdrh ** 1316b419a926Sdrh ** The arguments to this routine should be the same as the first six 13174adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks. 13180ca3e24bSdrh */ 13194adee20fSdanielk1977 void sqlite3CompleteInsertion( 13200ca3e24bSdrh Parse *pParse, /* The parser context */ 13210ca3e24bSdrh Table *pTab, /* the table into which we are inserting */ 132204adf416Sdrh int baseCur, /* Index of a read/write cursor pointing at pTab */ 132304adf416Sdrh int regRowid, /* Range of content */ 1324aa9b8963Sdrh int *aRegIdx, /* Register used by each index. 0 for unused indices */ 1325f0863fe5Sdrh int rowidChng, /* True if the record number will change */ 132670ce3f0cSdrh int isUpdate, /* True for UPDATE, False for INSERT */ 1327e4d90813Sdrh int newIdx, /* Index of NEW table for triggers. -1 if none */ 1328e4d90813Sdrh int appendBias /* True if this is likely to be an append */ 13290ca3e24bSdrh ){ 13300ca3e24bSdrh int i; 13310ca3e24bSdrh Vdbe *v; 13320ca3e24bSdrh int nIdx; 13330ca3e24bSdrh Index *pIdx; 1334b28af71aSdanielk1977 int pik_flags; 133504adf416Sdrh int regData; 1336b7654111Sdrh int regRec; 13370ca3e24bSdrh 13384adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 13390ca3e24bSdrh assert( v!=0 ); 1340417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 13410ca3e24bSdrh for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} 13420ca3e24bSdrh for(i=nIdx-1; i>=0; i--){ 1343aa9b8963Sdrh if( aRegIdx[i]==0 ) continue; 134404adf416Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]); 13450ca3e24bSdrh } 134604adf416Sdrh regData = regRowid + 1; 1347b7654111Sdrh regRec = sqlite3GetTempReg(pParse); 13481db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); 1349a37cdde0Sdanielk1977 sqlite3TableAffinityStr(v, pTab); 1350da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); 1351b84f96f8Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER 135270ce3f0cSdrh if( newIdx>=0 ){ 1353b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid); 135470ce3f0cSdrh } 1355b84f96f8Sdanielk1977 #endif 13564794f735Sdrh if( pParse->nested ){ 13574794f735Sdrh pik_flags = 0; 13584794f735Sdrh }else{ 135994eb6a14Sdanielk1977 pik_flags = OPFLAG_NCHANGE; 136094eb6a14Sdanielk1977 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); 13614794f735Sdrh } 1362e4d90813Sdrh if( appendBias ){ 1363e4d90813Sdrh pik_flags |= OPFLAG_APPEND; 1364e4d90813Sdrh } 1365b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid); 136694eb6a14Sdanielk1977 if( !pParse->nested ){ 136766a5167bSdrh sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); 136894eb6a14Sdanielk1977 } 1369b7654111Sdrh sqlite3VdbeChangeP5(v, pik_flags); 13700ca3e24bSdrh } 1371cd44690aSdrh 1372cd44690aSdrh /* 1373290c1948Sdrh ** Generate code that will open cursors for a table and for all 137404adf416Sdrh ** indices of that table. The "baseCur" parameter is the cursor number used 1375cd44690aSdrh ** for the table. Indices are opened on subsequent cursors. 1376aa9b8963Sdrh ** 1377aa9b8963Sdrh ** Return the number of indices on the table. 1378cd44690aSdrh */ 1379aa9b8963Sdrh int sqlite3OpenTableAndIndices( 1380290c1948Sdrh Parse *pParse, /* Parsing context */ 1381290c1948Sdrh Table *pTab, /* Table to be opened */ 138204adf416Sdrh int baseCur, /* Cursor number assigned to the table */ 1383290c1948Sdrh int op /* OP_OpenRead or OP_OpenWrite */ 1384290c1948Sdrh ){ 1385cd44690aSdrh int i; 13864cbdda9eSdrh int iDb; 1387cd44690aSdrh Index *pIdx; 13884cbdda9eSdrh Vdbe *v; 13894cbdda9eSdrh 1390aa9b8963Sdrh if( IsVirtual(pTab) ) return 0; 13914cbdda9eSdrh iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 13924cbdda9eSdrh v = sqlite3GetVdbe(pParse); 1393cd44690aSdrh assert( v!=0 ); 139404adf416Sdrh sqlite3OpenTable(pParse, baseCur, iDb, pTab, op); 1395cd44690aSdrh for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1396b3bf556eSdanielk1977 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); 1397da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 139804adf416Sdrh sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb, 139966a5167bSdrh (char*)pKey, P4_KEYINFO_HANDOFF); 1400207872a4Sdanielk1977 VdbeComment((v, "%s", pIdx->zName)); 1401cd44690aSdrh } 140204adf416Sdrh if( pParse->nTab<=baseCur+i ){ 140304adf416Sdrh pParse->nTab = baseCur+i; 1404290c1948Sdrh } 1405aa9b8963Sdrh return i-1; 1406cd44690aSdrh } 14079d9cf229Sdrh 140891c58e23Sdrh 140991c58e23Sdrh #ifdef SQLITE_TEST 141091c58e23Sdrh /* 141191c58e23Sdrh ** The following global variable is incremented whenever the 141291c58e23Sdrh ** transfer optimization is used. This is used for testing 141391c58e23Sdrh ** purposes only - to make sure the transfer optimization really 141491c58e23Sdrh ** is happening when it is suppose to. 141591c58e23Sdrh */ 141691c58e23Sdrh int sqlite3_xferopt_count; 141791c58e23Sdrh #endif /* SQLITE_TEST */ 141891c58e23Sdrh 141991c58e23Sdrh 14209d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 14219d9cf229Sdrh /* 14229d9cf229Sdrh ** Check to collation names to see if they are compatible. 14239d9cf229Sdrh */ 14249d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){ 14259d9cf229Sdrh if( z1==0 ){ 14269d9cf229Sdrh return z2==0; 14279d9cf229Sdrh } 14289d9cf229Sdrh if( z2==0 ){ 14299d9cf229Sdrh return 0; 14309d9cf229Sdrh } 14319d9cf229Sdrh return sqlite3StrICmp(z1, z2)==0; 14329d9cf229Sdrh } 14339d9cf229Sdrh 14349d9cf229Sdrh 14359d9cf229Sdrh /* 14369d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data 14379d9cf229Sdrh ** for index pDest in an insert transfer optimization. The rules 14389d9cf229Sdrh ** for a compatible index: 14399d9cf229Sdrh ** 14409d9cf229Sdrh ** * The index is over the same set of columns 14419d9cf229Sdrh ** * The same DESC and ASC markings occurs on all columns 14429d9cf229Sdrh ** * The same onError processing (OE_Abort, OE_Ignore, etc) 14439d9cf229Sdrh ** * The same collating sequence on each column 14449d9cf229Sdrh */ 14459d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 14469d9cf229Sdrh int i; 14479d9cf229Sdrh assert( pDest && pSrc ); 14489d9cf229Sdrh assert( pDest->pTable!=pSrc->pTable ); 14499d9cf229Sdrh if( pDest->nColumn!=pSrc->nColumn ){ 14509d9cf229Sdrh return 0; /* Different number of columns */ 14519d9cf229Sdrh } 14529d9cf229Sdrh if( pDest->onError!=pSrc->onError ){ 14539d9cf229Sdrh return 0; /* Different conflict resolution strategies */ 14549d9cf229Sdrh } 14559d9cf229Sdrh for(i=0; i<pSrc->nColumn; i++){ 14569d9cf229Sdrh if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 14579d9cf229Sdrh return 0; /* Different columns indexed */ 14589d9cf229Sdrh } 14599d9cf229Sdrh if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 14609d9cf229Sdrh return 0; /* Different sort orders */ 14619d9cf229Sdrh } 14629d9cf229Sdrh if( pSrc->azColl[i]!=pDest->azColl[i] ){ 146360a713c6Sdrh return 0; /* Different collating sequences */ 14649d9cf229Sdrh } 14659d9cf229Sdrh } 14669d9cf229Sdrh 14679d9cf229Sdrh /* If no test above fails then the indices must be compatible */ 14689d9cf229Sdrh return 1; 14699d9cf229Sdrh } 14709d9cf229Sdrh 14719d9cf229Sdrh /* 14729d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form 14739d9cf229Sdrh ** 14749d9cf229Sdrh ** INSERT INTO tab1 SELECT * FROM tab2; 14759d9cf229Sdrh ** 14769d9cf229Sdrh ** This optimization is only attempted if 14779d9cf229Sdrh ** 14789d9cf229Sdrh ** (1) tab1 and tab2 have identical schemas including all the 14798103b7d2Sdrh ** same indices and constraints 14809d9cf229Sdrh ** 14819d9cf229Sdrh ** (2) tab1 and tab2 are different tables 14829d9cf229Sdrh ** 14839d9cf229Sdrh ** (3) There must be no triggers on tab1 14849d9cf229Sdrh ** 14859d9cf229Sdrh ** (4) The result set of the SELECT statement is "*" 14869d9cf229Sdrh ** 14879d9cf229Sdrh ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY, 14889d9cf229Sdrh ** or LIMIT clause. 14899d9cf229Sdrh ** 14909d9cf229Sdrh ** (6) The SELECT statement is a simple (not a compound) select that 14919d9cf229Sdrh ** contains only tab2 in its FROM clause 14929d9cf229Sdrh ** 14939d9cf229Sdrh ** This method for implementing the INSERT transfers raw records from 14949d9cf229Sdrh ** tab2 over to tab1. The columns are not decoded. Raw records from 14959d9cf229Sdrh ** the indices of tab2 are transfered to tab1 as well. In so doing, 14969d9cf229Sdrh ** the resulting tab1 has much less fragmentation. 14979d9cf229Sdrh ** 14989d9cf229Sdrh ** This routine returns TRUE if the optimization is attempted. If any 14999d9cf229Sdrh ** of the conditions above fail so that the optimization should not 15009d9cf229Sdrh ** be attempted, then this routine returns FALSE. 15019d9cf229Sdrh */ 15029d9cf229Sdrh static int xferOptimization( 15039d9cf229Sdrh Parse *pParse, /* Parser context */ 15049d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 15059d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 15069d9cf229Sdrh int onError, /* How to handle constraint errors */ 15079d9cf229Sdrh int iDbDest /* The database of pDest */ 15089d9cf229Sdrh ){ 15099d9cf229Sdrh ExprList *pEList; /* The result set of the SELECT */ 15109d9cf229Sdrh Table *pSrc; /* The table in the FROM clause of SELECT */ 15119d9cf229Sdrh Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 15129d9cf229Sdrh struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 15139d9cf229Sdrh int i; /* Loop counter */ 15149d9cf229Sdrh int iDbSrc; /* The database of pSrc */ 15159d9cf229Sdrh int iSrc, iDest; /* Cursors from source and destination */ 15169d9cf229Sdrh int addr1, addr2; /* Loop addresses */ 15179d9cf229Sdrh int emptyDestTest; /* Address of test for empty pDest */ 15189d9cf229Sdrh int emptySrcTest; /* Address of test for empty pSrc */ 15199d9cf229Sdrh Vdbe *v; /* The VDBE we are building */ 15209d9cf229Sdrh KeyInfo *pKey; /* Key information for an index */ 15216a288a33Sdrh int regAutoinc; /* Memory register used by AUTOINC */ 1522f33c9fadSdrh int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 1523b7654111Sdrh int regData, regRowid; /* Registers holding data and rowid */ 15249d9cf229Sdrh 15259d9cf229Sdrh if( pSelect==0 ){ 15269d9cf229Sdrh return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 15279d9cf229Sdrh } 15289d9cf229Sdrh if( pDest->pTrigger ){ 15299d9cf229Sdrh return 0; /* tab1 must not have triggers */ 15309d9cf229Sdrh } 15319d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 15329d9cf229Sdrh if( pDest->isVirtual ){ 15339d9cf229Sdrh return 0; /* tab1 must not be a virtual table */ 15349d9cf229Sdrh } 15359d9cf229Sdrh #endif 15369d9cf229Sdrh if( onError==OE_Default ){ 15379d9cf229Sdrh onError = OE_Abort; 15389d9cf229Sdrh } 15399d9cf229Sdrh if( onError!=OE_Abort && onError!=OE_Rollback ){ 15409d9cf229Sdrh return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */ 15419d9cf229Sdrh } 15425ce240a6Sdanielk1977 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 15439d9cf229Sdrh if( pSelect->pSrc->nSrc!=1 ){ 15449d9cf229Sdrh return 0; /* FROM clause must have exactly one term */ 15459d9cf229Sdrh } 15469d9cf229Sdrh if( pSelect->pSrc->a[0].pSelect ){ 15479d9cf229Sdrh return 0; /* FROM clause cannot contain a subquery */ 15489d9cf229Sdrh } 15499d9cf229Sdrh if( pSelect->pWhere ){ 15509d9cf229Sdrh return 0; /* SELECT may not have a WHERE clause */ 15519d9cf229Sdrh } 15529d9cf229Sdrh if( pSelect->pOrderBy ){ 15539d9cf229Sdrh return 0; /* SELECT may not have an ORDER BY clause */ 15549d9cf229Sdrh } 15558103b7d2Sdrh /* Do not need to test for a HAVING clause. If HAVING is present but 15568103b7d2Sdrh ** there is no ORDER BY, we will get an error. */ 15579d9cf229Sdrh if( pSelect->pGroupBy ){ 15589d9cf229Sdrh return 0; /* SELECT may not have a GROUP BY clause */ 15599d9cf229Sdrh } 15609d9cf229Sdrh if( pSelect->pLimit ){ 15619d9cf229Sdrh return 0; /* SELECT may not have a LIMIT clause */ 15629d9cf229Sdrh } 15638103b7d2Sdrh assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ 15649d9cf229Sdrh if( pSelect->pPrior ){ 15659d9cf229Sdrh return 0; /* SELECT may not be a compound query */ 15669d9cf229Sdrh } 15679d9cf229Sdrh if( pSelect->isDistinct ){ 15689d9cf229Sdrh return 0; /* SELECT may not be DISTINCT */ 15699d9cf229Sdrh } 15709d9cf229Sdrh pEList = pSelect->pEList; 15719d9cf229Sdrh assert( pEList!=0 ); 15729d9cf229Sdrh if( pEList->nExpr!=1 ){ 15739d9cf229Sdrh return 0; /* The result set must have exactly one column */ 15749d9cf229Sdrh } 15759d9cf229Sdrh assert( pEList->a[0].pExpr ); 15769d9cf229Sdrh if( pEList->a[0].pExpr->op!=TK_ALL ){ 15779d9cf229Sdrh return 0; /* The result set must be the special operator "*" */ 15789d9cf229Sdrh } 15799d9cf229Sdrh 15809d9cf229Sdrh /* At this point we have established that the statement is of the 15819d9cf229Sdrh ** correct syntactic form to participate in this optimization. Now 15829d9cf229Sdrh ** we have to check the semantics. 15839d9cf229Sdrh */ 15849d9cf229Sdrh pItem = pSelect->pSrc->a; 1585ca424114Sdrh pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase); 15869d9cf229Sdrh if( pSrc==0 ){ 15879d9cf229Sdrh return 0; /* FROM clause does not contain a real table */ 15889d9cf229Sdrh } 15899d9cf229Sdrh if( pSrc==pDest ){ 15909d9cf229Sdrh return 0; /* tab1 and tab2 may not be the same table */ 15919d9cf229Sdrh } 15929d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 15939d9cf229Sdrh if( pSrc->isVirtual ){ 15949d9cf229Sdrh return 0; /* tab2 must not be a virtual table */ 15959d9cf229Sdrh } 15969d9cf229Sdrh #endif 15979d9cf229Sdrh if( pSrc->pSelect ){ 15989d9cf229Sdrh return 0; /* tab2 may not be a view */ 15999d9cf229Sdrh } 16009d9cf229Sdrh if( pDest->nCol!=pSrc->nCol ){ 16019d9cf229Sdrh return 0; /* Number of columns must be the same in tab1 and tab2 */ 16029d9cf229Sdrh } 16039d9cf229Sdrh if( pDest->iPKey!=pSrc->iPKey ){ 16049d9cf229Sdrh return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 16059d9cf229Sdrh } 16069d9cf229Sdrh for(i=0; i<pDest->nCol; i++){ 16079d9cf229Sdrh if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){ 16089d9cf229Sdrh return 0; /* Affinity must be the same on all columns */ 16099d9cf229Sdrh } 16109d9cf229Sdrh if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){ 16119d9cf229Sdrh return 0; /* Collating sequence must be the same on all columns */ 16129d9cf229Sdrh } 16139d9cf229Sdrh if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){ 16149d9cf229Sdrh return 0; /* tab2 must be NOT NULL if tab1 is */ 16159d9cf229Sdrh } 16169d9cf229Sdrh } 16179d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 1618f33c9fadSdrh if( pDestIdx->onError!=OE_None ){ 1619f33c9fadSdrh destHasUniqueIdx = 1; 1620f33c9fadSdrh } 16219d9cf229Sdrh for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 16229d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 16239d9cf229Sdrh } 16249d9cf229Sdrh if( pSrcIdx==0 ){ 16259d9cf229Sdrh return 0; /* pDestIdx has no corresponding index in pSrc */ 16269d9cf229Sdrh } 16279d9cf229Sdrh } 16287fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK 1629fb658dedSdrh if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){ 16308103b7d2Sdrh return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 16318103b7d2Sdrh } 16327fc2f41bSdrh #endif 16339d9cf229Sdrh 16349d9cf229Sdrh /* If we get this far, it means either: 16359d9cf229Sdrh ** 16369d9cf229Sdrh ** * We can always do the transfer if the table contains an 16379d9cf229Sdrh ** an integer primary key 16389d9cf229Sdrh ** 16399d9cf229Sdrh ** * We can conditionally do the transfer if the destination 16409d9cf229Sdrh ** table is empty. 16419d9cf229Sdrh */ 1642dd73521bSdrh #ifdef SQLITE_TEST 1643dd73521bSdrh sqlite3_xferopt_count++; 1644dd73521bSdrh #endif 16459d9cf229Sdrh iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema); 16469d9cf229Sdrh v = sqlite3GetVdbe(pParse); 1647f53e9b5aSdrh sqlite3CodeVerifySchema(pParse, iDbSrc); 16489d9cf229Sdrh iSrc = pParse->nTab++; 16499d9cf229Sdrh iDest = pParse->nTab++; 16506a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 16519d9cf229Sdrh sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 1652f33c9fadSdrh if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){ 1653bd36ba69Sdrh /* If tables do not have an INTEGER PRIMARY KEY and there 1654bd36ba69Sdrh ** are indices to be copied and the destination is not empty, 1655bd36ba69Sdrh ** we have to disallow the transfer optimization because the 1656bd36ba69Sdrh ** the rowids might change which will mess up indexing. 1657f33c9fadSdrh ** 1658f33c9fadSdrh ** Or if the destination has a UNIQUE index and is not empty, 1659f33c9fadSdrh ** we also disallow the transfer optimization because we cannot 1660f33c9fadSdrh ** insure that all entries in the union of DEST and SRC will be 1661f33c9fadSdrh ** unique. 16629d9cf229Sdrh */ 166366a5167bSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); 166466a5167bSdrh emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); 16659d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 16669d9cf229Sdrh }else{ 16679d9cf229Sdrh emptyDestTest = 0; 16689d9cf229Sdrh } 16699d9cf229Sdrh sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 167066a5167bSdrh emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); 1671b7654111Sdrh regData = sqlite3GetTempReg(pParse); 1672b7654111Sdrh regRowid = sqlite3GetTempReg(pParse); 167342242dedSdrh if( pDest->iPKey>=0 ){ 1674b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 1675b7654111Sdrh addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 167666a5167bSdrh sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, 167766a5167bSdrh "PRIMARY KEY must be unique", P4_STATIC); 16789d9cf229Sdrh sqlite3VdbeJumpHere(v, addr2); 1679b7654111Sdrh autoIncStep(pParse, regAutoinc, regRowid); 1680bd36ba69Sdrh }else if( pDest->pIndex==0 ){ 1681b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 168295bad4c7Sdrh }else{ 1683b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 168442242dedSdrh assert( pDest->autoInc==0 ); 168595bad4c7Sdrh } 1686b7654111Sdrh sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); 1687b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); 1688b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); 16891f4aa337Sdanielk1977 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); 169066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); 16916a288a33Sdrh autoIncEnd(pParse, iDbDest, pDest, regAutoinc); 16929d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 16939d9cf229Sdrh for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 16949d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 16959d9cf229Sdrh } 16969d9cf229Sdrh assert( pSrcIdx ); 169766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 169866a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 16999d9cf229Sdrh pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx); 1700207872a4Sdanielk1977 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc, 1701207872a4Sdanielk1977 (char*)pKey, P4_KEYINFO_HANDOFF); 1702d4e70ebdSdrh VdbeComment((v, "%s", pSrcIdx->zName)); 17039d9cf229Sdrh pKey = sqlite3IndexKeyinfo(pParse, pDestIdx); 1704207872a4Sdanielk1977 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest, 170566a5167bSdrh (char*)pKey, P4_KEYINFO_HANDOFF); 1706207872a4Sdanielk1977 VdbeComment((v, "%s", pDestIdx->zName)); 170766a5167bSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); 1708b7654111Sdrh sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); 1709b7654111Sdrh sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); 171066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); 17119d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 17129d9cf229Sdrh } 17139d9cf229Sdrh sqlite3VdbeJumpHere(v, emptySrcTest); 1714b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 1715b7654111Sdrh sqlite3ReleaseTempReg(pParse, regData); 171666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 171766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 17189d9cf229Sdrh if( emptyDestTest ){ 171966a5167bSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 17209d9cf229Sdrh sqlite3VdbeJumpHere(v, emptyDestTest); 172166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 17229d9cf229Sdrh return 0; 17239d9cf229Sdrh }else{ 17249d9cf229Sdrh return 1; 17259d9cf229Sdrh } 17269d9cf229Sdrh } 17279d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 1728f39d9588Sdrh 1729f39d9588Sdrh /* Make sure "isView" gets undefined in case this file becomes part of 1730f39d9588Sdrh ** the amalgamation - so that subsequent files do not see isView as a 1731f39d9588Sdrh ** macro. */ 1732f39d9588Sdrh #undef isView 1733