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*ca424114Sdrh ** $Id: insert.c,v 1.228 2008/01/25 15:04:50 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); 482d401ab8Sdrh pIdx->zColAff = (char *)sqlite3DbMallocZero(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 8917435752Sdrh zColAff = (char *)sqlite3DbMallocZero(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); 1786a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+8); 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); 1846a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+8); 1851db639ceSdrh sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2); 18666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iCur, 0); 1879d9cf229Sdrh } 1889d9cf229Sdrh return memId; 1899d9cf229Sdrh } 1909d9cf229Sdrh 1919d9cf229Sdrh /* 1929d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation. 1939d9cf229Sdrh ** 1949d9cf229Sdrh ** This routine should be called when the top of the stack holds a 1959d9cf229Sdrh ** new rowid that is about to be inserted. If that new rowid is 1969d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the 1979d9cf229Sdrh ** memory cell is updated. The stack is unchanged. 1989d9cf229Sdrh */ 1996a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){ 2009d9cf229Sdrh if( memId>0 ){ 2016a288a33Sdrh sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); 2029d9cf229Sdrh } 2039d9cf229Sdrh } 2049d9cf229Sdrh 2059d9cf229Sdrh /* 2069d9cf229Sdrh ** After doing one or more inserts, the maximum rowid is stored 2076a288a33Sdrh ** in reg[memId]. Generate code to write this value back into the 2089d9cf229Sdrh ** the sqlite_sequence table. 2099d9cf229Sdrh */ 2109d9cf229Sdrh static void autoIncEnd( 2119d9cf229Sdrh Parse *pParse, /* The parsing context */ 2129d9cf229Sdrh int iDb, /* Index of the database holding pTab */ 2139d9cf229Sdrh Table *pTab, /* Table we are inserting into */ 2149d9cf229Sdrh int memId /* Memory cell holding the maximum rowid */ 2159d9cf229Sdrh ){ 2169d9cf229Sdrh if( pTab->autoInc ){ 2179d9cf229Sdrh int iCur = pParse->nTab; 2189d9cf229Sdrh Vdbe *v = pParse->pVdbe; 2199d9cf229Sdrh Db *pDb = &pParse->db->aDb[iDb]; 2206a288a33Sdrh int j1; 2216a288a33Sdrh 2229d9cf229Sdrh assert( v ); 2239d9cf229Sdrh sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); 2246a288a33Sdrh j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); 2256a288a33Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1); 2266a288a33Sdrh sqlite3VdbeJumpHere(v, j1); 2271db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, memId-1); 2286a288a33Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iCur, memId-1, memId+1); 22935573356Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 2306a288a33Sdrh sqlite3VdbeAddOp1(v, OP_Close, iCur); 2319d9cf229Sdrh } 2329d9cf229Sdrh } 2339d9cf229Sdrh #else 2349d9cf229Sdrh /* 2359d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines 2369d9cf229Sdrh ** above are all no-ops 2379d9cf229Sdrh */ 2389d9cf229Sdrh # define autoIncBegin(A,B,C) (0) 239287fb61cSdanielk1977 # define autoIncStep(A,B,C) 2409d9cf229Sdrh # define autoIncEnd(A,B,C,D) 2419d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */ 2429d9cf229Sdrh 2439d9cf229Sdrh 2449d9cf229Sdrh /* Forward declaration */ 2459d9cf229Sdrh static int xferOptimization( 2469d9cf229Sdrh Parse *pParse, /* Parser context */ 2479d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 2489d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 2499d9cf229Sdrh int onError, /* How to handle constraint errors */ 2509d9cf229Sdrh int iDbDest /* The database of pDest */ 2519d9cf229Sdrh ); 2529d9cf229Sdrh 2533d1bfeaaSdanielk1977 /* 2541ccde15dSdrh ** This routine is call to handle SQL of the following forms: 255cce7d176Sdrh ** 256cce7d176Sdrh ** insert into TABLE (IDLIST) values(EXPRLIST) 2571ccde15dSdrh ** insert into TABLE (IDLIST) select 258cce7d176Sdrh ** 2591ccde15dSdrh ** The IDLIST following the table name is always optional. If omitted, 2601ccde15dSdrh ** then a list of all columns for the table is substituted. The IDLIST 261967e8b73Sdrh ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted. 2621ccde15dSdrh ** 2631ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT 2641ccde15dSdrh ** statement above, and pSelect is NULL. For the second form, pList is 2651ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate 2661ccde15dSdrh ** data for the insert. 267142e30dfSdrh ** 2689d9cf229Sdrh ** The code generated follows one of four templates. For a simple 269142e30dfSdrh ** select with data coming from a VALUES clause, the code executes 270142e30dfSdrh ** once straight down through. The template looks like this: 271142e30dfSdrh ** 272142e30dfSdrh ** open write cursor to <table> and its indices 273142e30dfSdrh ** puts VALUES clause expressions onto the stack 274142e30dfSdrh ** write the resulting record into <table> 275142e30dfSdrh ** cleanup 276142e30dfSdrh ** 2779d9cf229Sdrh ** The three remaining templates assume the statement is of the form 278142e30dfSdrh ** 279142e30dfSdrh ** INSERT INTO <table> SELECT ... 280142e30dfSdrh ** 2819d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - 2829d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table 2839d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and 2849d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical 2859d9cf229Sdrh ** schemas, including all the same indices, then a special optimization 2869d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>. 2879d9cf229Sdrh ** See the xferOptimization() function for the implementation of this 2889d9cf229Sdrh ** template. This is the second template. 2899d9cf229Sdrh ** 2909d9cf229Sdrh ** open a write cursor to <table> 2919d9cf229Sdrh ** open read cursor on <table2> 2929d9cf229Sdrh ** transfer all records in <table2> over to <table> 2939d9cf229Sdrh ** close cursors 2949d9cf229Sdrh ** foreach index on <table> 2959d9cf229Sdrh ** open a write cursor on the <table> index 2969d9cf229Sdrh ** open a read cursor on the corresponding <table2> index 2979d9cf229Sdrh ** transfer all records from the read to the write cursors 2989d9cf229Sdrh ** close cursors 2999d9cf229Sdrh ** end foreach 3009d9cf229Sdrh ** 3019d9cf229Sdrh ** The third template is for when the second template does not apply 3029d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time. 3039d9cf229Sdrh ** The generated code follows this template: 304142e30dfSdrh ** 305142e30dfSdrh ** goto B 306142e30dfSdrh ** A: setup for the SELECT 3079d9cf229Sdrh ** loop over the rows in the SELECT 308142e30dfSdrh ** gosub C 309142e30dfSdrh ** end loop 310142e30dfSdrh ** cleanup after the SELECT 311142e30dfSdrh ** goto D 312142e30dfSdrh ** B: open write cursor to <table> and its indices 313142e30dfSdrh ** goto A 314142e30dfSdrh ** C: insert the select result into <table> 315142e30dfSdrh ** return 316142e30dfSdrh ** D: cleanup 317142e30dfSdrh ** 3189d9cf229Sdrh ** The fourth template is used if the insert statement takes its 319142e30dfSdrh ** values from a SELECT but the data is being inserted into a table 320142e30dfSdrh ** that is also read as part of the SELECT. In the third form, 321142e30dfSdrh ** we have to use a intermediate table to store the results of 322142e30dfSdrh ** the select. The template is like this: 323142e30dfSdrh ** 324142e30dfSdrh ** goto B 325142e30dfSdrh ** A: setup for the SELECT 326142e30dfSdrh ** loop over the tables in the SELECT 327142e30dfSdrh ** gosub C 328142e30dfSdrh ** end loop 329142e30dfSdrh ** cleanup after the SELECT 330142e30dfSdrh ** goto D 331142e30dfSdrh ** C: insert the select result into the intermediate table 332142e30dfSdrh ** return 333142e30dfSdrh ** B: open a cursor to an intermediate table 334142e30dfSdrh ** goto A 335142e30dfSdrh ** D: open write cursor to <table> and its indices 336142e30dfSdrh ** loop over the intermediate table 337142e30dfSdrh ** transfer values form intermediate table into <table> 338142e30dfSdrh ** end the loop 339142e30dfSdrh ** cleanup 340cce7d176Sdrh */ 3414adee20fSdanielk1977 void sqlite3Insert( 342cce7d176Sdrh Parse *pParse, /* Parser context */ 343113088ecSdrh SrcList *pTabList, /* Name of table into which we are inserting */ 344cce7d176Sdrh ExprList *pList, /* List of values to be inserted */ 3455974a30fSdrh Select *pSelect, /* A SELECT statement to use as the data source */ 3469cfcf5d4Sdrh IdList *pColumn, /* Column names corresponding to IDLIST. */ 3479cfcf5d4Sdrh int onError /* How to handle constraint errors */ 348cce7d176Sdrh ){ 3496a288a33Sdrh sqlite3 *db; /* The main database structure */ 3506a288a33Sdrh Table *pTab; /* The table to insert into. aka TABLE */ 351113088ecSdrh char *zTab; /* Name of the table into which we are inserting */ 352e22a334bSdrh const char *zDb; /* Name of the database holding this table */ 3535974a30fSdrh int i, j, idx; /* Loop counters */ 3545974a30fSdrh Vdbe *v; /* Generate code into this virtual machine */ 3555974a30fSdrh Index *pIdx; /* For looping over indices of the table */ 356967e8b73Sdrh int nColumn; /* Number of columns in the data */ 3576a288a33Sdrh int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ 35804adf416Sdrh int baseCur = 0; /* VDBE Cursor number for pTab */ 3594a32431cSdrh int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ 3600ca3e24bSdrh int endOfLoop; /* Label for the end of the insertion loop */ 3614d88778bSdanielk1977 int useTempTable = 0; /* Store SELECT results in intermediate table */ 362cfe9a69fSdanielk1977 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ 3636a288a33Sdrh int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */ 364cfe9a69fSdanielk1977 int iSelectLoop = 0; /* Address of code that implements the SELECT */ 365cfe9a69fSdanielk1977 int iCleanup = 0; /* Address of the cleanup code */ 366cfe9a69fSdanielk1977 int iInsertBlock = 0; /* Address of the subroutine used to insert data */ 3676a288a33Sdrh int newIdx = -1; /* Cursor for the NEW pseudo-table */ 3686a288a33Sdrh int iDb; /* Index of database holding TABLE */ 3692958a4e6Sdrh Db *pDb; /* The database containing table being inserted into */ 370e4d90813Sdrh int appendFlag = 0; /* True if the insert is likely to be an append */ 371cce7d176Sdrh 3726a288a33Sdrh /* Register allocations */ 3736a288a33Sdrh int regFromSelect; /* Base register for data coming from SELECT */ 3746a288a33Sdrh int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ 3756a288a33Sdrh int regRowCount = 0; /* Memory cell used for the row counter */ 3766a288a33Sdrh int regIns; /* Block of regs holding rowid+data being inserted */ 3776a288a33Sdrh int regRowid; /* registers holding insert rowid */ 3786a288a33Sdrh int regData; /* register holding first column to insert */ 3796a288a33Sdrh int regRecord; /* Holds the assemblied row record */ 380aa9b8963Sdrh int *aRegIdx = 0; /* One register allocated to each index */ 3816a288a33Sdrh 382034ca14fSdanielk1977 383798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER 384798da52cSdrh int isView; /* True if attempting to insert into a view */ 385dca76841Sdrh int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */ 386798da52cSdrh #endif 387c3f9bad2Sdanielk1977 38817435752Sdrh db = pParse->db; 38917435752Sdrh if( pParse->nErr || db->mallocFailed ){ 3906f7adc8aSdrh goto insert_cleanup; 3916f7adc8aSdrh } 392daffd0e5Sdrh 3931ccde15dSdrh /* Locate the table into which we will be inserting new information. 3941ccde15dSdrh */ 395113088ecSdrh assert( pTabList->nSrc==1 ); 396113088ecSdrh zTab = pTabList->a[0].zName; 397daffd0e5Sdrh if( zTab==0 ) goto insert_cleanup; 3984adee20fSdanielk1977 pTab = sqlite3SrcListLookup(pParse, pTabList); 399c3f9bad2Sdanielk1977 if( pTab==0 ){ 400c3f9bad2Sdanielk1977 goto insert_cleanup; 401c3f9bad2Sdanielk1977 } 402da184236Sdanielk1977 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 403da184236Sdanielk1977 assert( iDb<db->nDb ); 404da184236Sdanielk1977 pDb = &db->aDb[iDb]; 4052958a4e6Sdrh zDb = pDb->zName; 4064adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ 4071962bda7Sdrh goto insert_cleanup; 4081962bda7Sdrh } 409c3f9bad2Sdanielk1977 410b7f9164eSdrh /* Figure out if we have any triggers and if the table being 411b7f9164eSdrh ** inserted into is a view 412b7f9164eSdrh */ 413b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER 414dca76841Sdrh triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0); 415b7f9164eSdrh isView = pTab->pSelect!=0; 416b7f9164eSdrh #else 417dca76841Sdrh # define triggers_exist 0 418b7f9164eSdrh # define isView 0 419b7f9164eSdrh #endif 420b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW 421b7f9164eSdrh # undef isView 422b7f9164eSdrh # define isView 0 423b7f9164eSdrh #endif 424b7f9164eSdrh 425c3f9bad2Sdanielk1977 /* Ensure that: 426c3f9bad2Sdanielk1977 * (a) the table is not read-only, 427c3f9bad2Sdanielk1977 * (b) that if it is a view then ON INSERT triggers exist 428c3f9bad2Sdanielk1977 */ 429dca76841Sdrh if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){ 430c3f9bad2Sdanielk1977 goto insert_cleanup; 431c3f9bad2Sdanielk1977 } 43243617e9aSdrh assert( pTab!=0 ); 4331ccde15dSdrh 434f573c99bSdrh /* If pTab is really a view, make sure it has been initialized. 435b3d24bf8Sdanielk1977 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 436b3d24bf8Sdanielk1977 ** module table). 437f573c99bSdrh */ 438b3d24bf8Sdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 439f573c99bSdrh goto insert_cleanup; 440f573c99bSdrh } 441f573c99bSdrh 4421ccde15dSdrh /* Allocate a VDBE 4431ccde15dSdrh */ 4444adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 4455974a30fSdrh if( v==0 ) goto insert_cleanup; 4464794f735Sdrh if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); 447da184236Sdanielk1977 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb); 4481ccde15dSdrh 449c3f9bad2Sdanielk1977 /* if there are row triggers, allocate a temp table for new.* references. */ 450dca76841Sdrh if( triggers_exist ){ 451c3f9bad2Sdanielk1977 newIdx = pParse->nTab++; 452f29ce559Sdanielk1977 } 453c3f9bad2Sdanielk1977 4549d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 4559d9cf229Sdrh /* If the statement is of the form 4569d9cf229Sdrh ** 4579d9cf229Sdrh ** INSERT INTO <table1> SELECT * FROM <table2>; 4589d9cf229Sdrh ** 4599d9cf229Sdrh ** Then special optimizations can be applied that make the transfer 4609d9cf229Sdrh ** very fast and which reduce fragmentation of indices. 4619d9cf229Sdrh */ 4629d9cf229Sdrh if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ 4639d9cf229Sdrh assert( !triggers_exist ); 4649d9cf229Sdrh assert( pList==0 ); 4659d9cf229Sdrh goto insert_cleanup; 4669d9cf229Sdrh } 4679d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 4689d9cf229Sdrh 4692958a4e6Sdrh /* If this is an AUTOINCREMENT table, look up the sequence number in the 4706a288a33Sdrh ** sqlite_sequence table and store it in memory cell regAutoinc. 4712958a4e6Sdrh */ 4726a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDb, pTab); 4732958a4e6Sdrh 4741ccde15dSdrh /* Figure out how many columns of data are supplied. If the data 475142e30dfSdrh ** is coming from a SELECT statement, then this step also generates 476142e30dfSdrh ** all the code to implement the SELECT statement and invoke a subroutine 477142e30dfSdrh ** to process each row of the result. (Template 2.) If the SELECT 478142e30dfSdrh ** statement uses the the table that is being inserted into, then the 479142e30dfSdrh ** subroutine is also coded here. That subroutine stores the SELECT 480142e30dfSdrh ** results in a temporary table. (Template 3.) 4811ccde15dSdrh */ 4825974a30fSdrh if( pSelect ){ 483142e30dfSdrh /* Data is coming from a SELECT. Generate code to implement that SELECT 484142e30dfSdrh */ 4851013c932Sdrh SelectDest dest; 486142e30dfSdrh int rc, iInitCode; 4871013c932Sdrh 48866a5167bSdrh iInitCode = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); 4894adee20fSdanielk1977 iSelectLoop = sqlite3VdbeCurrentAddr(v); 4904adee20fSdanielk1977 iInsertBlock = sqlite3VdbeMakeLabel(v); 4911013c932Sdrh sqlite3SelectDestInit(&dest, SRT_Subroutine, iInsertBlock); 492b3bce662Sdanielk1977 493b3bce662Sdanielk1977 /* Resolve the expressions in the SELECT statement and execute it. */ 4946c8c8ce0Sdanielk1977 rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0); 49517435752Sdrh if( rc || pParse->nErr || db->mallocFailed ){ 4966f7adc8aSdrh goto insert_cleanup; 4976f7adc8aSdrh } 498b3bce662Sdanielk1977 4996a288a33Sdrh regFromSelect = dest.iMem; 5004adee20fSdanielk1977 iCleanup = sqlite3VdbeMakeLabel(v); 50166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iCleanup); 5025974a30fSdrh assert( pSelect->pEList ); 503967e8b73Sdrh nColumn = pSelect->pEList->nExpr; 504142e30dfSdrh 505142e30dfSdrh /* Set useTempTable to TRUE if the result of the SELECT statement 506142e30dfSdrh ** should be written into a temporary table. Set to FALSE if each 507142e30dfSdrh ** row of the SELECT can be written directly into the result table. 508048c530cSdrh ** 509048c530cSdrh ** A temp table must be used if the table being updated is also one 510048c530cSdrh ** of the tables being read by the SELECT statement. Also use a 511048c530cSdrh ** temp table in the case of row triggers. 512142e30dfSdrh */ 51348d1178aSdrh if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){ 514048c530cSdrh useTempTable = 1; 515048c530cSdrh } 516142e30dfSdrh 517142e30dfSdrh if( useTempTable ){ 518142e30dfSdrh /* Generate the subroutine that SELECT calls to process each row of 519142e30dfSdrh ** the result. Store the result in a temporary table 520142e30dfSdrh */ 521b7654111Sdrh int regRec, regRowid; 522b7654111Sdrh 523142e30dfSdrh srcTab = pParse->nTab++; 524b7654111Sdrh regRec = sqlite3GetTempReg(pParse); 525b7654111Sdrh regRowid = sqlite3GetTempReg(pParse); 5264adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iInsertBlock); 5271db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); 528b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid); 529b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid); 53066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 531b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRec); 532b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 533142e30dfSdrh 534142e30dfSdrh /* The following code runs first because the GOTO at the very top 535142e30dfSdrh ** of the program jumps to it. Create the temporary table, then jump 536142e30dfSdrh ** back up and execute the SELECT code above. 537142e30dfSdrh */ 538d654be80Sdrh sqlite3VdbeJumpHere(v, iInitCode); 53966a5167bSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, 0); 54066a5167bSdrh sqlite3VdbeAddOp2(v, OP_SetNumColumns, srcTab, nColumn); 54166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop); 5424adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCleanup); 5435974a30fSdrh }else{ 544d654be80Sdrh sqlite3VdbeJumpHere(v, iInitCode); 545142e30dfSdrh } 546142e30dfSdrh }else{ 547142e30dfSdrh /* This is the case if the data for the INSERT is coming from a VALUES 548142e30dfSdrh ** clause 549142e30dfSdrh */ 550b3bce662Sdanielk1977 NameContext sNC; 551b3bce662Sdanielk1977 memset(&sNC, 0, sizeof(sNC)); 552b3bce662Sdanielk1977 sNC.pParse = pParse; 5535974a30fSdrh srcTab = -1; 55448d1178aSdrh assert( useTempTable==0 ); 555147d0cccSdrh nColumn = pList ? pList->nExpr : 0; 556e64e7b20Sdrh for(i=0; i<nColumn; i++){ 557b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){ 558b04a5d87Sdrh goto insert_cleanup; 559b04a5d87Sdrh } 560e64e7b20Sdrh } 5615974a30fSdrh } 5621ccde15dSdrh 5631ccde15dSdrh /* Make sure the number of columns in the source data matches the number 5641ccde15dSdrh ** of columns to be inserted into the table. 5651ccde15dSdrh */ 566034ca14fSdanielk1977 if( IsVirtual(pTab) ){ 567034ca14fSdanielk1977 for(i=0; i<pTab->nCol; i++){ 568034ca14fSdanielk1977 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); 569034ca14fSdanielk1977 } 570034ca14fSdanielk1977 } 571034ca14fSdanielk1977 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ 5724adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 573da93d238Sdrh "table %S has %d columns but %d values were supplied", 574da93d238Sdrh pTabList, 0, pTab->nCol, nColumn); 575cce7d176Sdrh goto insert_cleanup; 576cce7d176Sdrh } 577967e8b73Sdrh if( pColumn!=0 && nColumn!=pColumn->nId ){ 5784adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); 579cce7d176Sdrh goto insert_cleanup; 580cce7d176Sdrh } 5811ccde15dSdrh 5821ccde15dSdrh /* If the INSERT statement included an IDLIST term, then make sure 5831ccde15dSdrh ** all elements of the IDLIST really are columns of the table and 5841ccde15dSdrh ** remember the column indices. 585c8392586Sdrh ** 586c8392586Sdrh ** If the table has an INTEGER PRIMARY KEY column and that column 587c8392586Sdrh ** is named in the IDLIST, then record in the keyColumn variable 588c8392586Sdrh ** the index into IDLIST of the primary key column. keyColumn is 589c8392586Sdrh ** the index of the primary key as it appears in IDLIST, not as 590c8392586Sdrh ** is appears in the original table. (The index of the primary 591c8392586Sdrh ** key in the original table is pTab->iPKey.) 5921ccde15dSdrh */ 593967e8b73Sdrh if( pColumn ){ 594967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 595967e8b73Sdrh pColumn->a[i].idx = -1; 596cce7d176Sdrh } 597967e8b73Sdrh for(i=0; i<pColumn->nId; i++){ 598cce7d176Sdrh for(j=0; j<pTab->nCol; j++){ 5994adee20fSdanielk1977 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ 600967e8b73Sdrh pColumn->a[i].idx = j; 6014a32431cSdrh if( j==pTab->iPKey ){ 6029aa028daSdrh keyColumn = i; 6034a32431cSdrh } 604cce7d176Sdrh break; 605cce7d176Sdrh } 606cce7d176Sdrh } 607cce7d176Sdrh if( j>=pTab->nCol ){ 6084adee20fSdanielk1977 if( sqlite3IsRowid(pColumn->a[i].zName) ){ 609a0217ba7Sdrh keyColumn = i; 610a0217ba7Sdrh }else{ 6114adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "table %S has no column named %s", 612da93d238Sdrh pTabList, 0, pColumn->a[i].zName); 613cce7d176Sdrh pParse->nErr++; 614cce7d176Sdrh goto insert_cleanup; 615cce7d176Sdrh } 616cce7d176Sdrh } 617cce7d176Sdrh } 618a0217ba7Sdrh } 6191ccde15dSdrh 620aacc543eSdrh /* If there is no IDLIST term but the table has an integer primary 621c8392586Sdrh ** key, the set the keyColumn variable to the primary key column index 622c8392586Sdrh ** in the original table definition. 6234a32431cSdrh */ 624147d0cccSdrh if( pColumn==0 && nColumn>0 ){ 6254a32431cSdrh keyColumn = pTab->iPKey; 6264a32431cSdrh } 6274a32431cSdrh 628142e30dfSdrh /* Open the temp table for FOR EACH ROW triggers 629142e30dfSdrh */ 630dca76841Sdrh if( triggers_exist ){ 63166a5167bSdrh sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0); 63266a5167bSdrh sqlite3VdbeAddOp2(v, OP_SetNumColumns, newIdx, pTab->nCol); 633f29ce559Sdanielk1977 } 634c3f9bad2Sdanielk1977 635c3f9bad2Sdanielk1977 /* Initialize the count of rows to be inserted 6361ccde15dSdrh */ 637142e30dfSdrh if( db->flags & SQLITE_CountRows ){ 6386a288a33Sdrh regRowCount = ++pParse->nMem; 6396a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); 640c3f9bad2Sdanielk1977 } 641c3f9bad2Sdanielk1977 642e448dc4aSdanielk1977 /* If this is not a view, open the table and and all indices */ 643e448dc4aSdanielk1977 if( !isView ){ 644aa9b8963Sdrh int nIdx; 645aa9b8963Sdrh int i; 646aa9b8963Sdrh 64704adf416Sdrh baseCur = pParse->nTab; 64804adf416Sdrh nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite); 649aa9b8963Sdrh aRegIdx = sqlite3DbMallocZero(db, sizeof(int)*(nIdx+1)); 650aa9b8963Sdrh if( aRegIdx==0 ){ 651aa9b8963Sdrh goto insert_cleanup; 652aa9b8963Sdrh } 653aa9b8963Sdrh for(i=0; i<nIdx; i++){ 654aa9b8963Sdrh aRegIdx[i] = ++pParse->nMem; 655aa9b8963Sdrh } 656feeb1394Sdrh } 657feeb1394Sdrh 658142e30dfSdrh /* If the data source is a temporary table, then we have to create 6591ccde15dSdrh ** a loop because there might be multiple rows of data. If the data 660142e30dfSdrh ** source is a subroutine call from the SELECT statement, then we need 661142e30dfSdrh ** to launch the SELECT statement processing. 6621ccde15dSdrh */ 663142e30dfSdrh if( useTempTable ){ 6644adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 66566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Rewind, srcTab, iBreak); 6664adee20fSdanielk1977 iCont = sqlite3VdbeCurrentAddr(v); 667142e30dfSdrh }else if( pSelect ){ 66866a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop); 6694adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iInsertBlock); 670bed8690fSdrh } 6711ccde15dSdrh 6726a288a33Sdrh /* Allocate registers for holding the rowid of the new row, 6736a288a33Sdrh ** the content of the new row, and the assemblied row record. 6746a288a33Sdrh */ 6756a288a33Sdrh regRecord = ++pParse->nMem; 6766a288a33Sdrh regRowid = regIns = pParse->nMem+1; 6776a288a33Sdrh pParse->nMem += pTab->nCol + 1; 6786a288a33Sdrh if( IsVirtual(pTab) ){ 6796a288a33Sdrh regRowid++; 6806a288a33Sdrh pParse->nMem++; 6816a288a33Sdrh } 6826a288a33Sdrh regData = regRowid+1; 6836a288a33Sdrh 6845cf590c1Sdrh /* Run the BEFORE and INSTEAD OF triggers, if there are any 68570ce3f0cSdrh */ 6864adee20fSdanielk1977 endOfLoop = sqlite3VdbeMakeLabel(v); 687dca76841Sdrh if( triggers_exist & TRIGGER_BEFORE ){ 6882d401ab8Sdrh int regRowid; 6892d401ab8Sdrh int regCols; 6902d401ab8Sdrh int regRec; 691c3f9bad2Sdanielk1977 69270ce3f0cSdrh /* build the NEW.* reference row. Note that if there is an INTEGER 69370ce3f0cSdrh ** PRIMARY KEY into which a NULL is being inserted, that NULL will be 69470ce3f0cSdrh ** translated into a unique ID for the row. But on a BEFORE trigger, 69570ce3f0cSdrh ** we do not know what the unique ID will be (because the insert has 69670ce3f0cSdrh ** not happened yet) so we substitute a rowid of -1 69770ce3f0cSdrh */ 6982d401ab8Sdrh regRowid = sqlite3GetTempReg(pParse); 69970ce3f0cSdrh if( keyColumn<0 ){ 7002d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid); 70170ce3f0cSdrh }else if( useTempTable ){ 7022d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); 70370ce3f0cSdrh }else{ 7046a288a33Sdrh int j1; 705d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 7062d401ab8Sdrh sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); 7072d401ab8Sdrh j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); 7082d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid); 7096a288a33Sdrh sqlite3VdbeJumpHere(v, j1); 7102d401ab8Sdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); 71170ce3f0cSdrh } 71270ce3f0cSdrh 713034ca14fSdanielk1977 /* Cannot have triggers on a virtual table. If it were possible, 714034ca14fSdanielk1977 ** this block would have to account for hidden column. 715034ca14fSdanielk1977 */ 716034ca14fSdanielk1977 assert(!IsVirtual(pTab)); 717034ca14fSdanielk1977 71870ce3f0cSdrh /* Create the new column data 71970ce3f0cSdrh */ 7202d401ab8Sdrh regCols = sqlite3GetTempRange(pParse, pTab->nCol); 721c3f9bad2Sdanielk1977 for(i=0; i<pTab->nCol; i++){ 722c3f9bad2Sdanielk1977 if( pColumn==0 ){ 723c3f9bad2Sdanielk1977 j = i; 724c3f9bad2Sdanielk1977 }else{ 725c3f9bad2Sdanielk1977 for(j=0; j<pColumn->nId; j++){ 726c3f9bad2Sdanielk1977 if( pColumn->a[j].idx==i ) break; 727c3f9bad2Sdanielk1977 } 728c3f9bad2Sdanielk1977 } 729c3f9bad2Sdanielk1977 if( pColumn && j>=pColumn->nId ){ 7302d401ab8Sdrh sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i); 731142e30dfSdrh }else if( useTempTable ){ 7322d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); 733c3f9bad2Sdanielk1977 }else{ 734d6fe961eSdrh assert( pSelect==0 ); /* Otherwise useTempTable is true */ 7352d401ab8Sdrh sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i); 736c3f9bad2Sdanielk1977 } 737c3f9bad2Sdanielk1977 } 7382d401ab8Sdrh regRec = sqlite3GetTempReg(pParse); 7391db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec); 740a37cdde0Sdanielk1977 741a37cdde0Sdanielk1977 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, 742a37cdde0Sdanielk1977 ** do not attempt any conversions before assembling the record. 743a37cdde0Sdanielk1977 ** If this is a real table, attempt conversions as required by the 744a37cdde0Sdanielk1977 ** table column affinities. 745a37cdde0Sdanielk1977 */ 746a37cdde0Sdanielk1977 if( !isView ){ 747a37cdde0Sdanielk1977 sqlite3TableAffinityStr(v, pTab); 748a37cdde0Sdanielk1977 } 7492d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid); 7502d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRec); 7512d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 7522d401ab8Sdrh sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol); 753c3f9bad2Sdanielk1977 7545cf590c1Sdrh /* Fire BEFORE or INSTEAD OF triggers */ 755dca76841Sdrh if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 7568f2c54e6Sdanielk1977 newIdx, -1, onError, endOfLoop, 0, 0) ){ 757f29ce559Sdanielk1977 goto insert_cleanup; 758f29ce559Sdanielk1977 } 75970ce3f0cSdrh } 760c3f9bad2Sdanielk1977 7614a32431cSdrh /* Push the record number for the new entry onto the stack. The 762f0863fe5Sdrh ** record number is a randomly generate integer created by NewRowid 7634a32431cSdrh ** except when the table has an INTEGER PRIMARY KEY column, in which 764b419a926Sdrh ** case the record number is the same as that column. 7651ccde15dSdrh */ 7665cf590c1Sdrh if( !isView ){ 7674cbdda9eSdrh if( IsVirtual(pTab) ){ 7684cbdda9eSdrh /* The row that the VUpdate opcode will delete: none */ 7696a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); 7704cbdda9eSdrh } 7714a32431cSdrh if( keyColumn>=0 ){ 772142e30dfSdrh if( useTempTable ){ 7736a288a33Sdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); 774142e30dfSdrh }else if( pSelect ){ 775b7654111Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid); 7764a32431cSdrh }else{ 777e4d90813Sdrh VdbeOp *pOp; 7781db639ceSdrh sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); 779e4d90813Sdrh pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1); 78001256832Sdanielk1977 if( pOp && pOp->opcode==OP_Null ){ 781e4d90813Sdrh appendFlag = 1; 782e4d90813Sdrh pOp->opcode = OP_NewRowid; 78304adf416Sdrh pOp->p1 = baseCur; 7846a288a33Sdrh pOp->p2 = regRowid; 7856a288a33Sdrh pOp->p3 = regAutoinc; 786e4d90813Sdrh } 78727a32783Sdrh } 788f0863fe5Sdrh /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid 789e1e68f49Sdrh ** to generate a unique primary key value. 790e1e68f49Sdrh */ 791e4d90813Sdrh if( !appendFlag ){ 7921db639ceSdrh int j1; 7931db639ceSdrh j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); 79404adf416Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); 7951db639ceSdrh sqlite3VdbeJumpHere(v, j1); 7963c84ddffSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); 797e4d90813Sdrh } 7984cbdda9eSdrh }else if( IsVirtual(pTab) ){ 7996a288a33Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); 8004a32431cSdrh }else{ 80104adf416Sdrh sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); 802e4d90813Sdrh appendFlag = 1; 8034a32431cSdrh } 8046a288a33Sdrh autoIncStep(pParse, regAutoinc, regRowid); 8054a32431cSdrh 806aacc543eSdrh /* Push onto the stack, data for all columns of the new entry, beginning 8074a32431cSdrh ** with the first column. 8084a32431cSdrh */ 809034ca14fSdanielk1977 nHidden = 0; 810cce7d176Sdrh for(i=0; i<pTab->nCol; i++){ 8116a288a33Sdrh int iRegStore = regRowid+1+i; 8124a32431cSdrh if( i==pTab->iPKey ){ 8134a32431cSdrh /* The value of the INTEGER PRIMARY KEY column is always a NULL. 814aacc543eSdrh ** Whenever this column is read, the record number will be substituted 815aacc543eSdrh ** in its place. So will fill this column with a NULL to avoid 816aacc543eSdrh ** taking up data space with information that will never be used. */ 8174c583128Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore); 8184a32431cSdrh continue; 8194a32431cSdrh } 820967e8b73Sdrh if( pColumn==0 ){ 821034ca14fSdanielk1977 if( IsHiddenColumn(&pTab->aCol[i]) ){ 822034ca14fSdanielk1977 assert( IsVirtual(pTab) ); 823034ca14fSdanielk1977 j = -1; 824034ca14fSdanielk1977 nHidden++; 825034ca14fSdanielk1977 }else{ 826034ca14fSdanielk1977 j = i - nHidden; 827034ca14fSdanielk1977 } 828cce7d176Sdrh }else{ 829967e8b73Sdrh for(j=0; j<pColumn->nId; j++){ 830967e8b73Sdrh if( pColumn->a[j].idx==i ) break; 831cce7d176Sdrh } 832cce7d176Sdrh } 833034ca14fSdanielk1977 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ 834287fb61cSdanielk1977 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore); 835142e30dfSdrh }else if( useTempTable ){ 836287fb61cSdanielk1977 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 837142e30dfSdrh }else if( pSelect ){ 838b7654111Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); 839cce7d176Sdrh }else{ 840287fb61cSdanielk1977 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); 841cce7d176Sdrh } 842cce7d176Sdrh } 8431ccde15dSdrh 8440ca3e24bSdrh /* Generate code to check constraints and generate index keys and 8450ca3e24bSdrh ** do the insertion. 8464a32431cSdrh */ 8474cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 8484cbdda9eSdrh if( IsVirtual(pTab) ){ 849f9e7dda7Sdanielk1977 pParse->pVirtualLock = pTab; 8506a288a33Sdrh sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, 85166a5167bSdrh (const char*)pTab->pVtab, P4_VTAB); 8524cbdda9eSdrh }else 8534cbdda9eSdrh #endif 8544cbdda9eSdrh { 85504adf416Sdrh sqlite3GenerateConstraintChecks( 85604adf416Sdrh pParse, 85704adf416Sdrh pTab, 85804adf416Sdrh baseCur, 85904adf416Sdrh regIns, 86004adf416Sdrh aRegIdx, 86104adf416Sdrh keyColumn>=0, 86204adf416Sdrh 0, 86304adf416Sdrh onError, 86404adf416Sdrh endOfLoop 86504adf416Sdrh ); 86604adf416Sdrh sqlite3CompleteInsertion( 86704adf416Sdrh pParse, 86804adf416Sdrh pTab, 86904adf416Sdrh baseCur, 87004adf416Sdrh regIns, 87104adf416Sdrh aRegIdx, 87204adf416Sdrh 0, 87304adf416Sdrh 0, 874e4d90813Sdrh (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1, 87504adf416Sdrh appendFlag 87604adf416Sdrh ); 8775cf590c1Sdrh } 8784cbdda9eSdrh } 8791bee3d7bSdrh 880feeb1394Sdrh /* Update the count of rows that are inserted 8811bee3d7bSdrh */ 882142e30dfSdrh if( (db->flags & SQLITE_CountRows)!=0 ){ 8836a288a33Sdrh sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); 8841bee3d7bSdrh } 885c3f9bad2Sdanielk1977 886dca76841Sdrh if( triggers_exist ){ 887c3f9bad2Sdanielk1977 /* Code AFTER triggers */ 888dca76841Sdrh if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab, 8898f2c54e6Sdanielk1977 newIdx, -1, onError, endOfLoop, 0, 0) ){ 890f29ce559Sdanielk1977 goto insert_cleanup; 891f29ce559Sdanielk1977 } 892c3f9bad2Sdanielk1977 } 8931bee3d7bSdrh 8941ccde15dSdrh /* The bottom of the loop, if the data source is a SELECT statement 8951ccde15dSdrh */ 8964adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, endOfLoop); 897142e30dfSdrh if( useTempTable ){ 89866a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, srcTab, iCont); 8994adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 90066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, srcTab, 0); 901142e30dfSdrh }else if( pSelect ){ 90266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Return, 0, 0); 9034adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCleanup); 9046b56344dSdrh } 905c3f9bad2Sdanielk1977 906e448dc4aSdanielk1977 if( !IsVirtual(pTab) && !isView ){ 907c3f9bad2Sdanielk1977 /* Close all tables opened */ 90804adf416Sdrh sqlite3VdbeAddOp2(v, OP_Close, baseCur, 0); 9096b56344dSdrh for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ 91004adf416Sdrh sqlite3VdbeAddOp2(v, OP_Close, idx+baseCur, 0); 911cce7d176Sdrh } 912c3f9bad2Sdanielk1977 } 913c3f9bad2Sdanielk1977 914f3388144Sdrh /* Update the sqlite_sequence table by storing the content of the 9156a288a33Sdrh ** counter value in memory regAutoinc back into the sqlite_sequence 916f3388144Sdrh ** table. 9172958a4e6Sdrh */ 9186a288a33Sdrh autoIncEnd(pParse, iDb, pTab, regAutoinc); 9192958a4e6Sdrh 9201bee3d7bSdrh /* 921e7de6f25Sdanielk1977 ** Return the number of rows inserted. If this routine is 922e7de6f25Sdanielk1977 ** generating code because of a call to sqlite3NestedParse(), do not 923e7de6f25Sdanielk1977 ** invoke the callback function. 9241bee3d7bSdrh */ 925cc6bd383Sdanielk1977 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){ 9266a288a33Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); 92722322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, 1); 92866a5167bSdrh sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC); 9291bee3d7bSdrh } 930cce7d176Sdrh 931cce7d176Sdrh insert_cleanup: 9324adee20fSdanielk1977 sqlite3SrcListDelete(pTabList); 933d5d56523Sdanielk1977 sqlite3ExprListDelete(pList); 934d5d56523Sdanielk1977 sqlite3SelectDelete(pSelect); 9354adee20fSdanielk1977 sqlite3IdListDelete(pColumn); 936aa9b8963Sdrh sqlite3_free(aRegIdx); 937cce7d176Sdrh } 9389cfcf5d4Sdrh 9399cfcf5d4Sdrh /* 9406a288a33Sdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE. 9419cfcf5d4Sdrh ** 94204adf416Sdrh ** The input is a range of consecutive registers as follows: 9430ca3e24bSdrh ** 944f0863fe5Sdrh ** 1. The rowid of the row to be updated before the update. This 945b419a926Sdrh ** value is omitted unless we are doing an UPDATE that involves a 946a05a722fSdrh ** change to the record number or writing to a virtual table. 9470ca3e24bSdrh ** 948f0863fe5Sdrh ** 2. The rowid of the row after the update. 9490ca3e24bSdrh ** 9500ca3e24bSdrh ** 3. The data in the first column of the entry after the update. 9510ca3e24bSdrh ** 9520ca3e24bSdrh ** i. Data from middle columns... 9530ca3e24bSdrh ** 9540ca3e24bSdrh ** N. The data in the last column of the entry after the update. 9550ca3e24bSdrh ** 95604adf416Sdrh ** The regRowid parameter is the index of the register containing (2). 95704adf416Sdrh ** 958f0863fe5Sdrh ** The old rowid shown as entry (1) above is omitted unless both isUpdate 959f0863fe5Sdrh ** and rowidChng are 1. isUpdate is true for UPDATEs and false for 960a05a722fSdrh ** INSERTs. RowidChng means that the new rowid is explicitly specified by 961a05a722fSdrh ** the update or insert statement. If rowidChng is false, it means that 962a05a722fSdrh ** the rowid is computed automatically in an insert or that the rowid value 963a05a722fSdrh ** is not modified by the update. 9640ca3e24bSdrh ** 965aa9b8963Sdrh ** The code generated by this routine store new index entries into 966aa9b8963Sdrh ** registers identified by aRegIdx[]. No index entry is created for 967aa9b8963Sdrh ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is 968aa9b8963Sdrh ** the same as the order of indices on the linked list of indices 969aa9b8963Sdrh ** attached to the table. 9709cfcf5d4Sdrh ** 9719cfcf5d4Sdrh ** This routine also generates code to check constraints. NOT NULL, 9729cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, 9731c92853dSdrh ** then the appropriate action is performed. There are five possible 9741c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. 9759cfcf5d4Sdrh ** 9769cfcf5d4Sdrh ** Constraint type Action What Happens 9779cfcf5d4Sdrh ** --------------- ---------- ---------------------------------------- 9781c92853dSdrh ** any ROLLBACK The current transaction is rolled back and 97924b03fd0Sdanielk1977 ** sqlite3_exec() returns immediately with a 9809cfcf5d4Sdrh ** return code of SQLITE_CONSTRAINT. 9819cfcf5d4Sdrh ** 9821c92853dSdrh ** any ABORT Back out changes from the current command 9831c92853dSdrh ** only (do not do a complete rollback) then 98424b03fd0Sdanielk1977 ** cause sqlite3_exec() to return immediately 9851c92853dSdrh ** with SQLITE_CONSTRAINT. 9861c92853dSdrh ** 9871c92853dSdrh ** any FAIL Sqlite_exec() returns immediately with a 9881c92853dSdrh ** return code of SQLITE_CONSTRAINT. The 9891c92853dSdrh ** transaction is not rolled back and any 9901c92853dSdrh ** prior changes are retained. 9911c92853dSdrh ** 9929cfcf5d4Sdrh ** any IGNORE The record number and data is popped from 9939cfcf5d4Sdrh ** the stack and there is an immediate jump 9949cfcf5d4Sdrh ** to label ignoreDest. 9959cfcf5d4Sdrh ** 9969cfcf5d4Sdrh ** NOT NULL REPLACE The NULL value is replace by the default 9979cfcf5d4Sdrh ** value for that column. If the default value 9989cfcf5d4Sdrh ** is NULL, the action is the same as ABORT. 9999cfcf5d4Sdrh ** 10009cfcf5d4Sdrh ** UNIQUE REPLACE The other row that conflicts with the row 10019cfcf5d4Sdrh ** being inserted is removed. 10029cfcf5d4Sdrh ** 10039cfcf5d4Sdrh ** CHECK REPLACE Illegal. The results in an exception. 10049cfcf5d4Sdrh ** 10051c92853dSdrh ** Which action to take is determined by the overrideError parameter. 10061c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter 10071c92853dSdrh ** is used. Or if pParse->onError==OE_Default then the onError value 10081c92853dSdrh ** for the constraint is used. 10099cfcf5d4Sdrh ** 1010aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with 101104adf416Sdrh ** cursor number "baseCur". All indices of pTab must also have open 101204adf416Sdrh ** read/write cursors with cursor number baseCur+i for the i-th cursor. 10139cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then 1014aa9b8963Sdrh ** cursors do not need to be open for indices where aRegIdx[i]==0. 10159cfcf5d4Sdrh */ 10164adee20fSdanielk1977 void sqlite3GenerateConstraintChecks( 10179cfcf5d4Sdrh Parse *pParse, /* The parser context */ 10189cfcf5d4Sdrh Table *pTab, /* the table into which we are inserting */ 101904adf416Sdrh int baseCur, /* Index of a read/write cursor pointing at pTab */ 102004adf416Sdrh int regRowid, /* Index of the range of input registers */ 1021aa9b8963Sdrh int *aRegIdx, /* Register used by each index. 0 for unused indices */ 1022a05a722fSdrh int rowidChng, /* True if the rowid might collide with existing entry */ 1023b419a926Sdrh int isUpdate, /* True for UPDATE, False for INSERT */ 10249cfcf5d4Sdrh int overrideError, /* Override onError to this if not OE_Default */ 1025b419a926Sdrh int ignoreDest /* Jump to this label on an OE_Ignore resolution */ 10269cfcf5d4Sdrh ){ 10279cfcf5d4Sdrh int i; 10289cfcf5d4Sdrh Vdbe *v; 10299cfcf5d4Sdrh int nCol; 10309cfcf5d4Sdrh int onError; 1031a05a722fSdrh int j1, j2, j3; /* Addresses of jump instructions */ 103204adf416Sdrh int regData; /* Register containing first data column */ 10330ca3e24bSdrh int iCur; 10340ca3e24bSdrh Index *pIdx; 10350ca3e24bSdrh int seenReplace = 0; 1036f0863fe5Sdrh int hasTwoRowids = (isUpdate && rowidChng); 10379cfcf5d4Sdrh 10384adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 10399cfcf5d4Sdrh assert( v!=0 ); 1040417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 10419cfcf5d4Sdrh nCol = pTab->nCol; 1042aa9b8963Sdrh regData = regRowid + 1; 1043aa9b8963Sdrh 104404adf416Sdrh 10459cfcf5d4Sdrh /* Test all NOT NULL constraints. 10469cfcf5d4Sdrh */ 10479cfcf5d4Sdrh for(i=0; i<nCol; i++){ 10480ca3e24bSdrh if( i==pTab->iPKey ){ 10490ca3e24bSdrh continue; 10500ca3e24bSdrh } 10519cfcf5d4Sdrh onError = pTab->aCol[i].notNull; 10520ca3e24bSdrh if( onError==OE_None ) continue; 10539cfcf5d4Sdrh if( overrideError!=OE_Default ){ 10549cfcf5d4Sdrh onError = overrideError; 1055a996e477Sdrh }else if( onError==OE_Default ){ 1056a996e477Sdrh onError = OE_Abort; 10579cfcf5d4Sdrh } 10587977a17fSdanielk1977 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ 10599cfcf5d4Sdrh onError = OE_Abort; 10609cfcf5d4Sdrh } 1061aa9b8963Sdrh j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i); 1062b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1063b84f96f8Sdanielk1977 || onError==OE_Ignore || onError==OE_Replace ); 10649cfcf5d4Sdrh switch( onError ){ 10651c92853dSdrh case OE_Rollback: 10661c92853dSdrh case OE_Abort: 10671c92853dSdrh case OE_Fail: { 1068483750baSdrh char *zMsg = 0; 106966a5167bSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError); 10704adee20fSdanielk1977 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName, 107141743984Sdrh " may not be NULL", (char*)0); 107266a5167bSdrh sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC); 10739cfcf5d4Sdrh break; 10749cfcf5d4Sdrh } 10759cfcf5d4Sdrh case OE_Ignore: { 107666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 10779cfcf5d4Sdrh break; 10789cfcf5d4Sdrh } 10799cfcf5d4Sdrh case OE_Replace: { 108004adf416Sdrh sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i); 10819cfcf5d4Sdrh break; 10829cfcf5d4Sdrh } 10839cfcf5d4Sdrh } 1084aa9b8963Sdrh sqlite3VdbeJumpHere(v, j1); 10859cfcf5d4Sdrh } 10869cfcf5d4Sdrh 10879cfcf5d4Sdrh /* Test all CHECK constraints 10889cfcf5d4Sdrh */ 1089ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK 10900cd2d4c9Sdrh if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){ 1091ffe07b2dSdrh int allOk = sqlite3VdbeMakeLabel(v); 1092aa9b8963Sdrh pParse->ckBase = regData; 109335573356Sdrh sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL); 1094aa01c7e2Sdrh onError = overrideError!=OE_Default ? overrideError : OE_Abort; 10952e06c67cSdrh if( onError==OE_Ignore ){ 109666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 1097aa01c7e2Sdrh }else{ 109866a5167bSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError); 1099aa01c7e2Sdrh } 1100ffe07b2dSdrh sqlite3VdbeResolveLabel(v, allOk); 1101ffe07b2dSdrh } 1102ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */ 11039cfcf5d4Sdrh 11040bd1f4eaSdrh /* If we have an INTEGER PRIMARY KEY, make sure the primary key 11050bd1f4eaSdrh ** of the new record does not previously exist. Except, if this 11060bd1f4eaSdrh ** is an UPDATE and the primary key is not changing, that is OK. 11079cfcf5d4Sdrh */ 1108f0863fe5Sdrh if( rowidChng ){ 11090ca3e24bSdrh onError = pTab->keyConf; 11100ca3e24bSdrh if( overrideError!=OE_Default ){ 11110ca3e24bSdrh onError = overrideError; 1112a996e477Sdrh }else if( onError==OE_Default ){ 1113a996e477Sdrh onError = OE_Abort; 11140ca3e24bSdrh } 1115a0217ba7Sdrh 111660a713c6Sdrh if( onError!=OE_Replace || pTab->pIndex ){ 111779b0c956Sdrh if( isUpdate ){ 1118892d3179Sdrh j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1); 111979b0c956Sdrh } 112004adf416Sdrh j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid); 11210ca3e24bSdrh switch( onError ){ 1122a0217ba7Sdrh default: { 1123a0217ba7Sdrh onError = OE_Abort; 1124a0217ba7Sdrh /* Fall thru into the next case */ 1125a0217ba7Sdrh } 11261c92853dSdrh case OE_Rollback: 11271c92853dSdrh case OE_Abort: 11281c92853dSdrh case OE_Fail: { 112966a5167bSdrh sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, 113066a5167bSdrh "PRIMARY KEY must be unique", P4_STATIC); 11310ca3e24bSdrh break; 11320ca3e24bSdrh } 11335383ae5cSdrh case OE_Replace: { 11342d401ab8Sdrh sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0); 11355383ae5cSdrh seenReplace = 1; 11365383ae5cSdrh break; 11375383ae5cSdrh } 11380ca3e24bSdrh case OE_Ignore: { 11395383ae5cSdrh assert( seenReplace==0 ); 114066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 11410ca3e24bSdrh break; 11420ca3e24bSdrh } 11430ca3e24bSdrh } 1144aa9b8963Sdrh sqlite3VdbeJumpHere(v, j3); 1145f5905aa7Sdrh if( isUpdate ){ 1146aa9b8963Sdrh sqlite3VdbeJumpHere(v, j2); 1147a05a722fSdrh } 11480ca3e24bSdrh } 11490ca3e24bSdrh } 11500bd1f4eaSdrh 11510bd1f4eaSdrh /* Test all UNIQUE constraints by creating entries for each UNIQUE 11520bd1f4eaSdrh ** index and making sure that duplicate entries do not already exist. 11530bd1f4eaSdrh ** Add the new records to the indices as we go. 11540bd1f4eaSdrh */ 1155b2fe7d8cSdrh for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){ 11562d401ab8Sdrh int regIdx; 11572d401ab8Sdrh int regR; 11582d401ab8Sdrh 1159aa9b8963Sdrh if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */ 1160b2fe7d8cSdrh 1161b2fe7d8cSdrh /* Create a key for accessing the index entry */ 11622d401ab8Sdrh regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1); 11639cfcf5d4Sdrh for(i=0; i<pIdx->nColumn; i++){ 11649cfcf5d4Sdrh int idx = pIdx->aiColumn[i]; 11659cfcf5d4Sdrh if( idx==pTab->iPKey ){ 11662d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); 11679cfcf5d4Sdrh }else{ 11682d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i); 11699cfcf5d4Sdrh } 11709cfcf5d4Sdrh } 11712d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); 11721db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]); 1173a37cdde0Sdanielk1977 sqlite3IndexAffinityStr(v, pIdx); 11742d401ab8Sdrh sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); 1175b2fe7d8cSdrh 1176b2fe7d8cSdrh /* Find out what action to take in case there is an indexing conflict */ 11779cfcf5d4Sdrh onError = pIdx->onError; 1178b2fe7d8cSdrh if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */ 11799cfcf5d4Sdrh if( overrideError!=OE_Default ){ 11809cfcf5d4Sdrh onError = overrideError; 1181a996e477Sdrh }else if( onError==OE_Default ){ 1182a996e477Sdrh onError = OE_Abort; 11839cfcf5d4Sdrh } 11845383ae5cSdrh if( seenReplace ){ 11855383ae5cSdrh if( onError==OE_Ignore ) onError = OE_Replace; 11865383ae5cSdrh else if( onError==OE_Fail ) onError = OE_Abort; 11875383ae5cSdrh } 11885383ae5cSdrh 1189b2fe7d8cSdrh 1190b2fe7d8cSdrh /* Check to see if the new index entry will be unique */ 11912d401ab8Sdrh j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn); 11922d401ab8Sdrh regR = sqlite3GetTempReg(pParse); 11932d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR); 11942d401ab8Sdrh j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0, 11952d401ab8Sdrh regR, (char*)aRegIdx[iCur], P4_INT32); 1196b2fe7d8cSdrh 1197b2fe7d8cSdrh /* Generate code that executes if the new index entry is not unique */ 1198b84f96f8Sdanielk1977 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail 1199b84f96f8Sdanielk1977 || onError==OE_Ignore || onError==OE_Replace ); 12009cfcf5d4Sdrh switch( onError ){ 12011c92853dSdrh case OE_Rollback: 12021c92853dSdrh case OE_Abort: 12031c92853dSdrh case OE_Fail: { 120437ed48edSdrh int j, n1, n2; 120537ed48edSdrh char zErrMsg[200]; 12065bb3eb9bSdrh sqlite3_snprintf(sizeof(zErrMsg), zErrMsg, 12075bb3eb9bSdrh pIdx->nColumn>1 ? "columns " : "column "); 120837ed48edSdrh n1 = strlen(zErrMsg); 120937ed48edSdrh for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){ 121037ed48edSdrh char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; 121137ed48edSdrh n2 = strlen(zCol); 121237ed48edSdrh if( j>0 ){ 12135bb3eb9bSdrh sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", "); 121437ed48edSdrh n1 += 2; 121537ed48edSdrh } 121637ed48edSdrh if( n1+n2>sizeof(zErrMsg)-30 ){ 12175bb3eb9bSdrh sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "..."); 121837ed48edSdrh n1 += 3; 121937ed48edSdrh break; 122037ed48edSdrh }else{ 12215bb3eb9bSdrh sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol); 122237ed48edSdrh n1 += n2; 122337ed48edSdrh } 122437ed48edSdrh } 12255bb3eb9bSdrh sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], 122637ed48edSdrh pIdx->nColumn>1 ? " are not unique" : " is not unique"); 122766a5167bSdrh sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0); 12289cfcf5d4Sdrh break; 12299cfcf5d4Sdrh } 12309cfcf5d4Sdrh case OE_Ignore: { 12310ca3e24bSdrh assert( seenReplace==0 ); 123266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); 12339cfcf5d4Sdrh break; 12349cfcf5d4Sdrh } 12359cfcf5d4Sdrh case OE_Replace: { 12362d401ab8Sdrh sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0); 12370ca3e24bSdrh seenReplace = 1; 12389cfcf5d4Sdrh break; 12399cfcf5d4Sdrh } 12409cfcf5d4Sdrh } 1241aa9b8963Sdrh sqlite3VdbeJumpHere(v, j2); 12422d401ab8Sdrh sqlite3VdbeJumpHere(v, j3); 12432d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regR); 12449cfcf5d4Sdrh } 12459cfcf5d4Sdrh } 12460ca3e24bSdrh 12470ca3e24bSdrh /* 12480ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation 12494adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks. 125004adf416Sdrh ** A consecutive range of registers starting at regRowid contains the 125104adf416Sdrh ** rowid and the content to be inserted. 12520ca3e24bSdrh ** 1253b419a926Sdrh ** The arguments to this routine should be the same as the first six 12544adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks. 12550ca3e24bSdrh */ 12564adee20fSdanielk1977 void sqlite3CompleteInsertion( 12570ca3e24bSdrh Parse *pParse, /* The parser context */ 12580ca3e24bSdrh Table *pTab, /* the table into which we are inserting */ 125904adf416Sdrh int baseCur, /* Index of a read/write cursor pointing at pTab */ 126004adf416Sdrh int regRowid, /* Range of content */ 1261aa9b8963Sdrh int *aRegIdx, /* Register used by each index. 0 for unused indices */ 1262f0863fe5Sdrh int rowidChng, /* True if the record number will change */ 126370ce3f0cSdrh int isUpdate, /* True for UPDATE, False for INSERT */ 1264e4d90813Sdrh int newIdx, /* Index of NEW table for triggers. -1 if none */ 1265e4d90813Sdrh int appendBias /* True if this is likely to be an append */ 12660ca3e24bSdrh ){ 12670ca3e24bSdrh int i; 12680ca3e24bSdrh Vdbe *v; 12690ca3e24bSdrh int nIdx; 12700ca3e24bSdrh Index *pIdx; 1271b28af71aSdanielk1977 int pik_flags; 127204adf416Sdrh int regData; 1273b7654111Sdrh int regRec; 12740ca3e24bSdrh 12754adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 12760ca3e24bSdrh assert( v!=0 ); 1277417be79cSdrh assert( pTab->pSelect==0 ); /* This table is not a VIEW */ 12780ca3e24bSdrh for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} 12790ca3e24bSdrh for(i=nIdx-1; i>=0; i--){ 1280aa9b8963Sdrh if( aRegIdx[i]==0 ) continue; 128104adf416Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]); 12820ca3e24bSdrh } 128304adf416Sdrh regData = regRowid + 1; 1284b7654111Sdrh regRec = sqlite3GetTempReg(pParse); 12851db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); 1286a37cdde0Sdanielk1977 sqlite3TableAffinityStr(v, pTab); 1287b84f96f8Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER 128870ce3f0cSdrh if( newIdx>=0 ){ 1289b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid); 129070ce3f0cSdrh } 1291b84f96f8Sdanielk1977 #endif 12924794f735Sdrh if( pParse->nested ){ 12934794f735Sdrh pik_flags = 0; 12944794f735Sdrh }else{ 129594eb6a14Sdanielk1977 pik_flags = OPFLAG_NCHANGE; 129694eb6a14Sdanielk1977 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); 12974794f735Sdrh } 1298e4d90813Sdrh if( appendBias ){ 1299e4d90813Sdrh pik_flags |= OPFLAG_APPEND; 1300e4d90813Sdrh } 1301b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid); 130294eb6a14Sdanielk1977 if( !pParse->nested ){ 130366a5167bSdrh sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); 130494eb6a14Sdanielk1977 } 1305b7654111Sdrh sqlite3VdbeChangeP5(v, pik_flags); 13060ca3e24bSdrh } 1307cd44690aSdrh 1308cd44690aSdrh /* 1309290c1948Sdrh ** Generate code that will open cursors for a table and for all 131004adf416Sdrh ** indices of that table. The "baseCur" parameter is the cursor number used 1311cd44690aSdrh ** for the table. Indices are opened on subsequent cursors. 1312aa9b8963Sdrh ** 1313aa9b8963Sdrh ** Return the number of indices on the table. 1314cd44690aSdrh */ 1315aa9b8963Sdrh int sqlite3OpenTableAndIndices( 1316290c1948Sdrh Parse *pParse, /* Parsing context */ 1317290c1948Sdrh Table *pTab, /* Table to be opened */ 131804adf416Sdrh int baseCur, /* Cursor number assigned to the table */ 1319290c1948Sdrh int op /* OP_OpenRead or OP_OpenWrite */ 1320290c1948Sdrh ){ 1321cd44690aSdrh int i; 13224cbdda9eSdrh int iDb; 1323cd44690aSdrh Index *pIdx; 13244cbdda9eSdrh Vdbe *v; 13254cbdda9eSdrh 1326aa9b8963Sdrh if( IsVirtual(pTab) ) return 0; 13274cbdda9eSdrh iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 13284cbdda9eSdrh v = sqlite3GetVdbe(pParse); 1329cd44690aSdrh assert( v!=0 ); 133004adf416Sdrh sqlite3OpenTable(pParse, baseCur, iDb, pTab, op); 1331cd44690aSdrh for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ 1332b3bf556eSdanielk1977 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); 1333da184236Sdanielk1977 assert( pIdx->pSchema==pTab->pSchema ); 133404adf416Sdrh sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb, 133566a5167bSdrh (char*)pKey, P4_KEYINFO_HANDOFF); 1336207872a4Sdanielk1977 VdbeComment((v, "%s", pIdx->zName)); 1337cd44690aSdrh } 133804adf416Sdrh if( pParse->nTab<=baseCur+i ){ 133904adf416Sdrh pParse->nTab = baseCur+i; 1340290c1948Sdrh } 1341aa9b8963Sdrh return i-1; 1342cd44690aSdrh } 13439d9cf229Sdrh 134491c58e23Sdrh 134591c58e23Sdrh #ifdef SQLITE_TEST 134691c58e23Sdrh /* 134791c58e23Sdrh ** The following global variable is incremented whenever the 134891c58e23Sdrh ** transfer optimization is used. This is used for testing 134991c58e23Sdrh ** purposes only - to make sure the transfer optimization really 135091c58e23Sdrh ** is happening when it is suppose to. 135191c58e23Sdrh */ 135291c58e23Sdrh int sqlite3_xferopt_count; 135391c58e23Sdrh #endif /* SQLITE_TEST */ 135491c58e23Sdrh 135591c58e23Sdrh 13569d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT 13579d9cf229Sdrh /* 13589d9cf229Sdrh ** Check to collation names to see if they are compatible. 13599d9cf229Sdrh */ 13609d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){ 13619d9cf229Sdrh if( z1==0 ){ 13629d9cf229Sdrh return z2==0; 13639d9cf229Sdrh } 13649d9cf229Sdrh if( z2==0 ){ 13659d9cf229Sdrh return 0; 13669d9cf229Sdrh } 13679d9cf229Sdrh return sqlite3StrICmp(z1, z2)==0; 13689d9cf229Sdrh } 13699d9cf229Sdrh 13709d9cf229Sdrh 13719d9cf229Sdrh /* 13729d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data 13739d9cf229Sdrh ** for index pDest in an insert transfer optimization. The rules 13749d9cf229Sdrh ** for a compatible index: 13759d9cf229Sdrh ** 13769d9cf229Sdrh ** * The index is over the same set of columns 13779d9cf229Sdrh ** * The same DESC and ASC markings occurs on all columns 13789d9cf229Sdrh ** * The same onError processing (OE_Abort, OE_Ignore, etc) 13799d9cf229Sdrh ** * The same collating sequence on each column 13809d9cf229Sdrh */ 13819d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){ 13829d9cf229Sdrh int i; 13839d9cf229Sdrh assert( pDest && pSrc ); 13849d9cf229Sdrh assert( pDest->pTable!=pSrc->pTable ); 13859d9cf229Sdrh if( pDest->nColumn!=pSrc->nColumn ){ 13869d9cf229Sdrh return 0; /* Different number of columns */ 13879d9cf229Sdrh } 13889d9cf229Sdrh if( pDest->onError!=pSrc->onError ){ 13899d9cf229Sdrh return 0; /* Different conflict resolution strategies */ 13909d9cf229Sdrh } 13919d9cf229Sdrh for(i=0; i<pSrc->nColumn; i++){ 13929d9cf229Sdrh if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ 13939d9cf229Sdrh return 0; /* Different columns indexed */ 13949d9cf229Sdrh } 13959d9cf229Sdrh if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ 13969d9cf229Sdrh return 0; /* Different sort orders */ 13979d9cf229Sdrh } 13989d9cf229Sdrh if( pSrc->azColl[i]!=pDest->azColl[i] ){ 139960a713c6Sdrh return 0; /* Different collating sequences */ 14009d9cf229Sdrh } 14019d9cf229Sdrh } 14029d9cf229Sdrh 14039d9cf229Sdrh /* If no test above fails then the indices must be compatible */ 14049d9cf229Sdrh return 1; 14059d9cf229Sdrh } 14069d9cf229Sdrh 14079d9cf229Sdrh /* 14089d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form 14099d9cf229Sdrh ** 14109d9cf229Sdrh ** INSERT INTO tab1 SELECT * FROM tab2; 14119d9cf229Sdrh ** 14129d9cf229Sdrh ** This optimization is only attempted if 14139d9cf229Sdrh ** 14149d9cf229Sdrh ** (1) tab1 and tab2 have identical schemas including all the 14158103b7d2Sdrh ** same indices and constraints 14169d9cf229Sdrh ** 14179d9cf229Sdrh ** (2) tab1 and tab2 are different tables 14189d9cf229Sdrh ** 14199d9cf229Sdrh ** (3) There must be no triggers on tab1 14209d9cf229Sdrh ** 14219d9cf229Sdrh ** (4) The result set of the SELECT statement is "*" 14229d9cf229Sdrh ** 14239d9cf229Sdrh ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY, 14249d9cf229Sdrh ** or LIMIT clause. 14259d9cf229Sdrh ** 14269d9cf229Sdrh ** (6) The SELECT statement is a simple (not a compound) select that 14279d9cf229Sdrh ** contains only tab2 in its FROM clause 14289d9cf229Sdrh ** 14299d9cf229Sdrh ** This method for implementing the INSERT transfers raw records from 14309d9cf229Sdrh ** tab2 over to tab1. The columns are not decoded. Raw records from 14319d9cf229Sdrh ** the indices of tab2 are transfered to tab1 as well. In so doing, 14329d9cf229Sdrh ** the resulting tab1 has much less fragmentation. 14339d9cf229Sdrh ** 14349d9cf229Sdrh ** This routine returns TRUE if the optimization is attempted. If any 14359d9cf229Sdrh ** of the conditions above fail so that the optimization should not 14369d9cf229Sdrh ** be attempted, then this routine returns FALSE. 14379d9cf229Sdrh */ 14389d9cf229Sdrh static int xferOptimization( 14399d9cf229Sdrh Parse *pParse, /* Parser context */ 14409d9cf229Sdrh Table *pDest, /* The table we are inserting into */ 14419d9cf229Sdrh Select *pSelect, /* A SELECT statement to use as the data source */ 14429d9cf229Sdrh int onError, /* How to handle constraint errors */ 14439d9cf229Sdrh int iDbDest /* The database of pDest */ 14449d9cf229Sdrh ){ 14459d9cf229Sdrh ExprList *pEList; /* The result set of the SELECT */ 14469d9cf229Sdrh Table *pSrc; /* The table in the FROM clause of SELECT */ 14479d9cf229Sdrh Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ 14489d9cf229Sdrh struct SrcList_item *pItem; /* An element of pSelect->pSrc */ 14499d9cf229Sdrh int i; /* Loop counter */ 14509d9cf229Sdrh int iDbSrc; /* The database of pSrc */ 14519d9cf229Sdrh int iSrc, iDest; /* Cursors from source and destination */ 14529d9cf229Sdrh int addr1, addr2; /* Loop addresses */ 14539d9cf229Sdrh int emptyDestTest; /* Address of test for empty pDest */ 14549d9cf229Sdrh int emptySrcTest; /* Address of test for empty pSrc */ 14559d9cf229Sdrh Vdbe *v; /* The VDBE we are building */ 14569d9cf229Sdrh KeyInfo *pKey; /* Key information for an index */ 14576a288a33Sdrh int regAutoinc; /* Memory register used by AUTOINC */ 1458f33c9fadSdrh int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ 1459b7654111Sdrh int regData, regRowid; /* Registers holding data and rowid */ 14609d9cf229Sdrh 14619d9cf229Sdrh if( pSelect==0 ){ 14629d9cf229Sdrh return 0; /* Must be of the form INSERT INTO ... SELECT ... */ 14639d9cf229Sdrh } 14649d9cf229Sdrh if( pDest->pTrigger ){ 14659d9cf229Sdrh return 0; /* tab1 must not have triggers */ 14669d9cf229Sdrh } 14679d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 14689d9cf229Sdrh if( pDest->isVirtual ){ 14699d9cf229Sdrh return 0; /* tab1 must not be a virtual table */ 14709d9cf229Sdrh } 14719d9cf229Sdrh #endif 14729d9cf229Sdrh if( onError==OE_Default ){ 14739d9cf229Sdrh onError = OE_Abort; 14749d9cf229Sdrh } 14759d9cf229Sdrh if( onError!=OE_Abort && onError!=OE_Rollback ){ 14769d9cf229Sdrh return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */ 14779d9cf229Sdrh } 14785ce240a6Sdanielk1977 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ 14799d9cf229Sdrh if( pSelect->pSrc->nSrc!=1 ){ 14809d9cf229Sdrh return 0; /* FROM clause must have exactly one term */ 14819d9cf229Sdrh } 14829d9cf229Sdrh if( pSelect->pSrc->a[0].pSelect ){ 14839d9cf229Sdrh return 0; /* FROM clause cannot contain a subquery */ 14849d9cf229Sdrh } 14859d9cf229Sdrh if( pSelect->pWhere ){ 14869d9cf229Sdrh return 0; /* SELECT may not have a WHERE clause */ 14879d9cf229Sdrh } 14889d9cf229Sdrh if( pSelect->pOrderBy ){ 14899d9cf229Sdrh return 0; /* SELECT may not have an ORDER BY clause */ 14909d9cf229Sdrh } 14918103b7d2Sdrh /* Do not need to test for a HAVING clause. If HAVING is present but 14928103b7d2Sdrh ** there is no ORDER BY, we will get an error. */ 14939d9cf229Sdrh if( pSelect->pGroupBy ){ 14949d9cf229Sdrh return 0; /* SELECT may not have a GROUP BY clause */ 14959d9cf229Sdrh } 14969d9cf229Sdrh if( pSelect->pLimit ){ 14979d9cf229Sdrh return 0; /* SELECT may not have a LIMIT clause */ 14989d9cf229Sdrh } 14998103b7d2Sdrh assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ 15009d9cf229Sdrh if( pSelect->pPrior ){ 15019d9cf229Sdrh return 0; /* SELECT may not be a compound query */ 15029d9cf229Sdrh } 15039d9cf229Sdrh if( pSelect->isDistinct ){ 15049d9cf229Sdrh return 0; /* SELECT may not be DISTINCT */ 15059d9cf229Sdrh } 15069d9cf229Sdrh pEList = pSelect->pEList; 15079d9cf229Sdrh assert( pEList!=0 ); 15089d9cf229Sdrh if( pEList->nExpr!=1 ){ 15099d9cf229Sdrh return 0; /* The result set must have exactly one column */ 15109d9cf229Sdrh } 15119d9cf229Sdrh assert( pEList->a[0].pExpr ); 15129d9cf229Sdrh if( pEList->a[0].pExpr->op!=TK_ALL ){ 15139d9cf229Sdrh return 0; /* The result set must be the special operator "*" */ 15149d9cf229Sdrh } 15159d9cf229Sdrh 15169d9cf229Sdrh /* At this point we have established that the statement is of the 15179d9cf229Sdrh ** correct syntactic form to participate in this optimization. Now 15189d9cf229Sdrh ** we have to check the semantics. 15199d9cf229Sdrh */ 15209d9cf229Sdrh pItem = pSelect->pSrc->a; 1521*ca424114Sdrh pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase); 15229d9cf229Sdrh if( pSrc==0 ){ 15239d9cf229Sdrh return 0; /* FROM clause does not contain a real table */ 15249d9cf229Sdrh } 15259d9cf229Sdrh if( pSrc==pDest ){ 15269d9cf229Sdrh return 0; /* tab1 and tab2 may not be the same table */ 15279d9cf229Sdrh } 15289d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 15299d9cf229Sdrh if( pSrc->isVirtual ){ 15309d9cf229Sdrh return 0; /* tab2 must not be a virtual table */ 15319d9cf229Sdrh } 15329d9cf229Sdrh #endif 15339d9cf229Sdrh if( pSrc->pSelect ){ 15349d9cf229Sdrh return 0; /* tab2 may not be a view */ 15359d9cf229Sdrh } 15369d9cf229Sdrh if( pDest->nCol!=pSrc->nCol ){ 15379d9cf229Sdrh return 0; /* Number of columns must be the same in tab1 and tab2 */ 15389d9cf229Sdrh } 15399d9cf229Sdrh if( pDest->iPKey!=pSrc->iPKey ){ 15409d9cf229Sdrh return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ 15419d9cf229Sdrh } 15429d9cf229Sdrh for(i=0; i<pDest->nCol; i++){ 15439d9cf229Sdrh if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){ 15449d9cf229Sdrh return 0; /* Affinity must be the same on all columns */ 15459d9cf229Sdrh } 15469d9cf229Sdrh if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){ 15479d9cf229Sdrh return 0; /* Collating sequence must be the same on all columns */ 15489d9cf229Sdrh } 15499d9cf229Sdrh if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){ 15509d9cf229Sdrh return 0; /* tab2 must be NOT NULL if tab1 is */ 15519d9cf229Sdrh } 15529d9cf229Sdrh } 15539d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 1554f33c9fadSdrh if( pDestIdx->onError!=OE_None ){ 1555f33c9fadSdrh destHasUniqueIdx = 1; 1556f33c9fadSdrh } 15579d9cf229Sdrh for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 15589d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 15599d9cf229Sdrh } 15609d9cf229Sdrh if( pSrcIdx==0 ){ 15619d9cf229Sdrh return 0; /* pDestIdx has no corresponding index in pSrc */ 15629d9cf229Sdrh } 15639d9cf229Sdrh } 15647fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK 1565fb658dedSdrh if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){ 15668103b7d2Sdrh return 0; /* Tables have different CHECK constraints. Ticket #2252 */ 15678103b7d2Sdrh } 15687fc2f41bSdrh #endif 15699d9cf229Sdrh 15709d9cf229Sdrh /* If we get this far, it means either: 15719d9cf229Sdrh ** 15729d9cf229Sdrh ** * We can always do the transfer if the table contains an 15739d9cf229Sdrh ** an integer primary key 15749d9cf229Sdrh ** 15759d9cf229Sdrh ** * We can conditionally do the transfer if the destination 15769d9cf229Sdrh ** table is empty. 15779d9cf229Sdrh */ 1578dd73521bSdrh #ifdef SQLITE_TEST 1579dd73521bSdrh sqlite3_xferopt_count++; 1580dd73521bSdrh #endif 15819d9cf229Sdrh iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema); 15829d9cf229Sdrh v = sqlite3GetVdbe(pParse); 1583f53e9b5aSdrh sqlite3CodeVerifySchema(pParse, iDbSrc); 15849d9cf229Sdrh iSrc = pParse->nTab++; 15859d9cf229Sdrh iDest = pParse->nTab++; 15866a288a33Sdrh regAutoinc = autoIncBegin(pParse, iDbDest, pDest); 15879d9cf229Sdrh sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); 1588f33c9fadSdrh if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){ 1589bd36ba69Sdrh /* If tables do not have an INTEGER PRIMARY KEY and there 1590bd36ba69Sdrh ** are indices to be copied and the destination is not empty, 1591bd36ba69Sdrh ** we have to disallow the transfer optimization because the 1592bd36ba69Sdrh ** the rowids might change which will mess up indexing. 1593f33c9fadSdrh ** 1594f33c9fadSdrh ** Or if the destination has a UNIQUE index and is not empty, 1595f33c9fadSdrh ** we also disallow the transfer optimization because we cannot 1596f33c9fadSdrh ** insure that all entries in the union of DEST and SRC will be 1597f33c9fadSdrh ** unique. 15989d9cf229Sdrh */ 159966a5167bSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); 160066a5167bSdrh emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); 16019d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 16029d9cf229Sdrh }else{ 16039d9cf229Sdrh emptyDestTest = 0; 16049d9cf229Sdrh } 16059d9cf229Sdrh sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); 160666a5167bSdrh emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); 1607b7654111Sdrh regData = sqlite3GetTempReg(pParse); 1608b7654111Sdrh regRowid = sqlite3GetTempReg(pParse); 160942242dedSdrh if( pDest->iPKey>=0 ){ 1610b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 1611b7654111Sdrh addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); 161266a5167bSdrh sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, 161366a5167bSdrh "PRIMARY KEY must be unique", P4_STATIC); 16149d9cf229Sdrh sqlite3VdbeJumpHere(v, addr2); 1615b7654111Sdrh autoIncStep(pParse, regAutoinc, regRowid); 1616bd36ba69Sdrh }else if( pDest->pIndex==0 ){ 1617b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); 161895bad4c7Sdrh }else{ 1619b7654111Sdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); 162042242dedSdrh assert( pDest->autoInc==0 ); 162195bad4c7Sdrh } 1622b7654111Sdrh sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); 1623b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); 1624b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); 16251f4aa337Sdanielk1977 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); 162666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); 16276a288a33Sdrh autoIncEnd(pParse, iDbDest, pDest, regAutoinc); 16289d9cf229Sdrh for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ 16299d9cf229Sdrh for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ 16309d9cf229Sdrh if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; 16319d9cf229Sdrh } 16329d9cf229Sdrh assert( pSrcIdx ); 163366a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 163466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 16359d9cf229Sdrh pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx); 1636207872a4Sdanielk1977 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc, 1637207872a4Sdanielk1977 (char*)pKey, P4_KEYINFO_HANDOFF); 1638d4e70ebdSdrh VdbeComment((v, "%s", pSrcIdx->zName)); 16399d9cf229Sdrh pKey = sqlite3IndexKeyinfo(pParse, pDestIdx); 1640207872a4Sdanielk1977 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest, 164166a5167bSdrh (char*)pKey, P4_KEYINFO_HANDOFF); 1642207872a4Sdanielk1977 VdbeComment((v, "%s", pDestIdx->zName)); 164366a5167bSdrh addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); 1644b7654111Sdrh sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); 1645b7654111Sdrh sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); 164666a5167bSdrh sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); 16479d9cf229Sdrh sqlite3VdbeJumpHere(v, addr1); 16489d9cf229Sdrh } 16499d9cf229Sdrh sqlite3VdbeJumpHere(v, emptySrcTest); 1650b7654111Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 1651b7654111Sdrh sqlite3ReleaseTempReg(pParse, regData); 165266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); 165366a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 16549d9cf229Sdrh if( emptyDestTest ){ 165566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); 16569d9cf229Sdrh sqlite3VdbeJumpHere(v, emptyDestTest); 165766a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); 16589d9cf229Sdrh return 0; 16599d9cf229Sdrh }else{ 16609d9cf229Sdrh return 1; 16619d9cf229Sdrh } 16629d9cf229Sdrh } 16639d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */ 1664