| OLD | NEW |
| 1 /* | 1 /* |
| 2 ** 2001 September 15 | 2 ** 2001 September 15 |
| 3 ** | 3 ** |
| 4 ** The author disclaims copyright to this source code. In place of | 4 ** The author disclaims copyright to this source code. In place of |
| 5 ** a legal notice, here is a blessing: | 5 ** a legal notice, here is a blessing: |
| 6 ** | 6 ** |
| 7 ** May you do good and not evil. | 7 ** May you do good and not evil. |
| 8 ** May you find forgiveness for yourself and forgive others. | 8 ** May you find forgiveness for yourself and forgive others. |
| 9 ** May you share freely, never taking more than you give. | 9 ** May you share freely, never taking more than you give. |
| 10 ** | 10 ** |
| 11 ************************************************************************* | 11 ************************************************************************* |
| 12 ** This file contains C code routines that are called by the parser | 12 ** This file contains C code routines that are called by the parser |
| 13 ** to handle INSERT statements in SQLite. | 13 ** to handle INSERT statements in SQLite. |
| 14 */ | 14 */ |
| 15 #include "sqliteInt.h" | 15 #include "sqliteInt.h" |
| 16 | 16 |
| 17 /* | 17 /* |
| 18 ** Generate code that will open a table for reading. | 18 ** Generate code that will |
| 19 ** |
| 20 ** (1) acquire a lock for table pTab then |
| 21 ** (2) open pTab as cursor iCur. |
| 22 ** |
| 23 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index |
| 24 ** for that table that is actually opened. |
| 19 */ | 25 */ |
| 20 void sqlite3OpenTable( | 26 void sqlite3OpenTable( |
| 21 Parse *p, /* Generate code into this VDBE */ | 27 Parse *pParse, /* Generate code into this VDBE */ |
| 22 int iCur, /* The cursor number of the table */ | 28 int iCur, /* The cursor number of the table */ |
| 23 int iDb, /* The database index in sqlite3.aDb[] */ | 29 int iDb, /* The database index in sqlite3.aDb[] */ |
| 24 Table *pTab, /* The table to be opened */ | 30 Table *pTab, /* The table to be opened */ |
| 25 int opcode /* OP_OpenRead or OP_OpenWrite */ | 31 int opcode /* OP_OpenRead or OP_OpenWrite */ |
| 26 ){ | 32 ){ |
| 27 Vdbe *v; | 33 Vdbe *v; |
| 28 if( IsVirtual(pTab) ) return; | 34 assert( !IsVirtual(pTab) ); |
| 29 v = sqlite3GetVdbe(p); | 35 v = sqlite3GetVdbe(pParse); |
| 30 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); | 36 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); |
| 31 sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName); | 37 sqlite3TableLock(pParse, iDb, pTab->tnum, |
| 32 sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb); | 38 (opcode==OP_OpenWrite)?1:0, pTab->zName); |
| 33 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32); | 39 if( HasRowid(pTab) ){ |
| 34 VdbeComment((v, "%s", pTab->zName)); | 40 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol); |
| 41 VdbeComment((v, "%s", pTab->zName)); |
| 42 }else{ |
| 43 Index *pPk = sqlite3PrimaryKeyIndex(pTab); |
| 44 assert( pPk!=0 ); |
| 45 assert( pPk->tnum=pTab->tnum ); |
| 46 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb); |
| 47 sqlite3VdbeSetP4KeyInfo(pParse, pPk); |
| 48 VdbeComment((v, "%s", pTab->zName)); |
| 49 } |
| 35 } | 50 } |
| 36 | 51 |
| 37 /* | 52 /* |
| 38 ** Return a pointer to the column affinity string associated with index | 53 ** Return a pointer to the column affinity string associated with index |
| 39 ** pIdx. A column affinity string has one character for each column in | 54 ** pIdx. A column affinity string has one character for each column in |
| 40 ** the table, according to the affinity of the column: | 55 ** the table, according to the affinity of the column: |
| 41 ** | 56 ** |
| 42 ** Character Column affinity | 57 ** Character Column affinity |
| 43 ** ------------------------------ | 58 ** ------------------------------ |
| 44 ** 'a' TEXT | 59 ** 'A' NONE |
| 45 ** 'b' NONE | 60 ** 'B' TEXT |
| 46 ** 'c' NUMERIC | 61 ** 'C' NUMERIC |
| 47 ** 'd' INTEGER | 62 ** 'D' INTEGER |
| 48 ** 'e' REAL | 63 ** 'F' REAL |
| 49 ** | 64 ** |
| 50 ** An extra 'b' is appended to the end of the string to cover the | 65 ** An extra 'D' is appended to the end of the string to cover the |
| 51 ** rowid that appears as the last column in every index. | 66 ** rowid that appears as the last column in every index. |
| 52 ** | 67 ** |
| 53 ** Memory for the buffer containing the column index affinity string | 68 ** Memory for the buffer containing the column index affinity string |
| 54 ** is managed along with the rest of the Index structure. It will be | 69 ** is managed along with the rest of the Index structure. It will be |
| 55 ** released when sqlite3DeleteIndex() is called. | 70 ** released when sqlite3DeleteIndex() is called. |
| 56 */ | 71 */ |
| 57 const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ | 72 const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ |
| 58 if( !pIdx->zColAff ){ | 73 if( !pIdx->zColAff ){ |
| 59 /* The first time a column affinity string for a particular index is | 74 /* The first time a column affinity string for a particular index is |
| 60 ** required, it is allocated and populated here. It is then stored as | 75 ** required, it is allocated and populated here. It is then stored as |
| 61 ** a member of the Index structure for subsequent use. | 76 ** a member of the Index structure for subsequent use. |
| 62 ** | 77 ** |
| 63 ** The column affinity string will eventually be deleted by | 78 ** The column affinity string will eventually be deleted by |
| 64 ** sqliteDeleteIndex() when the Index structure itself is cleaned | 79 ** sqliteDeleteIndex() when the Index structure itself is cleaned |
| 65 ** up. | 80 ** up. |
| 66 */ | 81 */ |
| 67 int n; | 82 int n; |
| 68 Table *pTab = pIdx->pTable; | 83 Table *pTab = pIdx->pTable; |
| 69 sqlite3 *db = sqlite3VdbeDb(v); | 84 sqlite3 *db = sqlite3VdbeDb(v); |
| 70 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2); | 85 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1); |
| 71 if( !pIdx->zColAff ){ | 86 if( !pIdx->zColAff ){ |
| 72 db->mallocFailed = 1; | 87 db->mallocFailed = 1; |
| 73 return 0; | 88 return 0; |
| 74 } | 89 } |
| 75 for(n=0; n<pIdx->nColumn; n++){ | 90 for(n=0; n<pIdx->nColumn; n++){ |
| 76 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity; | 91 i16 x = pIdx->aiColumn[n]; |
| 92 pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity; |
| 77 } | 93 } |
| 78 pIdx->zColAff[n++] = SQLITE_AFF_NONE; | |
| 79 pIdx->zColAff[n] = 0; | 94 pIdx->zColAff[n] = 0; |
| 80 } | 95 } |
| 81 | 96 |
| 82 return pIdx->zColAff; | 97 return pIdx->zColAff; |
| 83 } | 98 } |
| 84 | 99 |
| 85 /* | 100 /* |
| 86 ** Set P4 of the most recently inserted opcode to a column affinity | 101 ** Compute the affinity string for table pTab, if it has not already been |
| 87 ** string for table pTab. A column affinity string has one character | 102 ** computed. As an optimization, omit trailing SQLITE_AFF_NONE affinities. |
| 88 ** for each column indexed by the index, according to the affinity of the | 103 ** |
| 89 ** column: | 104 ** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and |
| 105 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities |
| 106 ** for register iReg and following. Or if affinities exists and iReg==0, |
| 107 ** then just set the P4 operand of the previous opcode (which should be |
| 108 ** an OP_MakeRecord) to the affinity string. |
| 109 ** |
| 110 ** A column affinity string has one character per column: |
| 90 ** | 111 ** |
| 91 ** Character Column affinity | 112 ** Character Column affinity |
| 92 ** ------------------------------ | 113 ** ------------------------------ |
| 93 ** 'a' TEXT | 114 ** 'A' NONE |
| 94 ** 'b' NONE | 115 ** 'B' TEXT |
| 95 ** 'c' NUMERIC | 116 ** 'C' NUMERIC |
| 96 ** 'd' INTEGER | 117 ** 'D' INTEGER |
| 97 ** 'e' REAL | 118 ** 'E' REAL |
| 98 */ | 119 */ |
| 99 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){ | 120 void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ |
| 100 /* The first time a column affinity string for a particular table | 121 int i; |
| 101 ** is required, it is allocated and populated here. It is then | 122 char *zColAff = pTab->zColAff; |
| 102 ** stored as a member of the Table structure for subsequent use. | 123 if( zColAff==0 ){ |
| 103 ** | |
| 104 ** The column affinity string will eventually be deleted by | |
| 105 ** sqlite3DeleteTable() when the Table structure itself is cleaned up. | |
| 106 */ | |
| 107 if( !pTab->zColAff ){ | |
| 108 char *zColAff; | |
| 109 int i; | |
| 110 sqlite3 *db = sqlite3VdbeDb(v); | 124 sqlite3 *db = sqlite3VdbeDb(v); |
| 111 | |
| 112 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); | 125 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); |
| 113 if( !zColAff ){ | 126 if( !zColAff ){ |
| 114 db->mallocFailed = 1; | 127 db->mallocFailed = 1; |
| 115 return; | 128 return; |
| 116 } | 129 } |
| 117 | 130 |
| 118 for(i=0; i<pTab->nCol; i++){ | 131 for(i=0; i<pTab->nCol; i++){ |
| 119 zColAff[i] = pTab->aCol[i].affinity; | 132 zColAff[i] = pTab->aCol[i].affinity; |
| 120 } | 133 } |
| 121 zColAff[pTab->nCol] = '\0'; | 134 do{ |
| 122 | 135 zColAff[i--] = 0; |
| 136 }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE ); |
| 123 pTab->zColAff = zColAff; | 137 pTab->zColAff = zColAff; |
| 124 } | 138 } |
| 125 | 139 i = sqlite3Strlen30(zColAff); |
| 126 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT); | 140 if( i ){ |
| 141 if( iReg ){ |
| 142 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i); |
| 143 }else{ |
| 144 sqlite3VdbeChangeP4(v, -1, zColAff, i); |
| 145 } |
| 146 } |
| 127 } | 147 } |
| 128 | 148 |
| 129 /* | 149 /* |
| 130 ** Return non-zero if the table pTab in database iDb or any of its indices | 150 ** Return non-zero if the table pTab in database iDb or any of its indices |
| 131 ** have been opened at any point in the VDBE program beginning at location | 151 ** have been opened at any point in the VDBE program. This is used to see if |
| 132 ** iStartAddr throught the end of the program. This is used to see if | |
| 133 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can | 152 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can |
| 134 ** run without using temporary table for the results of the SELECT. | 153 ** run without using a temporary table for the results of the SELECT. |
| 135 */ | 154 */ |
| 136 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){ | 155 static int readsTable(Parse *p, int iDb, Table *pTab){ |
| 137 Vdbe *v = sqlite3GetVdbe(p); | 156 Vdbe *v = sqlite3GetVdbe(p); |
| 138 int i; | 157 int i; |
| 139 int iEnd = sqlite3VdbeCurrentAddr(v); | 158 int iEnd = sqlite3VdbeCurrentAddr(v); |
| 140 #ifndef SQLITE_OMIT_VIRTUALTABLE | 159 #ifndef SQLITE_OMIT_VIRTUALTABLE |
| 141 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; | 160 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; |
| 142 #endif | 161 #endif |
| 143 | 162 |
| 144 for(i=iStartAddr; i<iEnd; i++){ | 163 for(i=1; i<iEnd; i++){ |
| 145 VdbeOp *pOp = sqlite3VdbeGetOp(v, i); | 164 VdbeOp *pOp = sqlite3VdbeGetOp(v, i); |
| 146 assert( pOp!=0 ); | 165 assert( pOp!=0 ); |
| 147 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ | 166 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ |
| 148 Index *pIndex; | 167 Index *pIndex; |
| 149 int tnum = pOp->p2; | 168 int tnum = pOp->p2; |
| 150 if( tnum==pTab->tnum ){ | 169 if( tnum==pTab->tnum ){ |
| 151 return 1; | 170 return 1; |
| 152 } | 171 } |
| 153 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ | 172 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ |
| 154 if( tnum==pIndex->tnum ){ | 173 if( tnum==pIndex->tnum ){ |
| (...skipping 77 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 232 ** only called from the top-level */ | 251 ** only called from the top-level */ |
| 233 assert( pParse->pTriggerTab==0 ); | 252 assert( pParse->pTriggerTab==0 ); |
| 234 assert( pParse==sqlite3ParseToplevel(pParse) ); | 253 assert( pParse==sqlite3ParseToplevel(pParse) ); |
| 235 | 254 |
| 236 assert( v ); /* We failed long ago if this is not so */ | 255 assert( v ); /* We failed long ago if this is not so */ |
| 237 for(p = pParse->pAinc; p; p = p->pNext){ | 256 for(p = pParse->pAinc; p; p = p->pNext){ |
| 238 pDb = &db->aDb[p->iDb]; | 257 pDb = &db->aDb[p->iDb]; |
| 239 memId = p->regCtr; | 258 memId = p->regCtr; |
| 240 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); | 259 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); |
| 241 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); | 260 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); |
| 261 sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1); |
| 242 addr = sqlite3VdbeCurrentAddr(v); | 262 addr = sqlite3VdbeCurrentAddr(v); |
| 243 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0); | 263 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0); |
| 244 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); | 264 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v); |
| 245 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId); | 265 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId); |
| 246 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); | 266 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v); |
| 247 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); | 267 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); |
| 248 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1); | 268 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1); |
| 249 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId); | 269 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId); |
| 250 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9); | 270 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9); |
| 251 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); | 271 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v); |
| 252 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId); | 272 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId); |
| 253 sqlite3VdbeAddOp0(v, OP_Close); | 273 sqlite3VdbeAddOp0(v, OP_Close); |
| 254 } | 274 } |
| 255 } | 275 } |
| 256 | 276 |
| 257 /* | 277 /* |
| 258 ** Update the maximum rowid for an autoincrement calculation. | 278 ** Update the maximum rowid for an autoincrement calculation. |
| 259 ** | 279 ** |
| 260 ** This routine should be called when the top of the stack holds a | 280 ** This routine should be called when the top of the stack holds a |
| 261 ** new rowid that is about to be inserted. If that new rowid is | 281 ** new rowid that is about to be inserted. If that new rowid is |
| (...skipping 14 matching lines...) Expand all Loading... |
| 276 ** routine just before the "exit" code. | 296 ** routine just before the "exit" code. |
| 277 */ | 297 */ |
| 278 void sqlite3AutoincrementEnd(Parse *pParse){ | 298 void sqlite3AutoincrementEnd(Parse *pParse){ |
| 279 AutoincInfo *p; | 299 AutoincInfo *p; |
| 280 Vdbe *v = pParse->pVdbe; | 300 Vdbe *v = pParse->pVdbe; |
| 281 sqlite3 *db = pParse->db; | 301 sqlite3 *db = pParse->db; |
| 282 | 302 |
| 283 assert( v ); | 303 assert( v ); |
| 284 for(p = pParse->pAinc; p; p = p->pNext){ | 304 for(p = pParse->pAinc; p; p = p->pNext){ |
| 285 Db *pDb = &db->aDb[p->iDb]; | 305 Db *pDb = &db->aDb[p->iDb]; |
| 286 int j1, j2, j3, j4, j5; | 306 int j1; |
| 287 int iRec; | 307 int iRec; |
| 288 int memId = p->regCtr; | 308 int memId = p->regCtr; |
| 289 | 309 |
| 290 iRec = sqlite3GetTempReg(pParse); | 310 iRec = sqlite3GetTempReg(pParse); |
| 291 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); | 311 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); |
| 292 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); | 312 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); |
| 293 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); | 313 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v); |
| 294 j2 = sqlite3VdbeAddOp0(v, OP_Rewind); | |
| 295 j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec); | |
| 296 j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec); | |
| 297 sqlite3VdbeAddOp2(v, OP_Next, 0, j3); | |
| 298 sqlite3VdbeJumpHere(v, j2); | |
| 299 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1); | 314 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1); |
| 300 j5 = sqlite3VdbeAddOp0(v, OP_Goto); | |
| 301 sqlite3VdbeJumpHere(v, j4); | |
| 302 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1); | |
| 303 sqlite3VdbeJumpHere(v, j1); | 315 sqlite3VdbeJumpHere(v, j1); |
| 304 sqlite3VdbeJumpHere(v, j5); | |
| 305 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec); | 316 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec); |
| 306 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1); | 317 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1); |
| 307 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); | 318 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); |
| 308 sqlite3VdbeAddOp0(v, OP_Close); | 319 sqlite3VdbeAddOp0(v, OP_Close); |
| 309 sqlite3ReleaseTempReg(pParse, iRec); | 320 sqlite3ReleaseTempReg(pParse, iRec); |
| 310 } | 321 } |
| 311 } | 322 } |
| 312 #else | 323 #else |
| 313 /* | 324 /* |
| 314 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines | 325 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines |
| 315 ** above are all no-ops | 326 ** above are all no-ops |
| 316 */ | 327 */ |
| 317 # define autoIncBegin(A,B,C) (0) | 328 # define autoIncBegin(A,B,C) (0) |
| 318 # define autoIncStep(A,B,C) | 329 # define autoIncStep(A,B,C) |
| 319 #endif /* SQLITE_OMIT_AUTOINCREMENT */ | 330 #endif /* SQLITE_OMIT_AUTOINCREMENT */ |
| 320 | 331 |
| 321 | 332 |
| 322 /* Forward declaration */ | 333 /* Forward declaration */ |
| 323 static int xferOptimization( | 334 static int xferOptimization( |
| 324 Parse *pParse, /* Parser context */ | 335 Parse *pParse, /* Parser context */ |
| 325 Table *pDest, /* The table we are inserting into */ | 336 Table *pDest, /* The table we are inserting into */ |
| 326 Select *pSelect, /* A SELECT statement to use as the data source */ | 337 Select *pSelect, /* A SELECT statement to use as the data source */ |
| 327 int onError, /* How to handle constraint errors */ | 338 int onError, /* How to handle constraint errors */ |
| 328 int iDbDest /* The database of pDest */ | 339 int iDbDest /* The database of pDest */ |
| 329 ); | 340 ); |
| 330 | 341 |
| 331 /* | 342 /* |
| 332 ** This routine is call to handle SQL of the following forms: | 343 ** This routine is called to handle SQL of the following forms: |
| 333 ** | 344 ** |
| 334 ** insert into TABLE (IDLIST) values(EXPRLIST) | 345 ** insert into TABLE (IDLIST) values(EXPRLIST) |
| 335 ** insert into TABLE (IDLIST) select | 346 ** insert into TABLE (IDLIST) select |
| 336 ** | 347 ** |
| 337 ** The IDLIST following the table name is always optional. If omitted, | 348 ** The IDLIST following the table name is always optional. If omitted, |
| 338 ** then a list of all columns for the table is substituted. The IDLIST | 349 ** then a list of all columns for the table is substituted. The IDLIST |
| 339 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted. | 350 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted. |
| 340 ** | 351 ** |
| 341 ** The pList parameter holds EXPRLIST in the first form of the INSERT | 352 ** The pList parameter holds EXPRLIST in the first form of the INSERT |
| 342 ** statement above, and pSelect is NULL. For the second form, pList is | 353 ** statement above, and pSelect is NULL. For the second form, pList is |
| 343 ** NULL and pSelect is a pointer to the select statement used to generate | 354 ** NULL and pSelect is a pointer to the select statement used to generate |
| 344 ** data for the insert. | 355 ** data for the insert. |
| 345 ** | 356 ** |
| 346 ** The code generated follows one of four templates. For a simple | 357 ** The code generated follows one of four templates. For a simple |
| 347 ** select with data coming from a VALUES clause, the code executes | 358 ** insert with data coming from a VALUES clause, the code executes |
| 348 ** once straight down through. Pseudo-code follows (we call this | 359 ** once straight down through. Pseudo-code follows (we call this |
| 349 ** the "1st template"): | 360 ** the "1st template"): |
| 350 ** | 361 ** |
| 351 ** open write cursor to <table> and its indices | 362 ** open write cursor to <table> and its indices |
| 352 ** puts VALUES clause expressions onto the stack | 363 ** put VALUES clause expressions into registers |
| 353 ** write the resulting record into <table> | 364 ** write the resulting record into <table> |
| 354 ** cleanup | 365 ** cleanup |
| 355 ** | 366 ** |
| 356 ** The three remaining templates assume the statement is of the form | 367 ** The three remaining templates assume the statement is of the form |
| 357 ** | 368 ** |
| 358 ** INSERT INTO <table> SELECT ... | 369 ** INSERT INTO <table> SELECT ... |
| 359 ** | 370 ** |
| 360 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - | 371 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - |
| 361 ** in other words if the SELECT pulls all columns from a single table | 372 ** in other words if the SELECT pulls all columns from a single table |
| 362 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and | 373 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and |
| (...skipping 11 matching lines...) Expand all Loading... |
| 374 ** open a write cursor on the <table> index | 385 ** open a write cursor on the <table> index |
| 375 ** open a read cursor on the corresponding <table2> index | 386 ** open a read cursor on the corresponding <table2> index |
| 376 ** transfer all records from the read to the write cursors | 387 ** transfer all records from the read to the write cursors |
| 377 ** close cursors | 388 ** close cursors |
| 378 ** end foreach | 389 ** end foreach |
| 379 ** | 390 ** |
| 380 ** The 3rd template is for when the second template does not apply | 391 ** The 3rd template is for when the second template does not apply |
| 381 ** and the SELECT clause does not read from <table> at any time. | 392 ** and the SELECT clause does not read from <table> at any time. |
| 382 ** The generated code follows this template: | 393 ** The generated code follows this template: |
| 383 ** | 394 ** |
| 384 ** EOF <- 0 | |
| 385 ** X <- A | 395 ** X <- A |
| 386 ** goto B | 396 ** goto B |
| 387 ** A: setup for the SELECT | 397 ** A: setup for the SELECT |
| 388 ** loop over the rows in the SELECT | 398 ** loop over the rows in the SELECT |
| 389 ** load values into registers R..R+n | 399 ** load values into registers R..R+n |
| 390 ** yield X | 400 ** yield X |
| 391 ** end loop | 401 ** end loop |
| 392 ** cleanup after the SELECT | 402 ** cleanup after the SELECT |
| 393 ** EOF <- 1 | 403 ** end-coroutine X |
| 394 ** yield X | |
| 395 ** goto A | |
| 396 ** B: open write cursor to <table> and its indices | 404 ** B: open write cursor to <table> and its indices |
| 397 ** C: yield X | 405 ** C: yield X, at EOF goto D |
| 398 ** if EOF goto D | |
| 399 ** insert the select result into <table> from R..R+n | 406 ** insert the select result into <table> from R..R+n |
| 400 ** goto C | 407 ** goto C |
| 401 ** D: cleanup | 408 ** D: cleanup |
| 402 ** | 409 ** |
| 403 ** The 4th template is used if the insert statement takes its | 410 ** The 4th template is used if the insert statement takes its |
| 404 ** values from a SELECT but the data is being inserted into a table | 411 ** values from a SELECT but the data is being inserted into a table |
| 405 ** that is also read as part of the SELECT. In the third form, | 412 ** that is also read as part of the SELECT. In the third form, |
| 406 ** we have to use a intermediate table to store the results of | 413 ** we have to use an intermediate table to store the results of |
| 407 ** the select. The template is like this: | 414 ** the select. The template is like this: |
| 408 ** | 415 ** |
| 409 ** EOF <- 0 | |
| 410 ** X <- A | 416 ** X <- A |
| 411 ** goto B | 417 ** goto B |
| 412 ** A: setup for the SELECT | 418 ** A: setup for the SELECT |
| 413 ** loop over the tables in the SELECT | 419 ** loop over the tables in the SELECT |
| 414 ** load value into register R..R+n | 420 ** load value into register R..R+n |
| 415 ** yield X | 421 ** yield X |
| 416 ** end loop | 422 ** end loop |
| 417 ** cleanup after the SELECT | 423 ** cleanup after the SELECT |
| 418 ** EOF <- 1 | 424 ** end co-routine R |
| 419 ** yield X | |
| 420 ** halt-error | |
| 421 ** B: open temp table | 425 ** B: open temp table |
| 422 ** L: yield X | 426 ** L: yield X, at EOF goto M |
| 423 ** if EOF goto M | |
| 424 ** insert row from R..R+n into temp table | 427 ** insert row from R..R+n into temp table |
| 425 ** goto L | 428 ** goto L |
| 426 ** M: open write cursor to <table> and its indices | 429 ** M: open write cursor to <table> and its indices |
| 427 ** rewind temp table | 430 ** rewind temp table |
| 428 ** C: loop over rows of intermediate table | 431 ** C: loop over rows of intermediate table |
| 429 ** transfer values form intermediate table into <table> | 432 ** transfer values form intermediate table into <table> |
| 430 ** end loop | 433 ** end loop |
| 431 ** D: cleanup | 434 ** D: cleanup |
| 432 */ | 435 */ |
| 433 void sqlite3Insert( | 436 void sqlite3Insert( |
| 434 Parse *pParse, /* Parser context */ | 437 Parse *pParse, /* Parser context */ |
| 435 SrcList *pTabList, /* Name of table into which we are inserting */ | 438 SrcList *pTabList, /* Name of table into which we are inserting */ |
| 436 ExprList *pList, /* List of values to be inserted */ | |
| 437 Select *pSelect, /* A SELECT statement to use as the data source */ | 439 Select *pSelect, /* A SELECT statement to use as the data source */ |
| 438 IdList *pColumn, /* Column names corresponding to IDLIST. */ | 440 IdList *pColumn, /* Column names corresponding to IDLIST. */ |
| 439 int onError /* How to handle constraint errors */ | 441 int onError /* How to handle constraint errors */ |
| 440 ){ | 442 ){ |
| 441 sqlite3 *db; /* The main database structure */ | 443 sqlite3 *db; /* The main database structure */ |
| 442 Table *pTab; /* The table to insert into. aka TABLE */ | 444 Table *pTab; /* The table to insert into. aka TABLE */ |
| 443 char *zTab; /* Name of the table into which we are inserting */ | 445 char *zTab; /* Name of the table into which we are inserting */ |
| 444 const char *zDb; /* Name of the database holding this table */ | 446 const char *zDb; /* Name of the database holding this table */ |
| 445 int i, j, idx; /* Loop counters */ | 447 int i, j, idx; /* Loop counters */ |
| 446 Vdbe *v; /* Generate code into this virtual machine */ | 448 Vdbe *v; /* Generate code into this virtual machine */ |
| 447 Index *pIdx; /* For looping over indices of the table */ | 449 Index *pIdx; /* For looping over indices of the table */ |
| 448 int nColumn; /* Number of columns in the data */ | 450 int nColumn; /* Number of columns in the data */ |
| 449 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ | 451 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ |
| 450 int baseCur = 0; /* VDBE Cursor number for pTab */ | 452 int iDataCur = 0; /* VDBE cursor that is the main data repository */ |
| 451 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ | 453 int iIdxCur = 0; /* First index cursor */ |
| 454 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ |
| 452 int endOfLoop; /* Label for the end of the insertion loop */ | 455 int endOfLoop; /* Label for the end of the insertion loop */ |
| 453 int useTempTable = 0; /* Store SELECT results in intermediate table */ | |
| 454 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ | 456 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ |
| 455 int addrInsTop = 0; /* Jump to label "D" */ | 457 int addrInsTop = 0; /* Jump to label "D" */ |
| 456 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ | 458 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ |
| 457 int addrSelect = 0; /* Address of coroutine that implements the SELECT */ | |
| 458 SelectDest dest; /* Destination for SELECT on rhs of INSERT */ | 459 SelectDest dest; /* Destination for SELECT on rhs of INSERT */ |
| 459 int iDb; /* Index of database holding TABLE */ | 460 int iDb; /* Index of database holding TABLE */ |
| 460 Db *pDb; /* The database containing table being inserted into */ | 461 Db *pDb; /* The database containing table being inserted into */ |
| 461 int appendFlag = 0; /* True if the insert is likely to be an append */ | 462 u8 useTempTable = 0; /* Store SELECT results in intermediate table */ |
| 463 u8 appendFlag = 0; /* True if the insert is likely to be an append */ |
| 464 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ |
| 465 u8 bIdListInOrder = 1; /* True if IDLIST is in table order */ |
| 466 ExprList *pList = 0; /* List of VALUES() to be inserted */ |
| 462 | 467 |
| 463 /* Register allocations */ | 468 /* Register allocations */ |
| 464 int regFromSelect = 0;/* Base register for data coming from SELECT */ | 469 int regFromSelect = 0;/* Base register for data coming from SELECT */ |
| 465 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ | 470 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ |
| 466 int regRowCount = 0; /* Memory cell used for the row counter */ | 471 int regRowCount = 0; /* Memory cell used for the row counter */ |
| 467 int regIns; /* Block of regs holding rowid+data being inserted */ | 472 int regIns; /* Block of regs holding rowid+data being inserted */ |
| 468 int regRowid; /* registers holding insert rowid */ | 473 int regRowid; /* registers holding insert rowid */ |
| 469 int regData; /* register holding first column to insert */ | 474 int regData; /* register holding first column to insert */ |
| 470 int regEof = 0; /* Register recording end of SELECT data */ | |
| 471 int *aRegIdx = 0; /* One register allocated to each index */ | 475 int *aRegIdx = 0; /* One register allocated to each index */ |
| 472 | 476 |
| 473 #ifndef SQLITE_OMIT_TRIGGER | 477 #ifndef SQLITE_OMIT_TRIGGER |
| 474 int isView; /* True if attempting to insert into a view */ | 478 int isView; /* True if attempting to insert into a view */ |
| 475 Trigger *pTrigger; /* List of triggers on pTab, if required */ | 479 Trigger *pTrigger; /* List of triggers on pTab, if required */ |
| 476 int tmask; /* Mask of trigger times */ | 480 int tmask; /* Mask of trigger times */ |
| 477 #endif | 481 #endif |
| 478 | 482 |
| 479 db = pParse->db; | 483 db = pParse->db; |
| 480 memset(&dest, 0, sizeof(dest)); | 484 memset(&dest, 0, sizeof(dest)); |
| 481 if( pParse->nErr || db->mallocFailed ){ | 485 if( pParse->nErr || db->mallocFailed ){ |
| 482 goto insert_cleanup; | 486 goto insert_cleanup; |
| 483 } | 487 } |
| 484 | 488 |
| 489 /* If the Select object is really just a simple VALUES() list with a |
| 490 ** single row values (the common case) then keep that one row of values |
| 491 ** and go ahead and discard the Select object |
| 492 */ |
| 493 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){ |
| 494 pList = pSelect->pEList; |
| 495 pSelect->pEList = 0; |
| 496 sqlite3SelectDelete(db, pSelect); |
| 497 pSelect = 0; |
| 498 } |
| 499 |
| 485 /* Locate the table into which we will be inserting new information. | 500 /* Locate the table into which we will be inserting new information. |
| 486 */ | 501 */ |
| 487 assert( pTabList->nSrc==1 ); | 502 assert( pTabList->nSrc==1 ); |
| 488 zTab = pTabList->a[0].zName; | 503 zTab = pTabList->a[0].zName; |
| 489 if( NEVER(zTab==0) ) goto insert_cleanup; | 504 if( NEVER(zTab==0) ) goto insert_cleanup; |
| 490 pTab = sqlite3SrcListLookup(pParse, pTabList); | 505 pTab = sqlite3SrcListLookup(pParse, pTabList); |
| 491 if( pTab==0 ){ | 506 if( pTab==0 ){ |
| 492 goto insert_cleanup; | 507 goto insert_cleanup; |
| 493 } | 508 } |
| 494 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); | 509 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); |
| 495 assert( iDb<db->nDb ); | 510 assert( iDb<db->nDb ); |
| 496 pDb = &db->aDb[iDb]; | 511 pDb = &db->aDb[iDb]; |
| 497 zDb = pDb->zName; | 512 zDb = pDb->zName; |
| 498 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ | 513 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ |
| 499 goto insert_cleanup; | 514 goto insert_cleanup; |
| 500 } | 515 } |
| 516 withoutRowid = !HasRowid(pTab); |
| 501 | 517 |
| 502 /* Figure out if we have any triggers and if the table being | 518 /* Figure out if we have any triggers and if the table being |
| 503 ** inserted into is a view | 519 ** inserted into is a view |
| 504 */ | 520 */ |
| 505 #ifndef SQLITE_OMIT_TRIGGER | 521 #ifndef SQLITE_OMIT_TRIGGER |
| 506 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); | 522 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); |
| 507 isView = pTab->pSelect!=0; | 523 isView = pTab->pSelect!=0; |
| 508 #else | 524 #else |
| 509 # define pTrigger 0 | 525 # define pTrigger 0 |
| 510 # define tmask 0 | 526 # define tmask 0 |
| 511 # define isView 0 | 527 # define isView 0 |
| 512 #endif | 528 #endif |
| 513 #ifdef SQLITE_OMIT_VIEW | 529 #ifdef SQLITE_OMIT_VIEW |
| 514 # undef isView | 530 # undef isView |
| 515 # define isView 0 | 531 # define isView 0 |
| 516 #endif | 532 #endif |
| 517 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); | 533 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); |
| 518 | 534 |
| 519 /* If pTab is really a view, make sure it has been initialized. | 535 /* If pTab is really a view, make sure it has been initialized. |
| 520 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual | 536 ** ViewGetColumnNames() is a no-op if pTab is not a view. |
| 521 ** module table). | |
| 522 */ | 537 */ |
| 523 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ | 538 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ |
| 524 goto insert_cleanup; | 539 goto insert_cleanup; |
| 525 } | 540 } |
| 526 | 541 |
| 527 /* Ensure that: | 542 /* Cannot insert into a read-only table. |
| 528 * (a) the table is not read-only, | |
| 529 * (b) that if it is a view then ON INSERT triggers exist | |
| 530 */ | 543 */ |
| 531 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ | 544 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ |
| 532 goto insert_cleanup; | 545 goto insert_cleanup; |
| 533 } | 546 } |
| 534 | 547 |
| 535 /* Allocate a VDBE | 548 /* Allocate a VDBE |
| 536 */ | 549 */ |
| 537 v = sqlite3GetVdbe(pParse); | 550 v = sqlite3GetVdbe(pParse); |
| 538 if( v==0 ) goto insert_cleanup; | 551 if( v==0 ) goto insert_cleanup; |
| 539 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); | 552 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); |
| (...skipping 14 matching lines...) Expand all Loading... |
| 554 assert( pList==0 ); | 567 assert( pList==0 ); |
| 555 goto insert_end; | 568 goto insert_end; |
| 556 } | 569 } |
| 557 #endif /* SQLITE_OMIT_XFER_OPT */ | 570 #endif /* SQLITE_OMIT_XFER_OPT */ |
| 558 | 571 |
| 559 /* If this is an AUTOINCREMENT table, look up the sequence number in the | 572 /* If this is an AUTOINCREMENT table, look up the sequence number in the |
| 560 ** sqlite_sequence table and store it in memory cell regAutoinc. | 573 ** sqlite_sequence table and store it in memory cell regAutoinc. |
| 561 */ | 574 */ |
| 562 regAutoinc = autoIncBegin(pParse, iDb, pTab); | 575 regAutoinc = autoIncBegin(pParse, iDb, pTab); |
| 563 | 576 |
| 577 /* Allocate registers for holding the rowid of the new row, |
| 578 ** the content of the new row, and the assembled row record. |
| 579 */ |
| 580 regRowid = regIns = pParse->nMem+1; |
| 581 pParse->nMem += pTab->nCol + 1; |
| 582 if( IsVirtual(pTab) ){ |
| 583 regRowid++; |
| 584 pParse->nMem++; |
| 585 } |
| 586 regData = regRowid+1; |
| 587 |
| 588 /* If the INSERT statement included an IDLIST term, then make sure |
| 589 ** all elements of the IDLIST really are columns of the table and |
| 590 ** remember the column indices. |
| 591 ** |
| 592 ** If the table has an INTEGER PRIMARY KEY column and that column |
| 593 ** is named in the IDLIST, then record in the ipkColumn variable |
| 594 ** the index into IDLIST of the primary key column. ipkColumn is |
| 595 ** the index of the primary key as it appears in IDLIST, not as |
| 596 ** is appears in the original table. (The index of the INTEGER |
| 597 ** PRIMARY KEY in the original table is pTab->iPKey.) |
| 598 */ |
| 599 if( pColumn ){ |
| 600 for(i=0; i<pColumn->nId; i++){ |
| 601 pColumn->a[i].idx = -1; |
| 602 } |
| 603 for(i=0; i<pColumn->nId; i++){ |
| 604 for(j=0; j<pTab->nCol; j++){ |
| 605 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ |
| 606 pColumn->a[i].idx = j; |
| 607 if( i!=j ) bIdListInOrder = 0; |
| 608 if( j==pTab->iPKey ){ |
| 609 ipkColumn = i; assert( !withoutRowid ); |
| 610 } |
| 611 break; |
| 612 } |
| 613 } |
| 614 if( j>=pTab->nCol ){ |
| 615 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ |
| 616 ipkColumn = i; |
| 617 bIdListInOrder = 0; |
| 618 }else{ |
| 619 sqlite3ErrorMsg(pParse, "table %S has no column named %s", |
| 620 pTabList, 0, pColumn->a[i].zName); |
| 621 pParse->checkSchema = 1; |
| 622 goto insert_cleanup; |
| 623 } |
| 624 } |
| 625 } |
| 626 } |
| 627 |
| 564 /* Figure out how many columns of data are supplied. If the data | 628 /* Figure out how many columns of data are supplied. If the data |
| 565 ** is coming from a SELECT statement, then generate a co-routine that | 629 ** is coming from a SELECT statement, then generate a co-routine that |
| 566 ** produces a single row of the SELECT on each invocation. The | 630 ** produces a single row of the SELECT on each invocation. The |
| 567 ** co-routine is the common header to the 3rd and 4th templates. | 631 ** co-routine is the common header to the 3rd and 4th templates. |
| 568 */ | 632 */ |
| 569 if( pSelect ){ | 633 if( pSelect ){ |
| 570 /* Data is coming from a SELECT. Generate code to implement that SELECT | 634 /* Data is coming from a SELECT. Generate a co-routine to run the SELECT */ |
| 571 ** as a co-routine. The code is common to both the 3rd and 4th | 635 int regYield; /* Register holding co-routine entry-point */ |
| 572 ** templates: | 636 int addrTop; /* Top of the co-routine */ |
| 573 ** | 637 int rc; /* Result code */ |
| 574 ** EOF <- 0 | |
| 575 ** X <- A | |
| 576 ** goto B | |
| 577 ** A: setup for the SELECT | |
| 578 ** loop over the tables in the SELECT | |
| 579 ** load value into register R..R+n | |
| 580 ** yield X | |
| 581 ** end loop | |
| 582 ** cleanup after the SELECT | |
| 583 ** EOF <- 1 | |
| 584 ** yield X | |
| 585 ** halt-error | |
| 586 ** | |
| 587 ** On each invocation of the co-routine, it puts a single row of the | |
| 588 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1. | |
| 589 ** (These output registers are allocated by sqlite3Select().) When | |
| 590 ** the SELECT completes, it sets the EOF flag stored in regEof. | |
| 591 */ | |
| 592 int rc, j1; | |
| 593 | 638 |
| 594 regEof = ++pParse->nMem; | 639 regYield = ++pParse->nMem; |
| 595 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */ | 640 addrTop = sqlite3VdbeCurrentAddr(v) + 1; |
| 596 VdbeComment((v, "SELECT eof flag")); | 641 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); |
| 597 sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem); | 642 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); |
| 598 addrSelect = sqlite3VdbeCurrentAddr(v)+2; | 643 dest.iSdst = bIdListInOrder ? regData : 0; |
| 599 sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm); | 644 dest.nSdst = pTab->nCol; |
| 600 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); | |
| 601 VdbeComment((v, "Jump over SELECT coroutine")); | |
| 602 | |
| 603 /* Resolve the expressions in the SELECT statement and execute it. */ | |
| 604 rc = sqlite3Select(pParse, pSelect, &dest); | 645 rc = sqlite3Select(pParse, pSelect, &dest); |
| 646 regFromSelect = dest.iSdst; |
| 605 assert( pParse->nErr==0 || rc ); | 647 assert( pParse->nErr==0 || rc ); |
| 606 if( rc || NEVER(pParse->nErr) || db->mallocFailed ){ | 648 if( rc || db->mallocFailed ) goto insert_cleanup; |
| 607 goto insert_cleanup; | 649 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield); |
| 608 } | 650 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ |
| 609 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */ | |
| 610 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */ | |
| 611 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort); | |
| 612 VdbeComment((v, "End of SELECT coroutine")); | |
| 613 sqlite3VdbeJumpHere(v, j1); /* label B: */ | |
| 614 | |
| 615 regFromSelect = dest.iMem; | |
| 616 assert( pSelect->pEList ); | 651 assert( pSelect->pEList ); |
| 617 nColumn = pSelect->pEList->nExpr; | 652 nColumn = pSelect->pEList->nExpr; |
| 618 assert( dest.nMem==nColumn ); | |
| 619 | 653 |
| 620 /* Set useTempTable to TRUE if the result of the SELECT statement | 654 /* Set useTempTable to TRUE if the result of the SELECT statement |
| 621 ** should be written into a temporary table (template 4). Set to | 655 ** should be written into a temporary table (template 4). Set to |
| 622 ** FALSE if each* row of the SELECT can be written directly into | 656 ** FALSE if each output row of the SELECT can be written directly into |
| 623 ** the destination table (template 3). | 657 ** the destination table (template 3). |
| 624 ** | 658 ** |
| 625 ** A temp table must be used if the table being updated is also one | 659 ** A temp table must be used if the table being updated is also one |
| 626 ** of the tables being read by the SELECT statement. Also use a | 660 ** of the tables being read by the SELECT statement. Also use a |
| 627 ** temp table in the case of row triggers. | 661 ** temp table in the case of row triggers. |
| 628 */ | 662 */ |
| 629 if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){ | 663 if( pTrigger || readsTable(pParse, iDb, pTab) ){ |
| 630 useTempTable = 1; | 664 useTempTable = 1; |
| 631 } | 665 } |
| 632 | 666 |
| 633 if( useTempTable ){ | 667 if( useTempTable ){ |
| 634 /* Invoke the coroutine to extract information from the SELECT | 668 /* Invoke the coroutine to extract information from the SELECT |
| 635 ** and add it to a transient table srcTab. The code generated | 669 ** and add it to a transient table srcTab. The code generated |
| 636 ** here is from the 4th template: | 670 ** here is from the 4th template: |
| 637 ** | 671 ** |
| 638 ** B: open temp table | 672 ** B: open temp table |
| 639 ** L: yield X | 673 ** L: yield X, goto M at EOF |
| 640 ** if EOF goto M | |
| 641 ** insert row from R..R+n into temp table | 674 ** insert row from R..R+n into temp table |
| 642 ** goto L | 675 ** goto L |
| 643 ** M: ... | 676 ** M: ... |
| 644 */ | 677 */ |
| 645 int regRec; /* Register to hold packed record */ | 678 int regRec; /* Register to hold packed record */ |
| 646 int regTempRowid; /* Register to hold temp table ROWID */ | 679 int regTempRowid; /* Register to hold temp table ROWID */ |
| 647 int addrTop; /* Label "L" */ | 680 int addrL; /* Label "L" */ |
| 648 int addrIf; /* Address of jump to M */ | |
| 649 | 681 |
| 650 srcTab = pParse->nTab++; | 682 srcTab = pParse->nTab++; |
| 651 regRec = sqlite3GetTempReg(pParse); | 683 regRec = sqlite3GetTempReg(pParse); |
| 652 regTempRowid = sqlite3GetTempReg(pParse); | 684 regTempRowid = sqlite3GetTempReg(pParse); |
| 653 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); | 685 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); |
| 654 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); | 686 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); |
| 655 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof); | |
| 656 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); | 687 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); |
| 657 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); | 688 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); |
| 658 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); | 689 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); |
| 659 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop); | 690 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL); |
| 660 sqlite3VdbeJumpHere(v, addrIf); | 691 sqlite3VdbeJumpHere(v, addrL); |
| 661 sqlite3ReleaseTempReg(pParse, regRec); | 692 sqlite3ReleaseTempReg(pParse, regRec); |
| 662 sqlite3ReleaseTempReg(pParse, regTempRowid); | 693 sqlite3ReleaseTempReg(pParse, regTempRowid); |
| 663 } | 694 } |
| 664 }else{ | 695 }else{ |
| 665 /* This is the case if the data for the INSERT is coming from a VALUES | 696 /* This is the case if the data for the INSERT is coming from a VALUES |
| 666 ** clause | 697 ** clause |
| 667 */ | 698 */ |
| 668 NameContext sNC; | 699 NameContext sNC; |
| 669 memset(&sNC, 0, sizeof(sNC)); | 700 memset(&sNC, 0, sizeof(sNC)); |
| 670 sNC.pParse = pParse; | 701 sNC.pParse = pParse; |
| 671 srcTab = -1; | 702 srcTab = -1; |
| 672 assert( useTempTable==0 ); | 703 assert( useTempTable==0 ); |
| 673 nColumn = pList ? pList->nExpr : 0; | 704 nColumn = pList ? pList->nExpr : 0; |
| 674 for(i=0; i<nColumn; i++){ | 705 for(i=0; i<nColumn; i++){ |
| 675 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){ | 706 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){ |
| 676 goto insert_cleanup; | 707 goto insert_cleanup; |
| 677 } | 708 } |
| 678 } | 709 } |
| 679 } | 710 } |
| 680 | 711 |
| 712 /* If there is no IDLIST term but the table has an integer primary |
| 713 ** key, the set the ipkColumn variable to the integer primary key |
| 714 ** column index in the original table definition. |
| 715 */ |
| 716 if( pColumn==0 && nColumn>0 ){ |
| 717 ipkColumn = pTab->iPKey; |
| 718 } |
| 719 |
| 681 /* Make sure the number of columns in the source data matches the number | 720 /* Make sure the number of columns in the source data matches the number |
| 682 ** of columns to be inserted into the table. | 721 ** of columns to be inserted into the table. |
| 683 */ | 722 */ |
| 684 if( IsVirtual(pTab) ){ | 723 if( IsVirtual(pTab) ){ |
| 685 for(i=0; i<pTab->nCol; i++){ | 724 for(i=0; i<pTab->nCol; i++){ |
| 686 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); | 725 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); |
| 687 } | 726 } |
| 688 } | 727 } |
| 689 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ | 728 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ |
| 690 sqlite3ErrorMsg(pParse, | 729 sqlite3ErrorMsg(pParse, |
| 691 "table %S has %d columns but %d values were supplied", | 730 "table %S has %d columns but %d values were supplied", |
| 692 pTabList, 0, pTab->nCol-nHidden, nColumn); | 731 pTabList, 0, pTab->nCol-nHidden, nColumn); |
| 693 goto insert_cleanup; | 732 goto insert_cleanup; |
| 694 } | 733 } |
| 695 if( pColumn!=0 && nColumn!=pColumn->nId ){ | 734 if( pColumn!=0 && nColumn!=pColumn->nId ){ |
| 696 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); | 735 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); |
| 697 goto insert_cleanup; | 736 goto insert_cleanup; |
| 698 } | 737 } |
| 699 | |
| 700 /* If the INSERT statement included an IDLIST term, then make sure | |
| 701 ** all elements of the IDLIST really are columns of the table and | |
| 702 ** remember the column indices. | |
| 703 ** | |
| 704 ** If the table has an INTEGER PRIMARY KEY column and that column | |
| 705 ** is named in the IDLIST, then record in the keyColumn variable | |
| 706 ** the index into IDLIST of the primary key column. keyColumn is | |
| 707 ** the index of the primary key as it appears in IDLIST, not as | |
| 708 ** is appears in the original table. (The index of the primary | |
| 709 ** key in the original table is pTab->iPKey.) | |
| 710 */ | |
| 711 if( pColumn ){ | |
| 712 for(i=0; i<pColumn->nId; i++){ | |
| 713 pColumn->a[i].idx = -1; | |
| 714 } | |
| 715 for(i=0; i<pColumn->nId; i++){ | |
| 716 for(j=0; j<pTab->nCol; j++){ | |
| 717 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ | |
| 718 pColumn->a[i].idx = j; | |
| 719 if( j==pTab->iPKey ){ | |
| 720 keyColumn = i; | |
| 721 } | |
| 722 break; | |
| 723 } | |
| 724 } | |
| 725 if( j>=pTab->nCol ){ | |
| 726 if( sqlite3IsRowid(pColumn->a[i].zName) ){ | |
| 727 keyColumn = i; | |
| 728 }else{ | |
| 729 sqlite3ErrorMsg(pParse, "table %S has no column named %s", | |
| 730 pTabList, 0, pColumn->a[i].zName); | |
| 731 pParse->checkSchema = 1; | |
| 732 goto insert_cleanup; | |
| 733 } | |
| 734 } | |
| 735 } | |
| 736 } | |
| 737 | |
| 738 /* If there is no IDLIST term but the table has an integer primary | |
| 739 ** key, the set the keyColumn variable to the primary key column index | |
| 740 ** in the original table definition. | |
| 741 */ | |
| 742 if( pColumn==0 && nColumn>0 ){ | |
| 743 keyColumn = pTab->iPKey; | |
| 744 } | |
| 745 | 738 |
| 746 /* Initialize the count of rows to be inserted | 739 /* Initialize the count of rows to be inserted |
| 747 */ | 740 */ |
| 748 if( db->flags & SQLITE_CountRows ){ | 741 if( db->flags & SQLITE_CountRows ){ |
| 749 regRowCount = ++pParse->nMem; | 742 regRowCount = ++pParse->nMem; |
| 750 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); | 743 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); |
| 751 } | 744 } |
| 752 | 745 |
| 753 /* If this is not a view, open the table and and all indices */ | 746 /* If this is not a view, open the table and and all indices */ |
| 754 if( !isView ){ | 747 if( !isView ){ |
| 755 int nIdx; | 748 int nIdx; |
| 756 | 749 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0, |
| 757 baseCur = pParse->nTab; | 750 &iDataCur, &iIdxCur); |
| 758 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite); | |
| 759 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); | 751 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); |
| 760 if( aRegIdx==0 ){ | 752 if( aRegIdx==0 ){ |
| 761 goto insert_cleanup; | 753 goto insert_cleanup; |
| 762 } | 754 } |
| 763 for(i=0; i<nIdx; i++){ | 755 for(i=0; i<nIdx; i++){ |
| 764 aRegIdx[i] = ++pParse->nMem; | 756 aRegIdx[i] = ++pParse->nMem; |
| 765 } | 757 } |
| 766 } | 758 } |
| 767 | 759 |
| 768 /* This is the top of the main insertion loop */ | 760 /* This is the top of the main insertion loop */ |
| 769 if( useTempTable ){ | 761 if( useTempTable ){ |
| 770 /* This block codes the top of loop only. The complete loop is the | 762 /* This block codes the top of loop only. The complete loop is the |
| 771 ** following pseudocode (template 4): | 763 ** following pseudocode (template 4): |
| 772 ** | 764 ** |
| 773 ** rewind temp table | 765 ** rewind temp table, if empty goto D |
| 774 ** C: loop over rows of intermediate table | 766 ** C: loop over rows of intermediate table |
| 775 ** transfer values form intermediate table into <table> | 767 ** transfer values form intermediate table into <table> |
| 776 ** end loop | 768 ** end loop |
| 777 ** D: ... | 769 ** D: ... |
| 778 */ | 770 */ |
| 779 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); | 771 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); |
| 780 addrCont = sqlite3VdbeCurrentAddr(v); | 772 addrCont = sqlite3VdbeCurrentAddr(v); |
| 781 }else if( pSelect ){ | 773 }else if( pSelect ){ |
| 782 /* This block codes the top of loop only. The complete loop is the | 774 /* This block codes the top of loop only. The complete loop is the |
| 783 ** following pseudocode (template 3): | 775 ** following pseudocode (template 3): |
| 784 ** | 776 ** |
| 785 ** C: yield X | 777 ** C: yield X, at EOF goto D |
| 786 ** if EOF goto D | |
| 787 ** insert the select result into <table> from R..R+n | 778 ** insert the select result into <table> from R..R+n |
| 788 ** goto C | 779 ** goto C |
| 789 ** D: ... | 780 ** D: ... |
| 790 */ | 781 */ |
| 791 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); | 782 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); |
| 792 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof); | 783 VdbeCoverage(v); |
| 793 } | 784 } |
| 794 | 785 |
| 795 /* Allocate registers for holding the rowid of the new row, | |
| 796 ** the content of the new row, and the assemblied row record. | |
| 797 */ | |
| 798 regRowid = regIns = pParse->nMem+1; | |
| 799 pParse->nMem += pTab->nCol + 1; | |
| 800 if( IsVirtual(pTab) ){ | |
| 801 regRowid++; | |
| 802 pParse->nMem++; | |
| 803 } | |
| 804 regData = regRowid+1; | |
| 805 | |
| 806 /* Run the BEFORE and INSTEAD OF triggers, if there are any | 786 /* Run the BEFORE and INSTEAD OF triggers, if there are any |
| 807 */ | 787 */ |
| 808 endOfLoop = sqlite3VdbeMakeLabel(v); | 788 endOfLoop = sqlite3VdbeMakeLabel(v); |
| 809 if( tmask & TRIGGER_BEFORE ){ | 789 if( tmask & TRIGGER_BEFORE ){ |
| 810 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); | 790 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); |
| 811 | 791 |
| 812 /* build the NEW.* reference row. Note that if there is an INTEGER | 792 /* build the NEW.* reference row. Note that if there is an INTEGER |
| 813 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be | 793 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be |
| 814 ** translated into a unique ID for the row. But on a BEFORE trigger, | 794 ** translated into a unique ID for the row. But on a BEFORE trigger, |
| 815 ** we do not know what the unique ID will be (because the insert has | 795 ** we do not know what the unique ID will be (because the insert has |
| 816 ** not happened yet) so we substitute a rowid of -1 | 796 ** not happened yet) so we substitute a rowid of -1 |
| 817 */ | 797 */ |
| 818 if( keyColumn<0 ){ | 798 if( ipkColumn<0 ){ |
| 819 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); | 799 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); |
| 820 }else{ | 800 }else{ |
| 821 int j1; | 801 int j1; |
| 802 assert( !withoutRowid ); |
| 822 if( useTempTable ){ | 803 if( useTempTable ){ |
| 823 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols); | 804 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); |
| 824 }else{ | 805 }else{ |
| 825 assert( pSelect==0 ); /* Otherwise useTempTable is true */ | 806 assert( pSelect==0 ); /* Otherwise useTempTable is true */ |
| 826 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols); | 807 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); |
| 827 } | 808 } |
| 828 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); | 809 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); |
| 829 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); | 810 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); |
| 830 sqlite3VdbeJumpHere(v, j1); | 811 sqlite3VdbeJumpHere(v, j1); |
| 831 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); | 812 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); |
| 832 } | 813 } |
| 833 | 814 |
| 834 /* Cannot have triggers on a virtual table. If it were possible, | 815 /* Cannot have triggers on a virtual table. If it were possible, |
| 835 ** this block would have to account for hidden column. | 816 ** this block would have to account for hidden column. |
| 836 */ | 817 */ |
| 837 assert( !IsVirtual(pTab) ); | 818 assert( !IsVirtual(pTab) ); |
| 838 | 819 |
| 839 /* Create the new column data | 820 /* Create the new column data |
| 840 */ | 821 */ |
| 841 for(i=0; i<pTab->nCol; i++){ | 822 for(i=0; i<pTab->nCol; i++){ |
| (...skipping 13 matching lines...) Expand all Loading... |
| 855 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); | 836 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); |
| 856 } | 837 } |
| 857 } | 838 } |
| 858 | 839 |
| 859 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, | 840 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, |
| 860 ** do not attempt any conversions before assembling the record. | 841 ** do not attempt any conversions before assembling the record. |
| 861 ** If this is a real table, attempt conversions as required by the | 842 ** If this is a real table, attempt conversions as required by the |
| 862 ** table column affinities. | 843 ** table column affinities. |
| 863 */ | 844 */ |
| 864 if( !isView ){ | 845 if( !isView ){ |
| 865 sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol); | 846 sqlite3TableAffinity(v, pTab, regCols+1); |
| 866 sqlite3TableAffinityStr(v, pTab); | |
| 867 } | 847 } |
| 868 | 848 |
| 869 /* Fire BEFORE or INSTEAD OF triggers */ | 849 /* Fire BEFORE or INSTEAD OF triggers */ |
| 870 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, | 850 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, |
| 871 pTab, regCols-pTab->nCol-1, onError, endOfLoop); | 851 pTab, regCols-pTab->nCol-1, onError, endOfLoop); |
| 872 | 852 |
| 873 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); | 853 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); |
| 874 } | 854 } |
| 875 | 855 |
| 876 /* Push the record number for the new entry onto the stack. The | 856 /* Compute the content of the next row to insert into a range of |
| 877 ** record number is a randomly generate integer created by NewRowid | 857 ** registers beginning at regIns. |
| 878 ** except when the table has an INTEGER PRIMARY KEY column, in which | |
| 879 ** case the record number is the same as that column. | |
| 880 */ | 858 */ |
| 881 if( !isView ){ | 859 if( !isView ){ |
| 882 if( IsVirtual(pTab) ){ | 860 if( IsVirtual(pTab) ){ |
| 883 /* The row that the VUpdate opcode will delete: none */ | 861 /* The row that the VUpdate opcode will delete: none */ |
| 884 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); | 862 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); |
| 885 } | 863 } |
| 886 if( keyColumn>=0 ){ | 864 if( ipkColumn>=0 ){ |
| 887 if( useTempTable ){ | 865 if( useTempTable ){ |
| 888 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); | 866 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); |
| 889 }else if( pSelect ){ | 867 }else if( pSelect ){ |
| 890 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid); | 868 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); |
| 891 }else{ | 869 }else{ |
| 892 VdbeOp *pOp; | 870 VdbeOp *pOp; |
| 893 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); | 871 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); |
| 894 pOp = sqlite3VdbeGetOp(v, -1); | 872 pOp = sqlite3VdbeGetOp(v, -1); |
| 895 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ | 873 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ |
| 896 appendFlag = 1; | 874 appendFlag = 1; |
| 897 pOp->opcode = OP_NewRowid; | 875 pOp->opcode = OP_NewRowid; |
| 898 pOp->p1 = baseCur; | 876 pOp->p1 = iDataCur; |
| 899 pOp->p2 = regRowid; | 877 pOp->p2 = regRowid; |
| 900 pOp->p3 = regAutoinc; | 878 pOp->p3 = regAutoinc; |
| 901 } | 879 } |
| 902 } | 880 } |
| 903 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid | 881 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid |
| 904 ** to generate a unique primary key value. | 882 ** to generate a unique primary key value. |
| 905 */ | 883 */ |
| 906 if( !appendFlag ){ | 884 if( !appendFlag ){ |
| 907 int j1; | 885 int j1; |
| 908 if( !IsVirtual(pTab) ){ | 886 if( !IsVirtual(pTab) ){ |
| 909 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); | 887 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); |
| 910 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); | 888 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); |
| 911 sqlite3VdbeJumpHere(v, j1); | 889 sqlite3VdbeJumpHere(v, j1); |
| 912 }else{ | 890 }else{ |
| 913 j1 = sqlite3VdbeCurrentAddr(v); | 891 j1 = sqlite3VdbeCurrentAddr(v); |
| 914 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); | 892 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v); |
| 915 } | 893 } |
| 916 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); | 894 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); |
| 917 } | 895 } |
| 918 }else if( IsVirtual(pTab) ){ | 896 }else if( IsVirtual(pTab) || withoutRowid ){ |
| 919 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); | 897 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); |
| 920 }else{ | 898 }else{ |
| 921 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); | 899 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); |
| 922 appendFlag = 1; | 900 appendFlag = 1; |
| 923 } | 901 } |
| 924 autoIncStep(pParse, regAutoinc, regRowid); | 902 autoIncStep(pParse, regAutoinc, regRowid); |
| 925 | 903 |
| 926 /* Push onto the stack, data for all columns of the new entry, beginning | 904 /* Compute data for all columns of the new entry, beginning |
| 927 ** with the first column. | 905 ** with the first column. |
| 928 */ | 906 */ |
| 929 nHidden = 0; | 907 nHidden = 0; |
| 930 for(i=0; i<pTab->nCol; i++){ | 908 for(i=0; i<pTab->nCol; i++){ |
| 931 int iRegStore = regRowid+1+i; | 909 int iRegStore = regRowid+1+i; |
| 932 if( i==pTab->iPKey ){ | 910 if( i==pTab->iPKey ){ |
| 933 /* The value of the INTEGER PRIMARY KEY column is always a NULL. | 911 /* The value of the INTEGER PRIMARY KEY column is always a NULL. |
| 934 ** Whenever this column is read, the record number will be substituted | 912 ** Whenever this column is read, the rowid will be substituted |
| 935 ** in its place. So will fill this column with a NULL to avoid | 913 ** in its place. Hence, fill this column with a NULL to avoid |
| 936 ** taking up data space with information that will never be used. */ | 914 ** taking up data space with information that will never be used. |
| 937 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore); | 915 ** As there may be shallow copies of this value, make it a soft-NULL */ |
| 916 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); |
| 938 continue; | 917 continue; |
| 939 } | 918 } |
| 940 if( pColumn==0 ){ | 919 if( pColumn==0 ){ |
| 941 if( IsHiddenColumn(&pTab->aCol[i]) ){ | 920 if( IsHiddenColumn(&pTab->aCol[i]) ){ |
| 942 assert( IsVirtual(pTab) ); | 921 assert( IsVirtual(pTab) ); |
| 943 j = -1; | 922 j = -1; |
| 944 nHidden++; | 923 nHidden++; |
| 945 }else{ | 924 }else{ |
| 946 j = i - nHidden; | 925 j = i - nHidden; |
| 947 } | 926 } |
| 948 }else{ | 927 }else{ |
| 949 for(j=0; j<pColumn->nId; j++){ | 928 for(j=0; j<pColumn->nId; j++){ |
| 950 if( pColumn->a[j].idx==i ) break; | 929 if( pColumn->a[j].idx==i ) break; |
| 951 } | 930 } |
| 952 } | 931 } |
| 953 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ | 932 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ |
| 954 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore); | 933 sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); |
| 955 }else if( useTempTable ){ | 934 }else if( useTempTable ){ |
| 956 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); | 935 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); |
| 957 }else if( pSelect ){ | 936 }else if( pSelect ){ |
| 958 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); | 937 if( regFromSelect!=regData ){ |
| 938 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); |
| 939 } |
| 959 }else{ | 940 }else{ |
| 960 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); | 941 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); |
| 961 } | 942 } |
| 962 } | 943 } |
| 963 | 944 |
| 964 /* Generate code to check constraints and generate index keys and | 945 /* Generate code to check constraints and generate index keys and |
| 965 ** do the insertion. | 946 ** do the insertion. |
| 966 */ | 947 */ |
| 967 #ifndef SQLITE_OMIT_VIRTUALTABLE | 948 #ifndef SQLITE_OMIT_VIRTUALTABLE |
| 968 if( IsVirtual(pTab) ){ | 949 if( IsVirtual(pTab) ){ |
| 969 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); | 950 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); |
| 970 sqlite3VtabMakeWritable(pParse, pTab); | 951 sqlite3VtabMakeWritable(pParse, pTab); |
| 971 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); | 952 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); |
| 953 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); |
| 972 sqlite3MayAbort(pParse); | 954 sqlite3MayAbort(pParse); |
| 973 }else | 955 }else |
| 974 #endif | 956 #endif |
| 975 { | 957 { |
| 976 int isReplace; /* Set to true if constraints may cause a replace */ | 958 int isReplace; /* Set to true if constraints may cause a replace */ |
| 977 sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx, | 959 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, |
| 978 keyColumn>=0, 0, onError, endOfLoop, &isReplace | 960 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace |
| 979 ); | 961 ); |
| 980 sqlite3FkCheck(pParse, pTab, 0, regIns); | 962 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); |
| 981 sqlite3CompleteInsertion( | 963 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, |
| 982 pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0 | 964 regIns, aRegIdx, 0, appendFlag, isReplace==0); |
| 983 ); | |
| 984 } | 965 } |
| 985 } | 966 } |
| 986 | 967 |
| 987 /* Update the count of rows that are inserted | 968 /* Update the count of rows that are inserted |
| 988 */ | 969 */ |
| 989 if( (db->flags & SQLITE_CountRows)!=0 ){ | 970 if( (db->flags & SQLITE_CountRows)!=0 ){ |
| 990 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); | 971 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); |
| 991 } | 972 } |
| 992 | 973 |
| 993 if( pTrigger ){ | 974 if( pTrigger ){ |
| 994 /* Code AFTER triggers */ | 975 /* Code AFTER triggers */ |
| 995 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, | 976 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, |
| 996 pTab, regData-2-pTab->nCol, onError, endOfLoop); | 977 pTab, regData-2-pTab->nCol, onError, endOfLoop); |
| 997 } | 978 } |
| 998 | 979 |
| 999 /* The bottom of the main insertion loop, if the data source | 980 /* The bottom of the main insertion loop, if the data source |
| 1000 ** is a SELECT statement. | 981 ** is a SELECT statement. |
| 1001 */ | 982 */ |
| 1002 sqlite3VdbeResolveLabel(v, endOfLoop); | 983 sqlite3VdbeResolveLabel(v, endOfLoop); |
| 1003 if( useTempTable ){ | 984 if( useTempTable ){ |
| 1004 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); | 985 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); |
| 1005 sqlite3VdbeJumpHere(v, addrInsTop); | 986 sqlite3VdbeJumpHere(v, addrInsTop); |
| 1006 sqlite3VdbeAddOp1(v, OP_Close, srcTab); | 987 sqlite3VdbeAddOp1(v, OP_Close, srcTab); |
| 1007 }else if( pSelect ){ | 988 }else if( pSelect ){ |
| 1008 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont); | 989 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont); |
| 1009 sqlite3VdbeJumpHere(v, addrInsTop); | 990 sqlite3VdbeJumpHere(v, addrInsTop); |
| 1010 } | 991 } |
| 1011 | 992 |
| 1012 if( !IsVirtual(pTab) && !isView ){ | 993 if( !IsVirtual(pTab) && !isView ){ |
| 1013 /* Close all tables opened */ | 994 /* Close all tables opened */ |
| 1014 sqlite3VdbeAddOp1(v, OP_Close, baseCur); | 995 if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur); |
| 1015 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ | 996 for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ |
| 1016 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur); | 997 sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur); |
| 1017 } | 998 } |
| 1018 } | 999 } |
| 1019 | 1000 |
| 1020 insert_end: | 1001 insert_end: |
| 1021 /* Update the sqlite_sequence table by storing the content of the | 1002 /* Update the sqlite_sequence table by storing the content of the |
| 1022 ** maximum rowid counter values recorded while inserting into | 1003 ** maximum rowid counter values recorded while inserting into |
| 1023 ** autoincrement tables. | 1004 ** autoincrement tables. |
| 1024 */ | 1005 */ |
| 1025 if( pParse->nested==0 && pParse->pTriggerTab==0 ){ | 1006 if( pParse->nested==0 && pParse->pTriggerTab==0 ){ |
| 1026 sqlite3AutoincrementEnd(pParse); | 1007 sqlite3AutoincrementEnd(pParse); |
| (...skipping 12 matching lines...) Expand all Loading... |
| 1039 | 1020 |
| 1040 insert_cleanup: | 1021 insert_cleanup: |
| 1041 sqlite3SrcListDelete(db, pTabList); | 1022 sqlite3SrcListDelete(db, pTabList); |
| 1042 sqlite3ExprListDelete(db, pList); | 1023 sqlite3ExprListDelete(db, pList); |
| 1043 sqlite3SelectDelete(db, pSelect); | 1024 sqlite3SelectDelete(db, pSelect); |
| 1044 sqlite3IdListDelete(db, pColumn); | 1025 sqlite3IdListDelete(db, pColumn); |
| 1045 sqlite3DbFree(db, aRegIdx); | 1026 sqlite3DbFree(db, aRegIdx); |
| 1046 } | 1027 } |
| 1047 | 1028 |
| 1048 /* Make sure "isView" and other macros defined above are undefined. Otherwise | 1029 /* Make sure "isView" and other macros defined above are undefined. Otherwise |
| 1049 ** thely may interfere with compilation of other functions in this file | 1030 ** they may interfere with compilation of other functions in this file |
| 1050 ** (or in another file, if this file becomes part of the amalgamation). */ | 1031 ** (or in another file, if this file becomes part of the amalgamation). */ |
| 1051 #ifdef isView | 1032 #ifdef isView |
| 1052 #undef isView | 1033 #undef isView |
| 1053 #endif | 1034 #endif |
| 1054 #ifdef pTrigger | 1035 #ifdef pTrigger |
| 1055 #undef pTrigger | 1036 #undef pTrigger |
| 1056 #endif | 1037 #endif |
| 1057 #ifdef tmask | 1038 #ifdef tmask |
| 1058 #undef tmask | 1039 #undef tmask |
| 1059 #endif | 1040 #endif |
| 1060 | 1041 |
| 1061 | |
| 1062 /* | 1042 /* |
| 1063 ** Generate code to do constraint checks prior to an INSERT or an UPDATE. | 1043 ** Generate code to do constraint checks prior to an INSERT or an UPDATE |
| 1044 ** on table pTab. |
| 1064 ** | 1045 ** |
| 1065 ** The input is a range of consecutive registers as follows: | 1046 ** The regNewData parameter is the first register in a range that contains |
| 1047 ** the data to be inserted or the data after the update. There will be |
| 1048 ** pTab->nCol+1 registers in this range. The first register (the one |
| 1049 ** that regNewData points to) will contain the new rowid, or NULL in the |
| 1050 ** case of a WITHOUT ROWID table. The second register in the range will |
| 1051 ** contain the content of the first table column. The third register will |
| 1052 ** contain the content of the second table column. And so forth. |
| 1066 ** | 1053 ** |
| 1067 ** 1. The rowid of the row after the update. | 1054 ** The regOldData parameter is similar to regNewData except that it contains |
| 1055 ** the data prior to an UPDATE rather than afterwards. regOldData is zero |
| 1056 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by |
| 1057 ** checking regOldData for zero. |
| 1068 ** | 1058 ** |
| 1069 ** 2. The data in the first column of the entry after the update. | 1059 ** For an UPDATE, the pkChng boolean is true if the true primary key (the |
| 1060 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) |
| 1061 ** might be modified by the UPDATE. If pkChng is false, then the key of |
| 1062 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE. |
| 1070 ** | 1063 ** |
| 1071 ** i. Data from middle columns... | 1064 ** For an INSERT, the pkChng boolean indicates whether or not the rowid |
| 1065 ** was explicitly specified as part of the INSERT statement. If pkChng |
| 1066 ** is zero, it means that the either rowid is computed automatically or |
| 1067 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, |
| 1068 ** pkChng will only be true if the INSERT statement provides an integer |
| 1069 ** value for either the rowid column or its INTEGER PRIMARY KEY alias. |
| 1072 ** | 1070 ** |
| 1073 ** N. The data in the last column of the entry after the update. | 1071 ** The code generated by this routine will store new index entries into |
| 1074 ** | |
| 1075 ** The regRowid parameter is the index of the register containing (1). | |
| 1076 ** | |
| 1077 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains | |
| 1078 ** the address of a register containing the rowid before the update takes | |
| 1079 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate | |
| 1080 ** is false, indicating an INSERT statement, then a non-zero rowidChng | |
| 1081 ** indicates that the rowid was explicitly specified as part of the | |
| 1082 ** INSERT statement. If rowidChng is false, it means that the rowid is | |
| 1083 ** computed automatically in an insert or that the rowid value is not | |
| 1084 ** modified by an update. | |
| 1085 ** | |
| 1086 ** The code generated by this routine store new index entries into | |
| 1087 ** registers identified by aRegIdx[]. No index entry is created for | 1072 ** registers identified by aRegIdx[]. No index entry is created for |
| 1088 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is | 1073 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is |
| 1089 ** the same as the order of indices on the linked list of indices | 1074 ** the same as the order of indices on the linked list of indices |
| 1090 ** attached to the table. | 1075 ** at pTab->pIndex. |
| 1076 ** |
| 1077 ** The caller must have already opened writeable cursors on the main |
| 1078 ** table and all applicable indices (that is to say, all indices for which |
| 1079 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when |
| 1080 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY |
| 1081 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor |
| 1082 ** for the first index in the pTab->pIndex list. Cursors for other indices |
| 1083 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list. |
| 1091 ** | 1084 ** |
| 1092 ** This routine also generates code to check constraints. NOT NULL, | 1085 ** This routine also generates code to check constraints. NOT NULL, |
| 1093 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, | 1086 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, |
| 1094 ** then the appropriate action is performed. There are five possible | 1087 ** then the appropriate action is performed. There are five possible |
| 1095 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. | 1088 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. |
| 1096 ** | 1089 ** |
| 1097 ** Constraint type Action What Happens | 1090 ** Constraint type Action What Happens |
| 1098 ** --------------- ---------- ---------------------------------------- | 1091 ** --------------- ---------- ---------------------------------------- |
| 1099 ** any ROLLBACK The current transaction is rolled back and | 1092 ** any ROLLBACK The current transaction is rolled back and |
| 1100 ** sqlite3_exec() returns immediately with a | 1093 ** sqlite3_step() returns immediately with a |
| 1101 ** return code of SQLITE_CONSTRAINT. | 1094 ** return code of SQLITE_CONSTRAINT. |
| 1102 ** | 1095 ** |
| 1103 ** any ABORT Back out changes from the current command | 1096 ** any ABORT Back out changes from the current command |
| 1104 ** only (do not do a complete rollback) then | 1097 ** only (do not do a complete rollback) then |
| 1105 ** cause sqlite3_exec() to return immediately | 1098 ** cause sqlite3_step() to return immediately |
| 1106 ** with SQLITE_CONSTRAINT. | 1099 ** with SQLITE_CONSTRAINT. |
| 1107 ** | 1100 ** |
| 1108 ** any FAIL Sqlite_exec() returns immediately with a | 1101 ** any FAIL Sqlite3_step() returns immediately with a |
| 1109 ** return code of SQLITE_CONSTRAINT. The | 1102 ** return code of SQLITE_CONSTRAINT. The |
| 1110 ** transaction is not rolled back and any | 1103 ** transaction is not rolled back and any |
| 1111 ** prior changes are retained. | 1104 ** changes to prior rows are retained. |
| 1112 ** | 1105 ** |
| 1113 ** any IGNORE The record number and data is popped from | 1106 ** any IGNORE The attempt in insert or update the current |
| 1114 ** the stack and there is an immediate jump | 1107 ** row is skipped, without throwing an error. |
| 1115 ** to label ignoreDest. | 1108 ** Processing continues with the next row. |
| 1109 ** (There is an immediate jump to ignoreDest.) |
| 1116 ** | 1110 ** |
| 1117 ** NOT NULL REPLACE The NULL value is replace by the default | 1111 ** NOT NULL REPLACE The NULL value is replace by the default |
| 1118 ** value for that column. If the default value | 1112 ** value for that column. If the default value |
| 1119 ** is NULL, the action is the same as ABORT. | 1113 ** is NULL, the action is the same as ABORT. |
| 1120 ** | 1114 ** |
| 1121 ** UNIQUE REPLACE The other row that conflicts with the row | 1115 ** UNIQUE REPLACE The other row that conflicts with the row |
| 1122 ** being inserted is removed. | 1116 ** being inserted is removed. |
| 1123 ** | 1117 ** |
| 1124 ** CHECK REPLACE Illegal. The results in an exception. | 1118 ** CHECK REPLACE Illegal. The results in an exception. |
| 1125 ** | 1119 ** |
| 1126 ** Which action to take is determined by the overrideError parameter. | 1120 ** Which action to take is determined by the overrideError parameter. |
| 1127 ** Or if overrideError==OE_Default, then the pParse->onError parameter | 1121 ** Or if overrideError==OE_Default, then the pParse->onError parameter |
| 1128 ** is used. Or if pParse->onError==OE_Default then the onError value | 1122 ** is used. Or if pParse->onError==OE_Default then the onError value |
| 1129 ** for the constraint is used. | 1123 ** for the constraint is used. |
| 1130 ** | |
| 1131 ** The calling routine must open a read/write cursor for pTab with | |
| 1132 ** cursor number "baseCur". All indices of pTab must also have open | |
| 1133 ** read/write cursors with cursor number baseCur+i for the i-th cursor. | |
| 1134 ** Except, if there is no possibility of a REPLACE action then | |
| 1135 ** cursors do not need to be open for indices where aRegIdx[i]==0. | |
| 1136 */ | 1124 */ |
| 1137 void sqlite3GenerateConstraintChecks( | 1125 void sqlite3GenerateConstraintChecks( |
| 1138 Parse *pParse, /* The parser context */ | 1126 Parse *pParse, /* The parser context */ |
| 1139 Table *pTab, /* the table into which we are inserting */ | 1127 Table *pTab, /* The table being inserted or updated */ |
| 1140 int baseCur, /* Index of a read/write cursor pointing at pTab */ | 1128 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ |
| 1141 int regRowid, /* Index of the range of input registers */ | 1129 int iDataCur, /* Canonical data cursor (main table or PK index) */ |
| 1142 int *aRegIdx, /* Register used by each index. 0 for unused indices */ | 1130 int iIdxCur, /* First index cursor */ |
| 1143 int rowidChng, /* True if the rowid might collide with existing entry */ | 1131 int regNewData, /* First register in a range holding values to insert */ |
| 1144 int isUpdate, /* True for UPDATE, False for INSERT */ | 1132 int regOldData, /* Previous content. 0 for INSERTs */ |
| 1145 int overrideError, /* Override onError to this if not OE_Default */ | 1133 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ |
| 1146 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ | 1134 u8 overrideError, /* Override onError to this if not OE_Default */ |
| 1147 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */ | 1135 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ |
| 1136 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */ |
| 1148 ){ | 1137 ){ |
| 1149 int i; /* loop counter */ | 1138 Vdbe *v; /* VDBE under constrution */ |
| 1150 Vdbe *v; /* VDBE under constrution */ | |
| 1151 int nCol; /* Number of columns */ | |
| 1152 int onError; /* Conflict resolution strategy */ | |
| 1153 int j1; /* Addresss of jump instruction */ | |
| 1154 int j2 = 0, j3; /* Addresses of jump instructions */ | |
| 1155 int regData; /* Register containing first data column */ | |
| 1156 int iCur; /* Table cursor number */ | |
| 1157 Index *pIdx; /* Pointer to one of the indices */ | 1139 Index *pIdx; /* Pointer to one of the indices */ |
| 1140 Index *pPk = 0; /* The PRIMARY KEY index */ |
| 1141 sqlite3 *db; /* Database connection */ |
| 1142 int i; /* loop counter */ |
| 1143 int ix; /* Index loop counter */ |
| 1144 int nCol; /* Number of columns */ |
| 1145 int onError; /* Conflict resolution strategy */ |
| 1146 int j1; /* Address of jump instruction */ |
| 1158 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ | 1147 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ |
| 1159 int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid; | 1148 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ |
| 1149 int ipkTop = 0; /* Top of the rowid change constraint check */ |
| 1150 int ipkBottom = 0; /* Bottom of the rowid change constraint check */ |
| 1151 u8 isUpdate; /* True if this is an UPDATE operation */ |
| 1152 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ |
| 1153 int regRowid = -1; /* Register holding ROWID value */ |
| 1160 | 1154 |
| 1155 isUpdate = regOldData!=0; |
| 1156 db = pParse->db; |
| 1161 v = sqlite3GetVdbe(pParse); | 1157 v = sqlite3GetVdbe(pParse); |
| 1162 assert( v!=0 ); | 1158 assert( v!=0 ); |
| 1163 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ | 1159 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ |
| 1164 nCol = pTab->nCol; | 1160 nCol = pTab->nCol; |
| 1165 regData = regRowid + 1; | 1161 |
| 1162 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for |
| 1163 ** normal rowid tables. nPkField is the number of key fields in the |
| 1164 ** pPk index or 1 for a rowid table. In other words, nPkField is the |
| 1165 ** number of fields in the true primary key of the table. */ |
| 1166 if( HasRowid(pTab) ){ |
| 1167 pPk = 0; |
| 1168 nPkField = 1; |
| 1169 }else{ |
| 1170 pPk = sqlite3PrimaryKeyIndex(pTab); |
| 1171 nPkField = pPk->nKeyCol; |
| 1172 } |
| 1173 |
| 1174 /* Record that this module has started */ |
| 1175 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", |
| 1176 iDataCur, iIdxCur, regNewData, regOldData, pkChng)); |
| 1166 | 1177 |
| 1167 /* Test all NOT NULL constraints. | 1178 /* Test all NOT NULL constraints. |
| 1168 */ | 1179 */ |
| 1169 for(i=0; i<nCol; i++){ | 1180 for(i=0; i<nCol; i++){ |
| 1170 if( i==pTab->iPKey ){ | 1181 if( i==pTab->iPKey ){ |
| 1171 continue; | 1182 continue; |
| 1172 } | 1183 } |
| 1173 onError = pTab->aCol[i].notNull; | 1184 onError = pTab->aCol[i].notNull; |
| 1174 if( onError==OE_None ) continue; | 1185 if( onError==OE_None ) continue; |
| 1175 if( overrideError!=OE_Default ){ | 1186 if( overrideError!=OE_Default ){ |
| 1176 onError = overrideError; | 1187 onError = overrideError; |
| 1177 }else if( onError==OE_Default ){ | 1188 }else if( onError==OE_Default ){ |
| 1178 onError = OE_Abort; | 1189 onError = OE_Abort; |
| 1179 } | 1190 } |
| 1180 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ | 1191 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ |
| 1181 onError = OE_Abort; | 1192 onError = OE_Abort; |
| 1182 } | 1193 } |
| 1183 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail | 1194 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail |
| 1184 || onError==OE_Ignore || onError==OE_Replace ); | 1195 || onError==OE_Ignore || onError==OE_Replace ); |
| 1185 switch( onError ){ | 1196 switch( onError ){ |
| 1186 case OE_Abort: | 1197 case OE_Abort: |
| 1187 sqlite3MayAbort(pParse); | 1198 sqlite3MayAbort(pParse); |
| 1199 /* Fall through */ |
| 1188 case OE_Rollback: | 1200 case OE_Rollback: |
| 1189 case OE_Fail: { | 1201 case OE_Fail: { |
| 1190 char *zMsg; | 1202 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, |
| 1191 sqlite3VdbeAddOp3(v, OP_HaltIfNull, | 1203 pTab->aCol[i].zName); |
| 1192 SQLITE_CONSTRAINT, onError, regData+i); | 1204 sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError, |
| 1193 zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL", | 1205 regNewData+1+i, zMsg, P4_DYNAMIC); |
| 1194 pTab->zName, pTab->aCol[i].zName); | 1206 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); |
| 1195 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC); | 1207 VdbeCoverage(v); |
| 1196 break; | 1208 break; |
| 1197 } | 1209 } |
| 1198 case OE_Ignore: { | 1210 case OE_Ignore: { |
| 1199 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest); | 1211 sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest); |
| 1212 VdbeCoverage(v); |
| 1200 break; | 1213 break; |
| 1201 } | 1214 } |
| 1202 default: { | 1215 default: { |
| 1203 assert( onError==OE_Replace ); | 1216 assert( onError==OE_Replace ); |
| 1204 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i); | 1217 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v); |
| 1205 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i); | 1218 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); |
| 1206 sqlite3VdbeJumpHere(v, j1); | 1219 sqlite3VdbeJumpHere(v, j1); |
| 1207 break; | 1220 break; |
| 1208 } | 1221 } |
| 1209 } | 1222 } |
| 1210 } | 1223 } |
| 1211 | 1224 |
| 1212 /* Test all CHECK constraints | 1225 /* Test all CHECK constraints |
| 1213 */ | 1226 */ |
| 1214 #ifndef SQLITE_OMIT_CHECK | 1227 #ifndef SQLITE_OMIT_CHECK |
| 1215 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){ | 1228 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ |
| 1216 int allOk = sqlite3VdbeMakeLabel(v); | 1229 ExprList *pCheck = pTab->pCheck; |
| 1217 pParse->ckBase = regData; | 1230 pParse->ckBase = regNewData+1; |
| 1218 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL); | |
| 1219 onError = overrideError!=OE_Default ? overrideError : OE_Abort; | 1231 onError = overrideError!=OE_Default ? overrideError : OE_Abort; |
| 1220 if( onError==OE_Ignore ){ | 1232 for(i=0; i<pCheck->nExpr; i++){ |
| 1221 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); | 1233 int allOk = sqlite3VdbeMakeLabel(v); |
| 1222 }else{ | 1234 sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL); |
| 1223 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ | 1235 if( onError==OE_Ignore ){ |
| 1224 sqlite3HaltConstraint(pParse, onError, 0, 0); | 1236 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); |
| 1237 }else{ |
| 1238 char *zName = pCheck->a[i].zName; |
| 1239 if( zName==0 ) zName = pTab->zName; |
| 1240 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ |
| 1241 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, |
| 1242 onError, zName, P4_TRANSIENT, |
| 1243 P5_ConstraintCheck); |
| 1244 } |
| 1245 sqlite3VdbeResolveLabel(v, allOk); |
| 1225 } | 1246 } |
| 1226 sqlite3VdbeResolveLabel(v, allOk); | |
| 1227 } | 1247 } |
| 1228 #endif /* !defined(SQLITE_OMIT_CHECK) */ | 1248 #endif /* !defined(SQLITE_OMIT_CHECK) */ |
| 1229 | 1249 |
| 1230 /* If we have an INTEGER PRIMARY KEY, make sure the primary key | 1250 /* If rowid is changing, make sure the new rowid does not previously |
| 1231 ** of the new record does not previously exist. Except, if this | 1251 ** exist in the table. |
| 1232 ** is an UPDATE and the primary key is not changing, that is OK. | |
| 1233 */ | 1252 */ |
| 1234 if( rowidChng ){ | 1253 if( pkChng && pPk==0 ){ |
| 1254 int addrRowidOk = sqlite3VdbeMakeLabel(v); |
| 1255 |
| 1256 /* Figure out what action to take in case of a rowid collision */ |
| 1235 onError = pTab->keyConf; | 1257 onError = pTab->keyConf; |
| 1236 if( overrideError!=OE_Default ){ | 1258 if( overrideError!=OE_Default ){ |
| 1237 onError = overrideError; | 1259 onError = overrideError; |
| 1238 }else if( onError==OE_Default ){ | 1260 }else if( onError==OE_Default ){ |
| 1239 onError = OE_Abort; | 1261 onError = OE_Abort; |
| 1240 } | 1262 } |
| 1241 | 1263 |
| 1242 if( isUpdate ){ | 1264 if( isUpdate ){ |
| 1243 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng); | 1265 /* pkChng!=0 does not mean that the rowid has change, only that |
| 1266 ** it might have changed. Skip the conflict logic below if the rowid |
| 1267 ** is unchanged. */ |
| 1268 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); |
| 1269 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); |
| 1270 VdbeCoverage(v); |
| 1244 } | 1271 } |
| 1245 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid); | 1272 |
| 1273 /* If the response to a rowid conflict is REPLACE but the response |
| 1274 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need |
| 1275 ** to defer the running of the rowid conflict checking until after |
| 1276 ** the UNIQUE constraints have run. |
| 1277 */ |
| 1278 if( onError==OE_Replace && overrideError!=OE_Replace ){ |
| 1279 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ |
| 1280 if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){ |
| 1281 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto); |
| 1282 break; |
| 1283 } |
| 1284 } |
| 1285 } |
| 1286 |
| 1287 /* Check to see if the new rowid already exists in the table. Skip |
| 1288 ** the following conflict logic if it does not. */ |
| 1289 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); |
| 1290 VdbeCoverage(v); |
| 1291 |
| 1292 /* Generate code that deals with a rowid collision */ |
| 1246 switch( onError ){ | 1293 switch( onError ){ |
| 1247 default: { | 1294 default: { |
| 1248 onError = OE_Abort; | 1295 onError = OE_Abort; |
| 1249 /* Fall thru into the next case */ | 1296 /* Fall thru into the next case */ |
| 1250 } | 1297 } |
| 1251 case OE_Rollback: | 1298 case OE_Rollback: |
| 1252 case OE_Abort: | 1299 case OE_Abort: |
| 1253 case OE_Fail: { | 1300 case OE_Fail: { |
| 1254 sqlite3HaltConstraint( | 1301 sqlite3RowidConstraint(pParse, onError, pTab); |
| 1255 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC); | |
| 1256 break; | 1302 break; |
| 1257 } | 1303 } |
| 1258 case OE_Replace: { | 1304 case OE_Replace: { |
| 1259 /* If there are DELETE triggers on this table and the | 1305 /* If there are DELETE triggers on this table and the |
| 1260 ** recursive-triggers flag is set, call GenerateRowDelete() to | 1306 ** recursive-triggers flag is set, call GenerateRowDelete() to |
| 1261 ** remove the conflicting row from the the table. This will fire | 1307 ** remove the conflicting row from the table. This will fire |
| 1262 ** the triggers and remove both the table and index b-tree entries. | 1308 ** the triggers and remove both the table and index b-tree entries. |
| 1263 ** | 1309 ** |
| 1264 ** Otherwise, if there are no triggers or the recursive-triggers | 1310 ** Otherwise, if there are no triggers or the recursive-triggers |
| 1265 ** flag is not set, but the table has one or more indexes, call | 1311 ** flag is not set, but the table has one or more indexes, call |
| 1266 ** GenerateRowIndexDelete(). This removes the index b-tree entries | 1312 ** GenerateRowIndexDelete(). This removes the index b-tree entries |
| 1267 ** only. The table b-tree entry will be replaced by the new entry | 1313 ** only. The table b-tree entry will be replaced by the new entry |
| 1268 ** when it is inserted. | 1314 ** when it is inserted. |
| 1269 ** | 1315 ** |
| 1270 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, | 1316 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, |
| 1271 ** also invoke MultiWrite() to indicate that this VDBE may require | 1317 ** also invoke MultiWrite() to indicate that this VDBE may require |
| 1272 ** statement rollback (if the statement is aborted after the delete | 1318 ** statement rollback (if the statement is aborted after the delete |
| 1273 ** takes place). Earlier versions called sqlite3MultiWrite() regardless, | 1319 ** takes place). Earlier versions called sqlite3MultiWrite() regardless, |
| 1274 ** but being more selective here allows statements like: | 1320 ** but being more selective here allows statements like: |
| 1275 ** | 1321 ** |
| 1276 ** REPLACE INTO t(rowid) VALUES($newrowid) | 1322 ** REPLACE INTO t(rowid) VALUES($newrowid) |
| 1277 ** | 1323 ** |
| 1278 ** to run without a statement journal if there are no indexes on the | 1324 ** to run without a statement journal if there are no indexes on the |
| 1279 ** table. | 1325 ** table. |
| 1280 */ | 1326 */ |
| 1281 Trigger *pTrigger = 0; | 1327 Trigger *pTrigger = 0; |
| 1282 if( pParse->db->flags&SQLITE_RecTriggers ){ | 1328 if( db->flags&SQLITE_RecTriggers ){ |
| 1283 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); | 1329 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); |
| 1284 } | 1330 } |
| 1285 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ | 1331 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ |
| 1286 sqlite3MultiWrite(pParse); | 1332 sqlite3MultiWrite(pParse); |
| 1287 sqlite3GenerateRowDelete( | 1333 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, |
| 1288 pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace | 1334 regNewData, 1, 0, OE_Replace, 1); |
| 1289 ); | |
| 1290 }else if( pTab->pIndex ){ | 1335 }else if( pTab->pIndex ){ |
| 1291 sqlite3MultiWrite(pParse); | 1336 sqlite3MultiWrite(pParse); |
| 1292 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0); | 1337 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0); |
| 1293 } | 1338 } |
| 1294 seenReplace = 1; | 1339 seenReplace = 1; |
| 1295 break; | 1340 break; |
| 1296 } | 1341 } |
| 1297 case OE_Ignore: { | 1342 case OE_Ignore: { |
| 1298 assert( seenReplace==0 ); | 1343 /*assert( seenReplace==0 );*/ |
| 1299 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); | 1344 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); |
| 1300 break; | 1345 break; |
| 1301 } | 1346 } |
| 1302 } | 1347 } |
| 1303 sqlite3VdbeJumpHere(v, j3); | 1348 sqlite3VdbeResolveLabel(v, addrRowidOk); |
| 1304 if( isUpdate ){ | 1349 if( ipkTop ){ |
| 1305 sqlite3VdbeJumpHere(v, j2); | 1350 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); |
| 1351 sqlite3VdbeJumpHere(v, ipkTop); |
| 1306 } | 1352 } |
| 1307 } | 1353 } |
| 1308 | 1354 |
| 1309 /* Test all UNIQUE constraints by creating entries for each UNIQUE | 1355 /* Test all UNIQUE constraints by creating entries for each UNIQUE |
| 1310 ** index and making sure that duplicate entries do not already exist. | 1356 ** index and making sure that duplicate entries do not already exist. |
| 1311 ** Add the new records to the indices as we go. | 1357 ** Compute the revised record entries for indices as we go. |
| 1358 ** |
| 1359 ** This loop also handles the case of the PRIMARY KEY index for a |
| 1360 ** WITHOUT ROWID table. |
| 1312 */ | 1361 */ |
| 1313 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){ | 1362 for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ |
| 1314 int regIdx; | 1363 int regIdx; /* Range of registers hold conent for pIdx */ |
| 1315 int regR; | 1364 int regR; /* Range of registers holding conflicting PK */ |
| 1365 int iThisCur; /* Cursor for this UNIQUE index */ |
| 1366 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ |
| 1316 | 1367 |
| 1317 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */ | 1368 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ |
| 1369 if( bAffinityDone==0 ){ |
| 1370 sqlite3TableAffinity(v, pTab, regNewData+1); |
| 1371 bAffinityDone = 1; |
| 1372 } |
| 1373 iThisCur = iIdxCur+ix; |
| 1374 addrUniqueOk = sqlite3VdbeMakeLabel(v); |
| 1318 | 1375 |
| 1319 /* Create a key for accessing the index entry */ | 1376 /* Skip partial indices for which the WHERE clause is not true */ |
| 1320 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1); | 1377 if( pIdx->pPartIdxWhere ){ |
| 1378 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); |
| 1379 pParse->ckBase = regNewData+1; |
| 1380 sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk, |
| 1381 SQLITE_JUMPIFNULL); |
| 1382 pParse->ckBase = 0; |
| 1383 } |
| 1384 |
| 1385 /* Create a record for this index entry as it should appear after |
| 1386 ** the insert or update. Store that record in the aRegIdx[ix] register |
| 1387 */ |
| 1388 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn); |
| 1321 for(i=0; i<pIdx->nColumn; i++){ | 1389 for(i=0; i<pIdx->nColumn; i++){ |
| 1322 int idx = pIdx->aiColumn[i]; | 1390 int iField = pIdx->aiColumn[i]; |
| 1323 if( idx==pTab->iPKey ){ | 1391 int x; |
| 1324 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); | 1392 if( iField<0 || iField==pTab->iPKey ){ |
| 1393 if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */ |
| 1394 x = regNewData; |
| 1395 regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i; |
| 1325 }else{ | 1396 }else{ |
| 1326 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i); | 1397 x = iField + regNewData + 1; |
| 1327 } | 1398 } |
| 1399 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i); |
| 1400 VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName)); |
| 1328 } | 1401 } |
| 1329 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); | 1402 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); |
| 1330 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]); | 1403 VdbeComment((v, "for %s", pIdx->zName)); |
| 1331 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT); | 1404 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn); |
| 1332 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1); | |
| 1333 | 1405 |
| 1334 /* Find out what action to take in case there is an indexing conflict */ | 1406 /* In an UPDATE operation, if this index is the PRIMARY KEY index |
| 1407 ** of a WITHOUT ROWID table and there has been no change the |
| 1408 ** primary key, then no collision is possible. The collision detection |
| 1409 ** logic below can all be skipped. */ |
| 1410 if( isUpdate && pPk==pIdx && pkChng==0 ){ |
| 1411 sqlite3VdbeResolveLabel(v, addrUniqueOk); |
| 1412 continue; |
| 1413 } |
| 1414 |
| 1415 /* Find out what action to take in case there is a uniqueness conflict */ |
| 1335 onError = pIdx->onError; | 1416 onError = pIdx->onError; |
| 1336 if( onError==OE_None ){ | 1417 if( onError==OE_None ){ |
| 1337 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); | 1418 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); |
| 1419 sqlite3VdbeResolveLabel(v, addrUniqueOk); |
| 1338 continue; /* pIdx is not a UNIQUE index */ | 1420 continue; /* pIdx is not a UNIQUE index */ |
| 1339 } | 1421 } |
| 1340 if( overrideError!=OE_Default ){ | 1422 if( overrideError!=OE_Default ){ |
| 1341 onError = overrideError; | 1423 onError = overrideError; |
| 1342 }else if( onError==OE_Default ){ | 1424 }else if( onError==OE_Default ){ |
| 1343 onError = OE_Abort; | 1425 onError = OE_Abort; |
| 1344 } | 1426 } |
| 1345 if( seenReplace ){ | |
| 1346 if( onError==OE_Ignore ) onError = OE_Replace; | |
| 1347 else if( onError==OE_Fail ) onError = OE_Abort; | |
| 1348 } | |
| 1349 | 1427 |
| 1350 /* Check to see if the new index entry will be unique */ | 1428 /* Check to see if the new index entry will be unique */ |
| 1351 regR = sqlite3GetTempReg(pParse); | 1429 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, |
| 1352 sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR); | 1430 regIdx, pIdx->nKeyCol); VdbeCoverage(v); |
| 1353 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0, | 1431 |
| 1354 regR, SQLITE_INT_TO_PTR(regIdx), | 1432 /* Generate code to handle collisions */ |
| 1355 P4_INT32); | 1433 regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); |
| 1356 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); | 1434 if( isUpdate || onError==OE_Replace ){ |
| 1435 if( HasRowid(pTab) ){ |
| 1436 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); |
| 1437 /* Conflict only if the rowid of the existing index entry |
| 1438 ** is different from old-rowid */ |
| 1439 if( isUpdate ){ |
| 1440 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); |
| 1441 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); |
| 1442 VdbeCoverage(v); |
| 1443 } |
| 1444 }else{ |
| 1445 int x; |
| 1446 /* Extract the PRIMARY KEY from the end of the index entry and |
| 1447 ** store it in registers regR..regR+nPk-1 */ |
| 1448 if( pIdx!=pPk ){ |
| 1449 for(i=0; i<pPk->nKeyCol; i++){ |
| 1450 x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]); |
| 1451 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); |
| 1452 VdbeComment((v, "%s.%s", pTab->zName, |
| 1453 pTab->aCol[pPk->aiColumn[i]].zName)); |
| 1454 } |
| 1455 } |
| 1456 if( isUpdate ){ |
| 1457 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID |
| 1458 ** table, only conflict if the new PRIMARY KEY values are actually |
| 1459 ** different from the old. |
| 1460 ** |
| 1461 ** For a UNIQUE index, only conflict if the PRIMARY KEY values |
| 1462 ** of the matched index row are different from the original PRIMARY |
| 1463 ** KEY values of this row before the update. */ |
| 1464 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; |
| 1465 int op = OP_Ne; |
| 1466 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); |
| 1467 |
| 1468 for(i=0; i<pPk->nKeyCol; i++){ |
| 1469 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); |
| 1470 x = pPk->aiColumn[i]; |
| 1471 if( i==(pPk->nKeyCol-1) ){ |
| 1472 addrJump = addrUniqueOk; |
| 1473 op = OP_Eq; |
| 1474 } |
| 1475 sqlite3VdbeAddOp4(v, op, |
| 1476 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ |
| 1477 ); |
| 1478 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); |
| 1479 VdbeCoverageIf(v, op==OP_Eq); |
| 1480 VdbeCoverageIf(v, op==OP_Ne); |
| 1481 } |
| 1482 } |
| 1483 } |
| 1484 } |
| 1357 | 1485 |
| 1358 /* Generate code that executes if the new index entry is not unique */ | 1486 /* Generate code that executes if the new index entry is not unique */ |
| 1359 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail | 1487 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail |
| 1360 || onError==OE_Ignore || onError==OE_Replace ); | 1488 || onError==OE_Ignore || onError==OE_Replace ); |
| 1361 switch( onError ){ | 1489 switch( onError ){ |
| 1362 case OE_Rollback: | 1490 case OE_Rollback: |
| 1363 case OE_Abort: | 1491 case OE_Abort: |
| 1364 case OE_Fail: { | 1492 case OE_Fail: { |
| 1365 int j; | 1493 sqlite3UniqueConstraint(pParse, onError, pIdx); |
| 1366 StrAccum errMsg; | |
| 1367 const char *zSep; | |
| 1368 char *zErr; | |
| 1369 | |
| 1370 sqlite3StrAccumInit(&errMsg, 0, 0, 200); | |
| 1371 errMsg.db = pParse->db; | |
| 1372 zSep = pIdx->nColumn>1 ? "columns " : "column "; | |
| 1373 for(j=0; j<pIdx->nColumn; j++){ | |
| 1374 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; | |
| 1375 sqlite3StrAccumAppend(&errMsg, zSep, -1); | |
| 1376 zSep = ", "; | |
| 1377 sqlite3StrAccumAppend(&errMsg, zCol, -1); | |
| 1378 } | |
| 1379 sqlite3StrAccumAppend(&errMsg, | |
| 1380 pIdx->nColumn>1 ? " are not unique" : " is not unique", -1); | |
| 1381 zErr = sqlite3StrAccumFinish(&errMsg); | |
| 1382 sqlite3HaltConstraint(pParse, onError, zErr, 0); | |
| 1383 sqlite3DbFree(errMsg.db, zErr); | |
| 1384 break; | 1494 break; |
| 1385 } | 1495 } |
| 1386 case OE_Ignore: { | 1496 case OE_Ignore: { |
| 1387 assert( seenReplace==0 ); | |
| 1388 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); | 1497 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); |
| 1389 break; | 1498 break; |
| 1390 } | 1499 } |
| 1391 default: { | 1500 default: { |
| 1392 Trigger *pTrigger = 0; | 1501 Trigger *pTrigger = 0; |
| 1393 assert( onError==OE_Replace ); | 1502 assert( onError==OE_Replace ); |
| 1394 sqlite3MultiWrite(pParse); | 1503 sqlite3MultiWrite(pParse); |
| 1395 if( pParse->db->flags&SQLITE_RecTriggers ){ | 1504 if( db->flags&SQLITE_RecTriggers ){ |
| 1396 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); | 1505 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); |
| 1397 } | 1506 } |
| 1398 sqlite3GenerateRowDelete( | 1507 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, |
| 1399 pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace | 1508 regR, nPkField, 0, OE_Replace, pIdx==pPk); |
| 1400 ); | |
| 1401 seenReplace = 1; | 1509 seenReplace = 1; |
| 1402 break; | 1510 break; |
| 1403 } | 1511 } |
| 1404 } | 1512 } |
| 1405 sqlite3VdbeJumpHere(v, j3); | 1513 sqlite3VdbeResolveLabel(v, addrUniqueOk); |
| 1406 sqlite3ReleaseTempReg(pParse, regR); | 1514 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); |
| 1515 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); |
| 1516 } |
| 1517 if( ipkTop ){ |
| 1518 sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1); |
| 1519 sqlite3VdbeJumpHere(v, ipkBottom); |
| 1407 } | 1520 } |
| 1408 | 1521 |
| 1409 if( pbMayReplace ){ | 1522 *pbMayReplace = seenReplace; |
| 1410 *pbMayReplace = seenReplace; | 1523 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); |
| 1411 } | |
| 1412 } | 1524 } |
| 1413 | 1525 |
| 1414 /* | 1526 /* |
| 1415 ** This routine generates code to finish the INSERT or UPDATE operation | 1527 ** This routine generates code to finish the INSERT or UPDATE operation |
| 1416 ** that was started by a prior call to sqlite3GenerateConstraintChecks. | 1528 ** that was started by a prior call to sqlite3GenerateConstraintChecks. |
| 1417 ** A consecutive range of registers starting at regRowid contains the | 1529 ** A consecutive range of registers starting at regNewData contains the |
| 1418 ** rowid and the content to be inserted. | 1530 ** rowid and the content to be inserted. |
| 1419 ** | 1531 ** |
| 1420 ** The arguments to this routine should be the same as the first six | 1532 ** The arguments to this routine should be the same as the first six |
| 1421 ** arguments to sqlite3GenerateConstraintChecks. | 1533 ** arguments to sqlite3GenerateConstraintChecks. |
| 1422 */ | 1534 */ |
| 1423 void sqlite3CompleteInsertion( | 1535 void sqlite3CompleteInsertion( |
| 1424 Parse *pParse, /* The parser context */ | 1536 Parse *pParse, /* The parser context */ |
| 1425 Table *pTab, /* the table into which we are inserting */ | 1537 Table *pTab, /* the table into which we are inserting */ |
| 1426 int baseCur, /* Index of a read/write cursor pointing at pTab */ | 1538 int iDataCur, /* Cursor of the canonical data source */ |
| 1427 int regRowid, /* Range of content */ | 1539 int iIdxCur, /* First index cursor */ |
| 1540 int regNewData, /* Range of content */ |
| 1428 int *aRegIdx, /* Register used by each index. 0 for unused indices */ | 1541 int *aRegIdx, /* Register used by each index. 0 for unused indices */ |
| 1429 int isUpdate, /* True for UPDATE, False for INSERT */ | 1542 int isUpdate, /* True for UPDATE, False for INSERT */ |
| 1430 int appendBias, /* True if this is likely to be an append */ | 1543 int appendBias, /* True if this is likely to be an append */ |
| 1431 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ | 1544 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ |
| 1432 ){ | 1545 ){ |
| 1433 int i; | 1546 Vdbe *v; /* Prepared statements under construction */ |
| 1434 Vdbe *v; | 1547 Index *pIdx; /* An index being inserted or updated */ |
| 1435 int nIdx; | 1548 u8 pik_flags; /* flag values passed to the btree insert */ |
| 1436 Index *pIdx; | 1549 int regData; /* Content registers (after the rowid) */ |
| 1437 u8 pik_flags; | 1550 int regRec; /* Register holding assembled record for the table */ |
| 1438 int regData; | 1551 int i; /* Loop counter */ |
| 1439 int regRec; | 1552 u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */ |
| 1440 | 1553 |
| 1441 v = sqlite3GetVdbe(pParse); | 1554 v = sqlite3GetVdbe(pParse); |
| 1442 assert( v!=0 ); | 1555 assert( v!=0 ); |
| 1443 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ | 1556 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ |
| 1444 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} | 1557 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ |
| 1445 for(i=nIdx-1; i>=0; i--){ | |
| 1446 if( aRegIdx[i]==0 ) continue; | 1558 if( aRegIdx[i]==0 ) continue; |
| 1447 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]); | 1559 bAffinityDone = 1; |
| 1448 if( useSeekResult ){ | 1560 if( pIdx->pPartIdxWhere ){ |
| 1449 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); | 1561 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); |
| 1562 VdbeCoverage(v); |
| 1450 } | 1563 } |
| 1564 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]); |
| 1565 pik_flags = 0; |
| 1566 if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT; |
| 1567 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ |
| 1568 assert( pParse->nested==0 ); |
| 1569 pik_flags |= OPFLAG_NCHANGE; |
| 1570 } |
| 1571 if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags); |
| 1451 } | 1572 } |
| 1452 regData = regRowid + 1; | 1573 if( !HasRowid(pTab) ) return; |
| 1574 regData = regNewData + 1; |
| 1453 regRec = sqlite3GetTempReg(pParse); | 1575 regRec = sqlite3GetTempReg(pParse); |
| 1454 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); | 1576 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); |
| 1455 sqlite3TableAffinityStr(v, pTab); | 1577 if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0); |
| 1456 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); | 1578 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); |
| 1457 if( pParse->nested ){ | 1579 if( pParse->nested ){ |
| 1458 pik_flags = 0; | 1580 pik_flags = 0; |
| 1459 }else{ | 1581 }else{ |
| 1460 pik_flags = OPFLAG_NCHANGE; | 1582 pik_flags = OPFLAG_NCHANGE; |
| 1461 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); | 1583 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); |
| 1462 } | 1584 } |
| 1463 if( appendBias ){ | 1585 if( appendBias ){ |
| 1464 pik_flags |= OPFLAG_APPEND; | 1586 pik_flags |= OPFLAG_APPEND; |
| 1465 } | 1587 } |
| 1466 if( useSeekResult ){ | 1588 if( useSeekResult ){ |
| 1467 pik_flags |= OPFLAG_USESEEKRESULT; | 1589 pik_flags |= OPFLAG_USESEEKRESULT; |
| 1468 } | 1590 } |
| 1469 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid); | 1591 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData); |
| 1470 if( !pParse->nested ){ | 1592 if( !pParse->nested ){ |
| 1471 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT); | 1593 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT); |
| 1472 } | 1594 } |
| 1473 sqlite3VdbeChangeP5(v, pik_flags); | 1595 sqlite3VdbeChangeP5(v, pik_flags); |
| 1474 } | 1596 } |
| 1475 | 1597 |
| 1476 /* | 1598 /* |
| 1477 ** Generate code that will open cursors for a table and for all | 1599 ** Allocate cursors for the pTab table and all its indices and generate |
| 1478 ** indices of that table. The "baseCur" parameter is the cursor number used | 1600 ** code to open and initialized those cursors. |
| 1479 ** for the table. Indices are opened on subsequent cursors. | |
| 1480 ** | 1601 ** |
| 1481 ** Return the number of indices on the table. | 1602 ** The cursor for the object that contains the complete data (normally |
| 1603 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT |
| 1604 ** ROWID table) is returned in *piDataCur. The first index cursor is |
| 1605 ** returned in *piIdxCur. The number of indices is returned. |
| 1606 ** |
| 1607 ** Use iBase as the first cursor (either the *piDataCur for rowid tables |
| 1608 ** or the first index for WITHOUT ROWID tables) if it is non-negative. |
| 1609 ** If iBase is negative, then allocate the next available cursor. |
| 1610 ** |
| 1611 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. |
| 1612 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range |
| 1613 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the |
| 1614 ** pTab->pIndex list. |
| 1615 ** |
| 1616 ** If pTab is a virtual table, then this routine is a no-op and the |
| 1617 ** *piDataCur and *piIdxCur values are left uninitialized. |
| 1482 */ | 1618 */ |
| 1483 int sqlite3OpenTableAndIndices( | 1619 int sqlite3OpenTableAndIndices( |
| 1484 Parse *pParse, /* Parsing context */ | 1620 Parse *pParse, /* Parsing context */ |
| 1485 Table *pTab, /* Table to be opened */ | 1621 Table *pTab, /* Table to be opened */ |
| 1486 int baseCur, /* Cursor number assigned to the table */ | 1622 int op, /* OP_OpenRead or OP_OpenWrite */ |
| 1487 int op /* OP_OpenRead or OP_OpenWrite */ | 1623 int iBase, /* Use this for the table cursor, if there is one */ |
| 1624 u8 *aToOpen, /* If not NULL: boolean for each table and index */ |
| 1625 int *piDataCur, /* Write the database source cursor number here */ |
| 1626 int *piIdxCur /* Write the first index cursor number here */ |
| 1488 ){ | 1627 ){ |
| 1489 int i; | 1628 int i; |
| 1490 int iDb; | 1629 int iDb; |
| 1630 int iDataCur; |
| 1491 Index *pIdx; | 1631 Index *pIdx; |
| 1492 Vdbe *v; | 1632 Vdbe *v; |
| 1493 | 1633 |
| 1494 if( IsVirtual(pTab) ) return 0; | 1634 assert( op==OP_OpenRead || op==OP_OpenWrite ); |
| 1635 if( IsVirtual(pTab) ){ |
| 1636 /* This routine is a no-op for virtual tables. Leave the output |
| 1637 ** variables *piDataCur and *piIdxCur uninitialized so that valgrind |
| 1638 ** can detect if they are used by mistake in the caller. */ |
| 1639 return 0; |
| 1640 } |
| 1495 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); | 1641 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); |
| 1496 v = sqlite3GetVdbe(pParse); | 1642 v = sqlite3GetVdbe(pParse); |
| 1497 assert( v!=0 ); | 1643 assert( v!=0 ); |
| 1498 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op); | 1644 if( iBase<0 ) iBase = pParse->nTab; |
| 1499 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ | 1645 iDataCur = iBase++; |
| 1500 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); | 1646 if( piDataCur ) *piDataCur = iDataCur; |
| 1647 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ |
| 1648 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); |
| 1649 }else{ |
| 1650 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); |
| 1651 } |
| 1652 if( piIdxCur ) *piIdxCur = iBase; |
| 1653 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ |
| 1654 int iIdxCur = iBase++; |
| 1501 assert( pIdx->pSchema==pTab->pSchema ); | 1655 assert( pIdx->pSchema==pTab->pSchema ); |
| 1502 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb, | 1656 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){ |
| 1503 (char*)pKey, P4_KEYINFO_HANDOFF); | 1657 *piDataCur = iIdxCur; |
| 1504 VdbeComment((v, "%s", pIdx->zName)); | 1658 } |
| 1659 if( aToOpen==0 || aToOpen[i+1] ){ |
| 1660 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); |
| 1661 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); |
| 1662 VdbeComment((v, "%s", pIdx->zName)); |
| 1663 } |
| 1505 } | 1664 } |
| 1506 if( pParse->nTab<baseCur+i ){ | 1665 if( iBase>pParse->nTab ) pParse->nTab = iBase; |
| 1507 pParse->nTab = baseCur+i; | 1666 return i; |
| 1508 } | |
| 1509 return i-1; | |
| 1510 } | 1667 } |
| 1511 | 1668 |
| 1512 | 1669 |
| 1513 #ifdef SQLITE_TEST | 1670 #ifdef SQLITE_TEST |
| 1514 /* | 1671 /* |
| 1515 ** The following global variable is incremented whenever the | 1672 ** The following global variable is incremented whenever the |
| 1516 ** transfer optimization is used. This is used for testing | 1673 ** transfer optimization is used. This is used for testing |
| 1517 ** purposes only - to make sure the transfer optimization really | 1674 ** purposes only - to make sure the transfer optimization really |
| 1518 ** is happening when it is suppose to. | 1675 ** is happening when it is supposed to. |
| 1519 */ | 1676 */ |
| 1520 int sqlite3_xferopt_count; | 1677 int sqlite3_xferopt_count; |
| 1521 #endif /* SQLITE_TEST */ | 1678 #endif /* SQLITE_TEST */ |
| 1522 | 1679 |
| 1523 | 1680 |
| 1524 #ifndef SQLITE_OMIT_XFER_OPT | 1681 #ifndef SQLITE_OMIT_XFER_OPT |
| 1525 /* | 1682 /* |
| 1526 ** Check to collation names to see if they are compatible. | 1683 ** Check to collation names to see if they are compatible. |
| 1527 */ | 1684 */ |
| 1528 static int xferCompatibleCollation(const char *z1, const char *z2){ | 1685 static int xferCompatibleCollation(const char *z1, const char *z2){ |
| 1529 if( z1==0 ){ | 1686 if( z1==0 ){ |
| 1530 return z2==0; | 1687 return z2==0; |
| 1531 } | 1688 } |
| 1532 if( z2==0 ){ | 1689 if( z2==0 ){ |
| 1533 return 0; | 1690 return 0; |
| 1534 } | 1691 } |
| 1535 return sqlite3StrICmp(z1, z2)==0; | 1692 return sqlite3StrICmp(z1, z2)==0; |
| 1536 } | 1693 } |
| 1537 | 1694 |
| 1538 | 1695 |
| 1539 /* | 1696 /* |
| 1540 ** Check to see if index pSrc is compatible as a source of data | 1697 ** Check to see if index pSrc is compatible as a source of data |
| 1541 ** for index pDest in an insert transfer optimization. The rules | 1698 ** for index pDest in an insert transfer optimization. The rules |
| 1542 ** for a compatible index: | 1699 ** for a compatible index: |
| 1543 ** | 1700 ** |
| 1544 ** * The index is over the same set of columns | 1701 ** * The index is over the same set of columns |
| 1545 ** * The same DESC and ASC markings occurs on all columns | 1702 ** * The same DESC and ASC markings occurs on all columns |
| 1546 ** * The same onError processing (OE_Abort, OE_Ignore, etc) | 1703 ** * The same onError processing (OE_Abort, OE_Ignore, etc) |
| 1547 ** * The same collating sequence on each column | 1704 ** * The same collating sequence on each column |
| 1705 ** * The index has the exact same WHERE clause |
| 1548 */ | 1706 */ |
| 1549 static int xferCompatibleIndex(Index *pDest, Index *pSrc){ | 1707 static int xferCompatibleIndex(Index *pDest, Index *pSrc){ |
| 1550 int i; | 1708 int i; |
| 1551 assert( pDest && pSrc ); | 1709 assert( pDest && pSrc ); |
| 1552 assert( pDest->pTable!=pSrc->pTable ); | 1710 assert( pDest->pTable!=pSrc->pTable ); |
| 1553 if( pDest->nColumn!=pSrc->nColumn ){ | 1711 if( pDest->nKeyCol!=pSrc->nKeyCol ){ |
| 1554 return 0; /* Different number of columns */ | 1712 return 0; /* Different number of columns */ |
| 1555 } | 1713 } |
| 1556 if( pDest->onError!=pSrc->onError ){ | 1714 if( pDest->onError!=pSrc->onError ){ |
| 1557 return 0; /* Different conflict resolution strategies */ | 1715 return 0; /* Different conflict resolution strategies */ |
| 1558 } | 1716 } |
| 1559 for(i=0; i<pSrc->nColumn; i++){ | 1717 for(i=0; i<pSrc->nKeyCol; i++){ |
| 1560 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ | 1718 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ |
| 1561 return 0; /* Different columns indexed */ | 1719 return 0; /* Different columns indexed */ |
| 1562 } | 1720 } |
| 1563 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ | 1721 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ |
| 1564 return 0; /* Different sort orders */ | 1722 return 0; /* Different sort orders */ |
| 1565 } | 1723 } |
| 1566 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){ | 1724 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){ |
| 1567 return 0; /* Different collating sequences */ | 1725 return 0; /* Different collating sequences */ |
| 1568 } | 1726 } |
| 1569 } | 1727 } |
| 1728 if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ |
| 1729 return 0; /* Different WHERE clauses */ |
| 1730 } |
| 1570 | 1731 |
| 1571 /* If no test above fails then the indices must be compatible */ | 1732 /* If no test above fails then the indices must be compatible */ |
| 1572 return 1; | 1733 return 1; |
| 1573 } | 1734 } |
| 1574 | 1735 |
| 1575 /* | 1736 /* |
| 1576 ** Attempt the transfer optimization on INSERTs of the form | 1737 ** Attempt the transfer optimization on INSERTs of the form |
| 1577 ** | 1738 ** |
| 1578 ** INSERT INTO tab1 SELECT * FROM tab2; | 1739 ** INSERT INTO tab1 SELECT * FROM tab2; |
| 1579 ** | 1740 ** |
| 1580 ** This optimization is only attempted if | 1741 ** The xfer optimization transfers raw records from tab2 over to tab1. |
| 1742 ** Columns are not decoded and reassembled, which greatly improves |
| 1743 ** performance. Raw index records are transferred in the same way. |
| 1581 ** | 1744 ** |
| 1582 ** (1) tab1 and tab2 have identical schemas including all the | 1745 ** The xfer optimization is only attempted if tab1 and tab2 are compatible. |
| 1583 ** same indices and constraints | 1746 ** There are lots of rules for determining compatibility - see comments |
| 1747 ** embedded in the code for details. |
| 1584 ** | 1748 ** |
| 1585 ** (2) tab1 and tab2 are different tables | 1749 ** This routine returns TRUE if the optimization is guaranteed to be used. |
| 1750 ** Sometimes the xfer optimization will only work if the destination table |
| 1751 ** is empty - a factor that can only be determined at run-time. In that |
| 1752 ** case, this routine generates code for the xfer optimization but also |
| 1753 ** does a test to see if the destination table is empty and jumps over the |
| 1754 ** xfer optimization code if the test fails. In that case, this routine |
| 1755 ** returns FALSE so that the caller will know to go ahead and generate |
| 1756 ** an unoptimized transfer. This routine also returns FALSE if there |
| 1757 ** is no chance that the xfer optimization can be applied. |
| 1586 ** | 1758 ** |
| 1587 ** (3) There must be no triggers on tab1 | 1759 ** This optimization is particularly useful at making VACUUM run faster. |
| 1588 ** | |
| 1589 ** (4) The result set of the SELECT statement is "*" | |
| 1590 ** | |
| 1591 ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY, | |
| 1592 ** or LIMIT clause. | |
| 1593 ** | |
| 1594 ** (6) The SELECT statement is a simple (not a compound) select that | |
| 1595 ** contains only tab2 in its FROM clause | |
| 1596 ** | |
| 1597 ** This method for implementing the INSERT transfers raw records from | |
| 1598 ** tab2 over to tab1. The columns are not decoded. Raw records from | |
| 1599 ** the indices of tab2 are transfered to tab1 as well. In so doing, | |
| 1600 ** the resulting tab1 has much less fragmentation. | |
| 1601 ** | |
| 1602 ** This routine returns TRUE if the optimization is attempted. If any | |
| 1603 ** of the conditions above fail so that the optimization should not | |
| 1604 ** be attempted, then this routine returns FALSE. | |
| 1605 */ | 1760 */ |
| 1606 static int xferOptimization( | 1761 static int xferOptimization( |
| 1607 Parse *pParse, /* Parser context */ | 1762 Parse *pParse, /* Parser context */ |
| 1608 Table *pDest, /* The table we are inserting into */ | 1763 Table *pDest, /* The table we are inserting into */ |
| 1609 Select *pSelect, /* A SELECT statement to use as the data source */ | 1764 Select *pSelect, /* A SELECT statement to use as the data source */ |
| 1610 int onError, /* How to handle constraint errors */ | 1765 int onError, /* How to handle constraint errors */ |
| 1611 int iDbDest /* The database of pDest */ | 1766 int iDbDest /* The database of pDest */ |
| 1612 ){ | 1767 ){ |
| 1613 ExprList *pEList; /* The result set of the SELECT */ | 1768 ExprList *pEList; /* The result set of the SELECT */ |
| 1614 Table *pSrc; /* The table in the FROM clause of SELECT */ | 1769 Table *pSrc; /* The table in the FROM clause of SELECT */ |
| 1615 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ | 1770 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ |
| 1616 struct SrcList_item *pItem; /* An element of pSelect->pSrc */ | 1771 struct SrcList_item *pItem; /* An element of pSelect->pSrc */ |
| 1617 int i; /* Loop counter */ | 1772 int i; /* Loop counter */ |
| 1618 int iDbSrc; /* The database of pSrc */ | 1773 int iDbSrc; /* The database of pSrc */ |
| 1619 int iSrc, iDest; /* Cursors from source and destination */ | 1774 int iSrc, iDest; /* Cursors from source and destination */ |
| 1620 int addr1, addr2; /* Loop addresses */ | 1775 int addr1, addr2; /* Loop addresses */ |
| 1621 int emptyDestTest; /* Address of test for empty pDest */ | 1776 int emptyDestTest = 0; /* Address of test for empty pDest */ |
| 1622 int emptySrcTest; /* Address of test for empty pSrc */ | 1777 int emptySrcTest = 0; /* Address of test for empty pSrc */ |
| 1623 Vdbe *v; /* The VDBE we are building */ | 1778 Vdbe *v; /* The VDBE we are building */ |
| 1624 KeyInfo *pKey; /* Key information for an index */ | |
| 1625 int regAutoinc; /* Memory register used by AUTOINC */ | 1779 int regAutoinc; /* Memory register used by AUTOINC */ |
| 1626 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ | 1780 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ |
| 1627 int regData, regRowid; /* Registers holding data and rowid */ | 1781 int regData, regRowid; /* Registers holding data and rowid */ |
| 1628 | 1782 |
| 1629 if( pSelect==0 ){ | 1783 if( pSelect==0 ){ |
| 1630 return 0; /* Must be of the form INSERT INTO ... SELECT ... */ | 1784 return 0; /* Must be of the form INSERT INTO ... SELECT ... */ |
| 1631 } | 1785 } |
| 1786 if( pParse->pWith || pSelect->pWith ){ |
| 1787 /* Do not attempt to process this query if there are an WITH clauses |
| 1788 ** attached to it. Proceeding may generate a false "no such table: xxx" |
| 1789 ** error if pSelect reads from a CTE named "xxx". */ |
| 1790 return 0; |
| 1791 } |
| 1632 if( sqlite3TriggerList(pParse, pDest) ){ | 1792 if( sqlite3TriggerList(pParse, pDest) ){ |
| 1633 return 0; /* tab1 must not have triggers */ | 1793 return 0; /* tab1 must not have triggers */ |
| 1634 } | 1794 } |
| 1635 #ifndef SQLITE_OMIT_VIRTUALTABLE | 1795 #ifndef SQLITE_OMIT_VIRTUALTABLE |
| 1636 if( pDest->tabFlags & TF_Virtual ){ | 1796 if( pDest->tabFlags & TF_Virtual ){ |
| 1637 return 0; /* tab1 must not be a virtual table */ | 1797 return 0; /* tab1 must not be a virtual table */ |
| 1638 } | 1798 } |
| 1639 #endif | 1799 #endif |
| 1640 if( onError==OE_Default ){ | 1800 if( onError==OE_Default ){ |
| 1641 onError = OE_Abort; | 1801 if( pDest->iPKey>=0 ) onError = pDest->keyConf; |
| 1642 } | 1802 if( onError==OE_Default ) onError = OE_Abort; |
| 1643 if( onError!=OE_Abort && onError!=OE_Rollback ){ | |
| 1644 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */ | |
| 1645 } | 1803 } |
| 1646 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ | 1804 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ |
| 1647 if( pSelect->pSrc->nSrc!=1 ){ | 1805 if( pSelect->pSrc->nSrc!=1 ){ |
| 1648 return 0; /* FROM clause must have exactly one term */ | 1806 return 0; /* FROM clause must have exactly one term */ |
| 1649 } | 1807 } |
| 1650 if( pSelect->pSrc->a[0].pSelect ){ | 1808 if( pSelect->pSrc->a[0].pSelect ){ |
| 1651 return 0; /* FROM clause cannot contain a subquery */ | 1809 return 0; /* FROM clause cannot contain a subquery */ |
| 1652 } | 1810 } |
| 1653 if( pSelect->pWhere ){ | 1811 if( pSelect->pWhere ){ |
| 1654 return 0; /* SELECT may not have a WHERE clause */ | 1812 return 0; /* SELECT may not have a WHERE clause */ |
| (...skipping 24 matching lines...) Expand all Loading... |
| 1679 assert( pEList->a[0].pExpr ); | 1837 assert( pEList->a[0].pExpr ); |
| 1680 if( pEList->a[0].pExpr->op!=TK_ALL ){ | 1838 if( pEList->a[0].pExpr->op!=TK_ALL ){ |
| 1681 return 0; /* The result set must be the special operator "*" */ | 1839 return 0; /* The result set must be the special operator "*" */ |
| 1682 } | 1840 } |
| 1683 | 1841 |
| 1684 /* At this point we have established that the statement is of the | 1842 /* At this point we have established that the statement is of the |
| 1685 ** correct syntactic form to participate in this optimization. Now | 1843 ** correct syntactic form to participate in this optimization. Now |
| 1686 ** we have to check the semantics. | 1844 ** we have to check the semantics. |
| 1687 */ | 1845 */ |
| 1688 pItem = pSelect->pSrc->a; | 1846 pItem = pSelect->pSrc->a; |
| 1689 pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase); | 1847 pSrc = sqlite3LocateTableItem(pParse, 0, pItem); |
| 1690 if( pSrc==0 ){ | 1848 if( pSrc==0 ){ |
| 1691 return 0; /* FROM clause does not contain a real table */ | 1849 return 0; /* FROM clause does not contain a real table */ |
| 1692 } | 1850 } |
| 1693 if( pSrc==pDest ){ | 1851 if( pSrc==pDest ){ |
| 1694 return 0; /* tab1 and tab2 may not be the same table */ | 1852 return 0; /* tab1 and tab2 may not be the same table */ |
| 1695 } | 1853 } |
| 1854 if( HasRowid(pDest)!=HasRowid(pSrc) ){ |
| 1855 return 0; /* source and destination must both be WITHOUT ROWID or not */ |
| 1856 } |
| 1696 #ifndef SQLITE_OMIT_VIRTUALTABLE | 1857 #ifndef SQLITE_OMIT_VIRTUALTABLE |
| 1697 if( pSrc->tabFlags & TF_Virtual ){ | 1858 if( pSrc->tabFlags & TF_Virtual ){ |
| 1698 return 0; /* tab2 must not be a virtual table */ | 1859 return 0; /* tab2 must not be a virtual table */ |
| 1699 } | 1860 } |
| 1700 #endif | 1861 #endif |
| 1701 if( pSrc->pSelect ){ | 1862 if( pSrc->pSelect ){ |
| 1702 return 0; /* tab2 may not be a view */ | 1863 return 0; /* tab2 may not be a view */ |
| 1703 } | 1864 } |
| 1704 if( pDest->nCol!=pSrc->nCol ){ | 1865 if( pDest->nCol!=pSrc->nCol ){ |
| 1705 return 0; /* Number of columns must be the same in tab1 and tab2 */ | 1866 return 0; /* Number of columns must be the same in tab1 and tab2 */ |
| 1706 } | 1867 } |
| 1707 if( pDest->iPKey!=pSrc->iPKey ){ | 1868 if( pDest->iPKey!=pSrc->iPKey ){ |
| 1708 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ | 1869 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ |
| 1709 } | 1870 } |
| 1710 for(i=0; i<pDest->nCol; i++){ | 1871 for(i=0; i<pDest->nCol; i++){ |
| 1711 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){ | 1872 Column *pDestCol = &pDest->aCol[i]; |
| 1873 Column *pSrcCol = &pSrc->aCol[i]; |
| 1874 if( pDestCol->affinity!=pSrcCol->affinity ){ |
| 1712 return 0; /* Affinity must be the same on all columns */ | 1875 return 0; /* Affinity must be the same on all columns */ |
| 1713 } | 1876 } |
| 1714 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){ | 1877 if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){ |
| 1715 return 0; /* Collating sequence must be the same on all columns */ | 1878 return 0; /* Collating sequence must be the same on all columns */ |
| 1716 } | 1879 } |
| 1717 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){ | 1880 if( pDestCol->notNull && !pSrcCol->notNull ){ |
| 1718 return 0; /* tab2 must be NOT NULL if tab1 is */ | 1881 return 0; /* tab2 must be NOT NULL if tab1 is */ |
| 1719 } | 1882 } |
| 1883 /* Default values for second and subsequent columns need to match. */ |
| 1884 if( i>0 |
| 1885 && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0) |
| 1886 || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0)) |
| 1887 ){ |
| 1888 return 0; /* Default values must be the same for all columns */ |
| 1889 } |
| 1720 } | 1890 } |
| 1721 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ | 1891 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ |
| 1722 if( pDestIdx->onError!=OE_None ){ | 1892 if( IsUniqueIndex(pDestIdx) ){ |
| 1723 destHasUniqueIdx = 1; | 1893 destHasUniqueIdx = 1; |
| 1724 } | 1894 } |
| 1725 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ | 1895 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ |
| 1726 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; | 1896 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; |
| 1727 } | 1897 } |
| 1728 if( pSrcIdx==0 ){ | 1898 if( pSrcIdx==0 ){ |
| 1729 return 0; /* pDestIdx has no corresponding index in pSrc */ | 1899 return 0; /* pDestIdx has no corresponding index in pSrc */ |
| 1730 } | 1900 } |
| 1731 } | 1901 } |
| 1732 #ifndef SQLITE_OMIT_CHECK | 1902 #ifndef SQLITE_OMIT_CHECK |
| 1733 if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){ | 1903 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ |
| 1734 return 0; /* Tables have different CHECK constraints. Ticket #2252 */ | 1904 return 0; /* Tables have different CHECK constraints. Ticket #2252 */ |
| 1735 } | 1905 } |
| 1736 #endif | 1906 #endif |
| 1907 #ifndef SQLITE_OMIT_FOREIGN_KEY |
| 1908 /* Disallow the transfer optimization if the destination table constains |
| 1909 ** any foreign key constraints. This is more restrictive than necessary. |
| 1910 ** But the main beneficiary of the transfer optimization is the VACUUM |
| 1911 ** command, and the VACUUM command disables foreign key constraints. So |
| 1912 ** the extra complication to make this rule less restrictive is probably |
| 1913 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] |
| 1914 */ |
| 1915 if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ |
| 1916 return 0; |
| 1917 } |
| 1918 #endif |
| 1919 if( (pParse->db->flags & SQLITE_CountRows)!=0 ){ |
| 1920 return 0; /* xfer opt does not play well with PRAGMA count_changes */ |
| 1921 } |
| 1737 | 1922 |
| 1738 /* If we get this far, it means either: | 1923 /* If we get this far, it means that the xfer optimization is at |
| 1739 ** | 1924 ** least a possibility, though it might only work if the destination |
| 1740 ** * We can always do the transfer if the table contains an | 1925 ** table (tab1) is initially empty. |
| 1741 ** an integer primary key | |
| 1742 ** | |
| 1743 ** * We can conditionally do the transfer if the destination | |
| 1744 ** table is empty. | |
| 1745 */ | 1926 */ |
| 1746 #ifdef SQLITE_TEST | 1927 #ifdef SQLITE_TEST |
| 1747 sqlite3_xferopt_count++; | 1928 sqlite3_xferopt_count++; |
| 1748 #endif | 1929 #endif |
| 1749 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema); | 1930 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema); |
| 1750 v = sqlite3GetVdbe(pParse); | 1931 v = sqlite3GetVdbe(pParse); |
| 1751 sqlite3CodeVerifySchema(pParse, iDbSrc); | 1932 sqlite3CodeVerifySchema(pParse, iDbSrc); |
| 1752 iSrc = pParse->nTab++; | 1933 iSrc = pParse->nTab++; |
| 1753 iDest = pParse->nTab++; | 1934 iDest = pParse->nTab++; |
| 1754 regAutoinc = autoIncBegin(pParse, iDbDest, pDest); | 1935 regAutoinc = autoIncBegin(pParse, iDbDest, pDest); |
| 1936 regData = sqlite3GetTempReg(pParse); |
| 1937 regRowid = sqlite3GetTempReg(pParse); |
| 1755 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); | 1938 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); |
| 1756 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){ | 1939 assert( HasRowid(pDest) || destHasUniqueIdx ); |
| 1757 /* If tables do not have an INTEGER PRIMARY KEY and there | 1940 if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ |
| 1758 ** are indices to be copied and the destination is not empty, | 1941 || destHasUniqueIdx /* (2) */ |
| 1759 ** we have to disallow the transfer optimization because the | 1942 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ |
| 1760 ** the rowids might change which will mess up indexing. | 1943 ){ |
| 1944 /* In some circumstances, we are able to run the xfer optimization |
| 1945 ** only if the destination table is initially empty. This code makes |
| 1946 ** that determination. Conditions under which the destination must |
| 1947 ** be empty: |
| 1761 ** | 1948 ** |
| 1762 ** Or if the destination has a UNIQUE index and is not empty, | 1949 ** (1) There is no INTEGER PRIMARY KEY but there are indices. |
| 1763 ** we also disallow the transfer optimization because we cannot | 1950 ** (If the destination is not initially empty, the rowid fields |
| 1764 ** insure that all entries in the union of DEST and SRC will be | 1951 ** of index entries might need to change.) |
| 1765 ** unique. | 1952 ** |
| 1953 ** (2) The destination has a unique index. (The xfer optimization |
| 1954 ** is unable to test uniqueness.) |
| 1955 ** |
| 1956 ** (3) onError is something other than OE_Abort and OE_Rollback. |
| 1766 */ | 1957 */ |
| 1767 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); | 1958 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); |
| 1768 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); | 1959 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); |
| 1769 sqlite3VdbeJumpHere(v, addr1); | 1960 sqlite3VdbeJumpHere(v, addr1); |
| 1961 } |
| 1962 if( HasRowid(pSrc) ){ |
| 1963 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); |
| 1964 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); |
| 1965 if( pDest->iPKey>=0 ){ |
| 1966 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); |
| 1967 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); |
| 1968 VdbeCoverage(v); |
| 1969 sqlite3RowidConstraint(pParse, onError, pDest); |
| 1970 sqlite3VdbeJumpHere(v, addr2); |
| 1971 autoIncStep(pParse, regAutoinc, regRowid); |
| 1972 }else if( pDest->pIndex==0 ){ |
| 1973 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); |
| 1974 }else{ |
| 1975 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); |
| 1976 assert( (pDest->tabFlags & TF_Autoincrement)==0 ); |
| 1977 } |
| 1978 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); |
| 1979 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); |
| 1980 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); |
| 1981 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); |
| 1982 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); |
| 1983 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); |
| 1984 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); |
| 1770 }else{ | 1985 }else{ |
| 1771 emptyDestTest = 0; | 1986 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); |
| 1987 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); |
| 1772 } | 1988 } |
| 1773 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); | |
| 1774 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); | |
| 1775 regData = sqlite3GetTempReg(pParse); | |
| 1776 regRowid = sqlite3GetTempReg(pParse); | |
| 1777 if( pDest->iPKey>=0 ){ | |
| 1778 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); | |
| 1779 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); | |
| 1780 sqlite3HaltConstraint( | |
| 1781 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC); | |
| 1782 sqlite3VdbeJumpHere(v, addr2); | |
| 1783 autoIncStep(pParse, regAutoinc, regRowid); | |
| 1784 }else if( pDest->pIndex==0 ){ | |
| 1785 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); | |
| 1786 }else{ | |
| 1787 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); | |
| 1788 assert( (pDest->tabFlags & TF_Autoincrement)==0 ); | |
| 1789 } | |
| 1790 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); | |
| 1791 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); | |
| 1792 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); | |
| 1793 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); | |
| 1794 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); | |
| 1795 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ | 1989 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ |
| 1796 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ | 1990 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ |
| 1797 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; | 1991 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; |
| 1798 } | 1992 } |
| 1799 assert( pSrcIdx ); | 1993 assert( pSrcIdx ); |
| 1994 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); |
| 1995 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); |
| 1996 VdbeComment((v, "%s", pSrcIdx->zName)); |
| 1997 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); |
| 1998 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); |
| 1999 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); |
| 2000 VdbeComment((v, "%s", pDestIdx->zName)); |
| 2001 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); |
| 2002 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); |
| 2003 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); |
| 2004 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); |
| 2005 sqlite3VdbeJumpHere(v, addr1); |
| 1800 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); | 2006 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); |
| 1801 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); | 2007 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); |
| 1802 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx); | |
| 1803 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc, | |
| 1804 (char*)pKey, P4_KEYINFO_HANDOFF); | |
| 1805 VdbeComment((v, "%s", pSrcIdx->zName)); | |
| 1806 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx); | |
| 1807 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest, | |
| 1808 (char*)pKey, P4_KEYINFO_HANDOFF); | |
| 1809 VdbeComment((v, "%s", pDestIdx->zName)); | |
| 1810 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); | |
| 1811 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); | |
| 1812 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); | |
| 1813 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); | |
| 1814 sqlite3VdbeJumpHere(v, addr1); | |
| 1815 } | 2008 } |
| 1816 sqlite3VdbeJumpHere(v, emptySrcTest); | 2009 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); |
| 1817 sqlite3ReleaseTempReg(pParse, regRowid); | 2010 sqlite3ReleaseTempReg(pParse, regRowid); |
| 1818 sqlite3ReleaseTempReg(pParse, regData); | 2011 sqlite3ReleaseTempReg(pParse, regData); |
| 1819 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); | |
| 1820 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); | |
| 1821 if( emptyDestTest ){ | 2012 if( emptyDestTest ){ |
| 1822 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); | 2013 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); |
| 1823 sqlite3VdbeJumpHere(v, emptyDestTest); | 2014 sqlite3VdbeJumpHere(v, emptyDestTest); |
| 1824 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); | 2015 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); |
| 1825 return 0; | 2016 return 0; |
| 1826 }else{ | 2017 }else{ |
| 1827 return 1; | 2018 return 1; |
| 1828 } | 2019 } |
| 1829 } | 2020 } |
| 1830 #endif /* SQLITE_OMIT_XFER_OPT */ | 2021 #endif /* SQLITE_OMIT_XFER_OPT */ |
| OLD | NEW |