000001 /*
000002 ** 2001 September 15
000003 **
000004 ** The author disclaims copyright to this source code. In place of
000005 ** a legal notice, here is a blessing:
000006 **
000007 ** May you do good and not evil.
000008 ** May you find forgiveness for yourself and forgive others.
000009 ** May you share freely, never taking more than you give.
000010 **
000011 *************************************************************************
000012 ** This file contains C code routines that are called by the parser
000013 ** to handle INSERT statements in SQLite.
000014 */
000015 #include "sqliteInt.h"
000016
000017 /*
000018 ** Generate code that will
000019 **
000020 ** (1) acquire a lock for table pTab then
000021 ** (2) open pTab as cursor iCur.
000022 **
000023 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
000024 ** for that table that is actually opened.
000025 */
000026 void sqlite3OpenTable(
000027 Parse *pParse, /* Generate code into this VDBE */
000028 int iCur, /* The cursor number of the table */
000029 int iDb, /* The database index in sqlite3.aDb[] */
000030 Table *pTab, /* The table to be opened */
000031 int opcode /* OP_OpenRead or OP_OpenWrite */
000032 ){
000033 Vdbe *v;
000034 assert( !IsVirtual(pTab) );
000035 assert( pParse->pVdbe!=0 );
000036 v = pParse->pVdbe;
000037 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
000038 if( !pParse->db->noSharedCache ){
000039 sqlite3TableLock(pParse, iDb, pTab->tnum,
000040 (opcode==OP_OpenWrite)?1:0, pTab->zName);
000041 }
000042 if( HasRowid(pTab) ){
000043 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
000044 VdbeComment((v, "%s", pTab->zName));
000045 }else{
000046 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
000047 assert( pPk!=0 );
000048 assert( pPk->tnum==pTab->tnum || CORRUPT_DB );
000049 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
000050 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
000051 VdbeComment((v, "%s", pTab->zName));
000052 }
000053 }
000054
000055 /*
000056 ** Return a pointer to the column affinity string associated with index
000057 ** pIdx. A column affinity string has one character for each column in
000058 ** the table, according to the affinity of the column:
000059 **
000060 ** Character Column affinity
000061 ** ------------------------------
000062 ** 'A' BLOB
000063 ** 'B' TEXT
000064 ** 'C' NUMERIC
000065 ** 'D' INTEGER
000066 ** 'F' REAL
000067 **
000068 ** An extra 'D' is appended to the end of the string to cover the
000069 ** rowid that appears as the last column in every index.
000070 **
000071 ** Memory for the buffer containing the column index affinity string
000072 ** is managed along with the rest of the Index structure. It will be
000073 ** released when sqlite3DeleteIndex() is called.
000074 */
000075 static SQLITE_NOINLINE const char *computeIndexAffStr(sqlite3 *db, Index *pIdx){
000076 /* The first time a column affinity string for a particular index is
000077 ** required, it is allocated and populated here. It is then stored as
000078 ** a member of the Index structure for subsequent use.
000079 **
000080 ** The column affinity string will eventually be deleted by
000081 ** sqliteDeleteIndex() when the Index structure itself is cleaned
000082 ** up.
000083 */
000084 int n;
000085 Table *pTab = pIdx->pTable;
000086 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
000087 if( !pIdx->zColAff ){
000088 sqlite3OomFault(db);
000089 return 0;
000090 }
000091 for(n=0; n<pIdx->nColumn; n++){
000092 i16 x = pIdx->aiColumn[n];
000093 char aff;
000094 if( x>=0 ){
000095 aff = pTab->aCol[x].affinity;
000096 }else if( x==XN_ROWID ){
000097 aff = SQLITE_AFF_INTEGER;
000098 }else{
000099 assert( x==XN_EXPR );
000100 assert( pIdx->bHasExpr );
000101 assert( pIdx->aColExpr!=0 );
000102 aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
000103 }
000104 if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
000105 if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
000106 pIdx->zColAff[n] = aff;
000107 }
000108 pIdx->zColAff[n] = 0;
000109 return pIdx->zColAff;
000110 }
000111 const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
000112 if( !pIdx->zColAff ) return computeIndexAffStr(db, pIdx);
000113 return pIdx->zColAff;
000114 }
000115
000116
000117 /*
000118 ** Compute an affinity string for a table. Space is obtained
000119 ** from sqlite3DbMalloc(). The caller is responsible for freeing
000120 ** the space when done.
000121 */
000122 char *sqlite3TableAffinityStr(sqlite3 *db, const Table *pTab){
000123 char *zColAff;
000124 zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1);
000125 if( zColAff ){
000126 int i, j;
000127 for(i=j=0; i<pTab->nCol; i++){
000128 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
000129 zColAff[j++] = pTab->aCol[i].affinity;
000130 }
000131 }
000132 do{
000133 zColAff[j--] = 0;
000134 }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );
000135 }
000136 return zColAff;
000137 }
000138
000139 /*
000140 ** Make changes to the evolving bytecode to do affinity transformations
000141 ** of values that are about to be gathered into a row for table pTab.
000142 **
000143 ** For ordinary (legacy, non-strict) tables:
000144 ** -----------------------------------------
000145 **
000146 ** Compute the affinity string for table pTab, if it has not already been
000147 ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
000148 **
000149 ** If the affinity string is empty (because it was all SQLITE_AFF_BLOB entries
000150 ** which were then optimized out) then this routine becomes a no-op.
000151 **
000152 ** Otherwise if iReg>0 then code an OP_Affinity opcode that will set the
000153 ** affinities for register iReg and following. Or if iReg==0,
000154 ** then just set the P4 operand of the previous opcode (which should be
000155 ** an OP_MakeRecord) to the affinity string.
000156 **
000157 ** A column affinity string has one character per column:
000158 **
000159 ** Character Column affinity
000160 ** --------- ---------------
000161 ** 'A' BLOB
000162 ** 'B' TEXT
000163 ** 'C' NUMERIC
000164 ** 'D' INTEGER
000165 ** 'E' REAL
000166 **
000167 ** For STRICT tables:
000168 ** ------------------
000169 **
000170 ** Generate an appropriate OP_TypeCheck opcode that will verify the
000171 ** datatypes against the column definitions in pTab. If iReg==0, that
000172 ** means an OP_MakeRecord opcode has already been generated and should be
000173 ** the last opcode generated. The new OP_TypeCheck needs to be inserted
000174 ** before the OP_MakeRecord. The new OP_TypeCheck should use the same
000175 ** register set as the OP_MakeRecord. If iReg>0 then register iReg is
000176 ** the first of a series of registers that will form the new record.
000177 ** Apply the type checking to that array of registers.
000178 */
000179 void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
000180 int i;
000181 char *zColAff;
000182 if( pTab->tabFlags & TF_Strict ){
000183 if( iReg==0 ){
000184 /* Move the previous opcode (which should be OP_MakeRecord) forward
000185 ** by one slot and insert a new OP_TypeCheck where the current
000186 ** OP_MakeRecord is found */
000187 VdbeOp *pPrev;
000188 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
000189 pPrev = sqlite3VdbeGetLastOp(v);
000190 assert( pPrev!=0 );
000191 assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );
000192 pPrev->opcode = OP_TypeCheck;
000193 sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, pPrev->p3);
000194 }else{
000195 /* Insert an isolated OP_Typecheck */
000196 sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol);
000197 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
000198 }
000199 return;
000200 }
000201 zColAff = pTab->zColAff;
000202 if( zColAff==0 ){
000203 zColAff = sqlite3TableAffinityStr(0, pTab);
000204 if( !zColAff ){
000205 sqlite3OomFault(sqlite3VdbeDb(v));
000206 return;
000207 }
000208 pTab->zColAff = zColAff;
000209 }
000210 assert( zColAff!=0 );
000211 i = sqlite3Strlen30NN(zColAff);
000212 if( i ){
000213 if( iReg ){
000214 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
000215 }else{
000216 assert( sqlite3VdbeGetLastOp(v)->opcode==OP_MakeRecord
000217 || sqlite3VdbeDb(v)->mallocFailed );
000218 sqlite3VdbeChangeP4(v, -1, zColAff, i);
000219 }
000220 }
000221 }
000222
000223 /*
000224 ** Return non-zero if the table pTab in database iDb or any of its indices
000225 ** have been opened at any point in the VDBE program. This is used to see if
000226 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
000227 ** run without using a temporary table for the results of the SELECT.
000228 */
000229 static int readsTable(Parse *p, int iDb, Table *pTab){
000230 Vdbe *v = sqlite3GetVdbe(p);
000231 int i;
000232 int iEnd = sqlite3VdbeCurrentAddr(v);
000233 #ifndef SQLITE_OMIT_VIRTUALTABLE
000234 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
000235 #endif
000236
000237 for(i=1; i<iEnd; i++){
000238 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
000239 assert( pOp!=0 );
000240 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
000241 Index *pIndex;
000242 Pgno tnum = pOp->p2;
000243 if( tnum==pTab->tnum ){
000244 return 1;
000245 }
000246 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
000247 if( tnum==pIndex->tnum ){
000248 return 1;
000249 }
000250 }
000251 }
000252 #ifndef SQLITE_OMIT_VIRTUALTABLE
000253 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
000254 assert( pOp->p4.pVtab!=0 );
000255 assert( pOp->p4type==P4_VTAB );
000256 return 1;
000257 }
000258 #endif
000259 }
000260 return 0;
000261 }
000262
000263 /* This walker callback will compute the union of colFlags flags for all
000264 ** referenced columns in a CHECK constraint or generated column expression.
000265 */
000266 static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
000267 if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
000268 assert( pExpr->iColumn < pWalker->u.pTab->nCol );
000269 pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
000270 }
000271 return WRC_Continue;
000272 }
000273
000274 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
000275 /*
000276 ** All regular columns for table pTab have been puts into registers
000277 ** starting with iRegStore. The registers that correspond to STORED
000278 ** or VIRTUAL columns have not yet been initialized. This routine goes
000279 ** back and computes the values for those columns based on the previously
000280 ** computed normal columns.
000281 */
000282 void sqlite3ComputeGeneratedColumns(
000283 Parse *pParse, /* Parsing context */
000284 int iRegStore, /* Register holding the first column */
000285 Table *pTab /* The table */
000286 ){
000287 int i;
000288 Walker w;
000289 Column *pRedo;
000290 int eProgress;
000291 VdbeOp *pOp;
000292
000293 assert( pTab->tabFlags & TF_HasGenerated );
000294 testcase( pTab->tabFlags & TF_HasVirtual );
000295 testcase( pTab->tabFlags & TF_HasStored );
000296
000297 /* Before computing generated columns, first go through and make sure
000298 ** that appropriate affinity has been applied to the regular columns
000299 */
000300 sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
000301 if( (pTab->tabFlags & TF_HasStored)!=0 ){
000302 pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
000303 if( pOp->opcode==OP_Affinity ){
000304 /* Change the OP_Affinity argument to '@' (NONE) for all stored
000305 ** columns. '@' is the no-op affinity and those columns have not
000306 ** yet been computed. */
000307 int ii, jj;
000308 char *zP4 = pOp->p4.z;
000309 assert( zP4!=0 );
000310 assert( pOp->p4type==P4_DYNAMIC );
000311 for(ii=jj=0; zP4[jj]; ii++){
000312 if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
000313 continue;
000314 }
000315 if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
000316 zP4[jj] = SQLITE_AFF_NONE;
000317 }
000318 jj++;
000319 }
000320 }else if( pOp->opcode==OP_TypeCheck ){
000321 /* If an OP_TypeCheck was generated because the table is STRICT,
000322 ** then set the P3 operand to indicate that generated columns should
000323 ** not be checked */
000324 pOp->p3 = 1;
000325 }
000326 }
000327
000328 /* Because there can be multiple generated columns that refer to one another,
000329 ** this is a two-pass algorithm. On the first pass, mark all generated
000330 ** columns as "not available".
000331 */
000332 for(i=0; i<pTab->nCol; i++){
000333 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
000334 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
000335 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
000336 pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
000337 }
000338 }
000339
000340 w.u.pTab = pTab;
000341 w.xExprCallback = exprColumnFlagUnion;
000342 w.xSelectCallback = 0;
000343 w.xSelectCallback2 = 0;
000344
000345 /* On the second pass, compute the value of each NOT-AVAILABLE column.
000346 ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will
000347 ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as
000348 ** they are needed.
000349 */
000350 pParse->iSelfTab = -iRegStore;
000351 do{
000352 eProgress = 0;
000353 pRedo = 0;
000354 for(i=0; i<pTab->nCol; i++){
000355 Column *pCol = pTab->aCol + i;
000356 if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
000357 int x;
000358 pCol->colFlags |= COLFLAG_BUSY;
000359 w.eCode = 0;
000360 sqlite3WalkExpr(&w, sqlite3ColumnExpr(pTab, pCol));
000361 pCol->colFlags &= ~COLFLAG_BUSY;
000362 if( w.eCode & COLFLAG_NOTAVAIL ){
000363 pRedo = pCol;
000364 continue;
000365 }
000366 eProgress = 1;
000367 assert( pCol->colFlags & COLFLAG_GENERATED );
000368 x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
000369 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, x);
000370 pCol->colFlags &= ~COLFLAG_NOTAVAIL;
000371 }
000372 }
000373 }while( pRedo && eProgress );
000374 if( pRedo ){
000375 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zCnName);
000376 }
000377 pParse->iSelfTab = 0;
000378 }
000379 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
000380
000381
000382 #ifndef SQLITE_OMIT_AUTOINCREMENT
000383 /*
000384 ** Locate or create an AutoincInfo structure associated with table pTab
000385 ** which is in database iDb. Return the register number for the register
000386 ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
000387 ** table. (Also return zero when doing a VACUUM since we do not want to
000388 ** update the AUTOINCREMENT counters during a VACUUM.)
000389 **
000390 ** There is at most one AutoincInfo structure per table even if the
000391 ** same table is autoincremented multiple times due to inserts within
000392 ** triggers. A new AutoincInfo structure is created if this is the
000393 ** first use of table pTab. On 2nd and subsequent uses, the original
000394 ** AutoincInfo structure is used.
000395 **
000396 ** Four consecutive registers are allocated:
000397 **
000398 ** (1) The name of the pTab table.
000399 ** (2) The maximum ROWID of pTab.
000400 ** (3) The rowid in sqlite_sequence of pTab
000401 ** (4) The original value of the max ROWID in pTab, or NULL if none
000402 **
000403 ** The 2nd register is the one that is returned. That is all the
000404 ** insert routine needs to know about.
000405 */
000406 static int autoIncBegin(
000407 Parse *pParse, /* Parsing context */
000408 int iDb, /* Index of the database holding pTab */
000409 Table *pTab /* The table we are writing to */
000410 ){
000411 int memId = 0; /* Register holding maximum rowid */
000412 assert( pParse->db->aDb[iDb].pSchema!=0 );
000413 if( (pTab->tabFlags & TF_Autoincrement)!=0
000414 && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
000415 ){
000416 Parse *pToplevel = sqlite3ParseToplevel(pParse);
000417 AutoincInfo *pInfo;
000418 Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
000419
000420 /* Verify that the sqlite_sequence table exists and is an ordinary
000421 ** rowid table with exactly two columns.
000422 ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
000423 if( pSeqTab==0
000424 || !HasRowid(pSeqTab)
000425 || NEVER(IsVirtual(pSeqTab))
000426 || pSeqTab->nCol!=2
000427 ){
000428 pParse->nErr++;
000429 pParse->rc = SQLITE_CORRUPT_SEQUENCE;
000430 return 0;
000431 }
000432
000433 pInfo = pToplevel->pAinc;
000434 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
000435 if( pInfo==0 ){
000436 pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
000437 sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
000438 testcase( pParse->earlyCleanup );
000439 if( pParse->db->mallocFailed ) return 0;
000440 pInfo->pNext = pToplevel->pAinc;
000441 pToplevel->pAinc = pInfo;
000442 pInfo->pTab = pTab;
000443 pInfo->iDb = iDb;
000444 pToplevel->nMem++; /* Register to hold name of table */
000445 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
000446 pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
000447 }
000448 memId = pInfo->regCtr;
000449 }
000450 return memId;
000451 }
000452
000453 /*
000454 ** This routine generates code that will initialize all of the
000455 ** register used by the autoincrement tracker.
000456 */
000457 void sqlite3AutoincrementBegin(Parse *pParse){
000458 AutoincInfo *p; /* Information about an AUTOINCREMENT */
000459 sqlite3 *db = pParse->db; /* The database connection */
000460 Db *pDb; /* Database only autoinc table */
000461 int memId; /* Register holding max rowid */
000462 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
000463
000464 /* This routine is never called during trigger-generation. It is
000465 ** only called from the top-level */
000466 assert( pParse->pTriggerTab==0 );
000467 assert( sqlite3IsToplevel(pParse) );
000468
000469 assert( v ); /* We failed long ago if this is not so */
000470 for(p = pParse->pAinc; p; p = p->pNext){
000471 static const int iLn = VDBE_OFFSET_LINENO(2);
000472 static const VdbeOpList autoInc[] = {
000473 /* 0 */ {OP_Null, 0, 0, 0},
000474 /* 1 */ {OP_Rewind, 0, 10, 0},
000475 /* 2 */ {OP_Column, 0, 0, 0},
000476 /* 3 */ {OP_Ne, 0, 9, 0},
000477 /* 4 */ {OP_Rowid, 0, 0, 0},
000478 /* 5 */ {OP_Column, 0, 1, 0},
000479 /* 6 */ {OP_AddImm, 0, 0, 0},
000480 /* 7 */ {OP_Copy, 0, 0, 0},
000481 /* 8 */ {OP_Goto, 0, 11, 0},
000482 /* 9 */ {OP_Next, 0, 2, 0},
000483 /* 10 */ {OP_Integer, 0, 0, 0},
000484 /* 11 */ {OP_Close, 0, 0, 0}
000485 };
000486 VdbeOp *aOp;
000487 pDb = &db->aDb[p->iDb];
000488 memId = p->regCtr;
000489 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
000490 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
000491 sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
000492 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
000493 if( aOp==0 ) break;
000494 aOp[0].p2 = memId;
000495 aOp[0].p3 = memId+2;
000496 aOp[2].p3 = memId;
000497 aOp[3].p1 = memId-1;
000498 aOp[3].p3 = memId;
000499 aOp[3].p5 = SQLITE_JUMPIFNULL;
000500 aOp[4].p2 = memId+1;
000501 aOp[5].p3 = memId;
000502 aOp[6].p1 = memId;
000503 aOp[7].p2 = memId+2;
000504 aOp[7].p1 = memId;
000505 aOp[10].p2 = memId;
000506 if( pParse->nTab==0 ) pParse->nTab = 1;
000507 }
000508 }
000509
000510 /*
000511 ** Update the maximum rowid for an autoincrement calculation.
000512 **
000513 ** This routine should be called when the regRowid register holds a
000514 ** new rowid that is about to be inserted. If that new rowid is
000515 ** larger than the maximum rowid in the memId memory cell, then the
000516 ** memory cell is updated.
000517 */
000518 static void autoIncStep(Parse *pParse, int memId, int regRowid){
000519 if( memId>0 ){
000520 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
000521 }
000522 }
000523
000524 /*
000525 ** This routine generates the code needed to write autoincrement
000526 ** maximum rowid values back into the sqlite_sequence register.
000527 ** Every statement that might do an INSERT into an autoincrement
000528 ** table (either directly or through triggers) needs to call this
000529 ** routine just before the "exit" code.
000530 */
000531 static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
000532 AutoincInfo *p;
000533 Vdbe *v = pParse->pVdbe;
000534 sqlite3 *db = pParse->db;
000535
000536 assert( v );
000537 for(p = pParse->pAinc; p; p = p->pNext){
000538 static const int iLn = VDBE_OFFSET_LINENO(2);
000539 static const VdbeOpList autoIncEnd[] = {
000540 /* 0 */ {OP_NotNull, 0, 2, 0},
000541 /* 1 */ {OP_NewRowid, 0, 0, 0},
000542 /* 2 */ {OP_MakeRecord, 0, 2, 0},
000543 /* 3 */ {OP_Insert, 0, 0, 0},
000544 /* 4 */ {OP_Close, 0, 0, 0}
000545 };
000546 VdbeOp *aOp;
000547 Db *pDb = &db->aDb[p->iDb];
000548 int iRec;
000549 int memId = p->regCtr;
000550
000551 iRec = sqlite3GetTempReg(pParse);
000552 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
000553 sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
000554 VdbeCoverage(v);
000555 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
000556 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
000557 if( aOp==0 ) break;
000558 aOp[0].p1 = memId+1;
000559 aOp[1].p2 = memId+1;
000560 aOp[2].p1 = memId-1;
000561 aOp[2].p3 = iRec;
000562 aOp[3].p2 = iRec;
000563 aOp[3].p3 = memId+1;
000564 aOp[3].p5 = OPFLAG_APPEND;
000565 sqlite3ReleaseTempReg(pParse, iRec);
000566 }
000567 }
000568 void sqlite3AutoincrementEnd(Parse *pParse){
000569 if( pParse->pAinc ) autoIncrementEnd(pParse);
000570 }
000571 #else
000572 /*
000573 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
000574 ** above are all no-ops
000575 */
000576 # define autoIncBegin(A,B,C) (0)
000577 # define autoIncStep(A,B,C)
000578 #endif /* SQLITE_OMIT_AUTOINCREMENT */
000579
000580 /*
000581 ** If argument pVal is a Select object returned by an sqlite3MultiValues()
000582 ** that was able to use the co-routine optimization, finish coding the
000583 ** co-routine.
000584 */
000585 void sqlite3MultiValuesEnd(Parse *pParse, Select *pVal){
000586 if( ALWAYS(pVal) && pVal->pSrc->nSrc>0 ){
000587 SrcItem *pItem = &pVal->pSrc->a[0];
000588 assert( (pItem->fg.isSubquery && pItem->u4.pSubq!=0) || pParse->nErr );
000589 if( pItem->fg.isSubquery ){
000590 sqlite3VdbeEndCoroutine(pParse->pVdbe, pItem->u4.pSubq->regReturn);
000591 sqlite3VdbeJumpHere(pParse->pVdbe, pItem->u4.pSubq->addrFillSub - 1);
000592 }
000593 }
000594 }
000595
000596 /*
000597 ** Return true if all expressions in the expression-list passed as the
000598 ** only argument are constant.
000599 */
000600 static int exprListIsConstant(Parse *pParse, ExprList *pRow){
000601 int ii;
000602 for(ii=0; ii<pRow->nExpr; ii++){
000603 if( 0==sqlite3ExprIsConstant(pParse, pRow->a[ii].pExpr) ) return 0;
000604 }
000605 return 1;
000606 }
000607
000608 /*
000609 ** Return true if all expressions in the expression-list passed as the
000610 ** only argument are both constant and have no affinity.
000611 */
000612 static int exprListIsNoAffinity(Parse *pParse, ExprList *pRow){
000613 int ii;
000614 if( exprListIsConstant(pParse,pRow)==0 ) return 0;
000615 for(ii=0; ii<pRow->nExpr; ii++){
000616 Expr *pExpr = pRow->a[ii].pExpr;
000617 assert( pExpr->op!=TK_RAISE );
000618 assert( pExpr->affExpr==0 );
000619 if( 0!=sqlite3ExprAffinity(pExpr) ) return 0;
000620 }
000621 return 1;
000622
000623 }
000624
000625 /*
000626 ** This function is called by the parser for the second and subsequent
000627 ** rows of a multi-row VALUES clause. Argument pLeft is the part of
000628 ** the VALUES clause already parsed, argument pRow is the vector of values
000629 ** for the new row. The Select object returned represents the complete
000630 ** VALUES clause, including the new row.
000631 **
000632 ** There are two ways in which this may be achieved - by incremental
000633 ** coding of a co-routine (the "co-routine" method) or by returning a
000634 ** Select object equivalent to the following (the "UNION ALL" method):
000635 **
000636 ** "pLeft UNION ALL SELECT pRow"
000637 **
000638 ** If the VALUES clause contains a lot of rows, this compound Select
000639 ** object may consume a lot of memory.
000640 **
000641 ** When the co-routine method is used, each row that will be returned
000642 ** by the VALUES clause is coded into part of a co-routine as it is
000643 ** passed to this function. The returned Select object is equivalent to:
000644 **
000645 ** SELECT * FROM (
000646 ** Select object to read co-routine
000647 ** )
000648 **
000649 ** The co-routine method is used in most cases. Exceptions are:
000650 **
000651 ** a) If the current statement has a WITH clause. This is to avoid
000652 ** statements like:
000653 **
000654 ** WITH cte AS ( VALUES('x'), ('y') ... )
000655 ** SELECT * FROM cte AS a, cte AS b;
000656 **
000657 ** This will not work, as the co-routine uses a hard-coded register
000658 ** for its OP_Yield instructions, and so it is not possible for two
000659 ** cursors to iterate through it concurrently.
000660 **
000661 ** b) The schema is currently being parsed (i.e. the VALUES clause is part
000662 ** of a schema item like a VIEW or TRIGGER). In this case there is no VM
000663 ** being generated when parsing is taking place, and so generating
000664 ** a co-routine is not possible.
000665 **
000666 ** c) There are non-constant expressions in the VALUES clause (e.g.
000667 ** the VALUES clause is part of a correlated sub-query).
000668 **
000669 ** d) One or more of the values in the first row of the VALUES clause
000670 ** has an affinity (i.e. is a CAST expression). This causes problems
000671 ** because the complex rules SQLite uses (see function
000672 ** sqlite3SubqueryColumnTypes() in select.c) to determine the effective
000673 ** affinity of such a column for all rows require access to all values in
000674 ** the column simultaneously.
000675 */
000676 Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow){
000677
000678 if( pParse->bHasWith /* condition (a) above */
000679 || pParse->db->init.busy /* condition (b) above */
000680 || exprListIsConstant(pParse,pRow)==0 /* condition (c) above */
000681 || (pLeft->pSrc->nSrc==0 &&
000682 exprListIsNoAffinity(pParse,pLeft->pEList)==0) /* condition (d) above */
000683 || IN_SPECIAL_PARSE
000684 ){
000685 /* The co-routine method cannot be used. Fall back to UNION ALL. */
000686 Select *pSelect = 0;
000687 int f = SF_Values | SF_MultiValue;
000688 if( pLeft->pSrc->nSrc ){
000689 sqlite3MultiValuesEnd(pParse, pLeft);
000690 f = SF_Values;
000691 }else if( pLeft->pPrior ){
000692 /* In this case set the SF_MultiValue flag only if it was set on pLeft */
000693 f = (f & pLeft->selFlags);
000694 }
000695 pSelect = sqlite3SelectNew(pParse, pRow, 0, 0, 0, 0, 0, f, 0);
000696 pLeft->selFlags &= ~SF_MultiValue;
000697 if( pSelect ){
000698 pSelect->op = TK_ALL;
000699 pSelect->pPrior = pLeft;
000700 pLeft = pSelect;
000701 }
000702 }else{
000703 SrcItem *p = 0; /* SrcItem that reads from co-routine */
000704
000705 if( pLeft->pSrc->nSrc==0 ){
000706 /* Co-routine has not yet been started and the special Select object
000707 ** that accesses the co-routine has not yet been created. This block
000708 ** does both those things. */
000709 Vdbe *v = sqlite3GetVdbe(pParse);
000710 Select *pRet = sqlite3SelectNew(pParse, 0, 0, 0, 0, 0, 0, 0, 0);
000711
000712 /* Ensure the database schema has been read. This is to ensure we have
000713 ** the correct text encoding. */
000714 if( (pParse->db->mDbFlags & DBFLAG_SchemaKnownOk)==0 ){
000715 sqlite3ReadSchema(pParse);
000716 }
000717
000718 if( pRet ){
000719 SelectDest dest;
000720 Subquery *pSubq;
000721 pRet->pSrc->nSrc = 1;
000722 pRet->pPrior = pLeft->pPrior;
000723 pRet->op = pLeft->op;
000724 if( pRet->pPrior ) pRet->selFlags |= SF_Values;
000725 pLeft->pPrior = 0;
000726 pLeft->op = TK_SELECT;
000727 assert( pLeft->pNext==0 );
000728 assert( pRet->pNext==0 );
000729 p = &pRet->pSrc->a[0];
000730 p->fg.viaCoroutine = 1;
000731 p->iCursor = -1;
000732 assert( !p->fg.isIndexedBy && !p->fg.isTabFunc );
000733 p->u1.nRow = 2;
000734 if( sqlite3SrcItemAttachSubquery(pParse, p, pLeft, 0) ){
000735 pSubq = p->u4.pSubq;
000736 pSubq->addrFillSub = sqlite3VdbeCurrentAddr(v) + 1;
000737 pSubq->regReturn = ++pParse->nMem;
000738 sqlite3VdbeAddOp3(v, OP_InitCoroutine,
000739 pSubq->regReturn, 0, pSubq->addrFillSub);
000740 sqlite3SelectDestInit(&dest, SRT_Coroutine, pSubq->regReturn);
000741
000742 /* Allocate registers for the output of the co-routine. Do so so
000743 ** that there are two unused registers immediately before those
000744 ** used by the co-routine. This allows the code in sqlite3Insert()
000745 ** to use these registers directly, instead of copying the output
000746 ** of the co-routine to a separate array for processing. */
000747 dest.iSdst = pParse->nMem + 3;
000748 dest.nSdst = pLeft->pEList->nExpr;
000749 pParse->nMem += 2 + dest.nSdst;
000750
000751 pLeft->selFlags |= SF_MultiValue;
000752 sqlite3Select(pParse, pLeft, &dest);
000753 pSubq->regResult = dest.iSdst;
000754 assert( pParse->nErr || dest.iSdst>0 );
000755 }
000756 pLeft = pRet;
000757 }
000758 }else{
000759 p = &pLeft->pSrc->a[0];
000760 assert( !p->fg.isTabFunc && !p->fg.isIndexedBy );
000761 p->u1.nRow++;
000762 }
000763
000764 if( pParse->nErr==0 ){
000765 Subquery *pSubq;
000766 assert( p!=0 );
000767 assert( p->fg.isSubquery );
000768 pSubq = p->u4.pSubq;
000769 assert( pSubq!=0 );
000770 assert( pSubq->pSelect!=0 );
000771 assert( pSubq->pSelect->pEList!=0 );
000772 if( pSubq->pSelect->pEList->nExpr!=pRow->nExpr ){
000773 sqlite3SelectWrongNumTermsError(pParse, pSubq->pSelect);
000774 }else{
000775 sqlite3ExprCodeExprList(pParse, pRow, pSubq->regResult, 0, 0);
000776 sqlite3VdbeAddOp1(pParse->pVdbe, OP_Yield, pSubq->regReturn);
000777 }
000778 }
000779 sqlite3ExprListDelete(pParse->db, pRow);
000780 }
000781
000782 return pLeft;
000783 }
000784
000785 /* Forward declaration */
000786 static int xferOptimization(
000787 Parse *pParse, /* Parser context */
000788 Table *pDest, /* The table we are inserting into */
000789 Select *pSelect, /* A SELECT statement to use as the data source */
000790 int onError, /* How to handle constraint errors */
000791 int iDbDest /* The database of pDest */
000792 );
000793
000794 /*
000795 ** This routine is called to handle SQL of the following forms:
000796 **
000797 ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
000798 ** insert into TABLE (IDLIST) select
000799 ** insert into TABLE (IDLIST) default values
000800 **
000801 ** The IDLIST following the table name is always optional. If omitted,
000802 ** then a list of all (non-hidden) columns for the table is substituted.
000803 ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
000804 ** is omitted.
000805 **
000806 ** For the pSelect parameter holds the values to be inserted for the
000807 ** first two forms shown above. A VALUES clause is really just short-hand
000808 ** for a SELECT statement that omits the FROM clause and everything else
000809 ** that follows. If the pSelect parameter is NULL, that means that the
000810 ** DEFAULT VALUES form of the INSERT statement is intended.
000811 **
000812 ** The code generated follows one of four templates. For a simple
000813 ** insert with data coming from a single-row VALUES clause, the code executes
000814 ** once straight down through. Pseudo-code follows (we call this
000815 ** the "1st template"):
000816 **
000817 ** open write cursor to <table> and its indices
000818 ** put VALUES clause expressions into registers
000819 ** write the resulting record into <table>
000820 ** cleanup
000821 **
000822 ** The three remaining templates assume the statement is of the form
000823 **
000824 ** INSERT INTO <table> SELECT ...
000825 **
000826 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
000827 ** in other words if the SELECT pulls all columns from a single table
000828 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
000829 ** if <table2> and <table1> are distinct tables but have identical
000830 ** schemas, including all the same indices, then a special optimization
000831 ** is invoked that copies raw records from <table2> over to <table1>.
000832 ** See the xferOptimization() function for the implementation of this
000833 ** template. This is the 2nd template.
000834 **
000835 ** open a write cursor to <table>
000836 ** open read cursor on <table2>
000837 ** transfer all records in <table2> over to <table>
000838 ** close cursors
000839 ** foreach index on <table>
000840 ** open a write cursor on the <table> index
000841 ** open a read cursor on the corresponding <table2> index
000842 ** transfer all records from the read to the write cursors
000843 ** close cursors
000844 ** end foreach
000845 **
000846 ** The 3rd template is for when the second template does not apply
000847 ** and the SELECT clause does not read from <table> at any time.
000848 ** The generated code follows this template:
000849 **
000850 ** X <- A
000851 ** goto B
000852 ** A: setup for the SELECT
000853 ** loop over the rows in the SELECT
000854 ** load values into registers R..R+n
000855 ** yield X
000856 ** end loop
000857 ** cleanup after the SELECT
000858 ** end-coroutine X
000859 ** B: open write cursor to <table> and its indices
000860 ** C: yield X, at EOF goto D
000861 ** insert the select result into <table> from R..R+n
000862 ** goto C
000863 ** D: cleanup
000864 **
000865 ** The 4th template is used if the insert statement takes its
000866 ** values from a SELECT but the data is being inserted into a table
000867 ** that is also read as part of the SELECT. In the third form,
000868 ** we have to use an intermediate table to store the results of
000869 ** the select. The template is like this:
000870 **
000871 ** X <- A
000872 ** goto B
000873 ** A: setup for the SELECT
000874 ** loop over the tables in the SELECT
000875 ** load value into register R..R+n
000876 ** yield X
000877 ** end loop
000878 ** cleanup after the SELECT
000879 ** end co-routine R
000880 ** B: open temp table
000881 ** L: yield X, at EOF goto M
000882 ** insert row from R..R+n into temp table
000883 ** goto L
000884 ** M: open write cursor to <table> and its indices
000885 ** rewind temp table
000886 ** C: loop over rows of intermediate table
000887 ** transfer values form intermediate table into <table>
000888 ** end loop
000889 ** D: cleanup
000890 */
000891 void sqlite3Insert(
000892 Parse *pParse, /* Parser context */
000893 SrcList *pTabList, /* Name of table into which we are inserting */
000894 Select *pSelect, /* A SELECT statement to use as the data source */
000895 IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */
000896 int onError, /* How to handle constraint errors */
000897 Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
000898 ){
000899 sqlite3 *db; /* The main database structure */
000900 Table *pTab; /* The table to insert into. aka TABLE */
000901 int i, j; /* Loop counters */
000902 Vdbe *v; /* Generate code into this virtual machine */
000903 Index *pIdx; /* For looping over indices of the table */
000904 int nColumn; /* Number of columns in the data */
000905 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
000906 int iDataCur = 0; /* VDBE cursor that is the main data repository */
000907 int iIdxCur = 0; /* First index cursor */
000908 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
000909 int endOfLoop; /* Label for the end of the insertion loop */
000910 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
000911 int addrInsTop = 0; /* Jump to label "D" */
000912 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
000913 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
000914 int iDb; /* Index of database holding TABLE */
000915 u8 useTempTable = 0; /* Store SELECT results in intermediate table */
000916 u8 appendFlag = 0; /* True if the insert is likely to be an append */
000917 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
000918 u8 bIdListInOrder; /* True if IDLIST is in table order */
000919 ExprList *pList = 0; /* List of VALUES() to be inserted */
000920 int iRegStore; /* Register in which to store next column */
000921
000922 /* Register allocations */
000923 int regFromSelect = 0;/* Base register for data coming from SELECT */
000924 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
000925 int regRowCount = 0; /* Memory cell used for the row counter */
000926 int regIns; /* Block of regs holding rowid+data being inserted */
000927 int regRowid; /* registers holding insert rowid */
000928 int regData; /* register holding first column to insert */
000929 int *aRegIdx = 0; /* One register allocated to each index */
000930 int *aTabColMap = 0; /* Mapping from pTab columns to pCol entries */
000931
000932 #ifndef SQLITE_OMIT_TRIGGER
000933 int isView; /* True if attempting to insert into a view */
000934 Trigger *pTrigger; /* List of triggers on pTab, if required */
000935 int tmask; /* Mask of trigger times */
000936 #endif
000937
000938 db = pParse->db;
000939 assert( db->pParse==pParse );
000940 if( pParse->nErr ){
000941 goto insert_cleanup;
000942 }
000943 assert( db->mallocFailed==0 );
000944 dest.iSDParm = 0; /* Suppress a harmless compiler warning */
000945
000946 /* If the Select object is really just a simple VALUES() list with a
000947 ** single row (the common case) then keep that one row of values
000948 ** and discard the other (unused) parts of the pSelect object
000949 */
000950 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
000951 pList = pSelect->pEList;
000952 pSelect->pEList = 0;
000953 sqlite3SelectDelete(db, pSelect);
000954 pSelect = 0;
000955 }
000956
000957 /* Locate the table into which we will be inserting new information.
000958 */
000959 assert( pTabList->nSrc==1 );
000960 pTab = sqlite3SrcListLookup(pParse, pTabList);
000961 if( pTab==0 ){
000962 goto insert_cleanup;
000963 }
000964 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
000965 assert( iDb<db->nDb );
000966 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
000967 db->aDb[iDb].zDbSName) ){
000968 goto insert_cleanup;
000969 }
000970 withoutRowid = !HasRowid(pTab);
000971
000972 /* Figure out if we have any triggers and if the table being
000973 ** inserted into is a view
000974 */
000975 #ifndef SQLITE_OMIT_TRIGGER
000976 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
000977 isView = IsView(pTab);
000978 #else
000979 # define pTrigger 0
000980 # define tmask 0
000981 # define isView 0
000982 #endif
000983 #ifdef SQLITE_OMIT_VIEW
000984 # undef isView
000985 # define isView 0
000986 #endif
000987 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
000988
000989 #if TREETRACE_ENABLED
000990 if( sqlite3TreeTrace & 0x10000 ){
000991 sqlite3TreeViewLine(0, "In sqlite3Insert() at %s:%d", __FILE__, __LINE__);
000992 sqlite3TreeViewInsert(pParse->pWith, pTabList, pColumn, pSelect, pList,
000993 onError, pUpsert, pTrigger);
000994 }
000995 #endif
000996
000997 /* If pTab is really a view, make sure it has been initialized.
000998 ** ViewGetColumnNames() is a no-op if pTab is not a view.
000999 */
001000 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
001001 goto insert_cleanup;
001002 }
001003
001004 /* Cannot insert into a read-only table.
001005 */
001006 if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
001007 goto insert_cleanup;
001008 }
001009
001010 /* Allocate a VDBE
001011 */
001012 v = sqlite3GetVdbe(pParse);
001013 if( v==0 ) goto insert_cleanup;
001014 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
001015 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
001016
001017 #ifndef SQLITE_OMIT_XFER_OPT
001018 /* If the statement is of the form
001019 **
001020 ** INSERT INTO <table1> SELECT * FROM <table2>;
001021 **
001022 ** Then special optimizations can be applied that make the transfer
001023 ** very fast and which reduce fragmentation of indices.
001024 **
001025 ** This is the 2nd template.
001026 */
001027 if( pColumn==0
001028 && pSelect!=0
001029 && pTrigger==0
001030 && xferOptimization(pParse, pTab, pSelect, onError, iDb)
001031 ){
001032 assert( !pTrigger );
001033 assert( pList==0 );
001034 goto insert_end;
001035 }
001036 #endif /* SQLITE_OMIT_XFER_OPT */
001037
001038 /* If this is an AUTOINCREMENT table, look up the sequence number in the
001039 ** sqlite_sequence table and store it in memory cell regAutoinc.
001040 */
001041 regAutoinc = autoIncBegin(pParse, iDb, pTab);
001042
001043 /* Allocate a block registers to hold the rowid and the values
001044 ** for all columns of the new row.
001045 */
001046 regRowid = regIns = pParse->nMem+1;
001047 pParse->nMem += pTab->nCol + 1;
001048 if( IsVirtual(pTab) ){
001049 regRowid++;
001050 pParse->nMem++;
001051 }
001052 regData = regRowid+1;
001053
001054 /* If the INSERT statement included an IDLIST term, then make sure
001055 ** all elements of the IDLIST really are columns of the table and
001056 ** remember the column indices.
001057 **
001058 ** If the table has an INTEGER PRIMARY KEY column and that column
001059 ** is named in the IDLIST, then record in the ipkColumn variable
001060 ** the index into IDLIST of the primary key column. ipkColumn is
001061 ** the index of the primary key as it appears in IDLIST, not as
001062 ** is appears in the original table. (The index of the INTEGER
001063 ** PRIMARY KEY in the original table is pTab->iPKey.) After this
001064 ** loop, if ipkColumn==(-1), that means that integer primary key
001065 ** is unspecified, and hence the table is either WITHOUT ROWID or
001066 ** it will automatically generated an integer primary key.
001067 **
001068 ** bIdListInOrder is true if the columns in IDLIST are in storage
001069 ** order. This enables an optimization that avoids shuffling the
001070 ** columns into storage order. False negatives are harmless,
001071 ** but false positives will cause database corruption.
001072 */
001073 bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
001074 if( pColumn ){
001075 aTabColMap = sqlite3DbMallocZero(db, pTab->nCol*sizeof(int));
001076 if( aTabColMap==0 ) goto insert_cleanup;
001077 for(i=0; i<pColumn->nId; i++){
001078 const char *zCName = pColumn->a[i].zName;
001079 u8 hName = sqlite3StrIHash(zCName);
001080 for(j=0; j<pTab->nCol; j++){
001081 if( pTab->aCol[j].hName!=hName ) continue;
001082 if( sqlite3StrICmp(zCName, pTab->aCol[j].zCnName)==0 ){
001083 if( aTabColMap[j]==0 ) aTabColMap[j] = i+1;
001084 if( i!=j ) bIdListInOrder = 0;
001085 if( j==pTab->iPKey ){
001086 ipkColumn = i; assert( !withoutRowid );
001087 }
001088 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001089 if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
001090 sqlite3ErrorMsg(pParse,
001091 "cannot INSERT into generated column \"%s\"",
001092 pTab->aCol[j].zCnName);
001093 goto insert_cleanup;
001094 }
001095 #endif
001096 break;
001097 }
001098 }
001099 if( j>=pTab->nCol ){
001100 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
001101 ipkColumn = i;
001102 bIdListInOrder = 0;
001103 }else{
001104 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
001105 pTabList->a, pColumn->a[i].zName);
001106 pParse->checkSchema = 1;
001107 goto insert_cleanup;
001108 }
001109 }
001110 }
001111 }
001112
001113 /* Figure out how many columns of data are supplied. If the data
001114 ** is coming from a SELECT statement, then generate a co-routine that
001115 ** produces a single row of the SELECT on each invocation. The
001116 ** co-routine is the common header to the 3rd and 4th templates.
001117 */
001118 if( pSelect ){
001119 /* Data is coming from a SELECT or from a multi-row VALUES clause.
001120 ** Generate a co-routine to run the SELECT. */
001121 int rc; /* Result code */
001122
001123 if( pSelect->pSrc->nSrc==1
001124 && pSelect->pSrc->a[0].fg.viaCoroutine
001125 && pSelect->pPrior==0
001126 ){
001127 SrcItem *pItem = &pSelect->pSrc->a[0];
001128 Subquery *pSubq;
001129 assert( pItem->fg.isSubquery );
001130 pSubq = pItem->u4.pSubq;
001131 dest.iSDParm = pSubq->regReturn;
001132 regFromSelect = pSubq->regResult;
001133 assert( pSubq->pSelect!=0 );
001134 assert( pSubq->pSelect->pEList!=0 );
001135 nColumn = pSubq->pSelect->pEList->nExpr;
001136 ExplainQueryPlan((pParse, 0, "SCAN %S", pItem));
001137 if( bIdListInOrder && nColumn==pTab->nCol ){
001138 regData = regFromSelect;
001139 regRowid = regData - 1;
001140 regIns = regRowid - (IsVirtual(pTab) ? 1 : 0);
001141 }
001142 }else{
001143 int addrTop; /* Top of the co-routine */
001144 int regYield = ++pParse->nMem;
001145 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
001146 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
001147 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
001148 dest.iSdst = bIdListInOrder ? regData : 0;
001149 dest.nSdst = pTab->nCol;
001150 rc = sqlite3Select(pParse, pSelect, &dest);
001151 regFromSelect = dest.iSdst;
001152 assert( db->pParse==pParse );
001153 if( rc || pParse->nErr ) goto insert_cleanup;
001154 assert( db->mallocFailed==0 );
001155 sqlite3VdbeEndCoroutine(v, regYield);
001156 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
001157 assert( pSelect->pEList );
001158 nColumn = pSelect->pEList->nExpr;
001159 }
001160
001161 /* Set useTempTable to TRUE if the result of the SELECT statement
001162 ** should be written into a temporary table (template 4). Set to
001163 ** FALSE if each output row of the SELECT can be written directly into
001164 ** the destination table (template 3).
001165 **
001166 ** A temp table must be used if the table being updated is also one
001167 ** of the tables being read by the SELECT statement. Also use a
001168 ** temp table in the case of row triggers.
001169 */
001170 if( pTrigger || readsTable(pParse, iDb, pTab) ){
001171 useTempTable = 1;
001172 }
001173
001174 if( useTempTable ){
001175 /* Invoke the coroutine to extract information from the SELECT
001176 ** and add it to a transient table srcTab. The code generated
001177 ** here is from the 4th template:
001178 **
001179 ** B: open temp table
001180 ** L: yield X, goto M at EOF
001181 ** insert row from R..R+n into temp table
001182 ** goto L
001183 ** M: ...
001184 */
001185 int regRec; /* Register to hold packed record */
001186 int regTempRowid; /* Register to hold temp table ROWID */
001187 int addrL; /* Label "L" */
001188
001189 srcTab = pParse->nTab++;
001190 regRec = sqlite3GetTempReg(pParse);
001191 regTempRowid = sqlite3GetTempReg(pParse);
001192 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
001193 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
001194 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
001195 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
001196 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
001197 sqlite3VdbeGoto(v, addrL);
001198 sqlite3VdbeJumpHere(v, addrL);
001199 sqlite3ReleaseTempReg(pParse, regRec);
001200 sqlite3ReleaseTempReg(pParse, regTempRowid);
001201 }
001202 }else{
001203 /* This is the case if the data for the INSERT is coming from a
001204 ** single-row VALUES clause
001205 */
001206 NameContext sNC;
001207 memset(&sNC, 0, sizeof(sNC));
001208 sNC.pParse = pParse;
001209 srcTab = -1;
001210 assert( useTempTable==0 );
001211 if( pList ){
001212 nColumn = pList->nExpr;
001213 if( sqlite3ResolveExprListNames(&sNC, pList) ){
001214 goto insert_cleanup;
001215 }
001216 }else{
001217 nColumn = 0;
001218 }
001219 }
001220
001221 /* If there is no IDLIST term but the table has an integer primary
001222 ** key, the set the ipkColumn variable to the integer primary key
001223 ** column index in the original table definition.
001224 */
001225 if( pColumn==0 && nColumn>0 ){
001226 ipkColumn = pTab->iPKey;
001227 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001228 if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
001229 testcase( pTab->tabFlags & TF_HasVirtual );
001230 testcase( pTab->tabFlags & TF_HasStored );
001231 for(i=ipkColumn-1; i>=0; i--){
001232 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
001233 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
001234 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
001235 ipkColumn--;
001236 }
001237 }
001238 }
001239 #endif
001240
001241 /* Make sure the number of columns in the source data matches the number
001242 ** of columns to be inserted into the table.
001243 */
001244 assert( TF_HasHidden==COLFLAG_HIDDEN );
001245 assert( TF_HasGenerated==COLFLAG_GENERATED );
001246 assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) );
001247 if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
001248 for(i=0; i<pTab->nCol; i++){
001249 if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
001250 }
001251 }
001252 if( nColumn!=(pTab->nCol-nHidden) ){
001253 sqlite3ErrorMsg(pParse,
001254 "table %S has %d columns but %d values were supplied",
001255 pTabList->a, pTab->nCol-nHidden, nColumn);
001256 goto insert_cleanup;
001257 }
001258 }
001259 if( pColumn!=0 && nColumn!=pColumn->nId ){
001260 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
001261 goto insert_cleanup;
001262 }
001263
001264 /* Initialize the count of rows to be inserted
001265 */
001266 if( (db->flags & SQLITE_CountRows)!=0
001267 && !pParse->nested
001268 && !pParse->pTriggerTab
001269 && !pParse->bReturning
001270 ){
001271 regRowCount = ++pParse->nMem;
001272 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
001273 }
001274
001275 /* If this is not a view, open the table and and all indices */
001276 if( !isView ){
001277 int nIdx;
001278 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
001279 &iDataCur, &iIdxCur);
001280 aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
001281 if( aRegIdx==0 ){
001282 goto insert_cleanup;
001283 }
001284 for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
001285 assert( pIdx );
001286 aRegIdx[i] = ++pParse->nMem;
001287 pParse->nMem += pIdx->nColumn;
001288 }
001289 aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */
001290 }
001291 #ifndef SQLITE_OMIT_UPSERT
001292 if( pUpsert ){
001293 Upsert *pNx;
001294 if( IsVirtual(pTab) ){
001295 sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
001296 pTab->zName);
001297 goto insert_cleanup;
001298 }
001299 if( IsView(pTab) ){
001300 sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
001301 goto insert_cleanup;
001302 }
001303 if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
001304 goto insert_cleanup;
001305 }
001306 pTabList->a[0].iCursor = iDataCur;
001307 pNx = pUpsert;
001308 do{
001309 pNx->pUpsertSrc = pTabList;
001310 pNx->regData = regData;
001311 pNx->iDataCur = iDataCur;
001312 pNx->iIdxCur = iIdxCur;
001313 if( pNx->pUpsertTarget ){
001314 if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx, pUpsert) ){
001315 goto insert_cleanup;
001316 }
001317 }
001318 pNx = pNx->pNextUpsert;
001319 }while( pNx!=0 );
001320 }
001321 #endif
001322
001323
001324 /* This is the top of the main insertion loop */
001325 if( useTempTable ){
001326 /* This block codes the top of loop only. The complete loop is the
001327 ** following pseudocode (template 4):
001328 **
001329 ** rewind temp table, if empty goto D
001330 ** C: loop over rows of intermediate table
001331 ** transfer values form intermediate table into <table>
001332 ** end loop
001333 ** D: ...
001334 */
001335 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
001336 addrCont = sqlite3VdbeCurrentAddr(v);
001337 }else if( pSelect ){
001338 /* This block codes the top of loop only. The complete loop is the
001339 ** following pseudocode (template 3):
001340 **
001341 ** C: yield X, at EOF goto D
001342 ** insert the select result into <table> from R..R+n
001343 ** goto C
001344 ** D: ...
001345 */
001346 sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
001347 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
001348 VdbeCoverage(v);
001349 if( ipkColumn>=0 ){
001350 /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
001351 ** SELECT, go ahead and copy the value into the rowid slot now, so that
001352 ** the value does not get overwritten by a NULL at tag-20191021-002. */
001353 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
001354 }
001355 }
001356
001357 /* Compute data for ordinary columns of the new entry. Values
001358 ** are written in storage order into registers starting with regData.
001359 ** Only ordinary columns are computed in this loop. The rowid
001360 ** (if there is one) is computed later and generated columns are
001361 ** computed after the rowid since they might depend on the value
001362 ** of the rowid.
001363 */
001364 nHidden = 0;
001365 iRegStore = regData; assert( regData==regRowid+1 );
001366 for(i=0; i<pTab->nCol; i++, iRegStore++){
001367 int k;
001368 u32 colFlags;
001369 assert( i>=nHidden );
001370 if( i==pTab->iPKey ){
001371 /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
001372 ** using the rowid. So put a NULL in the IPK slot of the record to avoid
001373 ** using excess space. The file format definition requires this extra
001374 ** NULL - we cannot optimize further by skipping the column completely */
001375 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
001376 continue;
001377 }
001378 if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
001379 nHidden++;
001380 if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
001381 /* Virtual columns do not participate in OP_MakeRecord. So back up
001382 ** iRegStore by one slot to compensate for the iRegStore++ in the
001383 ** outer for() loop */
001384 iRegStore--;
001385 continue;
001386 }else if( (colFlags & COLFLAG_STORED)!=0 ){
001387 /* Stored columns are computed later. But if there are BEFORE
001388 ** triggers, the slots used for stored columns will be OP_Copy-ed
001389 ** to a second block of registers, so the register needs to be
001390 ** initialized to NULL to avoid an uninitialized register read */
001391 if( tmask & TRIGGER_BEFORE ){
001392 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
001393 }
001394 continue;
001395 }else if( pColumn==0 ){
001396 /* Hidden columns that are not explicitly named in the INSERT
001397 ** get there default value */
001398 sqlite3ExprCodeFactorable(pParse,
001399 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
001400 iRegStore);
001401 continue;
001402 }
001403 }
001404 if( pColumn ){
001405 j = aTabColMap[i];
001406 assert( j>=0 && j<=pColumn->nId );
001407 if( j==0 ){
001408 /* A column not named in the insert column list gets its
001409 ** default value */
001410 sqlite3ExprCodeFactorable(pParse,
001411 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
001412 iRegStore);
001413 continue;
001414 }
001415 k = j - 1;
001416 }else if( nColumn==0 ){
001417 /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */
001418 sqlite3ExprCodeFactorable(pParse,
001419 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
001420 iRegStore);
001421 continue;
001422 }else{
001423 k = i - nHidden;
001424 }
001425
001426 if( useTempTable ){
001427 sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
001428 }else if( pSelect ){
001429 if( regFromSelect!=regData ){
001430 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
001431 }
001432 }else{
001433 Expr *pX = pList->a[k].pExpr;
001434 int y = sqlite3ExprCodeTarget(pParse, pX, iRegStore);
001435 if( y!=iRegStore ){
001436 sqlite3VdbeAddOp2(v,
001437 ExprHasProperty(pX, EP_Subquery) ? OP_Copy : OP_SCopy, y, iRegStore);
001438 }
001439 }
001440 }
001441
001442
001443 /* Run the BEFORE and INSTEAD OF triggers, if there are any
001444 */
001445 endOfLoop = sqlite3VdbeMakeLabel(pParse);
001446 if( tmask & TRIGGER_BEFORE ){
001447 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
001448
001449 /* build the NEW.* reference row. Note that if there is an INTEGER
001450 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
001451 ** translated into a unique ID for the row. But on a BEFORE trigger,
001452 ** we do not know what the unique ID will be (because the insert has
001453 ** not happened yet) so we substitute a rowid of -1
001454 */
001455 if( ipkColumn<0 ){
001456 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
001457 }else{
001458 int addr1;
001459 assert( !withoutRowid );
001460 if( useTempTable ){
001461 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
001462 }else{
001463 assert( pSelect==0 ); /* Otherwise useTempTable is true */
001464 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
001465 }
001466 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
001467 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
001468 sqlite3VdbeJumpHere(v, addr1);
001469 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
001470 }
001471
001472 /* Copy the new data already generated. */
001473 assert( pTab->nNVCol>0 || pParse->nErr>0 );
001474 sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
001475
001476 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001477 /* Compute the new value for generated columns after all other
001478 ** columns have already been computed. This must be done after
001479 ** computing the ROWID in case one of the generated columns
001480 ** refers to the ROWID. */
001481 if( pTab->tabFlags & TF_HasGenerated ){
001482 testcase( pTab->tabFlags & TF_HasVirtual );
001483 testcase( pTab->tabFlags & TF_HasStored );
001484 sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
001485 }
001486 #endif
001487
001488 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
001489 ** do not attempt any conversions before assembling the record.
001490 ** If this is a real table, attempt conversions as required by the
001491 ** table column affinities.
001492 */
001493 if( !isView ){
001494 sqlite3TableAffinity(v, pTab, regCols+1);
001495 }
001496
001497 /* Fire BEFORE or INSTEAD OF triggers */
001498 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
001499 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
001500
001501 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
001502 }
001503
001504 if( !isView ){
001505 if( IsVirtual(pTab) ){
001506 /* The row that the VUpdate opcode will delete: none */
001507 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
001508 }
001509 if( ipkColumn>=0 ){
001510 /* Compute the new rowid */
001511 if( useTempTable ){
001512 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
001513 }else if( pSelect ){
001514 /* Rowid already initialized at tag-20191021-001 */
001515 }else{
001516 Expr *pIpk = pList->a[ipkColumn].pExpr;
001517 if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
001518 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
001519 appendFlag = 1;
001520 }else{
001521 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
001522 }
001523 }
001524 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
001525 ** to generate a unique primary key value.
001526 */
001527 if( !appendFlag ){
001528 int addr1;
001529 if( !IsVirtual(pTab) ){
001530 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
001531 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
001532 sqlite3VdbeJumpHere(v, addr1);
001533 }else{
001534 addr1 = sqlite3VdbeCurrentAddr(v);
001535 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
001536 }
001537 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
001538 }
001539 }else if( IsVirtual(pTab) || withoutRowid ){
001540 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
001541 }else{
001542 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
001543 appendFlag = 1;
001544 }
001545 autoIncStep(pParse, regAutoinc, regRowid);
001546
001547 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
001548 /* Compute the new value for generated columns after all other
001549 ** columns have already been computed. This must be done after
001550 ** computing the ROWID in case one of the generated columns
001551 ** is derived from the INTEGER PRIMARY KEY. */
001552 if( pTab->tabFlags & TF_HasGenerated ){
001553 sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
001554 }
001555 #endif
001556
001557 /* Generate code to check constraints and generate index keys and
001558 ** do the insertion.
001559 */
001560 #ifndef SQLITE_OMIT_VIRTUALTABLE
001561 if( IsVirtual(pTab) ){
001562 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
001563 sqlite3VtabMakeWritable(pParse, pTab);
001564 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
001565 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
001566 sqlite3MayAbort(pParse);
001567 }else
001568 #endif
001569 {
001570 int isReplace = 0;/* Set to true if constraints may cause a replace */
001571 int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
001572 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
001573 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
001574 );
001575 if( db->flags & SQLITE_ForeignKeys ){
001576 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
001577 }
001578
001579 /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
001580 ** constraints or (b) there are no triggers and this table is not a
001581 ** parent table in a foreign key constraint. It is safe to set the
001582 ** flag in the second case as if any REPLACE constraint is hit, an
001583 ** OP_Delete or OP_IdxDelete instruction will be executed on each
001584 ** cursor that is disturbed. And these instructions both clear the
001585 ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
001586 ** functionality. */
001587 bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
001588 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
001589 regIns, aRegIdx, 0, appendFlag, bUseSeek
001590 );
001591 }
001592 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
001593 }else if( pParse->bReturning ){
001594 /* If there is a RETURNING clause, populate the rowid register with
001595 ** constant value -1, in case one or more of the returned expressions
001596 ** refer to the "rowid" of the view. */
001597 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
001598 #endif
001599 }
001600
001601 /* Update the count of rows that are inserted
001602 */
001603 if( regRowCount ){
001604 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
001605 }
001606
001607 if( pTrigger ){
001608 /* Code AFTER triggers */
001609 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
001610 pTab, regData-2-pTab->nCol, onError, endOfLoop);
001611 }
001612
001613 /* The bottom of the main insertion loop, if the data source
001614 ** is a SELECT statement.
001615 */
001616 sqlite3VdbeResolveLabel(v, endOfLoop);
001617 if( useTempTable ){
001618 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
001619 sqlite3VdbeJumpHere(v, addrInsTop);
001620 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
001621 }else if( pSelect ){
001622 sqlite3VdbeGoto(v, addrCont);
001623 #ifdef SQLITE_DEBUG
001624 /* If we are jumping back to an OP_Yield that is preceded by an
001625 ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
001626 ** OP_ReleaseReg will be included in the loop. */
001627 if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
001628 assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
001629 sqlite3VdbeChangeP5(v, 1);
001630 }
001631 #endif
001632 sqlite3VdbeJumpHere(v, addrInsTop);
001633 }
001634
001635 #ifndef SQLITE_OMIT_XFER_OPT
001636 insert_end:
001637 #endif /* SQLITE_OMIT_XFER_OPT */
001638 /* Update the sqlite_sequence table by storing the content of the
001639 ** maximum rowid counter values recorded while inserting into
001640 ** autoincrement tables.
001641 */
001642 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
001643 sqlite3AutoincrementEnd(pParse);
001644 }
001645
001646 /*
001647 ** Return the number of rows inserted. If this routine is
001648 ** generating code because of a call to sqlite3NestedParse(), do not
001649 ** invoke the callback function.
001650 */
001651 if( regRowCount ){
001652 sqlite3CodeChangeCount(v, regRowCount, "rows inserted");
001653 }
001654
001655 insert_cleanup:
001656 sqlite3SrcListDelete(db, pTabList);
001657 sqlite3ExprListDelete(db, pList);
001658 sqlite3UpsertDelete(db, pUpsert);
001659 sqlite3SelectDelete(db, pSelect);
001660 if( pColumn ){
001661 sqlite3IdListDelete(db, pColumn);
001662 sqlite3DbFree(db, aTabColMap);
001663 }
001664 if( aRegIdx ) sqlite3DbNNFreeNN(db, aRegIdx);
001665 }
001666
001667 /* Make sure "isView" and other macros defined above are undefined. Otherwise
001668 ** they may interfere with compilation of other functions in this file
001669 ** (or in another file, if this file becomes part of the amalgamation). */
001670 #ifdef isView
001671 #undef isView
001672 #endif
001673 #ifdef pTrigger
001674 #undef pTrigger
001675 #endif
001676 #ifdef tmask
001677 #undef tmask
001678 #endif
001679
001680 /*
001681 ** Meanings of bits in of pWalker->eCode for
001682 ** sqlite3ExprReferencesUpdatedColumn()
001683 */
001684 #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
001685 #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
001686
001687 /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
001688 * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
001689 ** expression node references any of the
001690 ** columns that are being modified by an UPDATE statement.
001691 */
001692 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
001693 if( pExpr->op==TK_COLUMN ){
001694 assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
001695 if( pExpr->iColumn>=0 ){
001696 if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
001697 pWalker->eCode |= CKCNSTRNT_COLUMN;
001698 }
001699 }else{
001700 pWalker->eCode |= CKCNSTRNT_ROWID;
001701 }
001702 }
001703 return WRC_Continue;
001704 }
001705
001706 /*
001707 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
001708 ** only columns that are modified by the UPDATE are those for which
001709 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
001710 **
001711 ** Return true if CHECK constraint pExpr uses any of the
001712 ** changing columns (or the rowid if it is changing). In other words,
001713 ** return true if this CHECK constraint must be validated for
001714 ** the new row in the UPDATE statement.
001715 **
001716 ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
001717 ** The operation of this routine is the same - return true if an only if
001718 ** the expression uses one or more of columns identified by the second and
001719 ** third arguments.
001720 */
001721 int sqlite3ExprReferencesUpdatedColumn(
001722 Expr *pExpr, /* The expression to be checked */
001723 int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */
001724 int chngRowid /* True if UPDATE changes the rowid */
001725 ){
001726 Walker w;
001727 memset(&w, 0, sizeof(w));
001728 w.eCode = 0;
001729 w.xExprCallback = checkConstraintExprNode;
001730 w.u.aiCol = aiChng;
001731 sqlite3WalkExpr(&w, pExpr);
001732 if( !chngRowid ){
001733 testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
001734 w.eCode &= ~CKCNSTRNT_ROWID;
001735 }
001736 testcase( w.eCode==0 );
001737 testcase( w.eCode==CKCNSTRNT_COLUMN );
001738 testcase( w.eCode==CKCNSTRNT_ROWID );
001739 testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
001740 return w.eCode!=0;
001741 }
001742
001743 /*
001744 ** The sqlite3GenerateConstraintChecks() routine usually wants to visit
001745 ** the indexes of a table in the order provided in the Table->pIndex list.
001746 ** However, sometimes (rarely - when there is an upsert) it wants to visit
001747 ** the indexes in a different order. The following data structures accomplish
001748 ** this.
001749 **
001750 ** The IndexIterator object is used to walk through all of the indexes
001751 ** of a table in either Index.pNext order, or in some other order established
001752 ** by an array of IndexListTerm objects.
001753 */
001754 typedef struct IndexListTerm IndexListTerm;
001755 typedef struct IndexIterator IndexIterator;
001756 struct IndexIterator {
001757 int eType; /* 0 for Index.pNext list. 1 for an array of IndexListTerm */
001758 int i; /* Index of the current item from the list */
001759 union {
001760 struct { /* Use this object for eType==0: A Index.pNext list */
001761 Index *pIdx; /* The current Index */
001762 } lx;
001763 struct { /* Use this object for eType==1; Array of IndexListTerm */
001764 int nIdx; /* Size of the array */
001765 IndexListTerm *aIdx; /* Array of IndexListTerms */
001766 } ax;
001767 } u;
001768 };
001769
001770 /* When IndexIterator.eType==1, then each index is an array of instances
001771 ** of the following object
001772 */
001773 struct IndexListTerm {
001774 Index *p; /* The index */
001775 int ix; /* Which entry in the original Table.pIndex list is this index*/
001776 };
001777
001778 /* Return the first index on the list */
001779 static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){
001780 assert( pIter->i==0 );
001781 if( pIter->eType ){
001782 *pIx = pIter->u.ax.aIdx[0].ix;
001783 return pIter->u.ax.aIdx[0].p;
001784 }else{
001785 *pIx = 0;
001786 return pIter->u.lx.pIdx;
001787 }
001788 }
001789
001790 /* Return the next index from the list. Return NULL when out of indexes */
001791 static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){
001792 if( pIter->eType ){
001793 int i = ++pIter->i;
001794 if( i>=pIter->u.ax.nIdx ){
001795 *pIx = i;
001796 return 0;
001797 }
001798 *pIx = pIter->u.ax.aIdx[i].ix;
001799 return pIter->u.ax.aIdx[i].p;
001800 }else{
001801 ++(*pIx);
001802 pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
001803 return pIter->u.lx.pIdx;
001804 }
001805 }
001806
001807 /*
001808 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
001809 ** on table pTab.
001810 **
001811 ** The regNewData parameter is the first register in a range that contains
001812 ** the data to be inserted or the data after the update. There will be
001813 ** pTab->nCol+1 registers in this range. The first register (the one
001814 ** that regNewData points to) will contain the new rowid, or NULL in the
001815 ** case of a WITHOUT ROWID table. The second register in the range will
001816 ** contain the content of the first table column. The third register will
001817 ** contain the content of the second table column. And so forth.
001818 **
001819 ** The regOldData parameter is similar to regNewData except that it contains
001820 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
001821 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
001822 ** checking regOldData for zero.
001823 **
001824 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
001825 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
001826 ** might be modified by the UPDATE. If pkChng is false, then the key of
001827 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
001828 **
001829 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
001830 ** was explicitly specified as part of the INSERT statement. If pkChng
001831 ** is zero, it means that the either rowid is computed automatically or
001832 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
001833 ** pkChng will only be true if the INSERT statement provides an integer
001834 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
001835 **
001836 ** The code generated by this routine will store new index entries into
001837 ** registers identified by aRegIdx[]. No index entry is created for
001838 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
001839 ** the same as the order of indices on the linked list of indices
001840 ** at pTab->pIndex.
001841 **
001842 ** (2019-05-07) The generated code also creates a new record for the
001843 ** main table, if pTab is a rowid table, and stores that record in the
001844 ** register identified by aRegIdx[nIdx] - in other words in the first
001845 ** entry of aRegIdx[] past the last index. It is important that the
001846 ** record be generated during constraint checks to avoid affinity changes
001847 ** to the register content that occur after constraint checks but before
001848 ** the new record is inserted.
001849 **
001850 ** The caller must have already opened writeable cursors on the main
001851 ** table and all applicable indices (that is to say, all indices for which
001852 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
001853 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
001854 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
001855 ** for the first index in the pTab->pIndex list. Cursors for other indices
001856 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
001857 **
001858 ** This routine also generates code to check constraints. NOT NULL,
001859 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
001860 ** then the appropriate action is performed. There are five possible
001861 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
001862 **
001863 ** Constraint type Action What Happens
001864 ** --------------- ---------- ----------------------------------------
001865 ** any ROLLBACK The current transaction is rolled back and
001866 ** sqlite3_step() returns immediately with a
001867 ** return code of SQLITE_CONSTRAINT.
001868 **
001869 ** any ABORT Back out changes from the current command
001870 ** only (do not do a complete rollback) then
001871 ** cause sqlite3_step() to return immediately
001872 ** with SQLITE_CONSTRAINT.
001873 **
001874 ** any FAIL Sqlite3_step() returns immediately with a
001875 ** return code of SQLITE_CONSTRAINT. The
001876 ** transaction is not rolled back and any
001877 ** changes to prior rows are retained.
001878 **
001879 ** any IGNORE The attempt in insert or update the current
001880 ** row is skipped, without throwing an error.
001881 ** Processing continues with the next row.
001882 ** (There is an immediate jump to ignoreDest.)
001883 **
001884 ** NOT NULL REPLACE The NULL value is replace by the default
001885 ** value for that column. If the default value
001886 ** is NULL, the action is the same as ABORT.
001887 **
001888 ** UNIQUE REPLACE The other row that conflicts with the row
001889 ** being inserted is removed.
001890 **
001891 ** CHECK REPLACE Illegal. The results in an exception.
001892 **
001893 ** Which action to take is determined by the overrideError parameter.
001894 ** Or if overrideError==OE_Default, then the pParse->onError parameter
001895 ** is used. Or if pParse->onError==OE_Default then the onError value
001896 ** for the constraint is used.
001897 */
001898 void sqlite3GenerateConstraintChecks(
001899 Parse *pParse, /* The parser context */
001900 Table *pTab, /* The table being inserted or updated */
001901 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
001902 int iDataCur, /* Canonical data cursor (main table or PK index) */
001903 int iIdxCur, /* First index cursor */
001904 int regNewData, /* First register in a range holding values to insert */
001905 int regOldData, /* Previous content. 0 for INSERTs */
001906 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
001907 u8 overrideError, /* Override onError to this if not OE_Default */
001908 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
001909 int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
001910 int *aiChng, /* column i is unchanged if aiChng[i]<0 */
001911 Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
001912 ){
001913 Vdbe *v; /* VDBE under construction */
001914 Index *pIdx; /* Pointer to one of the indices */
001915 Index *pPk = 0; /* The PRIMARY KEY index for WITHOUT ROWID tables */
001916 sqlite3 *db; /* Database connection */
001917 int i; /* loop counter */
001918 int ix; /* Index loop counter */
001919 int nCol; /* Number of columns */
001920 int onError; /* Conflict resolution strategy */
001921 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
001922 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
001923 Upsert *pUpsertClause = 0; /* The specific ON CONFLICT clause for pIdx */
001924 u8 isUpdate; /* True if this is an UPDATE operation */
001925 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
001926 int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */
001927 int upsertIpkDelay = 0; /* Address of Goto to bypass initial IPK check */
001928 int ipkTop = 0; /* Top of the IPK uniqueness check */
001929 int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */
001930 /* Variables associated with retesting uniqueness constraints after
001931 ** replace triggers fire have run */
001932 int regTrigCnt; /* Register used to count replace trigger invocations */
001933 int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */
001934 int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
001935 Trigger *pTrigger; /* List of DELETE triggers on the table pTab */
001936 int nReplaceTrig = 0; /* Number of replace triggers coded */
001937 IndexIterator sIdxIter; /* Index iterator */
001938
001939 isUpdate = regOldData!=0;
001940 db = pParse->db;
001941 v = pParse->pVdbe;
001942 assert( v!=0 );
001943 assert( !IsView(pTab) ); /* This table is not a VIEW */
001944 nCol = pTab->nCol;
001945
001946 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
001947 ** normal rowid tables. nPkField is the number of key fields in the
001948 ** pPk index or 1 for a rowid table. In other words, nPkField is the
001949 ** number of fields in the true primary key of the table. */
001950 if( HasRowid(pTab) ){
001951 pPk = 0;
001952 nPkField = 1;
001953 }else{
001954 pPk = sqlite3PrimaryKeyIndex(pTab);
001955 nPkField = pPk->nKeyCol;
001956 }
001957
001958 /* Record that this module has started */
001959 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
001960 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
001961
001962 /* Test all NOT NULL constraints.
001963 */
001964 if( pTab->tabFlags & TF_HasNotNull ){
001965 int b2ndPass = 0; /* True if currently running 2nd pass */
001966 int nSeenReplace = 0; /* Number of ON CONFLICT REPLACE operations */
001967 int nGenerated = 0; /* Number of generated columns with NOT NULL */
001968 while(1){ /* Make 2 passes over columns. Exit loop via "break" */
001969 for(i=0; i<nCol; i++){
001970 int iReg; /* Register holding column value */
001971 Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */
001972 int isGenerated; /* non-zero if column is generated */
001973 onError = pCol->notNull;
001974 if( onError==OE_None ) continue; /* No NOT NULL on this column */
001975 if( i==pTab->iPKey ){
001976 continue; /* ROWID is never NULL */
001977 }
001978 isGenerated = pCol->colFlags & COLFLAG_GENERATED;
001979 if( isGenerated && !b2ndPass ){
001980 nGenerated++;
001981 continue; /* Generated columns processed on 2nd pass */
001982 }
001983 if( aiChng && aiChng[i]<0 && !isGenerated ){
001984 /* Do not check NOT NULL on columns that do not change */
001985 continue;
001986 }
001987 if( overrideError!=OE_Default ){
001988 onError = overrideError;
001989 }else if( onError==OE_Default ){
001990 onError = OE_Abort;
001991 }
001992 if( onError==OE_Replace ){
001993 if( b2ndPass /* REPLACE becomes ABORT on the 2nd pass */
001994 || pCol->iDflt==0 /* REPLACE is ABORT if no DEFAULT value */
001995 ){
001996 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
001997 testcase( pCol->colFlags & COLFLAG_STORED );
001998 testcase( pCol->colFlags & COLFLAG_GENERATED );
001999 onError = OE_Abort;
002000 }else{
002001 assert( !isGenerated );
002002 }
002003 }else if( b2ndPass && !isGenerated ){
002004 continue;
002005 }
002006 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
002007 || onError==OE_Ignore || onError==OE_Replace );
002008 testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
002009 iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
002010 switch( onError ){
002011 case OE_Replace: {
002012 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
002013 VdbeCoverage(v);
002014 assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
002015 nSeenReplace++;
002016 sqlite3ExprCodeCopy(pParse,
002017 sqlite3ColumnExpr(pTab, pCol), iReg);
002018 sqlite3VdbeJumpHere(v, addr1);
002019 break;
002020 }
002021 case OE_Abort:
002022 sqlite3MayAbort(pParse);
002023 /* no break */ deliberate_fall_through
002024 case OE_Rollback:
002025 case OE_Fail: {
002026 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
002027 pCol->zCnName);
002028 testcase( zMsg==0 && db->mallocFailed==0 );
002029 sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
002030 onError, iReg);
002031 sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
002032 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
002033 VdbeCoverage(v);
002034 break;
002035 }
002036 default: {
002037 assert( onError==OE_Ignore );
002038 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
002039 VdbeCoverage(v);
002040 break;
002041 }
002042 } /* end switch(onError) */
002043 } /* end loop i over columns */
002044 if( nGenerated==0 && nSeenReplace==0 ){
002045 /* If there are no generated columns with NOT NULL constraints
002046 ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
002047 ** pass is sufficient */
002048 break;
002049 }
002050 if( b2ndPass ) break; /* Never need more than 2 passes */
002051 b2ndPass = 1;
002052 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
002053 if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
002054 /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
002055 ** first pass, recomputed values for all generated columns, as
002056 ** those values might depend on columns affected by the REPLACE.
002057 */
002058 sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
002059 }
002060 #endif
002061 } /* end of 2-pass loop */
002062 } /* end if( has-not-null-constraints ) */
002063
002064 /* Test all CHECK constraints
002065 */
002066 #ifndef SQLITE_OMIT_CHECK
002067 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
002068 ExprList *pCheck = pTab->pCheck;
002069 pParse->iSelfTab = -(regNewData+1);
002070 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
002071 for(i=0; i<pCheck->nExpr; i++){
002072 int allOk;
002073 Expr *pCopy;
002074 Expr *pExpr = pCheck->a[i].pExpr;
002075 if( aiChng
002076 && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
002077 ){
002078 /* The check constraints do not reference any of the columns being
002079 ** updated so there is no point it verifying the check constraint */
002080 continue;
002081 }
002082 if( bAffinityDone==0 ){
002083 sqlite3TableAffinity(v, pTab, regNewData+1);
002084 bAffinityDone = 1;
002085 }
002086 allOk = sqlite3VdbeMakeLabel(pParse);
002087 sqlite3VdbeVerifyAbortable(v, onError);
002088 pCopy = sqlite3ExprDup(db, pExpr, 0);
002089 if( !db->mallocFailed ){
002090 sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
002091 }
002092 sqlite3ExprDelete(db, pCopy);
002093 if( onError==OE_Ignore ){
002094 sqlite3VdbeGoto(v, ignoreDest);
002095 }else{
002096 char *zName = pCheck->a[i].zEName;
002097 assert( zName!=0 || pParse->db->mallocFailed );
002098 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
002099 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
002100 onError, zName, P4_TRANSIENT,
002101 P5_ConstraintCheck);
002102 }
002103 sqlite3VdbeResolveLabel(v, allOk);
002104 }
002105 pParse->iSelfTab = 0;
002106 }
002107 #endif /* !defined(SQLITE_OMIT_CHECK) */
002108
002109 /* UNIQUE and PRIMARY KEY constraints should be handled in the following
002110 ** order:
002111 **
002112 ** (1) OE_Update
002113 ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
002114 ** (3) OE_Replace
002115 **
002116 ** OE_Fail and OE_Ignore must happen before any changes are made.
002117 ** OE_Update guarantees that only a single row will change, so it
002118 ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
002119 ** could happen in any order, but they are grouped up front for
002120 ** convenience.
002121 **
002122 ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
002123 ** The order of constraints used to have OE_Update as (2) and OE_Abort
002124 ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
002125 ** constraint before any others, so it had to be moved.
002126 **
002127 ** Constraint checking code is generated in this order:
002128 ** (A) The rowid constraint
002129 ** (B) Unique index constraints that do not have OE_Replace as their
002130 ** default conflict resolution strategy
002131 ** (C) Unique index that do use OE_Replace by default.
002132 **
002133 ** The ordering of (2) and (3) is accomplished by making sure the linked
002134 ** list of indexes attached to a table puts all OE_Replace indexes last
002135 ** in the list. See sqlite3CreateIndex() for where that happens.
002136 */
002137 sIdxIter.eType = 0;
002138 sIdxIter.i = 0;
002139 sIdxIter.u.ax.aIdx = 0; /* Silence harmless compiler warning */
002140 sIdxIter.u.lx.pIdx = pTab->pIndex;
002141 if( pUpsert ){
002142 if( pUpsert->pUpsertTarget==0 ){
002143 /* There is just on ON CONFLICT clause and it has no constraint-target */
002144 assert( pUpsert->pNextUpsert==0 );
002145 if( pUpsert->isDoUpdate==0 ){
002146 /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
002147 ** Make all unique constraint resolution be OE_Ignore */
002148 overrideError = OE_Ignore;
002149 pUpsert = 0;
002150 }else{
002151 /* A single ON CONFLICT DO UPDATE. Make all resolutions OE_Update */
002152 overrideError = OE_Update;
002153 }
002154 }else if( pTab->pIndex!=0 ){
002155 /* Otherwise, we'll need to run the IndexListTerm array version of the
002156 ** iterator to ensure that all of the ON CONFLICT conditions are
002157 ** checked first and in order. */
002158 int nIdx, jj;
002159 u64 nByte;
002160 Upsert *pTerm;
002161 u8 *bUsed;
002162 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
002163 assert( aRegIdx[nIdx]>0 );
002164 }
002165 sIdxIter.eType = 1;
002166 sIdxIter.u.ax.nIdx = nIdx;
002167 nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx;
002168 sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte);
002169 if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */
002170 bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx];
002171 pUpsert->pToFree = sIdxIter.u.ax.aIdx;
002172 for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
002173 if( pTerm->pUpsertTarget==0 ) break;
002174 if( pTerm->pUpsertIdx==0 ) continue; /* Skip ON CONFLICT for the IPK */
002175 jj = 0;
002176 pIdx = pTab->pIndex;
002177 while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
002178 pIdx = pIdx->pNext;
002179 jj++;
002180 }
002181 if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */
002182 bUsed[jj] = 1;
002183 sIdxIter.u.ax.aIdx[i].p = pIdx;
002184 sIdxIter.u.ax.aIdx[i].ix = jj;
002185 i++;
002186 }
002187 for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
002188 if( bUsed[jj] ) continue;
002189 sIdxIter.u.ax.aIdx[i].p = pIdx;
002190 sIdxIter.u.ax.aIdx[i].ix = jj;
002191 i++;
002192 }
002193 assert( i==nIdx );
002194 }
002195 }
002196
002197 /* Determine if it is possible that triggers (either explicitly coded
002198 ** triggers or FK resolution actions) might run as a result of deletes
002199 ** that happen when OE_Replace conflict resolution occurs. (Call these
002200 ** "replace triggers".) If any replace triggers run, we will need to
002201 ** recheck all of the uniqueness constraints after they have all run.
002202 ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
002203 **
002204 ** If replace triggers are a possibility, then
002205 **
002206 ** (1) Allocate register regTrigCnt and initialize it to zero.
002207 ** That register will count the number of replace triggers that
002208 ** fire. Constraint recheck only occurs if the number is positive.
002209 ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
002210 ** (3) Initialize addrRecheck and lblRecheckOk
002211 **
002212 ** The uniqueness rechecking code will create a series of tests to run
002213 ** in a second pass. The addrRecheck and lblRecheckOk variables are
002214 ** used to link together these tests which are separated from each other
002215 ** in the generate bytecode.
002216 */
002217 if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
002218 /* There are not DELETE triggers nor FK constraints. No constraint
002219 ** rechecks are needed. */
002220 pTrigger = 0;
002221 regTrigCnt = 0;
002222 }else{
002223 if( db->flags&SQLITE_RecTriggers ){
002224 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
002225 regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
002226 }else{
002227 pTrigger = 0;
002228 regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
002229 }
002230 if( regTrigCnt ){
002231 /* Replace triggers might exist. Allocate the counter and
002232 ** initialize it to zero. */
002233 regTrigCnt = ++pParse->nMem;
002234 sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
002235 VdbeComment((v, "trigger count"));
002236 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
002237 addrRecheck = lblRecheckOk;
002238 }
002239 }
002240
002241 /* If rowid is changing, make sure the new rowid does not previously
002242 ** exist in the table.
002243 */
002244 if( pkChng && pPk==0 ){
002245 int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
002246
002247 /* Figure out what action to take in case of a rowid collision */
002248 onError = pTab->keyConf;
002249 if( overrideError!=OE_Default ){
002250 onError = overrideError;
002251 }else if( onError==OE_Default ){
002252 onError = OE_Abort;
002253 }
002254
002255 /* figure out whether or not upsert applies in this case */
002256 if( pUpsert ){
002257 pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0);
002258 if( pUpsertClause!=0 ){
002259 if( pUpsertClause->isDoUpdate==0 ){
002260 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
002261 }else{
002262 onError = OE_Update; /* DO UPDATE */
002263 }
002264 }
002265 if( pUpsertClause!=pUpsert ){
002266 /* The first ON CONFLICT clause has a conflict target other than
002267 ** the IPK. We have to jump ahead to that first ON CONFLICT clause
002268 ** and then come back here and deal with the IPK afterwards */
002269 upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto);
002270 }
002271 }
002272
002273 /* If the response to a rowid conflict is REPLACE but the response
002274 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
002275 ** to defer the running of the rowid conflict checking until after
002276 ** the UNIQUE constraints have run.
002277 */
002278 if( onError==OE_Replace /* IPK rule is REPLACE */
002279 && onError!=overrideError /* Rules for other constraints are different */
002280 && pTab->pIndex /* There exist other constraints */
002281 && !upsertIpkDelay /* IPK check already deferred by UPSERT */
002282 ){
002283 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
002284 VdbeComment((v, "defer IPK REPLACE until last"));
002285 }
002286
002287 if( isUpdate ){
002288 /* pkChng!=0 does not mean that the rowid has changed, only that
002289 ** it might have changed. Skip the conflict logic below if the rowid
002290 ** is unchanged. */
002291 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
002292 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
002293 VdbeCoverage(v);
002294 }
002295
002296 /* Check to see if the new rowid already exists in the table. Skip
002297 ** the following conflict logic if it does not. */
002298 VdbeNoopComment((v, "uniqueness check for ROWID"));
002299 sqlite3VdbeVerifyAbortable(v, onError);
002300 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
002301 VdbeCoverage(v);
002302
002303 switch( onError ){
002304 default: {
002305 onError = OE_Abort;
002306 /* no break */ deliberate_fall_through
002307 }
002308 case OE_Rollback:
002309 case OE_Abort:
002310 case OE_Fail: {
002311 testcase( onError==OE_Rollback );
002312 testcase( onError==OE_Abort );
002313 testcase( onError==OE_Fail );
002314 sqlite3RowidConstraint(pParse, onError, pTab);
002315 break;
002316 }
002317 case OE_Replace: {
002318 /* If there are DELETE triggers on this table and the
002319 ** recursive-triggers flag is set, call GenerateRowDelete() to
002320 ** remove the conflicting row from the table. This will fire
002321 ** the triggers and remove both the table and index b-tree entries.
002322 **
002323 ** Otherwise, if there are no triggers or the recursive-triggers
002324 ** flag is not set, but the table has one or more indexes, call
002325 ** GenerateRowIndexDelete(). This removes the index b-tree entries
002326 ** only. The table b-tree entry will be replaced by the new entry
002327 ** when it is inserted.
002328 **
002329 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
002330 ** also invoke MultiWrite() to indicate that this VDBE may require
002331 ** statement rollback (if the statement is aborted after the delete
002332 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
002333 ** but being more selective here allows statements like:
002334 **
002335 ** REPLACE INTO t(rowid) VALUES($newrowid)
002336 **
002337 ** to run without a statement journal if there are no indexes on the
002338 ** table.
002339 */
002340 if( regTrigCnt ){
002341 sqlite3MultiWrite(pParse);
002342 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
002343 regNewData, 1, 0, OE_Replace, 1, -1);
002344 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
002345 nReplaceTrig++;
002346 }else{
002347 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002348 assert( HasRowid(pTab) );
002349 /* This OP_Delete opcode fires the pre-update-hook only. It does
002350 ** not modify the b-tree. It is more efficient to let the coming
002351 ** OP_Insert replace the existing entry than it is to delete the
002352 ** existing entry and then insert a new one. */
002353 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
002354 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
002355 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
002356 if( pTab->pIndex ){
002357 sqlite3MultiWrite(pParse);
002358 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
002359 }
002360 }
002361 seenReplace = 1;
002362 break;
002363 }
002364 #ifndef SQLITE_OMIT_UPSERT
002365 case OE_Update: {
002366 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
002367 /* no break */ deliberate_fall_through
002368 }
002369 #endif
002370 case OE_Ignore: {
002371 testcase( onError==OE_Ignore );
002372 sqlite3VdbeGoto(v, ignoreDest);
002373 break;
002374 }
002375 }
002376 sqlite3VdbeResolveLabel(v, addrRowidOk);
002377 if( pUpsert && pUpsertClause!=pUpsert ){
002378 upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
002379 }else if( ipkTop ){
002380 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
002381 sqlite3VdbeJumpHere(v, ipkTop-1);
002382 }
002383 }
002384
002385 /* Test all UNIQUE constraints by creating entries for each UNIQUE
002386 ** index and making sure that duplicate entries do not already exist.
002387 ** Compute the revised record entries for indices as we go.
002388 **
002389 ** This loop also handles the case of the PRIMARY KEY index for a
002390 ** WITHOUT ROWID table.
002391 */
002392 for(pIdx = indexIteratorFirst(&sIdxIter, &ix);
002393 pIdx;
002394 pIdx = indexIteratorNext(&sIdxIter, &ix)
002395 ){
002396 int regIdx; /* Range of registers holding content for pIdx */
002397 int regR; /* Range of registers holding conflicting PK */
002398 int iThisCur; /* Cursor for this UNIQUE index */
002399 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
002400 int addrConflictCk; /* First opcode in the conflict check logic */
002401
002402 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
002403 if( pUpsert ){
002404 pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
002405 if( upsertIpkDelay && pUpsertClause==pUpsert ){
002406 sqlite3VdbeJumpHere(v, upsertIpkDelay);
002407 }
002408 }
002409 addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
002410 if( bAffinityDone==0 ){
002411 sqlite3TableAffinity(v, pTab, regNewData+1);
002412 bAffinityDone = 1;
002413 }
002414 VdbeNoopComment((v, "prep index %s", pIdx->zName));
002415 iThisCur = iIdxCur+ix;
002416
002417
002418 /* Skip partial indices for which the WHERE clause is not true */
002419 if( pIdx->pPartIdxWhere ){
002420 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
002421 pParse->iSelfTab = -(regNewData+1);
002422 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
002423 SQLITE_JUMPIFNULL);
002424 pParse->iSelfTab = 0;
002425 }
002426
002427 /* Create a record for this index entry as it should appear after
002428 ** the insert or update. Store that record in the aRegIdx[ix] register
002429 */
002430 regIdx = aRegIdx[ix]+1;
002431 for(i=0; i<pIdx->nColumn; i++){
002432 int iField = pIdx->aiColumn[i];
002433 int x;
002434 if( iField==XN_EXPR ){
002435 pParse->iSelfTab = -(regNewData+1);
002436 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
002437 pParse->iSelfTab = 0;
002438 VdbeComment((v, "%s column %d", pIdx->zName, i));
002439 }else if( iField==XN_ROWID || iField==pTab->iPKey ){
002440 x = regNewData;
002441 sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
002442 VdbeComment((v, "rowid"));
002443 }else{
002444 testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
002445 x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
002446 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
002447 VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
002448 }
002449 }
002450 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
002451 VdbeComment((v, "for %s", pIdx->zName));
002452 #ifdef SQLITE_ENABLE_NULL_TRIM
002453 if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
002454 sqlite3SetMakeRecordP5(v, pIdx->pTable);
002455 }
002456 #endif
002457 sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
002458
002459 /* In an UPDATE operation, if this index is the PRIMARY KEY index
002460 ** of a WITHOUT ROWID table and there has been no change the
002461 ** primary key, then no collision is possible. The collision detection
002462 ** logic below can all be skipped. */
002463 if( isUpdate && pPk==pIdx && pkChng==0 ){
002464 sqlite3VdbeResolveLabel(v, addrUniqueOk);
002465 continue;
002466 }
002467
002468 /* Find out what action to take in case there is a uniqueness conflict */
002469 onError = pIdx->onError;
002470 if( onError==OE_None ){
002471 sqlite3VdbeResolveLabel(v, addrUniqueOk);
002472 continue; /* pIdx is not a UNIQUE index */
002473 }
002474 if( overrideError!=OE_Default ){
002475 onError = overrideError;
002476 }else if( onError==OE_Default ){
002477 onError = OE_Abort;
002478 }
002479
002480 /* Figure out if the upsert clause applies to this index */
002481 if( pUpsertClause ){
002482 if( pUpsertClause->isDoUpdate==0 ){
002483 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
002484 }else{
002485 onError = OE_Update; /* DO UPDATE */
002486 }
002487 }
002488
002489 /* Collision detection may be omitted if all of the following are true:
002490 ** (1) The conflict resolution algorithm is REPLACE
002491 ** (2) The table is a WITHOUT ROWID table
002492 ** (3) There are no secondary indexes on the table
002493 ** (4) No delete triggers need to be fired if there is a conflict
002494 ** (5) No FK constraint counters need to be updated if a conflict occurs.
002495 **
002496 ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
002497 ** must be explicitly deleted in order to ensure any pre-update hook
002498 ** is invoked. */
002499 assert( IsOrdinaryTable(pTab) );
002500 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
002501 if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
002502 && pPk==pIdx /* Condition 2 */
002503 && onError==OE_Replace /* Condition 1 */
002504 && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
002505 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
002506 && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
002507 (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
002508 ){
002509 sqlite3VdbeResolveLabel(v, addrUniqueOk);
002510 continue;
002511 }
002512 #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
002513
002514 /* Check to see if the new index entry will be unique */
002515 sqlite3VdbeVerifyAbortable(v, onError);
002516 addrConflictCk =
002517 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
002518 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
002519
002520 /* Generate code to handle collisions */
002521 regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField);
002522 if( isUpdate || onError==OE_Replace ){
002523 if( HasRowid(pTab) ){
002524 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
002525 /* Conflict only if the rowid of the existing index entry
002526 ** is different from old-rowid */
002527 if( isUpdate ){
002528 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
002529 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
002530 VdbeCoverage(v);
002531 }
002532 }else{
002533 int x;
002534 /* Extract the PRIMARY KEY from the end of the index entry and
002535 ** store it in registers regR..regR+nPk-1 */
002536 if( pIdx!=pPk ){
002537 for(i=0; i<pPk->nKeyCol; i++){
002538 assert( pPk->aiColumn[i]>=0 );
002539 x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
002540 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
002541 VdbeComment((v, "%s.%s", pTab->zName,
002542 pTab->aCol[pPk->aiColumn[i]].zCnName));
002543 }
002544 }
002545 if( isUpdate ){
002546 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
002547 ** table, only conflict if the new PRIMARY KEY values are actually
002548 ** different from the old. See TH3 withoutrowid04.test.
002549 **
002550 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
002551 ** of the matched index row are different from the original PRIMARY
002552 ** KEY values of this row before the update. */
002553 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
002554 int op = OP_Ne;
002555 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
002556
002557 for(i=0; i<pPk->nKeyCol; i++){
002558 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
002559 x = pPk->aiColumn[i];
002560 assert( x>=0 );
002561 if( i==(pPk->nKeyCol-1) ){
002562 addrJump = addrUniqueOk;
002563 op = OP_Eq;
002564 }
002565 x = sqlite3TableColumnToStorage(pTab, x);
002566 sqlite3VdbeAddOp4(v, op,
002567 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
002568 );
002569 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
002570 VdbeCoverageIf(v, op==OP_Eq);
002571 VdbeCoverageIf(v, op==OP_Ne);
002572 }
002573 }
002574 }
002575 }
002576
002577 /* Generate code that executes if the new index entry is not unique */
002578 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
002579 || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
002580 switch( onError ){
002581 case OE_Rollback:
002582 case OE_Abort:
002583 case OE_Fail: {
002584 testcase( onError==OE_Rollback );
002585 testcase( onError==OE_Abort );
002586 testcase( onError==OE_Fail );
002587 sqlite3UniqueConstraint(pParse, onError, pIdx);
002588 break;
002589 }
002590 #ifndef SQLITE_OMIT_UPSERT
002591 case OE_Update: {
002592 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
002593 /* no break */ deliberate_fall_through
002594 }
002595 #endif
002596 case OE_Ignore: {
002597 testcase( onError==OE_Ignore );
002598 sqlite3VdbeGoto(v, ignoreDest);
002599 break;
002600 }
002601 default: {
002602 int nConflictCk; /* Number of opcodes in conflict check logic */
002603
002604 assert( onError==OE_Replace );
002605 nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
002606 assert( nConflictCk>0 || db->mallocFailed );
002607 testcase( nConflictCk<=0 );
002608 testcase( nConflictCk>1 );
002609 if( regTrigCnt ){
002610 sqlite3MultiWrite(pParse);
002611 nReplaceTrig++;
002612 }
002613 if( pTrigger && isUpdate ){
002614 sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
002615 }
002616 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
002617 regR, nPkField, 0, OE_Replace,
002618 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
002619 if( pTrigger && isUpdate ){
002620 sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
002621 }
002622 if( regTrigCnt ){
002623 int addrBypass; /* Jump destination to bypass recheck logic */
002624
002625 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
002626 addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
002627 VdbeComment((v, "bypass recheck"));
002628
002629 /* Here we insert code that will be invoked after all constraint
002630 ** checks have run, if and only if one or more replace triggers
002631 ** fired. */
002632 sqlite3VdbeResolveLabel(v, lblRecheckOk);
002633 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
002634 if( pIdx->pPartIdxWhere ){
002635 /* Bypass the recheck if this partial index is not defined
002636 ** for the current row */
002637 sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
002638 VdbeCoverage(v);
002639 }
002640 /* Copy the constraint check code from above, except change
002641 ** the constraint-ok jump destination to be the address of
002642 ** the next retest block */
002643 while( nConflictCk>0 ){
002644 VdbeOp x; /* Conflict check opcode to copy */
002645 /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
002646 ** Hence, make a complete copy of the opcode, rather than using
002647 ** a pointer to the opcode. */
002648 x = *sqlite3VdbeGetOp(v, addrConflictCk);
002649 if( x.opcode!=OP_IdxRowid ){
002650 int p2; /* New P2 value for copied conflict check opcode */
002651 const char *zP4;
002652 if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
002653 p2 = lblRecheckOk;
002654 }else{
002655 p2 = x.p2;
002656 }
002657 zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
002658 sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
002659 sqlite3VdbeChangeP5(v, x.p5);
002660 VdbeCoverageIf(v, p2!=x.p2);
002661 }
002662 nConflictCk--;
002663 addrConflictCk++;
002664 }
002665 /* If the retest fails, issue an abort */
002666 sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
002667
002668 sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
002669 }
002670 seenReplace = 1;
002671 break;
002672 }
002673 }
002674 sqlite3VdbeResolveLabel(v, addrUniqueOk);
002675 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
002676 if( pUpsertClause
002677 && upsertIpkReturn
002678 && sqlite3UpsertNextIsIPK(pUpsertClause)
002679 ){
002680 sqlite3VdbeGoto(v, upsertIpkDelay+1);
002681 sqlite3VdbeJumpHere(v, upsertIpkReturn);
002682 upsertIpkReturn = 0;
002683 }
002684 }
002685
002686 /* If the IPK constraint is a REPLACE, run it last */
002687 if( ipkTop ){
002688 sqlite3VdbeGoto(v, ipkTop);
002689 VdbeComment((v, "Do IPK REPLACE"));
002690 assert( ipkBottom>0 );
002691 sqlite3VdbeJumpHere(v, ipkBottom);
002692 }
002693
002694 /* Recheck all uniqueness constraints after replace triggers have run */
002695 testcase( regTrigCnt!=0 && nReplaceTrig==0 );
002696 assert( regTrigCnt!=0 || nReplaceTrig==0 );
002697 if( nReplaceTrig ){
002698 sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
002699 if( !pPk ){
002700 if( isUpdate ){
002701 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
002702 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
002703 VdbeCoverage(v);
002704 }
002705 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
002706 VdbeCoverage(v);
002707 sqlite3RowidConstraint(pParse, OE_Abort, pTab);
002708 }else{
002709 sqlite3VdbeGoto(v, addrRecheck);
002710 }
002711 sqlite3VdbeResolveLabel(v, lblRecheckOk);
002712 }
002713
002714 /* Generate the table record */
002715 if( HasRowid(pTab) ){
002716 int regRec = aRegIdx[ix];
002717 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
002718 sqlite3SetMakeRecordP5(v, pTab);
002719 if( !bAffinityDone ){
002720 sqlite3TableAffinity(v, pTab, 0);
002721 }
002722 }
002723
002724 *pbMayReplace = seenReplace;
002725 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
002726 }
002727
002728 #ifdef SQLITE_ENABLE_NULL_TRIM
002729 /*
002730 ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
002731 ** to be the number of columns in table pTab that must not be NULL-trimmed.
002732 **
002733 ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
002734 */
002735 void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
002736 u16 i;
002737
002738 /* Records with omitted columns are only allowed for schema format
002739 ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
002740 if( pTab->pSchema->file_format<2 ) return;
002741
002742 for(i=pTab->nCol-1; i>0; i--){
002743 if( pTab->aCol[i].iDflt!=0 ) break;
002744 if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
002745 }
002746 sqlite3VdbeChangeP5(v, i+1);
002747 }
002748 #endif
002749
002750 /*
002751 ** Table pTab is a WITHOUT ROWID table that is being written to. The cursor
002752 ** number is iCur, and register regData contains the new record for the
002753 ** PK index. This function adds code to invoke the pre-update hook,
002754 ** if one is registered.
002755 */
002756 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002757 static void codeWithoutRowidPreupdate(
002758 Parse *pParse, /* Parse context */
002759 Table *pTab, /* Table being updated */
002760 int iCur, /* Cursor number for table */
002761 int regData /* Data containing new record */
002762 ){
002763 Vdbe *v = pParse->pVdbe;
002764 int r = sqlite3GetTempReg(pParse);
002765 assert( !HasRowid(pTab) );
002766 assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
002767 sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
002768 sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE);
002769 sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
002770 sqlite3ReleaseTempReg(pParse, r);
002771 }
002772 #else
002773 # define codeWithoutRowidPreupdate(a,b,c,d)
002774 #endif
002775
002776 /*
002777 ** This routine generates code to finish the INSERT or UPDATE operation
002778 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
002779 ** A consecutive range of registers starting at regNewData contains the
002780 ** rowid and the content to be inserted.
002781 **
002782 ** The arguments to this routine should be the same as the first six
002783 ** arguments to sqlite3GenerateConstraintChecks.
002784 */
002785 void sqlite3CompleteInsertion(
002786 Parse *pParse, /* The parser context */
002787 Table *pTab, /* the table into which we are inserting */
002788 int iDataCur, /* Cursor of the canonical data source */
002789 int iIdxCur, /* First index cursor */
002790 int regNewData, /* Range of content */
002791 int *aRegIdx, /* Register used by each index. 0 for unused indices */
002792 int update_flags, /* True for UPDATE, False for INSERT */
002793 int appendBias, /* True if this is likely to be an append */
002794 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
002795 ){
002796 Vdbe *v; /* Prepared statements under construction */
002797 Index *pIdx; /* An index being inserted or updated */
002798 u8 pik_flags; /* flag values passed to the btree insert */
002799 int i; /* Loop counter */
002800
002801 assert( update_flags==0
002802 || update_flags==OPFLAG_ISUPDATE
002803 || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
002804 );
002805
002806 v = pParse->pVdbe;
002807 assert( v!=0 );
002808 assert( !IsView(pTab) ); /* This table is not a VIEW */
002809 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
002810 /* All REPLACE indexes are at the end of the list */
002811 assert( pIdx->onError!=OE_Replace
002812 || pIdx->pNext==0
002813 || pIdx->pNext->onError==OE_Replace );
002814 if( aRegIdx[i]==0 ) continue;
002815 if( pIdx->pPartIdxWhere ){
002816 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
002817 VdbeCoverage(v);
002818 }
002819 pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
002820 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
002821 pik_flags |= OPFLAG_NCHANGE;
002822 pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
002823 if( update_flags==0 ){
002824 codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]);
002825 }
002826 }
002827 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
002828 aRegIdx[i]+1,
002829 pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
002830 sqlite3VdbeChangeP5(v, pik_flags);
002831 }
002832 if( !HasRowid(pTab) ) return;
002833 if( pParse->nested ){
002834 pik_flags = 0;
002835 }else{
002836 pik_flags = OPFLAG_NCHANGE;
002837 pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
002838 }
002839 if( appendBias ){
002840 pik_flags |= OPFLAG_APPEND;
002841 }
002842 if( useSeekResult ){
002843 pik_flags |= OPFLAG_USESEEKRESULT;
002844 }
002845 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
002846 if( !pParse->nested ){
002847 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
002848 }
002849 sqlite3VdbeChangeP5(v, pik_flags);
002850 }
002851
002852 /*
002853 ** Allocate cursors for the pTab table and all its indices and generate
002854 ** code to open and initialized those cursors.
002855 **
002856 ** The cursor for the object that contains the complete data (normally
002857 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
002858 ** ROWID table) is returned in *piDataCur. The first index cursor is
002859 ** returned in *piIdxCur. The number of indices is returned.
002860 **
002861 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
002862 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
002863 ** If iBase is negative, then allocate the next available cursor.
002864 **
002865 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
002866 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
002867 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
002868 ** pTab->pIndex list.
002869 **
002870 ** If pTab is a virtual table, then this routine is a no-op and the
002871 ** *piDataCur and *piIdxCur values are left uninitialized.
002872 */
002873 int sqlite3OpenTableAndIndices(
002874 Parse *pParse, /* Parsing context */
002875 Table *pTab, /* Table to be opened */
002876 int op, /* OP_OpenRead or OP_OpenWrite */
002877 u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
002878 int iBase, /* Use this for the table cursor, if there is one */
002879 u8 *aToOpen, /* If not NULL: boolean for each table and index */
002880 int *piDataCur, /* Write the database source cursor number here */
002881 int *piIdxCur /* Write the first index cursor number here */
002882 ){
002883 int i;
002884 int iDb;
002885 int iDataCur;
002886 Index *pIdx;
002887 Vdbe *v;
002888
002889 assert( op==OP_OpenRead || op==OP_OpenWrite );
002890 assert( op==OP_OpenWrite || p5==0 );
002891 assert( piDataCur!=0 );
002892 assert( piIdxCur!=0 );
002893 if( IsVirtual(pTab) ){
002894 /* This routine is a no-op for virtual tables. Leave the output
002895 ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
002896 ** for improved error detection. */
002897 *piDataCur = *piIdxCur = -999;
002898 return 0;
002899 }
002900 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
002901 v = pParse->pVdbe;
002902 assert( v!=0 );
002903 if( iBase<0 ) iBase = pParse->nTab;
002904 iDataCur = iBase++;
002905 *piDataCur = iDataCur;
002906 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
002907 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
002908 }else if( pParse->db->noSharedCache==0 ){
002909 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
002910 }
002911 *piIdxCur = iBase;
002912 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
002913 int iIdxCur = iBase++;
002914 assert( pIdx->pSchema==pTab->pSchema );
002915 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
002916 *piDataCur = iIdxCur;
002917 p5 = 0;
002918 }
002919 if( aToOpen==0 || aToOpen[i+1] ){
002920 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
002921 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
002922 sqlite3VdbeChangeP5(v, p5);
002923 VdbeComment((v, "%s", pIdx->zName));
002924 }
002925 }
002926 if( iBase>pParse->nTab ) pParse->nTab = iBase;
002927 return i;
002928 }
002929
002930
002931 #ifdef SQLITE_TEST
002932 /*
002933 ** The following global variable is incremented whenever the
002934 ** transfer optimization is used. This is used for testing
002935 ** purposes only - to make sure the transfer optimization really
002936 ** is happening when it is supposed to.
002937 */
002938 int sqlite3_xferopt_count;
002939 #endif /* SQLITE_TEST */
002940
002941
002942 #ifndef SQLITE_OMIT_XFER_OPT
002943 /*
002944 ** Check to see if index pSrc is compatible as a source of data
002945 ** for index pDest in an insert transfer optimization. The rules
002946 ** for a compatible index:
002947 **
002948 ** * The index is over the same set of columns
002949 ** * The same DESC and ASC markings occurs on all columns
002950 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
002951 ** * The same collating sequence on each column
002952 ** * The index has the exact same WHERE clause
002953 */
002954 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
002955 int i;
002956 assert( pDest && pSrc );
002957 assert( pDest->pTable!=pSrc->pTable );
002958 if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
002959 return 0; /* Different number of columns */
002960 }
002961 if( pDest->onError!=pSrc->onError ){
002962 return 0; /* Different conflict resolution strategies */
002963 }
002964 for(i=0; i<pSrc->nKeyCol; i++){
002965 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
002966 return 0; /* Different columns indexed */
002967 }
002968 if( pSrc->aiColumn[i]==XN_EXPR ){
002969 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
002970 if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
002971 pDest->aColExpr->a[i].pExpr, -1)!=0 ){
002972 return 0; /* Different expressions in the index */
002973 }
002974 }
002975 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
002976 return 0; /* Different sort orders */
002977 }
002978 if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
002979 return 0; /* Different collating sequences */
002980 }
002981 }
002982 if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
002983 return 0; /* Different WHERE clauses */
002984 }
002985
002986 /* If no test above fails then the indices must be compatible */
002987 return 1;
002988 }
002989
002990 /*
002991 ** Attempt the transfer optimization on INSERTs of the form
002992 **
002993 ** INSERT INTO tab1 SELECT * FROM tab2;
002994 **
002995 ** The xfer optimization transfers raw records from tab2 over to tab1.
002996 ** Columns are not decoded and reassembled, which greatly improves
002997 ** performance. Raw index records are transferred in the same way.
002998 **
002999 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
003000 ** There are lots of rules for determining compatibility - see comments
003001 ** embedded in the code for details.
003002 **
003003 ** This routine returns TRUE if the optimization is guaranteed to be used.
003004 ** Sometimes the xfer optimization will only work if the destination table
003005 ** is empty - a factor that can only be determined at run-time. In that
003006 ** case, this routine generates code for the xfer optimization but also
003007 ** does a test to see if the destination table is empty and jumps over the
003008 ** xfer optimization code if the test fails. In that case, this routine
003009 ** returns FALSE so that the caller will know to go ahead and generate
003010 ** an unoptimized transfer. This routine also returns FALSE if there
003011 ** is no chance that the xfer optimization can be applied.
003012 **
003013 ** This optimization is particularly useful at making VACUUM run faster.
003014 */
003015 static int xferOptimization(
003016 Parse *pParse, /* Parser context */
003017 Table *pDest, /* The table we are inserting into */
003018 Select *pSelect, /* A SELECT statement to use as the data source */
003019 int onError, /* How to handle constraint errors */
003020 int iDbDest /* The database of pDest */
003021 ){
003022 sqlite3 *db = pParse->db;
003023 ExprList *pEList; /* The result set of the SELECT */
003024 Table *pSrc; /* The table in the FROM clause of SELECT */
003025 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
003026 SrcItem *pItem; /* An element of pSelect->pSrc */
003027 int i; /* Loop counter */
003028 int iDbSrc; /* The database of pSrc */
003029 int iSrc, iDest; /* Cursors from source and destination */
003030 int addr1, addr2; /* Loop addresses */
003031 int emptyDestTest = 0; /* Address of test for empty pDest */
003032 int emptySrcTest = 0; /* Address of test for empty pSrc */
003033 Vdbe *v; /* The VDBE we are building */
003034 int regAutoinc; /* Memory register used by AUTOINC */
003035 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
003036 int regData, regRowid; /* Registers holding data and rowid */
003037
003038 assert( pSelect!=0 );
003039 if( pParse->pWith || pSelect->pWith ){
003040 /* Do not attempt to process this query if there are an WITH clauses
003041 ** attached to it. Proceeding may generate a false "no such table: xxx"
003042 ** error if pSelect reads from a CTE named "xxx". */
003043 return 0;
003044 }
003045 #ifndef SQLITE_OMIT_VIRTUALTABLE
003046 if( IsVirtual(pDest) ){
003047 return 0; /* tab1 must not be a virtual table */
003048 }
003049 #endif
003050 if( onError==OE_Default ){
003051 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
003052 if( onError==OE_Default ) onError = OE_Abort;
003053 }
003054 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
003055 if( pSelect->pSrc->nSrc!=1 ){
003056 return 0; /* FROM clause must have exactly one term */
003057 }
003058 if( pSelect->pSrc->a[0].fg.isSubquery ){
003059 return 0; /* FROM clause cannot contain a subquery */
003060 }
003061 if( pSelect->pWhere ){
003062 return 0; /* SELECT may not have a WHERE clause */
003063 }
003064 if( pSelect->pOrderBy ){
003065 return 0; /* SELECT may not have an ORDER BY clause */
003066 }
003067 /* Do not need to test for a HAVING clause. If HAVING is present but
003068 ** there is no ORDER BY, we will get an error. */
003069 if( pSelect->pGroupBy ){
003070 return 0; /* SELECT may not have a GROUP BY clause */
003071 }
003072 if( pSelect->pLimit ){
003073 return 0; /* SELECT may not have a LIMIT clause */
003074 }
003075 if( pSelect->pPrior ){
003076 return 0; /* SELECT may not be a compound query */
003077 }
003078 if( pSelect->selFlags & SF_Distinct ){
003079 return 0; /* SELECT may not be DISTINCT */
003080 }
003081 pEList = pSelect->pEList;
003082 assert( pEList!=0 );
003083 if( pEList->nExpr!=1 ){
003084 return 0; /* The result set must have exactly one column */
003085 }
003086 assert( pEList->a[0].pExpr );
003087 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
003088 return 0; /* The result set must be the special operator "*" */
003089 }
003090
003091 /* At this point we have established that the statement is of the
003092 ** correct syntactic form to participate in this optimization. Now
003093 ** we have to check the semantics.
003094 */
003095 pItem = pSelect->pSrc->a;
003096 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
003097 if( pSrc==0 ){
003098 return 0; /* FROM clause does not contain a real table */
003099 }
003100 if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
003101 testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
003102 return 0; /* tab1 and tab2 may not be the same table */
003103 }
003104 if( HasRowid(pDest)!=HasRowid(pSrc) ){
003105 return 0; /* source and destination must both be WITHOUT ROWID or not */
003106 }
003107 if( !IsOrdinaryTable(pSrc) ){
003108 return 0; /* tab2 may not be a view or virtual table */
003109 }
003110 if( pDest->nCol!=pSrc->nCol ){
003111 return 0; /* Number of columns must be the same in tab1 and tab2 */
003112 }
003113 if( pDest->iPKey!=pSrc->iPKey ){
003114 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
003115 }
003116 if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
003117 return 0; /* Cannot feed from a non-strict into a strict table */
003118 }
003119 for(i=0; i<pDest->nCol; i++){
003120 Column *pDestCol = &pDest->aCol[i];
003121 Column *pSrcCol = &pSrc->aCol[i];
003122 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
003123 if( (db->mDbFlags & DBFLAG_Vacuum)==0
003124 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
003125 ){
003126 return 0; /* Neither table may have __hidden__ columns */
003127 }
003128 #endif
003129 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
003130 /* Even if tables t1 and t2 have identical schemas, if they contain
003131 ** generated columns, then this statement is semantically incorrect:
003132 **
003133 ** INSERT INTO t2 SELECT * FROM t1;
003134 **
003135 ** The reason is that generated column values are returned by the
003136 ** the SELECT statement on the right but the INSERT statement on the
003137 ** left wants them to be omitted.
003138 **
003139 ** Nevertheless, this is a useful notational shorthand to tell SQLite
003140 ** to do a bulk transfer all of the content from t1 over to t2.
003141 **
003142 ** We could, in theory, disable this (except for internal use by the
003143 ** VACUUM command where it is actually needed). But why do that? It
003144 ** seems harmless enough, and provides a useful service.
003145 */
003146 if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
003147 (pSrcCol->colFlags & COLFLAG_GENERATED) ){
003148 return 0; /* Both columns have the same generated-column type */
003149 }
003150 /* But the transfer is only allowed if both the source and destination
003151 ** tables have the exact same expressions for generated columns.
003152 ** This requirement could be relaxed for VIRTUAL columns, I suppose.
003153 */
003154 if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
003155 if( sqlite3ExprCompare(0,
003156 sqlite3ColumnExpr(pSrc, pSrcCol),
003157 sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
003158 testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
003159 testcase( pDestCol->colFlags & COLFLAG_STORED );
003160 return 0; /* Different generator expressions */
003161 }
003162 }
003163 #endif
003164 if( pDestCol->affinity!=pSrcCol->affinity ){
003165 return 0; /* Affinity must be the same on all columns */
003166 }
003167 if( sqlite3_stricmp(sqlite3ColumnColl(pDestCol),
003168 sqlite3ColumnColl(pSrcCol))!=0 ){
003169 return 0; /* Collating sequence must be the same on all columns */
003170 }
003171 if( pDestCol->notNull && !pSrcCol->notNull ){
003172 return 0; /* tab2 must be NOT NULL if tab1 is */
003173 }
003174 /* Default values for second and subsequent columns need to match. */
003175 if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
003176 Expr *pDestExpr = sqlite3ColumnExpr(pDest, pDestCol);
003177 Expr *pSrcExpr = sqlite3ColumnExpr(pSrc, pSrcCol);
003178 assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
003179 assert( pDestExpr==0 || !ExprHasProperty(pDestExpr, EP_IntValue) );
003180 assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
003181 assert( pSrcExpr==0 || !ExprHasProperty(pSrcExpr, EP_IntValue) );
003182 if( (pDestExpr==0)!=(pSrcExpr==0)
003183 || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
003184 pSrcExpr->u.zToken)!=0)
003185 ){
003186 return 0; /* Default values must be the same for all columns */
003187 }
003188 }
003189 }
003190 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
003191 if( IsUniqueIndex(pDestIdx) ){
003192 destHasUniqueIdx = 1;
003193 }
003194 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
003195 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
003196 }
003197 if( pSrcIdx==0 ){
003198 return 0; /* pDestIdx has no corresponding index in pSrc */
003199 }
003200 if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
003201 && sqlite3FaultSim(411)==SQLITE_OK ){
003202 /* The sqlite3FaultSim() call allows this corruption test to be
003203 ** bypassed during testing, in order to exercise other corruption tests
003204 ** further downstream. */
003205 return 0; /* Corrupt schema - two indexes on the same btree */
003206 }
003207 }
003208 #ifndef SQLITE_OMIT_CHECK
003209 if( pDest->pCheck
003210 && (db->mDbFlags & DBFLAG_Vacuum)==0
003211 && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1)
003212 ){
003213 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
003214 }
003215 #endif
003216 #ifndef SQLITE_OMIT_FOREIGN_KEY
003217 /* Disallow the transfer optimization if the destination table contains
003218 ** any foreign key constraints. This is more restrictive than necessary.
003219 ** But the main beneficiary of the transfer optimization is the VACUUM
003220 ** command, and the VACUUM command disables foreign key constraints. So
003221 ** the extra complication to make this rule less restrictive is probably
003222 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
003223 */
003224 assert( IsOrdinaryTable(pDest) );
003225 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
003226 return 0;
003227 }
003228 #endif
003229 if( (db->flags & SQLITE_CountRows)!=0 ){
003230 return 0; /* xfer opt does not play well with PRAGMA count_changes */
003231 }
003232
003233 /* If we get this far, it means that the xfer optimization is at
003234 ** least a possibility, though it might only work if the destination
003235 ** table (tab1) is initially empty.
003236 */
003237 #ifdef SQLITE_TEST
003238 sqlite3_xferopt_count++;
003239 #endif
003240 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
003241 v = sqlite3GetVdbe(pParse);
003242 sqlite3CodeVerifySchema(pParse, iDbSrc);
003243 iSrc = pParse->nTab++;
003244 iDest = pParse->nTab++;
003245 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
003246 regData = sqlite3GetTempReg(pParse);
003247 sqlite3VdbeAddOp2(v, OP_Null, 0, regData);
003248 regRowid = sqlite3GetTempReg(pParse);
003249 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
003250 assert( HasRowid(pDest) || destHasUniqueIdx );
003251 if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
003252 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
003253 || destHasUniqueIdx /* (2) */
003254 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
003255 )){
003256 /* In some circumstances, we are able to run the xfer optimization
003257 ** only if the destination table is initially empty. Unless the
003258 ** DBFLAG_Vacuum flag is set, this block generates code to make
003259 ** that determination. If DBFLAG_Vacuum is set, then the destination
003260 ** table is always empty.
003261 **
003262 ** Conditions under which the destination must be empty:
003263 **
003264 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
003265 ** (If the destination is not initially empty, the rowid fields
003266 ** of index entries might need to change.)
003267 **
003268 ** (2) The destination has a unique index. (The xfer optimization
003269 ** is unable to test uniqueness.)
003270 **
003271 ** (3) onError is something other than OE_Abort and OE_Rollback.
003272 */
003273 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
003274 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
003275 sqlite3VdbeJumpHere(v, addr1);
003276 }
003277 if( HasRowid(pSrc) ){
003278 u8 insFlags;
003279 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
003280 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
003281 if( pDest->iPKey>=0 ){
003282 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
003283 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
003284 sqlite3VdbeVerifyAbortable(v, onError);
003285 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
003286 VdbeCoverage(v);
003287 sqlite3RowidConstraint(pParse, onError, pDest);
003288 sqlite3VdbeJumpHere(v, addr2);
003289 }
003290 autoIncStep(pParse, regAutoinc, regRowid);
003291 }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
003292 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
003293 }else{
003294 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
003295 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
003296 }
003297
003298 if( db->mDbFlags & DBFLAG_Vacuum ){
003299 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
003300 insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
003301 }else{
003302 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT;
003303 }
003304 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
003305 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
003306 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
003307 insFlags &= ~OPFLAG_PREFORMAT;
003308 }else
003309 #endif
003310 {
003311 sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid);
003312 }
003313 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
003314 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
003315 sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
003316 }
003317 sqlite3VdbeChangeP5(v, insFlags);
003318
003319 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
003320 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
003321 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
003322 }else{
003323 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
003324 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
003325 }
003326 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
003327 u8 idxInsFlags = 0;
003328 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
003329 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
003330 }
003331 assert( pSrcIdx );
003332 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
003333 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
003334 VdbeComment((v, "%s", pSrcIdx->zName));
003335 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
003336 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
003337 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
003338 VdbeComment((v, "%s", pDestIdx->zName));
003339 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
003340 if( db->mDbFlags & DBFLAG_Vacuum ){
003341 /* This INSERT command is part of a VACUUM operation, which guarantees
003342 ** that the destination table is empty. If all indexed columns use
003343 ** collation sequence BINARY, then it can also be assumed that the
003344 ** index will be populated by inserting keys in strictly sorted
003345 ** order. In this case, instead of seeking within the b-tree as part
003346 ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
003347 ** OP_IdxInsert to seek to the point within the b-tree where each key
003348 ** should be inserted. This is faster.
003349 **
003350 ** If any of the indexed columns use a collation sequence other than
003351 ** BINARY, this optimization is disabled. This is because the user
003352 ** might change the definition of a collation sequence and then run
003353 ** a VACUUM command. In that case keys may not be written in strictly
003354 ** sorted order. */
003355 for(i=0; i<pSrcIdx->nColumn; i++){
003356 const char *zColl = pSrcIdx->azColl[i];
003357 if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
003358 }
003359 if( i==pSrcIdx->nColumn ){
003360 idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
003361 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
003362 sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc);
003363 }
003364 }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
003365 idxInsFlags |= OPFLAG_NCHANGE;
003366 }
003367 if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){
003368 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
003369 if( (db->mDbFlags & DBFLAG_Vacuum)==0
003370 && !HasRowid(pDest)
003371 && IsPrimaryKeyIndex(pDestIdx)
003372 ){
003373 codeWithoutRowidPreupdate(pParse, pDest, iDest, regData);
003374 }
003375 }
003376 sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
003377 sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
003378 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
003379 sqlite3VdbeJumpHere(v, addr1);
003380 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
003381 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
003382 }
003383 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
003384 sqlite3ReleaseTempReg(pParse, regRowid);
003385 sqlite3ReleaseTempReg(pParse, regData);
003386 if( emptyDestTest ){
003387 sqlite3AutoincrementEnd(pParse);
003388 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
003389 sqlite3VdbeJumpHere(v, emptyDestTest);
003390 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
003391 return 0;
003392 }else{
003393 return 1;
003394 }
003395 }
003396 #endif /* SQLITE_OMIT_XFER_OPT */