interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / insert.c

3513 lines · 134638 bytes Raw Blame History
1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains C code routines that are called by the parser
13** to handle INSERT statements in SQLite.
14*/
15#include "sqliteInt.h"
16
17/*
18** Generate code that will
19**
20** (1) acquire a lock for table pTab then
21** (2) open pTab as cursor iCur.
22**
23** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
24** for that table that is actually opened.
25*/
26void sqlite3OpenTable(
27 Parse *pParse, /* Generate code into this VDBE */
28 int iCur, /* The cursor number of the table */
29 int iDb, /* The database index in sqlite3.aDb[] */
30 Table *pTab, /* The table to be opened */
31 int opcode /* OP_OpenRead or OP_OpenWrite */
32){
33 Vdbe *v;
34 assert( !IsVirtual(pTab) );
35 assert( pParse->pVdbe!=0 );
36 v = pParse->pVdbe;
37 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
38 if( !pParse->db->noSharedCache ){
39 sqlite3TableLock(pParse, iDb, pTab->tnum,
40 (opcode==OP_OpenWrite)?1:0, pTab->zName);
41 }
42 if( HasRowid(pTab) ){
43 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
44 VdbeComment((v, "%s", pTab->zName));
45 }else{
46 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
47 assert( pPk!=0 );
48 assert( pPk->tnum==pTab->tnum || CORRUPT_DB );
49 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
50 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
51 VdbeComment((v, "%s", pTab->zName));
52 }
53}
54
55/*
56** Return a pointer to the column affinity string associated with index
57** pIdx. A column affinity string has one character for each column in
58** the table, according to the affinity of the column:
59**
60** Character Column affinity
61** ------------------------------
62** 'A' BLOB
63** 'B' TEXT
64** 'C' NUMERIC
65** 'D' INTEGER
66** 'F' REAL
67**
68** An extra 'D' is appended to the end of the string to cover the
69** rowid that appears as the last column in every index.
70**
71** Memory for the buffer containing the column index affinity string
72** is managed along with the rest of the Index structure. It will be
73** released when sqlite3DeleteIndex() is called.
74*/
75static SQLITE_NOINLINE const char *computeIndexAffStr(sqlite3 *db, Index *pIdx){
76 /* The first time a column affinity string for a particular index is
77 ** required, it is allocated and populated here. It is then stored as
78 ** a member of the Index structure for subsequent use.
79 **
80 ** The column affinity string will eventually be deleted by
81 ** sqliteDeleteIndex() when the Index structure itself is cleaned
82 ** up.
83 */
84 int n;
85 Table *pTab = pIdx->pTable;
86 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
87 if( !pIdx->zColAff ){
88 sqlite3OomFault(db);
89 return 0;
90 }
91 for(n=0; n<pIdx->nColumn; n++){
92 i16 x = pIdx->aiColumn[n];
93 char aff;
94 if( x>=0 ){
95 aff = pTab->aCol[x].affinity;
96 }else if( x==XN_ROWID ){
97 aff = SQLITE_AFF_INTEGER;
98 }else{
99 assert( x==XN_EXPR );
100 assert( pIdx->bHasExpr );
101 assert( pIdx->aColExpr!=0 );
102 aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
103 }
104 if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
105 if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
106 pIdx->zColAff[n] = aff;
107 }
108 pIdx->zColAff[n] = 0;
109 return pIdx->zColAff;
110}
111const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
112 if( !pIdx->zColAff ) return computeIndexAffStr(db, pIdx);
113 return pIdx->zColAff;
114}
115
116
117/*
118** Compute an affinity string for a table. Space is obtained
119** from sqlite3DbMalloc(). The caller is responsible for freeing
120** the space when done.
121*/
122char *sqlite3TableAffinityStr(sqlite3 *db, const Table *pTab){
123 char *zColAff;
124 zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1);
125 if( zColAff ){
126 int i, j;
127 for(i=j=0; i<pTab->nCol; i++){
128 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
129 zColAff[j++] = pTab->aCol[i].affinity;
130 }
131 }
132 do{
133 zColAff[j--] = 0;
134 }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );
135 }
136 return zColAff;
137}
138
139/*
140** Make changes to the evolving bytecode to do affinity transformations
141** of values that are about to be gathered into a row for table pTab.
142**
143** For ordinary (legacy, non-strict) tables:
144** -----------------------------------------
145**
146** Compute the affinity string for table pTab, if it has not already been
147** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
148**
149** If the affinity string is empty (because it was all SQLITE_AFF_BLOB entries
150** which were then optimized out) then this routine becomes a no-op.
151**
152** Otherwise if iReg>0 then code an OP_Affinity opcode that will set the
153** affinities for register iReg and following. Or if iReg==0,
154** then just set the P4 operand of the previous opcode (which should be
155** an OP_MakeRecord) to the affinity string.
156**
157** A column affinity string has one character per column:
158**
159** Character Column affinity
160** --------- ---------------
161** 'A' BLOB
162** 'B' TEXT
163** 'C' NUMERIC
164** 'D' INTEGER
165** 'E' REAL
166**
167** For STRICT tables:
168** ------------------
169**
170** Generate an appropriate OP_TypeCheck opcode that will verify the
171** datatypes against the column definitions in pTab. If iReg==0, that
172** means an OP_MakeRecord opcode has already been generated and should be
173** the last opcode generated. The new OP_TypeCheck needs to be inserted
174** before the OP_MakeRecord. The new OP_TypeCheck should use the same
175** register set as the OP_MakeRecord. If iReg>0 then register iReg is
176** the first of a series of registers that will form the new record.
177** Apply the type checking to that array of registers.
178*/
179void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
180 int i;
181 char *zColAff;
182 if( pTab->tabFlags & TF_Strict ){
183 if( iReg==0 ){
184 /* Move the previous opcode (which should be OP_MakeRecord) forward
185 ** by one slot and insert a new OP_TypeCheck where the current
186 ** OP_MakeRecord is found */
187 VdbeOp *pPrev;
188 int p3;
189 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
190 pPrev = sqlite3VdbeGetLastOp(v);
191 assert( pPrev!=0 );
192 assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );
193 pPrev->opcode = OP_TypeCheck;
194 p3 = pPrev->p3;
195 pPrev->p3 = 0;
196 sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, p3);
197 }else{
198 /* Insert an isolated OP_Typecheck */
199 sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol);
200 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
201 }
202 return;
203 }
204 zColAff = pTab->zColAff;
205 if( zColAff==0 ){
206 zColAff = sqlite3TableAffinityStr(0, pTab);
207 if( !zColAff ){
208 sqlite3OomFault(sqlite3VdbeDb(v));
209 return;
210 }
211 pTab->zColAff = zColAff;
212 }
213 assert( zColAff!=0 );
214 i = sqlite3Strlen30NN(zColAff);
215 if( i ){
216 if( iReg ){
217 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
218 }else{
219 assert( sqlite3VdbeGetLastOp(v)->opcode==OP_MakeRecord
220 || sqlite3VdbeDb(v)->mallocFailed );
221 sqlite3VdbeChangeP4(v, -1, zColAff, i);
222 }
223 }
224}
225
226/*
227** Return non-zero if the table pTab in database iDb or any of its indices
228** have been opened at any point in the VDBE program. This is used to see if
229** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
230** run without using a temporary table for the results of the SELECT.
231*/
232static int readsTable(Parse *p, int iDb, Table *pTab){
233 Vdbe *v = sqlite3GetVdbe(p);
234 int i;
235 int iEnd = sqlite3VdbeCurrentAddr(v);
236#ifndef SQLITE_OMIT_VIRTUALTABLE
237 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
238#endif
239
240 for(i=1; i<iEnd; i++){
241 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
242 assert( pOp!=0 );
243 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
244 Index *pIndex;
245 Pgno tnum = pOp->p2;
246 if( tnum==pTab->tnum ){
247 return 1;
248 }
249 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
250 if( tnum==pIndex->tnum ){
251 return 1;
252 }
253 }
254 }
255#ifndef SQLITE_OMIT_VIRTUALTABLE
256 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
257 assert( pOp->p4.pVtab!=0 );
258 assert( pOp->p4type==P4_VTAB );
259 return 1;
260 }
261#endif
262 }
263 return 0;
264}
265
266/* This walker callback will compute the union of colFlags flags for all
267** referenced columns in a CHECK constraint or generated column expression.
268*/
269static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
270 if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
271 assert( pExpr->iColumn < pWalker->u.pTab->nCol );
272 pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
273 }
274 return WRC_Continue;
275}
276
277#ifndef SQLITE_OMIT_GENERATED_COLUMNS
278/*
279** All regular columns for table pTab have been puts into registers
280** starting with iRegStore. The registers that correspond to STORED
281** or VIRTUAL columns have not yet been initialized. This routine goes
282** back and computes the values for those columns based on the previously
283** computed normal columns.
284*/
285void sqlite3ComputeGeneratedColumns(
286 Parse *pParse, /* Parsing context */
287 int iRegStore, /* Register holding the first column */
288 Table *pTab /* The table */
289){
290 int i;
291 Walker w;
292 Column *pRedo;
293 int eProgress;
294 VdbeOp *pOp;
295
296 assert( pTab->tabFlags & TF_HasGenerated );
297 testcase( pTab->tabFlags & TF_HasVirtual );
298 testcase( pTab->tabFlags & TF_HasStored );
299
300 /* Before computing generated columns, first go through and make sure
301 ** that appropriate affinity has been applied to the regular columns
302 */
303 sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
304 if( (pTab->tabFlags & TF_HasStored)!=0 ){
305 pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
306 if( pOp->opcode==OP_Affinity ){
307 /* Change the OP_Affinity argument to '@' (NONE) for all stored
308 ** columns. '@' is the no-op affinity and those columns have not
309 ** yet been computed. */
310 int ii, jj;
311 char *zP4 = pOp->p4.z;
312 assert( zP4!=0 );
313 assert( pOp->p4type==P4_DYNAMIC );
314 for(ii=jj=0; zP4[jj]; ii++){
315 if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
316 continue;
317 }
318 if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
319 zP4[jj] = SQLITE_AFF_NONE;
320 }
321 jj++;
322 }
323 }else if( pOp->opcode==OP_TypeCheck ){
324 /* If an OP_TypeCheck was generated because the table is STRICT,
325 ** then set the P3 operand to indicate that generated columns should
326 ** not be checked */
327 pOp->p3 = 1;
328 }
329 }
330
331 /* Because there can be multiple generated columns that refer to one another,
332 ** this is a two-pass algorithm. On the first pass, mark all generated
333 ** columns as "not available".
334 */
335 for(i=0; i<pTab->nCol; i++){
336 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
337 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
338 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
339 pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
340 }
341 }
342
343 w.u.pTab = pTab;
344 w.xExprCallback = exprColumnFlagUnion;
345 w.xSelectCallback = 0;
346 w.xSelectCallback2 = 0;
347
348 /* On the second pass, compute the value of each NOT-AVAILABLE column.
349 ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will
350 ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as
351 ** they are needed.
352 */
353 pParse->iSelfTab = -iRegStore;
354 do{
355 eProgress = 0;
356 pRedo = 0;
357 for(i=0; i<pTab->nCol; i++){
358 Column *pCol = pTab->aCol + i;
359 if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
360 int x;
361 pCol->colFlags |= COLFLAG_BUSY;
362 w.eCode = 0;
363 sqlite3WalkExpr(&w, sqlite3ColumnExpr(pTab, pCol));
364 pCol->colFlags &= ~COLFLAG_BUSY;
365 if( w.eCode & COLFLAG_NOTAVAIL ){
366 pRedo = pCol;
367 continue;
368 }
369 eProgress = 1;
370 assert( pCol->colFlags & COLFLAG_GENERATED );
371 x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
372 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, x);
373 pCol->colFlags &= ~COLFLAG_NOTAVAIL;
374 }
375 }
376 }while( pRedo && eProgress );
377 if( pRedo ){
378 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zCnName);
379 }
380 pParse->iSelfTab = 0;
381}
382#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
383
384
385#ifndef SQLITE_OMIT_AUTOINCREMENT
386/*
387** Locate or create an AutoincInfo structure associated with table pTab
388** which is in database iDb. Return the register number for the register
389** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
390** table. (Also return zero when doing a VACUUM since we do not want to
391** update the AUTOINCREMENT counters during a VACUUM.)
392**
393** There is at most one AutoincInfo structure per table even if the
394** same table is autoincremented multiple times due to inserts within
395** triggers. A new AutoincInfo structure is created if this is the
396** first use of table pTab. On 2nd and subsequent uses, the original
397** AutoincInfo structure is used.
398**
399** Four consecutive registers are allocated:
400**
401** (1) The name of the pTab table.
402** (2) The maximum ROWID of pTab.
403** (3) The rowid in sqlite_sequence of pTab
404** (4) The original value of the max ROWID in pTab, or NULL if none
405**
406** The 2nd register is the one that is returned. That is all the
407** insert routine needs to know about.
408*/
409static int autoIncBegin(
410 Parse *pParse, /* Parsing context */
411 int iDb, /* Index of the database holding pTab */
412 Table *pTab /* The table we are writing to */
413){
414 int memId = 0; /* Register holding maximum rowid */
415 assert( pParse->db->aDb[iDb].pSchema!=0 );
416 if( (pTab->tabFlags & TF_Autoincrement)!=0
417 && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
418 ){
419 Parse *pToplevel = sqlite3ParseToplevel(pParse);
420 AutoincInfo *pInfo;
421 Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
422
423 /* Verify that the sqlite_sequence table exists and is an ordinary
424 ** rowid table with exactly two columns.
425 ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
426 if( pSeqTab==0
427 || !HasRowid(pSeqTab)
428 || NEVER(IsVirtual(pSeqTab))
429 || pSeqTab->nCol!=2
430 ){
431 pParse->nErr++;
432 pParse->rc = SQLITE_CORRUPT_SEQUENCE;
433 return 0;
434 }
435
436 if( pToplevel->usesAinc==0 ){
437 pToplevel->pAinc = 0;
438 }
439 pInfo = pToplevel->pAinc;
440 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
441 if( pInfo==0 ){
442 pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
443 sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
444 testcase( pParse->earlyCleanup );
445 if( pParse->db->mallocFailed ) return 0;
446 pInfo->pNext = pToplevel->pAinc;
447 pToplevel->pAinc = pInfo;
448 pToplevel->usesAinc = 1;
449 pInfo->pTab = pTab;
450 pInfo->iDb = iDb;
451 pToplevel->nMem++; /* Register to hold name of table */
452 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
453 pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
454 }
455 memId = pInfo->regCtr;
456 }
457 return memId;
458}
459
460/*
461** This routine generates code that will initialize all of the
462** register used by the autoincrement tracker.
463*/
464void sqlite3AutoincrementBegin(Parse *pParse){
465 AutoincInfo *p; /* Information about an AUTOINCREMENT */
466 sqlite3 *db = pParse->db; /* The database connection */
467 Db *pDb; /* Database only autoinc table */
468 int memId; /* Register holding max rowid */
469 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
470
471 /* This routine is never called during trigger-generation. It is
472 ** only called from the top-level */
473 assert( pParse->pTriggerTab==0 );
474 assert( sqlite3IsToplevel(pParse) );
475
476 assert( v ); /* We failed long ago if this is not so */
477 assert( pParse->usesAinc );
478 for(p = pParse->pAinc; p; p = p->pNext){
479 static const int iLn = VDBE_OFFSET_LINENO(2);
480 static const VdbeOpList autoInc[] = {
481 /* 0 */ {OP_Null, 0, 0, 0},
482 /* 1 */ {OP_Rewind, 0, 10, 0},
483 /* 2 */ {OP_Column, 0, 0, 0},
484 /* 3 */ {OP_Ne, 0, 9, 0},
485 /* 4 */ {OP_Rowid, 0, 0, 0},
486 /* 5 */ {OP_Column, 0, 1, 0},
487 /* 6 */ {OP_AddImm, 0, 0, 0},
488 /* 7 */ {OP_Copy, 0, 0, 0},
489 /* 8 */ {OP_Goto, 0, 11, 0},
490 /* 9 */ {OP_Next, 0, 2, 0},
491 /* 10 */ {OP_Integer, 0, 0, 0},
492 /* 11 */ {OP_Close, 0, 0, 0}
493 };
494 VdbeOp *aOp;
495 pDb = &db->aDb[p->iDb];
496 memId = p->regCtr;
497 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
498 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
499 sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
500 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
501 if( aOp==0 ) break;
502 aOp[0].p2 = memId;
503 aOp[0].p3 = memId+2;
504 aOp[2].p3 = memId;
505 aOp[3].p1 = memId-1;
506 aOp[3].p3 = memId;
507 aOp[3].p5 = SQLITE_JUMPIFNULL;
508 aOp[4].p2 = memId+1;
509 aOp[5].p3 = memId;
510 aOp[6].p1 = memId;
511 aOp[7].p2 = memId+2;
512 aOp[7].p1 = memId;
513 aOp[10].p2 = memId;
514 if( pParse->nTab==0 ) pParse->nTab = 1;
515 }
516}
517
518/*
519** Update the maximum rowid for an autoincrement calculation.
520**
521** This routine should be called when the regRowid register holds a
522** new rowid that is about to be inserted. If that new rowid is
523** larger than the maximum rowid in the memId memory cell, then the
524** memory cell is updated.
525*/
526static void autoIncStep(Parse *pParse, int memId, int regRowid){
527 if( memId>0 ){
528 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
529 }
530}
531
532/*
533** This routine generates the code needed to write autoincrement
534** maximum rowid values back into the sqlite_sequence register.
535** Every statement that might do an INSERT into an autoincrement
536** table (either directly or through triggers) needs to call this
537** routine just before the "exit" code.
538*/
539static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
540 AutoincInfo *p;
541 Vdbe *v = pParse->pVdbe;
542 sqlite3 *db = pParse->db;
543
544 assert( v );
545 assert( pParse->usesAinc );
546 for(p = pParse->pAinc; p; p = p->pNext){
547 static const int iLn = VDBE_OFFSET_LINENO(2);
548 static const VdbeOpList autoIncEnd[] = {
549 /* 0 */ {OP_NotNull, 0, 2, 0},
550 /* 1 */ {OP_NewRowid, 0, 0, 0},
551 /* 2 */ {OP_MakeRecord, 0, 2, 0},
552 /* 3 */ {OP_Insert, 0, 0, 0},
553 /* 4 */ {OP_Close, 0, 0, 0}
554 };
555 VdbeOp *aOp;
556 Db *pDb = &db->aDb[p->iDb];
557 int iRec;
558 int memId = p->regCtr;
559
560 iRec = sqlite3GetTempReg(pParse);
561 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
562 sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
563 VdbeCoverage(v);
564 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
565 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
566 if( aOp==0 ) break;
567 aOp[0].p1 = memId+1;
568 aOp[1].p2 = memId+1;
569 aOp[2].p1 = memId-1;
570 aOp[2].p3 = iRec;
571 aOp[3].p2 = iRec;
572 aOp[3].p3 = memId+1;
573 aOp[3].p5 = OPFLAG_APPEND;
574 sqlite3ReleaseTempReg(pParse, iRec);
575 }
576}
577void sqlite3AutoincrementEnd(Parse *pParse){
578 if( pParse->usesAinc ) autoIncrementEnd(pParse);
579}
580#else
581/*
582** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
583** above are all no-ops
584*/
585# define autoIncBegin(A,B,C) (0)
586# define autoIncStep(A,B,C)
587#endif /* SQLITE_OMIT_AUTOINCREMENT */
588
589/*
590** If argument pVal is a Select object returned by an sqlite3MultiValues()
591** that was able to use the co-routine optimization, finish coding the
592** co-routine.
593*/
594void sqlite3MultiValuesEnd(Parse *pParse, Select *pVal){
595 if( ALWAYS(pVal) && pVal->pSrc->nSrc>0 ){
596 SrcItem *pItem = &pVal->pSrc->a[0];
597 assert( (pItem->fg.isSubquery && pItem->u4.pSubq!=0) || pParse->nErr );
598 if( pItem->fg.isSubquery ){
599 sqlite3VdbeEndCoroutine(pParse->pVdbe, pItem->u4.pSubq->regReturn);
600 sqlite3VdbeJumpHere(pParse->pVdbe, pItem->u4.pSubq->addrFillSub - 1);
601 }
602 }
603}
604
605/*
606** Return true if all expressions in the expression-list passed as the
607** only argument are both constant and have no affinity.
608*/
609static int exprListIsNoAffinity(Parse *pParse, ExprList *pRow){
610 int ii;
611 if( sqlite3ExprListIsConstant(pParse, pRow, 0)==0 ) return 0;
612 for(ii=0; ii<pRow->nExpr; ii++){
613 Expr *pExpr = pRow->a[ii].pExpr;
614 assert( pExpr->op!=TK_RAISE );
615 assert( pExpr->affExpr==0 );
616 if( 0!=sqlite3ExprAffinity(pExpr) ) return 0;
617 }
618 return 1;
619
620}
621
622/*
623** Return true if any expression in the expression-list passed as the
624** only argument contains a COLLATE operator.
625*/
626static int exprListHasCollate(ExprList *pRow){
627 int ii;
628 for(ii=0; ii<pRow->nExpr; ii++){
629 if( ExprHasProperty(pRow->a[ii].pExpr, EP_Collate) ) return 1;
630 }
631 return 0;
632}
633
634/*
635** This function is called by the parser for the second and subsequent
636** rows of a multi-row VALUES clause. Argument pLeft is the part of
637** the VALUES clause already parsed, argument pRow is the vector of values
638** for the new row. The Select object returned represents the complete
639** VALUES clause, including the new row.
640**
641** There are two ways in which this may be achieved - by incremental
642** coding of a co-routine (the "co-routine" method) or by returning a
643** Select object equivalent to the following (the "UNION ALL" method):
644**
645** "pLeft UNION ALL SELECT pRow"
646**
647** If the VALUES clause contains a lot of rows, this compound Select
648** object may consume a lot of memory.
649**
650** When the co-routine method is used, each row that will be returned
651** by the VALUES clause is coded into part of a co-routine as it is
652** passed to this function. The returned Select object is equivalent to:
653**
654** SELECT * FROM (
655** Select object to read co-routine
656** )
657**
658** The co-routine method is used in most cases. Exceptions are:
659**
660** a) If the current statement has a WITH clause. This is to avoid
661** statements like:
662**
663** WITH cte AS ( VALUES('x'), ('y') ... )
664** SELECT * FROM cte AS a, cte AS b;
665**
666** This will not work, as the co-routine uses a hard-coded register
667** for its OP_Yield instructions, and so it is not possible for two
668** cursors to iterate through it concurrently.
669**
670** b) The schema is currently being parsed (i.e. the VALUES clause is part
671** of a schema item like a VIEW or TRIGGER). In this case there is no VM
672** being generated when parsing is taking place, and so generating
673** a co-routine is not possible.
674**
675** c) There are non-constant expressions in the VALUES clause (e.g.
676** the VALUES clause is part of a correlated sub-query).
677**
678** d) One or more of the values in the first row of the VALUES clause
679** has an affinity (i.e. is a CAST expression). This causes problems
680** because the complex rules SQLite uses (see function
681** sqlite3SubqueryColumnTypes() in select.c) to determine the effective
682** affinity of such a column for all rows require access to all values in
683** the column simultaneously.
684**
685** e) The new row, or the row that would become the first row of the
686** co-routine, contains a COLLATE operator. This ensures that the
687** columns of a co-routine never have a collation sequence (see
688** multiSelectCollSeq() in select.c). Each explicit COLLATE in a VALUES
689** clause is instead part of an ordinary SELECT in a UNION ALL
690** compound, where it is available when the collation sequence for a
691** compound SELECT column is determined.
692*/
693Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow){
694
695 if( pParse->bHasWith /* condition (a) above */
696 || pParse->db->init.busy /* condition (b) above */
697 || sqlite3ExprListIsConstant(pParse, pRow, 1)==0 /* condition (c) above */
698 || (pLeft->pSrc->nSrc==0 &&
699 exprListIsNoAffinity(pParse,pLeft->pEList)==0) /* condition (d) above */
700 || exprListHasCollate(pRow) /* condition (e) above */
701 || (pLeft->pSrc->nSrc==0 && exprListHasCollate(pLeft->pEList))
702 || IN_SPECIAL_PARSE
703 ){
704 /* The co-routine method cannot be used. Fall back to UNION ALL. */
705 Select *pSelect = 0;
706 int f = SF_Values | SF_MultiValue;
707 if( pLeft->pSrc->nSrc ){
708 sqlite3MultiValuesEnd(pParse, pLeft);
709 f = SF_Values;
710 }else if( pLeft->pPrior ){
711 /* In this case set the SF_MultiValue flag only if it was set on pLeft */
712 f = (f & pLeft->selFlags);
713 }
714 pSelect = sqlite3SelectNew(pParse, pRow, 0, 0, 0, 0, 0, f, 0);
715 pLeft->selFlags &= ~(u32)SF_MultiValue;
716 if( pSelect ){
717 pSelect->op = TK_ALL;
718 pSelect->pPrior = pLeft;
719 pLeft = pSelect;
720 }
721 }else{
722 SrcItem *p = 0; /* SrcItem that reads from co-routine */
723
724 if( pLeft->pSrc->nSrc==0 ){
725 /* Co-routine has not yet been started and the special Select object
726 ** that accesses the co-routine has not yet been created. This block
727 ** does both those things. */
728 Vdbe *v = sqlite3GetVdbe(pParse);
729 Select *pRet = sqlite3SelectNew(pParse, 0, 0, 0, 0, 0, 0, 0, 0);
730
731 /* Ensure the database schema has been read. This is to ensure we have
732 ** the correct text encoding. */
733 if( (pParse->db->mDbFlags & DBFLAG_SchemaKnownOk)==0 ){
734 sqlite3ReadSchema(pParse);
735 }
736
737 if( pRet ){
738 SelectDest dest;
739 Subquery *pSubq;
740 pRet->pSrc->nSrc = 1;
741 pRet->pPrior = pLeft->pPrior;
742 pRet->op = pLeft->op;
743 pRet->selFlags |= SF_Values;
744 pLeft->pPrior = 0;
745 pLeft->op = TK_SELECT;
746 assert( pLeft->pNext==0 );
747 assert( pRet->pNext==0 );
748 p = &pRet->pSrc->a[0];
749 p->fg.viaCoroutine = 1;
750 p->iCursor = -1;
751 assert( !p->fg.isIndexedBy && !p->fg.isTabFunc );
752 p->u1.nRow = 2;
753 if( sqlite3SrcItemAttachSubquery(pParse, p, pLeft, 0) ){
754 pSubq = p->u4.pSubq;
755 pSubq->addrFillSub = sqlite3VdbeCurrentAddr(v) + 1;
756 pSubq->regReturn = ++pParse->nMem;
757 sqlite3VdbeAddOp3(v, OP_InitCoroutine,
758 pSubq->regReturn, 0, pSubq->addrFillSub);
759 sqlite3SelectDestInit(&dest, SRT_Coroutine, pSubq->regReturn);
760
761 /* Allocate registers for the output of the co-routine. Do so so
762 ** that there are two unused registers immediately before those
763 ** used by the co-routine. This allows the code in sqlite3Insert()
764 ** to use these registers directly, instead of copying the output
765 ** of the co-routine to a separate array for processing. */
766 dest.iSdst = pParse->nMem + 3;
767 dest.nSdst = pLeft->pEList->nExpr;
768 pParse->nMem += 2 + dest.nSdst;
769
770 pLeft->selFlags |= SF_MultiValue;
771 sqlite3Select(pParse, pLeft, &dest);
772 pSubq->regResult = dest.iSdst;
773 assert( pParse->nErr || dest.iSdst>0 );
774 }
775 pLeft = pRet;
776 }
777 }else{
778 p = &pLeft->pSrc->a[0];
779 assert( !p->fg.isTabFunc && !p->fg.isIndexedBy );
780 p->u1.nRow++;
781 }
782
783 if( pParse->nErr==0 ){
784 Subquery *pSubq;
785 assert( p!=0 );
786 assert( p->fg.isSubquery );
787 pSubq = p->u4.pSubq;
788 assert( pSubq!=0 );
789 assert( pSubq->pSelect!=0 );
790 assert( pSubq->pSelect->pEList!=0 );
791 if( pSubq->pSelect->pEList->nExpr!=pRow->nExpr ){
792 sqlite3SelectWrongNumTermsError(pParse, pSubq->pSelect);
793 }else{
794 sqlite3ExprCodeExprList(pParse, pRow, pSubq->regResult, 0, 0);
795 sqlite3VdbeAddOp1(pParse->pVdbe, OP_Yield, pSubq->regReturn);
796 }
797 }
798 sqlite3ExprListDelete(pParse->db, pRow);
799 }
800
801 return pLeft;
802}
803
804/* Forward declaration */
805static int xferOptimization(
806 Parse *pParse, /* Parser context */
807 Table *pDest, /* The table we are inserting into */
808 Select *pSelect, /* A SELECT statement to use as the data source */
809 int onError, /* How to handle constraint errors */
810 int iDbDest /* The database of pDest */
811);
812
813/*
814** This routine is called to handle SQL of the following forms:
815**
816** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
817** insert into TABLE (IDLIST) select
818** insert into TABLE (IDLIST) default values
819**
820** The IDLIST following the table name is always optional. If omitted,
821** then a list of all (non-hidden) columns for the table is substituted.
822** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
823** is omitted.
824**
825** For the pSelect parameter holds the values to be inserted for the
826** first two forms shown above. A VALUES clause is really just short-hand
827** for a SELECT statement that omits the FROM clause and everything else
828** that follows. If the pSelect parameter is NULL, that means that the
829** DEFAULT VALUES form of the INSERT statement is intended.
830**
831** The code generated follows one of four templates. For a simple
832** insert with data coming from a single-row VALUES clause, the code executes
833** once straight down through. Pseudo-code follows (we call this
834** the "1st template"):
835**
836** open write cursor to <table> and its indices
837** put VALUES clause expressions into registers
838** write the resulting record into <table>
839** cleanup
840**
841** The three remaining templates assume the statement is of the form
842**
843** INSERT INTO <table> SELECT ...
844**
845** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
846** in other words if the SELECT pulls all columns from a single table
847** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
848** if <table2> and <table1> are distinct tables but have identical
849** schemas, including all the same indices, then a special optimization
850** is invoked that copies raw records from <table2> over to <table1>.
851** See the xferOptimization() function for the implementation of this
852** template. This is the 2nd template.
853**
854** open a write cursor to <table>
855** open read cursor on <table2>
856** transfer all records in <table2> over to <table>
857** close cursors
858** foreach index on <table>
859** open a write cursor on the <table> index
860** open a read cursor on the corresponding <table2> index
861** transfer all records from the read to the write cursors
862** close cursors
863** end foreach
864**
865** The 3rd template is for when the second template does not apply
866** and the SELECT clause does not read from <table> at any time.
867** The generated code follows this template:
868**
869** X <- A
870** goto B
871** A: setup for the SELECT
872** loop over the rows in the SELECT
873** load values into registers R..R+n
874** yield X
875** end loop
876** cleanup after the SELECT
877** end-coroutine X
878** B: open write cursor to <table> and its indices
879** C: yield X, at EOF goto D
880** insert the select result into <table> from R..R+n
881** goto C
882** D: cleanup
883**
884** The 4th template is used if the insert statement takes its
885** values from a SELECT but the data is being inserted into a table
886** that is also read as part of the SELECT. In the third form,
887** we have to use an intermediate table to store the results of
888** the select. The template is like this:
889**
890** X <- A
891** goto B
892** A: setup for the SELECT
893** loop over the tables in the SELECT
894** load value into register R..R+n
895** yield X
896** end loop
897** cleanup after the SELECT
898** end co-routine R
899** B: open temp table
900** L: yield X, at EOF goto M
901** insert row from R..R+n into temp table
902** goto L
903** M: open write cursor to <table> and its indices
904** rewind temp table
905** C: loop over rows of intermediate table
906** transfer values form intermediate table into <table>
907** end loop
908** D: cleanup
909*/
910void sqlite3Insert(
911 Parse *pParse, /* Parser context */
912 SrcList *pTabList, /* Name of table into which we are inserting */
913 Select *pSelect, /* A SELECT statement to use as the data source */
914 IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */
915 int onError, /* How to handle constraint errors */
916 Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
917){
918 sqlite3 *db; /* The main database structure */
919 Table *pTab; /* The table to insert into. aka TABLE */
920 int i, j; /* Loop counters */
921 Vdbe *v; /* Generate code into this virtual machine */
922 Index *pIdx; /* For looping over indices of the table */
923 int nColumn; /* Number of columns in the data */
924 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
925 int iDataCur = 0; /* VDBE cursor that is the main data repository */
926 int iIdxCur = 0; /* First index cursor */
927 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
928 int endOfLoop; /* Label for the end of the insertion loop */
929 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
930 int addrInsTop = 0; /* Jump to label "D" */
931 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
932 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
933 int iDb; /* Index of database holding TABLE */
934 u8 useTempTable = 0; /* Store SELECT results in intermediate table */
935 u8 appendFlag = 0; /* True if the insert is likely to be an append */
936 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
937 u8 bIdListInOrder; /* True if IDLIST is in table order */
938 ExprList *pList = 0; /* List of VALUES() to be inserted */
939 int iRegStore; /* Register in which to store next column */
940
941 /* Register allocations */
942 int regFromSelect = 0;/* Base register for data coming from SELECT */
943 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
944 int regRowCount = 0; /* Memory cell used for the row counter */
945 int regIns; /* Block of regs holding rowid+data being inserted */
946 int regRowid; /* registers holding insert rowid */
947 int regData; /* register holding first column to insert */
948 int *aRegIdx = 0; /* One register allocated to each index */
949 int *aTabColMap = 0; /* Mapping from pTab columns to pCol entries */
950
951#ifndef SQLITE_OMIT_TRIGGER
952 int isView; /* True if attempting to insert into a view */
953 Trigger *pTrigger; /* List of triggers on pTab, if required */
954 int tmask; /* Mask of trigger times */
955#endif
956
957 db = pParse->db;
958 assert( db->pParse==pParse );
959 if( pParse->nErr ){
960 goto insert_cleanup;
961 }
962 assert( db->mallocFailed==0 );
963 dest.iSDParm = 0; /* Suppress a harmless compiler warning */
964
965 /* If the Select object is really just a simple VALUES() list with a
966 ** single row (the common case) then keep that one row of values
967 ** and discard the other (unused) parts of the pSelect object
968 */
969 if( pSelect
970 && (pSelect->selFlags & SF_Values)!=0
971 && pSelect->pPrior==0
972 && pSelect->pSrc->nSrc==0
973 ){
974 pList = pSelect->pEList;
975 pSelect->pEList = 0;
976 sqlite3SelectDelete(db, pSelect);
977 pSelect = 0;
978 }
979
980 /* Locate the table into which we will be inserting new information.
981 */
982 assert( pTabList->nSrc==1 );
983 pTab = sqlite3SrcListLookup(pParse, pTabList);
984 if( pTab==0 ){
985 goto insert_cleanup;
986 }
987 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
988 assert( iDb<db->nDb );
989 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
990 db->aDb[iDb].zDbSName) ){
991 goto insert_cleanup;
992 }
993 withoutRowid = !HasRowid(pTab);
994
995 /* Figure out if we have any triggers and if the table being
996 ** inserted into is a view
997 */
998#ifndef SQLITE_OMIT_TRIGGER
999 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
1000 isView = IsView(pTab);
1001#else
1002# define pTrigger 0
1003# define tmask 0
1004# define isView 0
1005#endif
1006#ifdef SQLITE_OMIT_VIEW
1007# undef isView
1008# define isView 0
1009#endif
1010 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
1011
1012#if TREETRACE_ENABLED
1013 if( sqlite3TreeTrace & 0x10000 ){
1014 sqlite3TreeViewLine(0, "In sqlite3Insert() at %s:%d", __FILE__, __LINE__);
1015 sqlite3TreeViewInsert(pParse->pWith, pTabList, pColumn, pSelect, pList,
1016 onError, pUpsert, pTrigger);
1017 }
1018#endif
1019
1020 /* If pTab is really a view, make sure it has been initialized.
1021 ** ViewGetColumnNames() is a no-op if pTab is not a view.
1022 */
1023 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1024 goto insert_cleanup;
1025 }
1026
1027 /* Cannot insert into a read-only table.
1028 */
1029 if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
1030 goto insert_cleanup;
1031 }
1032
1033 /* Allocate a VDBE
1034 */
1035 v = sqlite3GetVdbe(pParse);
1036 if( v==0 ) goto insert_cleanup;
1037 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
1038 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
1039
1040#ifndef SQLITE_OMIT_XFER_OPT
1041 /* If the statement is of the form
1042 **
1043 ** INSERT INTO <table1> SELECT * FROM <table2>;
1044 **
1045 ** Then special optimizations can be applied that make the transfer
1046 ** very fast and which reduce fragmentation of indices.
1047 **
1048 ** This is the 2nd template.
1049 */
1050 if( pColumn==0
1051 && pSelect!=0
1052 && pTrigger==0
1053 && xferOptimization(pParse, pTab, pSelect, onError, iDb)
1054 ){
1055 assert( !pTrigger );
1056 assert( pList==0 );
1057 goto insert_end;
1058 }
1059#endif /* SQLITE_OMIT_XFER_OPT */
1060
1061 /* If this is an AUTOINCREMENT table, look up the sequence number in the
1062 ** sqlite_sequence table and store it in memory cell regAutoinc.
1063 */
1064 regAutoinc = autoIncBegin(pParse, iDb, pTab);
1065
1066 /* Allocate a block registers to hold the rowid and the values
1067 ** for all columns of the new row.
1068 */
1069 regRowid = regIns = pParse->nMem+1;
1070 pParse->nMem += pTab->nCol + 1;
1071 if( IsVirtual(pTab) ){
1072 regRowid++;
1073 pParse->nMem++;
1074 }
1075 regData = regRowid+1;
1076
1077 /* If the INSERT statement included an IDLIST term, then make sure
1078 ** all elements of the IDLIST really are columns of the table and
1079 ** remember the column indices.
1080 **
1081 ** If the table has an INTEGER PRIMARY KEY column and that column
1082 ** is named in the IDLIST, then record in the ipkColumn variable
1083 ** the index into IDLIST of the primary key column. ipkColumn is
1084 ** the index of the primary key as it appears in IDLIST, not as
1085 ** is appears in the original table. (The index of the INTEGER
1086 ** PRIMARY KEY in the original table is pTab->iPKey.) After this
1087 ** loop, if ipkColumn==(-1), that means that integer primary key
1088 ** is unspecified, and hence the table is either WITHOUT ROWID or
1089 ** it will automatically generated an integer primary key.
1090 **
1091 ** bIdListInOrder is true if the columns in IDLIST are in storage
1092 ** order. This enables an optimization that avoids shuffling the
1093 ** columns into storage order. False negatives are harmless,
1094 ** but false positives will cause database corruption.
1095 */
1096 bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
1097 if( pColumn ){
1098 aTabColMap = sqlite3DbMallocZero(db, pTab->nCol*sizeof(int));
1099 if( aTabColMap==0 ) goto insert_cleanup;
1100 for(i=0; i<pColumn->nId; i++){
1101 j = sqlite3ColumnIndex(pTab, pColumn->a[i].zName);
1102 if( j>=0 ){
1103 if( aTabColMap[j]==0 ) aTabColMap[j] = i+1;
1104 if( i!=j ) bIdListInOrder = 0;
1105 if( j==pTab->iPKey ){
1106 ipkColumn = i; assert( !withoutRowid );
1107 }
1108#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1109 if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
1110 sqlite3ErrorMsg(pParse,
1111 "cannot INSERT into generated column \"%s\"",
1112 pTab->aCol[j].zCnName);
1113 goto insert_cleanup;
1114 }
1115#endif
1116 }else{
1117 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
1118 ipkColumn = i;
1119 bIdListInOrder = 0;
1120 }else{
1121 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
1122 pTabList->a, pColumn->a[i].zName);
1123 pParse->checkSchema = 1;
1124 goto insert_cleanup;
1125 }
1126 }
1127 }
1128 }
1129
1130 /* Figure out how many columns of data are supplied. If the data
1131 ** is coming from a SELECT statement, then generate a co-routine that
1132 ** produces a single row of the SELECT on each invocation. The
1133 ** co-routine is the common header to the 3rd and 4th templates.
1134 */
1135 if( pSelect ){
1136 /* Data is coming from a SELECT or from a multi-row VALUES clause.
1137 ** Generate a co-routine to run the SELECT. */
1138 int rc; /* Result code */
1139
1140 if( pSelect->pSrc->nSrc==1
1141 && pSelect->pSrc->a[0].fg.viaCoroutine
1142 && pSelect->pPrior==0
1143 ){
1144 SrcItem *pItem = &pSelect->pSrc->a[0];
1145 Subquery *pSubq;
1146 assert( pItem->fg.isSubquery );
1147 pSubq = pItem->u4.pSubq;
1148 dest.iSDParm = pSubq->regReturn;
1149 regFromSelect = pSubq->regResult;
1150 assert( pSubq->pSelect!=0 );
1151 assert( pSubq->pSelect->pEList!=0 );
1152 nColumn = pSubq->pSelect->pEList->nExpr;
1153 ExplainQueryPlan((pParse, 0, "SCAN %S", pItem));
1154 if( bIdListInOrder && nColumn==pTab->nCol ){
1155 regData = regFromSelect;
1156 regRowid = regData - 1;
1157 regIns = regRowid - (IsVirtual(pTab) ? 1 : 0);
1158 }
1159 }else{
1160 int addrTop; /* Top of the co-routine */
1161 int regYield = ++pParse->nMem;
1162 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
1163 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
1164 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
1165 dest.iSdst = bIdListInOrder ? regData : 0;
1166 dest.nSdst = pTab->nCol;
1167 rc = sqlite3Select(pParse, pSelect, &dest);
1168 regFromSelect = dest.iSdst;
1169 assert( db->pParse==pParse );
1170 if( rc || pParse->nErr ) goto insert_cleanup;
1171 assert( db->mallocFailed==0 );
1172 sqlite3VdbeEndCoroutine(v, regYield);
1173 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
1174 assert( pSelect->pEList );
1175 nColumn = pSelect->pEList->nExpr;
1176 }
1177
1178 /* Set useTempTable to TRUE if the result of the SELECT statement
1179 ** should be written into a temporary table (template 4). Set to
1180 ** FALSE if each output row of the SELECT can be written directly into
1181 ** the destination table (template 3).
1182 **
1183 ** A temp table must be used if the table being updated is also one
1184 ** of the tables being read by the SELECT statement. Also use a
1185 ** temp table in the case of row triggers.
1186 */
1187 if( pTrigger || readsTable(pParse, iDb, pTab) ){
1188 useTempTable = 1;
1189 }
1190
1191 if( useTempTable ){
1192 /* Invoke the coroutine to extract information from the SELECT
1193 ** and add it to a transient table srcTab. The code generated
1194 ** here is from the 4th template:
1195 **
1196 ** B: open temp table
1197 ** L: yield X, goto M at EOF
1198 ** insert row from R..R+n into temp table
1199 ** goto L
1200 ** M: ...
1201 */
1202 int regRec; /* Register to hold packed record */
1203 int regTempRowid; /* Register to hold temp table ROWID */
1204 int addrL; /* Label "L" */
1205
1206 srcTab = pParse->nTab++;
1207 regRec = sqlite3GetTempReg(pParse);
1208 regTempRowid = sqlite3GetTempReg(pParse);
1209 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
1210 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
1211 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
1212 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
1213 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
1214 sqlite3VdbeGoto(v, addrL);
1215 sqlite3VdbeJumpHere(v, addrL);
1216 sqlite3ReleaseTempReg(pParse, regRec);
1217 sqlite3ReleaseTempReg(pParse, regTempRowid);
1218 }
1219 }else{
1220 /* This is the case if the data for the INSERT is coming from a
1221 ** single-row VALUES clause
1222 */
1223 NameContext sNC;
1224 memset(&sNC, 0, sizeof(sNC));
1225 sNC.pParse = pParse;
1226 srcTab = -1;
1227 assert( useTempTable==0 );
1228 if( pList ){
1229 nColumn = pList->nExpr;
1230 if( sqlite3ResolveExprListNames(&sNC, pList) ){
1231 goto insert_cleanup;
1232 }
1233 }else{
1234 nColumn = 0;
1235 }
1236 }
1237
1238 /* If there is no IDLIST term but the table has an integer primary
1239 ** key, the set the ipkColumn variable to the integer primary key
1240 ** column index in the original table definition.
1241 */
1242 if( pColumn==0 && nColumn>0 ){
1243 ipkColumn = pTab->iPKey;
1244#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1245 if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
1246 testcase( pTab->tabFlags & TF_HasVirtual );
1247 testcase( pTab->tabFlags & TF_HasStored );
1248 for(i=ipkColumn-1; i>=0; i--){
1249 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
1250 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
1251 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
1252 ipkColumn--;
1253 }
1254 }
1255 }
1256#endif
1257
1258 /* Make sure the number of columns in the source data matches the number
1259 ** of columns to be inserted into the table.
1260 */
1261 assert( TF_HasHidden==COLFLAG_HIDDEN );
1262 assert( TF_HasGenerated==COLFLAG_GENERATED );
1263 assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) );
1264 if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
1265 for(i=0; i<pTab->nCol; i++){
1266 if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
1267 }
1268 }
1269 if( nColumn!=(pTab->nCol-nHidden) ){
1270 sqlite3ErrorMsg(pParse,
1271 "table %S has %d columns but %d values were supplied",
1272 pTabList->a, pTab->nCol-nHidden, nColumn);
1273 goto insert_cleanup;
1274 }
1275 }
1276 if( pColumn!=0 && nColumn!=pColumn->nId ){
1277 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
1278 goto insert_cleanup;
1279 }
1280
1281 /* Initialize the count of rows to be inserted
1282 */
1283 if( (db->flags & SQLITE_CountRows)!=0
1284 && !pParse->nested
1285 && !pParse->pTriggerTab
1286 && !pParse->bReturning
1287 ){
1288 regRowCount = ++pParse->nMem;
1289 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
1290 }
1291
1292 /* If this is not a view, open the table and and all indices */
1293 if( !isView ){
1294 int nIdx;
1295 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
1296 &iDataCur, &iIdxCur);
1297 aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
1298 if( aRegIdx==0 ){
1299 goto insert_cleanup;
1300 }
1301 for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
1302 assert( pIdx );
1303 aRegIdx[i] = ++pParse->nMem;
1304 pParse->nMem += pIdx->nColumn;
1305 }
1306 aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */
1307 }
1308#ifndef SQLITE_OMIT_UPSERT
1309 if( pUpsert ){
1310 Upsert *pNx;
1311 if( IsVirtual(pTab) ){
1312 sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
1313 pTab->zName);
1314 goto insert_cleanup;
1315 }
1316 if( IsView(pTab) ){
1317 sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
1318 goto insert_cleanup;
1319 }
1320 if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
1321 goto insert_cleanup;
1322 }
1323 pTabList->a[0].iCursor = iDataCur;
1324 pNx = pUpsert;
1325 do{
1326 pNx->pUpsertSrc = pTabList;
1327 pNx->regData = regData;
1328 pNx->iDataCur = iDataCur;
1329 pNx->iIdxCur = iIdxCur;
1330 if( pNx->pUpsertTarget ){
1331 if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx, pUpsert) ){
1332 goto insert_cleanup;
1333 }
1334 }
1335 pNx = pNx->pNextUpsert;
1336 }while( pNx!=0 );
1337 }
1338#endif
1339
1340
1341 /* This is the top of the main insertion loop */
1342 if( useTempTable ){
1343 /* This block codes the top of loop only. The complete loop is the
1344 ** following pseudocode (template 4):
1345 **
1346 ** rewind temp table, if empty goto D
1347 ** C: loop over rows of intermediate table
1348 ** transfer values form intermediate table into <table>
1349 ** end loop
1350 ** D: ...
1351 */
1352 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
1353 addrCont = sqlite3VdbeCurrentAddr(v);
1354 }else if( pSelect ){
1355 /* This block codes the top of loop only. The complete loop is the
1356 ** following pseudocode (template 3):
1357 **
1358 ** C: yield X, at EOF goto D
1359 ** insert the select result into <table> from R..R+n
1360 ** goto C
1361 ** D: ...
1362 */
1363 sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
1364 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
1365 VdbeCoverage(v);
1366 if( ipkColumn>=0 ){
1367 /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
1368 ** SELECT, go ahead and copy the value into the rowid slot now, so that
1369 ** the value does not get overwritten by a NULL at tag-20191021-002. */
1370 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
1371 }
1372 }
1373
1374 /* Compute data for ordinary columns of the new entry. Values
1375 ** are written in storage order into registers starting with regData.
1376 ** Only ordinary columns are computed in this loop. The rowid
1377 ** (if there is one) is computed later and generated columns are
1378 ** computed after the rowid since they might depend on the value
1379 ** of the rowid.
1380 */
1381 nHidden = 0;
1382 iRegStore = regData; assert( regData==regRowid+1 );
1383 for(i=0; i<pTab->nCol; i++, iRegStore++){
1384 int k;
1385 u32 colFlags;
1386 assert( i>=nHidden );
1387 if( i==pTab->iPKey ){
1388 /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
1389 ** using the rowid. So put a NULL in the IPK slot of the record to avoid
1390 ** using excess space. The file format definition requires this extra
1391 ** NULL - we cannot optimize further by skipping the column completely */
1392 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1393 continue;
1394 }
1395 if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
1396 nHidden++;
1397 if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
1398 /* Virtual columns do not participate in OP_MakeRecord. So back up
1399 ** iRegStore by one slot to compensate for the iRegStore++ in the
1400 ** outer for() loop */
1401 iRegStore--;
1402 continue;
1403 }else if( (colFlags & COLFLAG_STORED)!=0 ){
1404 /* Stored columns are computed later. But if there are BEFORE
1405 ** triggers, the slots used for stored columns will be OP_Copy-ed
1406 ** to a second block of registers, so the register needs to be
1407 ** initialized to NULL to avoid an uninitialized register read */
1408 if( tmask & TRIGGER_BEFORE ){
1409 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1410 }
1411 continue;
1412 }else if( pColumn==0 ){
1413 /* Hidden columns that are not explicitly named in the INSERT
1414 ** get their default value */
1415 sqlite3ExprCodeFactorable(pParse,
1416 sqlite3ColumnExprAuth(pTab, &pTab->aCol[i], pParse),
1417 iRegStore);
1418 continue;
1419 }
1420 }
1421 if( pColumn ){
1422 j = aTabColMap[i];
1423 assert( j>=0 && j<=pColumn->nId );
1424 if( j==0 ){
1425 /* A column not named in the insert column list gets its
1426 ** default value */
1427 sqlite3ExprCodeFactorable(pParse,
1428 sqlite3ColumnExprAuth(pTab, &pTab->aCol[i], pParse),
1429 iRegStore);
1430 continue;
1431 }
1432 k = j - 1;
1433 }else if( nColumn==0 ){
1434 /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */
1435 sqlite3ExprCodeFactorable(pParse,
1436 sqlite3ColumnExprAuth(pTab, &pTab->aCol[i], pParse),
1437 iRegStore);
1438 continue;
1439 }else{
1440 k = i - nHidden;
1441 }
1442
1443 if( useTempTable ){
1444 sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
1445 }else if( pSelect ){
1446 if( regFromSelect!=regData ){
1447 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
1448 }
1449 }else{
1450 Expr *pX = pList->a[k].pExpr;
1451 int y = sqlite3ExprCodeTarget(pParse, pX, iRegStore);
1452 if( y!=iRegStore ){
1453 sqlite3VdbeAddOp2(v,
1454 ExprHasProperty(pX, EP_Subquery) ? OP_Copy : OP_SCopy, y, iRegStore);
1455 }
1456 }
1457 }
1458
1459
1460 /* Run the BEFORE and INSTEAD OF triggers, if there are any
1461 */
1462 endOfLoop = sqlite3VdbeMakeLabel(pParse);
1463 if( tmask & TRIGGER_BEFORE ){
1464 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
1465
1466 /* build the NEW.* reference row. Note that if there is an INTEGER
1467 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
1468 ** translated into a unique ID for the row. But on a BEFORE trigger,
1469 ** we do not know what the unique ID will be (because the insert has
1470 ** not happened yet) so we substitute a rowid of -1
1471 */
1472 if( ipkColumn<0 ){
1473 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1474 }else{
1475 int addr1;
1476 assert( !withoutRowid );
1477 if( useTempTable ){
1478 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
1479 }else{
1480 assert( pSelect==0 ); /* Otherwise useTempTable is true */
1481 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
1482 }
1483 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
1484 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
1485 sqlite3VdbeJumpHere(v, addr1);
1486 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
1487 sqlite3MayAbort(pParse);
1488 }
1489
1490 /* Copy the new data already generated. */
1491 assert( pTab->nNVCol>0 || pParse->nErr>0 );
1492 sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
1493
1494#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1495 /* Compute the new value for generated columns after all other
1496 ** columns have already been computed. This must be done after
1497 ** computing the ROWID in case one of the generated columns
1498 ** refers to the ROWID. */
1499 if( pTab->tabFlags & TF_HasGenerated ){
1500 testcase( pTab->tabFlags & TF_HasVirtual );
1501 testcase( pTab->tabFlags & TF_HasStored );
1502 sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
1503 }
1504#endif
1505
1506 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
1507 ** do not attempt any conversions before assembling the record.
1508 ** If this is a real table, attempt conversions as required by the
1509 ** table column affinities.
1510 */
1511 if( !isView ){
1512 sqlite3TableAffinity(v, pTab, regCols+1);
1513 }
1514
1515 /* Fire BEFORE or INSTEAD OF triggers */
1516 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
1517 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
1518
1519 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
1520 }
1521
1522 if( !isView ){
1523 if( IsVirtual(pTab) ){
1524 /* The row that the VUpdate opcode will delete: none */
1525 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
1526 }
1527 if( ipkColumn>=0 ){
1528 /* Compute the new rowid */
1529 if( useTempTable ){
1530 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
1531 }else if( pSelect ){
1532 /* Rowid already initialized at tag-20191021-001 */
1533 }else{
1534 Expr *pIpk = pList->a[ipkColumn].pExpr;
1535 if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
1536 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1537 appendFlag = 1;
1538 }else{
1539 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
1540 }
1541 }
1542 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
1543 ** to generate a unique primary key value.
1544 */
1545 if( !appendFlag ){
1546 int addr1;
1547 if( !IsVirtual(pTab) ){
1548 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
1549 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1550 sqlite3VdbeJumpHere(v, addr1);
1551 }else{
1552 addr1 = sqlite3VdbeCurrentAddr(v);
1553 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
1554 }
1555 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
1556 sqlite3MayAbort(pParse);
1557 }
1558 }else if( IsVirtual(pTab) || withoutRowid ){
1559 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
1560 }else{
1561 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
1562 appendFlag = 1;
1563 }
1564 autoIncStep(pParse, regAutoinc, regRowid);
1565
1566#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1567 /* Compute the new value for generated columns after all other
1568 ** columns have already been computed. This must be done after
1569 ** computing the ROWID in case one of the generated columns
1570 ** is derived from the INTEGER PRIMARY KEY. */
1571 if( pTab->tabFlags & TF_HasGenerated ){
1572 sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
1573 }
1574#endif
1575
1576 /* Generate code to check constraints and generate index keys and
1577 ** do the insertion.
1578 */
1579#ifndef SQLITE_OMIT_VIRTUALTABLE
1580 if( IsVirtual(pTab) ){
1581 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
1582 sqlite3VtabMakeWritable(pParse, pTab);
1583 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
1584 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1585 sqlite3MayAbort(pParse);
1586 }else
1587#endif
1588 {
1589 int isReplace = 0;/* Set to true if constraints may cause a replace */
1590 int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
1591 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1592 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
1593 );
1594 if( db->flags & SQLITE_ForeignKeys ){
1595 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
1596 }
1597
1598 /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
1599 ** constraints or (b) there are no triggers and this table is not a
1600 ** parent table in a foreign key constraint. It is safe to set the
1601 ** flag in the second case as if any REPLACE constraint is hit, an
1602 ** OP_Delete or OP_IdxDelete instruction will be executed on each
1603 ** cursor that is disturbed. And these instructions both clear the
1604 ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
1605 ** functionality. */
1606 bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
1607 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
1608 regIns, aRegIdx, 0, appendFlag, bUseSeek
1609 );
1610 }
1611#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
1612 }else if( pParse->bReturning ){
1613 /* If there is a RETURNING clause, populate the rowid register with
1614 ** constant value -1, in case one or more of the returned expressions
1615 ** refer to the "rowid" of the view. */
1616 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
1617#endif
1618 }
1619
1620 /* Update the count of rows that are inserted
1621 */
1622 if( regRowCount ){
1623 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
1624 }
1625
1626 if( pTrigger ){
1627 /* Code AFTER triggers */
1628 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
1629 pTab, regData-2-pTab->nCol, onError, endOfLoop);
1630 }
1631
1632 /* The bottom of the main insertion loop, if the data source
1633 ** is a SELECT statement.
1634 */
1635 sqlite3VdbeResolveLabel(v, endOfLoop);
1636 if( useTempTable ){
1637 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
1638 sqlite3VdbeJumpHere(v, addrInsTop);
1639 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1640 }else if( pSelect ){
1641 sqlite3VdbeGoto(v, addrCont);
1642#ifdef SQLITE_DEBUG
1643 /* If we are jumping back to an OP_Yield that is preceded by an
1644 ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
1645 ** OP_ReleaseReg will be included in the loop. */
1646 if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
1647 assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
1648 sqlite3VdbeChangeP5(v, 1);
1649 }
1650#endif
1651 sqlite3VdbeJumpHere(v, addrInsTop);
1652 }
1653
1654#ifndef SQLITE_OMIT_XFER_OPT
1655insert_end:
1656#endif /* SQLITE_OMIT_XFER_OPT */
1657 /* Update the sqlite_sequence table by storing the content of the
1658 ** maximum rowid counter values recorded while inserting into
1659 ** autoincrement tables.
1660 */
1661 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
1662 sqlite3AutoincrementEnd(pParse);
1663 }
1664
1665 /*
1666 ** Return the number of rows inserted. If this routine is
1667 ** generating code because of a call to sqlite3NestedParse(), do not
1668 ** invoke the callback function.
1669 */
1670 if( regRowCount ){
1671 sqlite3CodeChangeCount(v, regRowCount, "rows inserted");
1672 }
1673
1674insert_cleanup:
1675 sqlite3SrcListDelete(db, pTabList);
1676 sqlite3ExprListDelete(db, pList);
1677 sqlite3UpsertDelete(db, pUpsert);
1678 sqlite3SelectDelete(db, pSelect);
1679 if( pColumn ){
1680 sqlite3IdListDelete(db, pColumn);
1681 sqlite3DbFree(db, aTabColMap);
1682 }
1683 if( aRegIdx ) sqlite3DbNNFreeNN(db, aRegIdx);
1684}
1685
1686/* Make sure "isView" and other macros defined above are undefined. Otherwise
1687** they may interfere with compilation of other functions in this file
1688** (or in another file, if this file becomes part of the amalgamation). */
1689#ifdef isView
1690 #undef isView
1691#endif
1692#ifdef pTrigger
1693 #undef pTrigger
1694#endif
1695#ifdef tmask
1696 #undef tmask
1697#endif
1698
1699/*
1700** Meanings of bits in of pWalker->eCode for
1701** sqlite3ExprReferencesUpdatedColumn()
1702*/
1703#define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
1704#define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
1705
1706/* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
1707* Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
1708** expression node references any of the
1709** columns that are being modified by an UPDATE statement.
1710*/
1711static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
1712 if( pExpr->op==TK_COLUMN ){
1713 assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
1714 if( pExpr->iColumn>=0 ){
1715 if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
1716 pWalker->eCode |= CKCNSTRNT_COLUMN;
1717 }
1718 }else{
1719 pWalker->eCode |= CKCNSTRNT_ROWID;
1720 }
1721 }
1722 return WRC_Continue;
1723}
1724
1725/*
1726** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
1727** only columns that are modified by the UPDATE are those for which
1728** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
1729**
1730** Return true if CHECK constraint pExpr uses any of the
1731** changing columns (or the rowid if it is changing). In other words,
1732** return true if this CHECK constraint must be validated for
1733** the new row in the UPDATE statement.
1734**
1735** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
1736** The operation of this routine is the same - return true if an only if
1737** the expression uses one or more of columns identified by the second and
1738** third arguments.
1739*/
1740int sqlite3ExprReferencesUpdatedColumn(
1741 Expr *pExpr, /* The expression to be checked */
1742 int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */
1743 int chngRowid /* True if UPDATE changes the rowid */
1744){
1745 Walker w;
1746 memset(&w, 0, sizeof(w));
1747 w.eCode = 0;
1748 w.xExprCallback = checkConstraintExprNode;
1749 w.u.aiCol = aiChng;
1750 sqlite3WalkExpr(&w, pExpr);
1751 if( !chngRowid ){
1752 testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
1753 w.eCode &= ~CKCNSTRNT_ROWID;
1754 }
1755 testcase( w.eCode==0 );
1756 testcase( w.eCode==CKCNSTRNT_COLUMN );
1757 testcase( w.eCode==CKCNSTRNT_ROWID );
1758 testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
1759 return w.eCode!=0;
1760}
1761
1762/*
1763** The sqlite3GenerateConstraintChecks() routine usually wants to visit
1764** the indexes of a table in the order provided in the Table->pIndex list.
1765** However, sometimes (rarely - when there is an upsert) it wants to visit
1766** the indexes in a different order. The following data structures accomplish
1767** this.
1768**
1769** The IndexIterator object is used to walk through all of the indexes
1770** of a table in either Index.pNext order, or in some other order established
1771** by an array of IndexListTerm objects.
1772*/
1773typedef struct IndexListTerm IndexListTerm;
1774typedef struct IndexIterator IndexIterator;
1775struct IndexIterator {
1776 int eType; /* 0 for Index.pNext list. 1 for an array of IndexListTerm */
1777 int i; /* Index of the current item from the list */
1778 union {
1779 struct { /* Use this object for eType==0: A Index.pNext list */
1780 Index *pIdx; /* The current Index */
1781 } lx;
1782 struct { /* Use this object for eType==1; Array of IndexListTerm */
1783 int nIdx; /* Size of the array */
1784 IndexListTerm *aIdx; /* Array of IndexListTerms */
1785 } ax;
1786 } u;
1787};
1788
1789/* When IndexIterator.eType==1, then each index is an array of instances
1790** of the following object
1791*/
1792struct IndexListTerm {
1793 Index *p; /* The index */
1794 int ix; /* Which entry in the original Table.pIndex list is this index*/
1795};
1796
1797/* Return the first index on the list */
1798static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){
1799 assert( pIter->i==0 );
1800 if( pIter->eType ){
1801 *pIx = pIter->u.ax.aIdx[0].ix;
1802 return pIter->u.ax.aIdx[0].p;
1803 }else{
1804 *pIx = 0;
1805 return pIter->u.lx.pIdx;
1806 }
1807}
1808
1809/* Return the next index from the list. Return NULL when out of indexes */
1810static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){
1811 if( pIter->eType ){
1812 int i = ++pIter->i;
1813 if( i>=pIter->u.ax.nIdx ){
1814 *pIx = i;
1815 return 0;
1816 }
1817 *pIx = pIter->u.ax.aIdx[i].ix;
1818 return pIter->u.ax.aIdx[i].p;
1819 }else{
1820 ++(*pIx);
1821 pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
1822 return pIter->u.lx.pIdx;
1823 }
1824}
1825
1826/*
1827** Generate code to do constraint checks prior to an INSERT or an UPDATE
1828** on table pTab.
1829**
1830** The regNewData parameter is the first register in a range that contains
1831** the data to be inserted or the data after the update. There will be
1832** pTab->nCol+1 registers in this range. The first register (the one
1833** that regNewData points to) will contain the new rowid, or NULL in the
1834** case of a WITHOUT ROWID table. The second register in the range will
1835** contain the content of the first table column. The third register will
1836** contain the content of the second table column. And so forth.
1837**
1838** The regOldData parameter is similar to regNewData except that it contains
1839** the data prior to an UPDATE rather than afterwards. regOldData is zero
1840** for an INSERT. This routine can distinguish between UPDATE and INSERT by
1841** checking regOldData for zero.
1842**
1843** For an UPDATE, the pkChng boolean is true if the true primary key (the
1844** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1845** might be modified by the UPDATE. If pkChng is false, then the key of
1846** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
1847**
1848** For an INSERT, the pkChng boolean indicates whether or not the rowid
1849** was explicitly specified as part of the INSERT statement. If pkChng
1850** is zero, it means that the either rowid is computed automatically or
1851** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
1852** pkChng will only be true if the INSERT statement provides an integer
1853** value for either the rowid column or its INTEGER PRIMARY KEY alias.
1854**
1855** The code generated by this routine will store new index entries into
1856** registers identified by aRegIdx[]. No index entry is created for
1857** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1858** the same as the order of indices on the linked list of indices
1859** at pTab->pIndex.
1860**
1861** (2019-05-07) The generated code also creates a new record for the
1862** main table, if pTab is a rowid table, and stores that record in the
1863** register identified by aRegIdx[nIdx] - in other words in the first
1864** entry of aRegIdx[] past the last index. It is important that the
1865** record be generated during constraint checks to avoid affinity changes
1866** to the register content that occur after constraint checks but before
1867** the new record is inserted.
1868**
1869** The caller must have already opened writeable cursors on the main
1870** table and all applicable indices (that is to say, all indices for which
1871** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
1872** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
1873** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
1874** for the first index in the pTab->pIndex list. Cursors for other indices
1875** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
1876**
1877** This routine also generates code to check constraints. NOT NULL,
1878** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
1879** then the appropriate action is performed. There are five possible
1880** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
1881**
1882** Constraint type Action What Happens
1883** --------------- ---------- ----------------------------------------
1884** any ROLLBACK The current transaction is rolled back and
1885** sqlite3_step() returns immediately with a
1886** return code of SQLITE_CONSTRAINT.
1887**
1888** any ABORT Back out changes from the current command
1889** only (do not do a complete rollback) then
1890** cause sqlite3_step() to return immediately
1891** with SQLITE_CONSTRAINT.
1892**
1893** any FAIL Sqlite3_step() returns immediately with a
1894** return code of SQLITE_CONSTRAINT. The
1895** transaction is not rolled back and any
1896** changes to prior rows are retained.
1897**
1898** any IGNORE The attempt in insert or update the current
1899** row is skipped, without throwing an error.
1900** Processing continues with the next row.
1901** (There is an immediate jump to ignoreDest.)
1902**
1903** NOT NULL REPLACE The NULL value is replace by the default
1904** value for that column. If the default value
1905** is NULL, the action is the same as ABORT.
1906**
1907** UNIQUE REPLACE The other row that conflicts with the row
1908** being inserted is removed.
1909**
1910** CHECK REPLACE Illegal. The results in an exception.
1911**
1912** Which action to take is determined by the overrideError parameter.
1913** Or if overrideError==OE_Default, then the pParse->onError parameter
1914** is used. Or if pParse->onError==OE_Default then the onError value
1915** for the constraint is used.
1916*/
1917void sqlite3GenerateConstraintChecks(
1918 Parse *pParse, /* The parser context */
1919 Table *pTab, /* The table being inserted or updated */
1920 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
1921 int iDataCur, /* Canonical data cursor (main table or PK index) */
1922 int iIdxCur, /* First index cursor */
1923 int regNewData, /* First register in a range holding values to insert */
1924 int regOldData, /* Previous content. 0 for INSERTs */
1925 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
1926 u8 overrideError, /* Override onError to this if not OE_Default */
1927 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
1928 int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
1929 int *aiChng, /* column i is unchanged if aiChng[i]<0 */
1930 Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
1931){
1932 Vdbe *v; /* VDBE under construction */
1933 Index *pIdx; /* Pointer to one of the indices */
1934 Index *pPk = 0; /* The PRIMARY KEY index for WITHOUT ROWID tables */
1935 sqlite3 *db; /* Database connection */
1936 int i; /* loop counter */
1937 int ix; /* Index loop counter */
1938 int nCol; /* Number of columns */
1939 int onError; /* Conflict resolution strategy */
1940 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
1941 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
1942 Upsert *pUpsertClause = 0; /* The specific ON CONFLICT clause for pIdx */
1943 u8 isUpdate; /* True if this is an UPDATE operation */
1944 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
1945 int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */
1946 int upsertIpkDelay = 0; /* Address of Goto to bypass initial IPK check */
1947 int ipkTop = 0; /* Top of the IPK uniqueness check */
1948 int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */
1949 /* Variables associated with retesting uniqueness constraints after
1950 ** replace triggers fire have run */
1951 int regTrigCnt; /* Register used to count replace trigger invocations */
1952 int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */
1953 int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
1954 Trigger *pTrigger; /* List of DELETE triggers on the table pTab */
1955 int nReplaceTrig = 0; /* Number of replace triggers coded */
1956 IndexIterator sIdxIter; /* Index iterator */
1957
1958 isUpdate = regOldData!=0;
1959 db = pParse->db;
1960 v = pParse->pVdbe;
1961 assert( v!=0 );
1962 assert( !IsView(pTab) ); /* This table is not a VIEW */
1963 nCol = pTab->nCol;
1964
1965 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
1966 ** normal rowid tables. nPkField is the number of key fields in the
1967 ** pPk index or 1 for a rowid table. In other words, nPkField is the
1968 ** number of fields in the true primary key of the table. */
1969 if( HasRowid(pTab) ){
1970 pPk = 0;
1971 nPkField = 1;
1972 }else{
1973 pPk = sqlite3PrimaryKeyIndex(pTab);
1974 nPkField = pPk->nKeyCol;
1975 }
1976
1977 /* Record that this module has started */
1978 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
1979 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
1980
1981 /* Test all NOT NULL constraints.
1982 */
1983 if( pTab->tabFlags & TF_HasNotNull ){
1984 int b2ndPass = 0; /* True if currently running 2nd pass */
1985 int nSeenReplace = 0; /* Number of ON CONFLICT REPLACE operations */
1986 int nGenerated = 0; /* Number of generated columns with NOT NULL */
1987 while(1){ /* Make 2 passes over columns. Exit loop via "break" */
1988 for(i=0; i<nCol; i++){
1989 int iReg; /* Register holding column value */
1990 Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */
1991 int isGenerated; /* non-zero if column is generated */
1992 onError = pCol->notNull;
1993 if( onError==OE_None ) continue; /* No NOT NULL on this column */
1994 if( i==pTab->iPKey ){
1995 continue; /* ROWID is never NULL */
1996 }
1997 isGenerated = pCol->colFlags & COLFLAG_GENERATED;
1998 if( isGenerated && !b2ndPass ){
1999 nGenerated++;
2000 continue; /* Generated columns processed on 2nd pass */
2001 }
2002 if( aiChng && aiChng[i]<0 && !isGenerated ){
2003 /* Do not check NOT NULL on columns that do not change */
2004 continue;
2005 }
2006 if( overrideError!=OE_Default ){
2007 onError = overrideError;
2008 }else if( onError==OE_Default ){
2009 onError = OE_Abort;
2010 }
2011 if( onError==OE_Replace ){
2012 if( b2ndPass /* REPLACE becomes ABORT on the 2nd pass */
2013 || pCol->iDflt==0 /* REPLACE is ABORT if no DEFAULT value */
2014 ){
2015 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
2016 testcase( pCol->colFlags & COLFLAG_STORED );
2017 testcase( pCol->colFlags & COLFLAG_GENERATED );
2018 onError = OE_Abort;
2019 }else{
2020 assert( !isGenerated );
2021 }
2022 }else if( b2ndPass && !isGenerated ){
2023 continue;
2024 }
2025 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
2026 || onError==OE_Ignore || onError==OE_Replace );
2027 testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
2028 iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
2029 switch( onError ){
2030 case OE_Replace: {
2031 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
2032 VdbeCoverage(v);
2033 assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
2034 nSeenReplace++;
2035 sqlite3ExprCodeCopy(pParse,
2036 sqlite3ColumnExprAuth(pTab, pCol, pParse), iReg);
2037 sqlite3VdbeJumpHere(v, addr1);
2038 break;
2039 }
2040 case OE_Abort:
2041 sqlite3MayAbort(pParse);
2042 /* no break */ deliberate_fall_through
2043 case OE_Rollback:
2044 case OE_Fail: {
2045 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
2046 pCol->zCnName);
2047 testcase( zMsg==0 && db->mallocFailed==0 );
2048 sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
2049 onError, iReg);
2050 sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
2051 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
2052 VdbeCoverage(v);
2053 break;
2054 }
2055 default: {
2056 assert( onError==OE_Ignore );
2057 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
2058 VdbeCoverage(v);
2059 break;
2060 }
2061 } /* end switch(onError) */
2062 } /* end loop i over columns */
2063 if( nGenerated==0 && nSeenReplace==0 ){
2064 /* If there are no generated columns with NOT NULL constraints
2065 ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
2066 ** pass is sufficient */
2067 break;
2068 }
2069 if( b2ndPass ) break; /* Never need more than 2 passes */
2070 b2ndPass = 1;
2071#ifndef SQLITE_OMIT_GENERATED_COLUMNS
2072 if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
2073 /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
2074 ** first pass, recomputed values for all generated columns, as
2075 ** those values might depend on columns affected by the REPLACE.
2076 */
2077 sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
2078 }
2079#endif
2080 } /* end of 2-pass loop */
2081 } /* end if( has-not-null-constraints ) */
2082
2083 /* Test all CHECK constraints
2084 */
2085#ifndef SQLITE_OMIT_CHECK
2086 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
2087 ExprList *pCheck = pTab->pCheck;
2088 pParse->iSelfTab = -(regNewData+1);
2089 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
2090 for(i=0; i<pCheck->nExpr; i++){
2091 int allOk;
2092 Expr *pCopy;
2093 Expr *pExpr = pCheck->a[i].pExpr;
2094 if( aiChng
2095 && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
2096 ){
2097 /* The check constraints do not reference any of the columns being
2098 ** updated so there is no point it verifying the check constraint */
2099 continue;
2100 }
2101 if( bAffinityDone==0 ){
2102 sqlite3TableAffinity(v, pTab, regNewData+1);
2103 bAffinityDone = 1;
2104 }
2105 allOk = sqlite3VdbeMakeLabel(pParse);
2106 sqlite3VdbeVerifyAbortable(v, onError);
2107 pCopy = sqlite3ExprDup(db, pExpr, 0);
2108 if( !db->mallocFailed ){
2109 sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
2110 }
2111 sqlite3ExprDelete(db, pCopy);
2112 if( onError==OE_Ignore ){
2113 sqlite3VdbeGoto(v, ignoreDest);
2114 }else{
2115 char *zName = pCheck->a[i].zEName;
2116 assert( zName!=0 || pParse->db->mallocFailed );
2117 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
2118 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
2119 onError, zName, P4_TRANSIENT,
2120 P5_ConstraintCheck);
2121 }
2122 sqlite3VdbeResolveLabel(v, allOk);
2123 }
2124 pParse->iSelfTab = 0;
2125 }
2126#endif /* !defined(SQLITE_OMIT_CHECK) */
2127
2128 /* UNIQUE and PRIMARY KEY constraints should be handled in the following
2129 ** order:
2130 **
2131 ** (1) OE_Update
2132 ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
2133 ** (3) OE_Replace
2134 **
2135 ** OE_Fail and OE_Ignore must happen before any changes are made.
2136 ** OE_Update guarantees that only a single row will change, so it
2137 ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
2138 ** could happen in any order, but they are grouped up front for
2139 ** convenience.
2140 **
2141 ** 2018-08-14: Ticket https://sqlite.org/src/info/908f001483982c43
2142 ** The order of constraints used to have OE_Update as (2) and OE_Abort
2143 ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
2144 ** constraint before any others, so it had to be moved.
2145 **
2146 ** Constraint checking code is generated in this order:
2147 ** (A) The rowid constraint
2148 ** (B) Unique index constraints that do not have OE_Replace as their
2149 ** default conflict resolution strategy
2150 ** (C) Unique index that do use OE_Replace by default.
2151 **
2152 ** The ordering of (2) and (3) is accomplished by making sure the linked
2153 ** list of indexes attached to a table puts all OE_Replace indexes last
2154 ** in the list. See sqlite3CreateIndex() for where that happens.
2155 */
2156 sIdxIter.eType = 0;
2157 sIdxIter.i = 0;
2158 sIdxIter.u.ax.aIdx = 0; /* Silence harmless compiler warning */
2159 sIdxIter.u.lx.pIdx = pTab->pIndex;
2160 if( pUpsert ){
2161 if( pUpsert->pUpsertTarget==0 ){
2162 /* There is just on ON CONFLICT clause and it has no constraint-target */
2163 assert( pUpsert->pNextUpsert==0 );
2164 if( pUpsert->isDoUpdate==0 ){
2165 /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
2166 ** Make all unique constraint resolution be OE_Ignore */
2167 overrideError = OE_Ignore;
2168 pUpsert = 0;
2169 }else{
2170 /* A single ON CONFLICT DO UPDATE. Make all resolutions OE_Update */
2171 overrideError = OE_Update;
2172 }
2173 }else if( pTab->pIndex!=0 ){
2174 /* Otherwise, we'll need to run the IndexListTerm array version of the
2175 ** iterator to ensure that all of the ON CONFLICT conditions are
2176 ** checked first and in order. */
2177 int nIdx, jj;
2178 u64 nByte;
2179 Upsert *pTerm;
2180 u8 *bUsed;
2181 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
2182 assert( aRegIdx[nIdx]>0 );
2183 }
2184 sIdxIter.eType = 1;
2185 sIdxIter.u.ax.nIdx = nIdx;
2186 nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx;
2187 sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte);
2188 if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */
2189 bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx];
2190 pUpsert->pToFree = sIdxIter.u.ax.aIdx;
2191 for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
2192 if( pTerm->pUpsertTarget==0 ) break;
2193 if( pTerm->pUpsertIdx==0 ) continue; /* Skip ON CONFLICT for the IPK */
2194 jj = 0;
2195 pIdx = pTab->pIndex;
2196 while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
2197 pIdx = pIdx->pNext;
2198 jj++;
2199 }
2200 if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */
2201 bUsed[jj] = 1;
2202 sIdxIter.u.ax.aIdx[i].p = pIdx;
2203 sIdxIter.u.ax.aIdx[i].ix = jj;
2204 i++;
2205 }
2206 for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
2207 if( bUsed[jj] ) continue;
2208 sIdxIter.u.ax.aIdx[i].p = pIdx;
2209 sIdxIter.u.ax.aIdx[i].ix = jj;
2210 i++;
2211 }
2212 assert( i==nIdx );
2213 }
2214 }
2215
2216 /* Determine if it is possible that triggers (either explicitly coded
2217 ** triggers or FK resolution actions) might run as a result of deletes
2218 ** that happen when OE_Replace conflict resolution occurs. (Call these
2219 ** "replace triggers".) If any replace triggers run, we will need to
2220 ** recheck all of the uniqueness constraints after they have all run.
2221 ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
2222 **
2223 ** If replace triggers are a possibility, then
2224 **
2225 ** (1) Allocate register regTrigCnt and initialize it to zero.
2226 ** That register will count the number of replace triggers that
2227 ** fire. Constraint recheck only occurs if the number is positive.
2228 ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
2229 ** (3) Initialize addrRecheck and lblRecheckOk
2230 **
2231 ** The uniqueness rechecking code will create a series of tests to run
2232 ** in a second pass. The addrRecheck and lblRecheckOk variables are
2233 ** used to link together these tests which are separated from each other
2234 ** in the generate bytecode.
2235 */
2236 if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
2237 /* There are not DELETE triggers nor FK constraints. No constraint
2238 ** rechecks are needed. */
2239 pTrigger = 0;
2240 regTrigCnt = 0;
2241 }else{
2242 if( db->flags&SQLITE_RecTriggers ){
2243 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
2244 regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
2245 }else{
2246 pTrigger = 0;
2247 regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
2248 }
2249 if( regTrigCnt ){
2250 /* At this point regTrigCnt is non-zero if there are DELETE triggers
2251 ** or FK triggers. But we only care about these things if there is
2252 ** a chance that a row will be deleted by an ON CONFLICT REPLACE
2253 ** constraint. So zero regTrigCnt if no such constraint can be found. */
2254 if( overrideError!=OE_Replace ){
2255 if( overrideError!=OE_Default ){
2256 regTrigCnt = 0;
2257 }else if( pkChng==0 || pPk || pTab->keyConf!=OE_Replace ){
2258 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2259 if( pIdx->onError==OE_Replace ) break;
2260 }
2261 if( pIdx==0 ) regTrigCnt = 0;
2262 }
2263 }
2264 }
2265 if( regTrigCnt ){
2266 /* Replace triggers might exist. Allocate the counter and
2267 ** initialize it to zero. */
2268 regTrigCnt = ++pParse->nMem;
2269 sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
2270 VdbeComment((v, "trigger count"));
2271 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2272 addrRecheck = lblRecheckOk;
2273 }
2274 }
2275
2276 /* If rowid is changing, make sure the new rowid does not previously
2277 ** exist in the table.
2278 */
2279 if( pkChng && pPk==0 ){
2280 int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
2281
2282 /* Figure out what action to take in case of a rowid collision */
2283 onError = pTab->keyConf;
2284 if( overrideError!=OE_Default ){
2285 onError = overrideError;
2286 }else if( onError==OE_Default ){
2287 onError = OE_Abort;
2288 }
2289
2290 /* figure out whether or not upsert applies in this case */
2291 if( pUpsert ){
2292 pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0);
2293 if( pUpsertClause!=0 ){
2294 if( pUpsertClause->isDoUpdate==0 ){
2295 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
2296 }else{
2297 onError = OE_Update; /* DO UPDATE */
2298 /* The excluded.* values used by the DO UPDATE must have
2299 ** column affinity applied before the rowid conflict check. */
2300 if( bAffinityDone==0 ){
2301 sqlite3TableAffinity(v, pTab, regNewData+1);
2302 bAffinityDone = 1;
2303 }
2304 }
2305 }
2306 if( pUpsertClause!=pUpsert ){
2307 /* The first ON CONFLICT clause has a conflict target other than
2308 ** the IPK. We have to jump ahead to that first ON CONFLICT clause
2309 ** and then come back here and deal with the IPK afterwards */
2310 upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto);
2311 }
2312 }
2313
2314 /* If the response to a rowid conflict is REPLACE but the response
2315 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
2316 ** to defer the running of the rowid conflict checking until after
2317 ** the UNIQUE constraints have run.
2318 */
2319 if( onError==OE_Replace /* IPK rule is REPLACE */
2320 && onError!=overrideError /* Rules for other constraints are different */
2321 && pTab->pIndex /* There exist other constraints */
2322 ){
2323 if( upsertIpkDelay ){
2324 ipkTop = upsertIpkDelay + 1;
2325 upsertIpkDelay = 0;
2326 }else{
2327 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
2328 }
2329 VdbeComment((v, "defer IPK REPLACE until last"));
2330 }
2331
2332 if( isUpdate ){
2333 /* pkChng!=0 does not mean that the rowid has changed, only that
2334 ** it might have changed. Skip the conflict logic below if the rowid
2335 ** is unchanged. */
2336 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
2337 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2338 VdbeCoverage(v);
2339 }
2340
2341 /* Check to see if the new rowid already exists in the table. Skip
2342 ** the following conflict logic if it does not. */
2343 VdbeNoopComment((v, "uniqueness check for ROWID"));
2344 sqlite3VdbeVerifyAbortable(v, onError);
2345 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
2346 VdbeCoverage(v);
2347
2348 switch( onError ){
2349 default: {
2350 onError = OE_Abort;
2351 /* no break */ deliberate_fall_through
2352 }
2353 case OE_Rollback:
2354 case OE_Abort:
2355 case OE_Fail: {
2356 testcase( onError==OE_Rollback );
2357 testcase( onError==OE_Abort );
2358 testcase( onError==OE_Fail );
2359 sqlite3RowidConstraint(pParse, onError, pTab);
2360 break;
2361 }
2362 case OE_Replace: {
2363 /* If there are DELETE triggers on this table and the
2364 ** recursive-triggers flag is set, call GenerateRowDelete() to
2365 ** remove the conflicting row from the table. This will fire
2366 ** the triggers and remove both the table and index b-tree entries.
2367 **
2368 ** Otherwise, if there are no triggers or the recursive-triggers
2369 ** flag is not set, but the table has one or more indexes, call
2370 ** GenerateRowIndexDelete(). This removes the index b-tree entries
2371 ** only. The table b-tree entry will be replaced by the new entry
2372 ** when it is inserted.
2373 **
2374 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
2375 ** also invoke MultiWrite() to indicate that this VDBE may require
2376 ** statement rollback (if the statement is aborted after the delete
2377 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
2378 ** but being more selective here allows statements like:
2379 **
2380 ** REPLACE INTO t(rowid) VALUES($newrowid)
2381 **
2382 ** to run without a statement journal if there are no indexes on the
2383 ** table.
2384 */
2385 if( regTrigCnt ){
2386 sqlite3MultiWrite(pParse);
2387 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2388 regNewData, 1, 0, OE_Replace, 1, -1);
2389 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2390 nReplaceTrig++;
2391 }else{
2392#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2393 assert( HasRowid(pTab) );
2394 /* This OP_Delete opcode fires the pre-update-hook only. It does
2395 ** not modify the b-tree. It is more efficient to let the coming
2396 ** OP_Insert replace the existing entry than it is to delete the
2397 ** existing entry and then insert a new one. */
2398 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
2399 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
2400#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2401 if( pTab->pIndex ){
2402 sqlite3MultiWrite(pParse);
2403 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
2404 }
2405 }
2406 seenReplace = 1;
2407 break;
2408 }
2409#ifndef SQLITE_OMIT_UPSERT
2410 case OE_Update: {
2411 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
2412 /* no break */ deliberate_fall_through
2413 }
2414#endif
2415 case OE_Ignore: {
2416 testcase( onError==OE_Ignore );
2417 sqlite3VdbeGoto(v, ignoreDest);
2418 break;
2419 }
2420 }
2421 sqlite3VdbeResolveLabel(v, addrRowidOk);
2422 if( ipkTop ){
2423 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
2424 sqlite3VdbeJumpHere(v, ipkTop-1);
2425 }else if( pUpsert && pUpsertClause!=pUpsert ){
2426 upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
2427 }
2428 }
2429
2430 /* Test all UNIQUE constraints by creating entries for each UNIQUE
2431 ** index and making sure that duplicate entries do not already exist.
2432 ** Compute the revised record entries for indices as we go.
2433 **
2434 ** This loop also handles the case of the PRIMARY KEY index for a
2435 ** WITHOUT ROWID table.
2436 */
2437 for(pIdx = indexIteratorFirst(&sIdxIter, &ix);
2438 pIdx;
2439 pIdx = indexIteratorNext(&sIdxIter, &ix)
2440 ){
2441 int regIdx; /* Range of registers holding content for pIdx */
2442 int regR; /* Range of registers holding conflicting PK */
2443 int iThisCur; /* Cursor for this UNIQUE index */
2444 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
2445 int addrConflictCk; /* First opcode in the conflict check logic */
2446 int nConflictCk; /* Number of opcodes in conflict check logic */
2447
2448 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
2449 if( pUpsert ){
2450 pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
2451 if( upsertIpkDelay && pUpsertClause==pUpsert ){
2452 sqlite3VdbeJumpHere(v, upsertIpkDelay);
2453 }
2454 }
2455 addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
2456 if( bAffinityDone==0 ){
2457 sqlite3TableAffinity(v, pTab, regNewData+1);
2458 bAffinityDone = 1;
2459 }
2460 VdbeNoopComment((v, "prep index %s", pIdx->zName));
2461 iThisCur = iIdxCur+ix;
2462
2463 /* If an OE_Replace resolution earlier in the constraint checks may
2464 ** have already deleted a conflicting row, and evaluating the partial
2465 ** index WHERE clause or an indexed expression for this index might
2466 ** raise an error, then a statement journal may be required to undo
2467 ** the deletion. */
2468 if( seenReplace && (pIdx->pPartIdxWhere || pIdx->aColExpr) ){
2469 sqlite3MultiWrite(pParse);
2470 }
2471
2472 /* Skip partial indices for which the WHERE clause is not true */
2473 if( pIdx->pPartIdxWhere ){
2474 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
2475 pParse->iSelfTab = -(regNewData+1);
2476 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
2477 SQLITE_JUMPIFNULL);
2478 pParse->iSelfTab = 0;
2479 }
2480
2481 /* Create a record for this index entry as it should appear after
2482 ** the insert or update. Store that record in the aRegIdx[ix] register
2483 */
2484 regIdx = aRegIdx[ix]+1;
2485 for(i=0; i<pIdx->nColumn; i++){
2486 int iField = pIdx->aiColumn[i];
2487 int x;
2488 if( iField==XN_EXPR ){
2489 pParse->iSelfTab = -(regNewData+1);
2490 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
2491 pParse->iSelfTab = 0;
2492 VdbeComment((v, "%s column %d", pIdx->zName, i));
2493 }else if( iField==XN_ROWID || iField==pTab->iPKey ){
2494 x = regNewData;
2495 sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
2496 VdbeComment((v, "rowid"));
2497 }else{
2498 testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
2499 x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
2500 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
2501 VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
2502 }
2503 }
2504 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
2505 VdbeComment((v, "for %s", pIdx->zName));
2506#ifdef SQLITE_ENABLE_NULL_TRIM
2507 if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
2508 sqlite3SetMakeRecordP5(v, pIdx->pTable);
2509 }
2510#endif
2511 sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
2512
2513 /* In an UPDATE operation, if this index is the PRIMARY KEY index
2514 ** of a WITHOUT ROWID table and there has been no change the
2515 ** primary key, then no collision is possible. The collision detection
2516 ** logic below can all be skipped. */
2517 if( isUpdate && pPk==pIdx && pkChng==0 ){
2518 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2519 continue;
2520 }
2521
2522 /* Find out what action to take in case there is a uniqueness conflict */
2523 onError = pIdx->onError;
2524 if( onError==OE_None ){
2525 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2526 continue; /* pIdx is not a UNIQUE index */
2527 }
2528 if( overrideError!=OE_Default ){
2529 onError = overrideError;
2530 }else if( onError==OE_Default ){
2531 onError = OE_Abort;
2532 }
2533
2534 /* Figure out if the upsert clause applies to this index */
2535 if( pUpsertClause ){
2536 if( pUpsertClause->isDoUpdate==0 ){
2537 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
2538 }else{
2539 onError = OE_Update; /* DO UPDATE */
2540 }
2541 }
2542
2543 /* Collision detection may be omitted if all of the following are true:
2544 ** (1) The conflict resolution algorithm is REPLACE
2545 ** (2) The table is a WITHOUT ROWID table
2546 ** (3) There are no secondary indexes on the table
2547 ** (4) No delete triggers need to be fired if there is a conflict
2548 ** (5) No FK constraint counters need to be updated if a conflict occurs.
2549 **
2550 ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
2551 ** must be explicitly deleted in order to ensure any pre-update hook
2552 ** is invoked. */
2553 assert( IsOrdinaryTable(pTab) );
2554#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
2555 if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
2556 && pPk==pIdx /* Condition 2 */
2557 && onError==OE_Replace /* Condition 1 */
2558 && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
2559 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
2560 && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
2561 (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
2562 ){
2563 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2564 continue;
2565 }
2566#endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
2567
2568 /* Check to see if the new index entry will be unique */
2569 sqlite3VdbeVerifyAbortable(v, onError);
2570 addrConflictCk =
2571 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
2572 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
2573
2574 /* Generate code to handle collisions */
2575 regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField);
2576 if( isUpdate || onError==OE_Replace ){
2577 if( HasRowid(pTab) ){
2578 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
2579 /* Conflict only if the rowid of the existing index entry
2580 ** is different from old-rowid */
2581 if( isUpdate ){
2582 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
2583 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2584 VdbeCoverage(v);
2585 }
2586 }else{
2587 int x;
2588 /* Extract the PRIMARY KEY from the end of the index entry and
2589 ** store it in registers regR..regR+nPk-1 */
2590 if( pIdx!=pPk ){
2591 for(i=0; i<pPk->nKeyCol; i++){
2592 assert( pPk->aiColumn[i]>=0 );
2593 x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
2594 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
2595 VdbeComment((v, "%s.%s", pTab->zName,
2596 pTab->aCol[pPk->aiColumn[i]].zCnName));
2597 }
2598 }
2599 if( isUpdate ){
2600 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
2601 ** table, only conflict if the new PRIMARY KEY values are actually
2602 ** different from the old. See TH3 withoutrowid04.test.
2603 **
2604 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
2605 ** of the matched index row are different from the original PRIMARY
2606 ** KEY values of this row before the update. */
2607 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
2608 int op = OP_Ne;
2609 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
2610
2611 for(i=0; i<pPk->nKeyCol; i++){
2612 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
2613 x = pPk->aiColumn[i];
2614 assert( x>=0 );
2615 if( i==(pPk->nKeyCol-1) ){
2616 addrJump = addrUniqueOk;
2617 op = OP_Eq;
2618 }
2619 x = sqlite3TableColumnToStorage(pTab, x);
2620 sqlite3VdbeAddOp4(v, op,
2621 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
2622 );
2623 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2624 VdbeCoverageIf(v, op==OP_Eq);
2625 VdbeCoverageIf(v, op==OP_Ne);
2626 }
2627 }
2628 }
2629 }
2630
2631 nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
2632 assert( nConflictCk>0 || db->mallocFailed );
2633 testcase( nConflictCk<=0 );
2634 testcase( nConflictCk>1 );
2635
2636 /* Generate code that executes if the new index entry is not unique */
2637 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
2638 || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
2639 switch( onError ){
2640 case OE_Rollback:
2641 case OE_Abort:
2642 case OE_Fail: {
2643 testcase( onError==OE_Rollback );
2644 testcase( onError==OE_Abort );
2645 testcase( onError==OE_Fail );
2646 sqlite3UniqueConstraint(pParse, onError, pIdx);
2647 break;
2648 }
2649#ifndef SQLITE_OMIT_UPSERT
2650 case OE_Update: {
2651 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
2652 /* no break */ deliberate_fall_through
2653 }
2654#endif
2655 case OE_Ignore: {
2656 testcase( onError==OE_Ignore );
2657 sqlite3VdbeGoto(v, ignoreDest);
2658 break;
2659 }
2660 default: {
2661 assert( onError==OE_Replace );
2662 if( regTrigCnt ){
2663 sqlite3MultiWrite(pParse);
2664 nReplaceTrig++;
2665 }
2666 if( pTrigger && isUpdate ){
2667 sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
2668 }
2669 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
2670 regR, nPkField, 0, OE_Replace,
2671 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
2672 if( pTrigger && isUpdate ){
2673 sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
2674 }
2675 seenReplace = 1;
2676 break;
2677 }
2678 }
2679 if( regTrigCnt ){
2680 int addrBypass; /* Jump destination to bypass recheck logic */
2681
2682 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2683 addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
2684 VdbeComment((v, "bypass recheck"));
2685
2686 /* Here we insert code that will be invoked after all constraint
2687 ** checks have run, if and only if one or more replace triggers
2688 ** fired. */
2689 sqlite3VdbeResolveLabel(v, lblRecheckOk);
2690 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2691 if( pIdx->pPartIdxWhere ){
2692 /* Bypass the recheck if this partial index is not defined
2693 ** for the current row */
2694 sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
2695 VdbeCoverage(v);
2696 }
2697 /* Copy the constraint check code from above, except change
2698 ** the constraint-ok jump destination to be the address of
2699 ** the next retest block */
2700 while( nConflictCk>0 ){
2701 VdbeOp x; /* Conflict check opcode to copy */
2702 /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
2703 ** Hence, make a complete copy of the opcode, rather than using
2704 ** a pointer to the opcode. */
2705 x = *sqlite3VdbeGetOp(v, addrConflictCk);
2706 if( x.opcode!=OP_IdxRowid || isUpdate ){
2707 int p2; /* New P2 value for copied conflict check opcode */
2708 const char *zP4;
2709 if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
2710 p2 = lblRecheckOk;
2711 }else{
2712 p2 = x.p2;
2713 }
2714 zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
2715 sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
2716 sqlite3VdbeChangeP5(v, x.p5);
2717 VdbeCoverageIf(v, p2!=x.p2);
2718 }
2719 nConflictCk--;
2720 addrConflictCk++;
2721 }
2722 /* If the retest fails, issue an abort */
2723 sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
2724
2725 sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
2726 }
2727 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2728 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
2729 if( pUpsertClause
2730 && upsertIpkReturn
2731 && sqlite3UpsertNextIsIPK(pUpsertClause)
2732 ){
2733 sqlite3VdbeGoto(v, upsertIpkDelay+1);
2734 sqlite3VdbeJumpHere(v, upsertIpkReturn);
2735 upsertIpkReturn = 0;
2736 }
2737 }
2738
2739 /* If the IPK constraint is a REPLACE, run it last */
2740 if( ipkTop ){
2741 sqlite3VdbeGoto(v, ipkTop);
2742 VdbeComment((v, "Do IPK REPLACE"));
2743 assert( ipkBottom>0 );
2744 sqlite3VdbeJumpHere(v, ipkBottom);
2745 }
2746
2747 /* Recheck all uniqueness constraints after replace triggers have run */
2748 testcase( regTrigCnt!=0 && nReplaceTrig==0 );
2749 assert( regTrigCnt!=0 || nReplaceTrig==0 );
2750 if( nReplaceTrig ){
2751 sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
2752 if( !pPk ){
2753 if( isUpdate ){
2754 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
2755 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2756 VdbeCoverage(v);
2757 }
2758 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
2759 VdbeCoverage(v);
2760 sqlite3RowidConstraint(pParse, OE_Abort, pTab);
2761 }else{
2762 sqlite3VdbeGoto(v, addrRecheck);
2763 }
2764 }
2765 if( regTrigCnt ) sqlite3VdbeResolveLabel(v, lblRecheckOk);
2766
2767 /* Generate the table record */
2768 if( HasRowid(pTab) ){
2769 int regRec = aRegIdx[ix];
2770 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
2771 sqlite3SetMakeRecordP5(v, pTab);
2772 if( !bAffinityDone ){
2773 sqlite3TableAffinity(v, pTab, 0);
2774 }
2775 }
2776
2777 *pbMayReplace = seenReplace;
2778 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
2779}
2780
2781#ifdef SQLITE_ENABLE_NULL_TRIM
2782/*
2783** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
2784** to be the number of columns in table pTab that must not be NULL-trimmed.
2785**
2786** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
2787*/
2788void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
2789 u16 i;
2790
2791 /* Records with omitted columns are only allowed for schema format
2792 ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
2793 if( pTab->pSchema->file_format<2 ) return;
2794
2795 for(i=pTab->nCol-1; i>0; i--){
2796 if( pTab->aCol[i].iDflt!=0 ) break;
2797 if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
2798 }
2799 sqlite3VdbeChangeP5(v, i+1);
2800}
2801#endif
2802
2803/*
2804** Table pTab is a WITHOUT ROWID table that is being written to. The cursor
2805** number is iCur, and register regData contains the new record for the
2806** PK index. This function adds code to invoke the pre-update hook,
2807** if one is registered.
2808*/
2809#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2810static void codeWithoutRowidPreupdate(
2811 Parse *pParse, /* Parse context */
2812 Table *pTab, /* Table being updated */
2813 int iCur, /* Cursor number for table */
2814 int regData /* Data containing new record */
2815){
2816 Vdbe *v = pParse->pVdbe;
2817 int r = sqlite3GetTempReg(pParse);
2818 assert( !HasRowid(pTab) );
2819 assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
2820 sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
2821 sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE);
2822 sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
2823 sqlite3ReleaseTempReg(pParse, r);
2824}
2825#else
2826# define codeWithoutRowidPreupdate(a,b,c,d)
2827#endif
2828
2829/*
2830** This routine generates code to finish the INSERT or UPDATE operation
2831** that was started by a prior call to sqlite3GenerateConstraintChecks.
2832** A consecutive range of registers starting at regNewData contains the
2833** rowid and the content to be inserted.
2834**
2835** The arguments to this routine should be the same as the first six
2836** arguments to sqlite3GenerateConstraintChecks.
2837*/
2838void sqlite3CompleteInsertion(
2839 Parse *pParse, /* The parser context */
2840 Table *pTab, /* the table into which we are inserting */
2841 int iDataCur, /* Cursor of the canonical data source */
2842 int iIdxCur, /* First index cursor */
2843 int regNewData, /* Range of content */
2844 int *aRegIdx, /* Register used by each index. 0 for unused indices */
2845 int update_flags, /* True for UPDATE, False for INSERT */
2846 int appendBias, /* True if this is likely to be an append */
2847 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
2848){
2849 Vdbe *v; /* Prepared statements under construction */
2850 Index *pIdx; /* An index being inserted or updated */
2851 u8 pik_flags; /* flag values passed to the btree insert */
2852 int i; /* Loop counter */
2853
2854 assert( update_flags==0
2855 || update_flags==OPFLAG_ISUPDATE
2856 || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
2857 );
2858
2859 v = pParse->pVdbe;
2860 assert( v!=0 );
2861 assert( !IsView(pTab) ); /* This table is not a VIEW */
2862 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2863 /* All REPLACE indexes are at the end of the list */
2864 assert( pIdx->onError!=OE_Replace
2865 || pIdx->pNext==0
2866 || pIdx->pNext->onError==OE_Replace );
2867 if( aRegIdx[i]==0 ) continue;
2868 if( pIdx->pPartIdxWhere || (update_flags && pIdx->bHasExpr) ){
2869 /* If this is a partial index, or an UPDATE of an index on an
2870 ** expression, then the record register may be set to NULL to indicate
2871 ** that no record should be inserted into this index. */
2872 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
2873 VdbeCoverage(v);
2874 }
2875 pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
2876 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2877 pik_flags |= OPFLAG_NCHANGE;
2878 pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
2879 if( update_flags==0 ){
2880 codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]);
2881 }
2882 }
2883 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
2884 aRegIdx[i]+1,
2885 pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
2886 sqlite3VdbeChangeP5(v, pik_flags);
2887 }
2888 if( !HasRowid(pTab) ) return;
2889 if( pParse->nested ){
2890 pik_flags = 0;
2891 }else{
2892 pik_flags = OPFLAG_NCHANGE;
2893 pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
2894 }
2895 if( appendBias ){
2896 pik_flags |= OPFLAG_APPEND;
2897 }
2898 if( useSeekResult ){
2899 pik_flags |= OPFLAG_USESEEKRESULT;
2900 }
2901 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
2902 if( !pParse->nested ){
2903 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
2904 }
2905 sqlite3VdbeChangeP5(v, pik_flags);
2906}
2907
2908/*
2909** Allocate cursors for the pTab table and all its indices and generate
2910** code to open and initialized those cursors.
2911**
2912** The cursor for the object that contains the complete data (normally
2913** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
2914** ROWID table) is returned in *piDataCur. The first index cursor is
2915** returned in *piIdxCur. The number of indices is returned.
2916**
2917** Use iBase as the first cursor (either the *piDataCur for rowid tables
2918** or the first index for WITHOUT ROWID tables) if it is non-negative.
2919** If iBase is negative, then allocate the next available cursor.
2920**
2921** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
2922** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
2923** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
2924** pTab->pIndex list.
2925**
2926** If pTab is a virtual table, then this routine is a no-op and the
2927** *piDataCur and *piIdxCur values are left uninitialized.
2928*/
2929int sqlite3OpenTableAndIndices(
2930 Parse *pParse, /* Parsing context */
2931 Table *pTab, /* Table to be opened */
2932 int op, /* OP_OpenRead or OP_OpenWrite */
2933 u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
2934 int iBase, /* Use this for the table cursor, if there is one */
2935 u8 *aToOpen, /* If not NULL: boolean for each table and index */
2936 int *piDataCur, /* Write the database source cursor number here */
2937 int *piIdxCur /* Write the first index cursor number here */
2938){
2939 int i;
2940 int iDb;
2941 int iDataCur;
2942 Index *pIdx;
2943 Vdbe *v;
2944
2945 assert( op==OP_OpenRead || op==OP_OpenWrite );
2946 assert( op==OP_OpenWrite || p5==0 );
2947 assert( piDataCur!=0 );
2948 assert( piIdxCur!=0 );
2949 if( IsVirtual(pTab) ){
2950 /* This routine is a no-op for virtual tables. Leave the output
2951 ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
2952 ** for improved error detection. */
2953 *piDataCur = *piIdxCur = -999;
2954 return 0;
2955 }
2956 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2957 v = pParse->pVdbe;
2958 assert( v!=0 );
2959 if( iBase<0 ) iBase = pParse->nTab;
2960 iDataCur = iBase++;
2961 *piDataCur = iDataCur;
2962 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
2963 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
2964 }else if( pParse->db->noSharedCache==0 ){
2965 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
2966 }
2967 *piIdxCur = iBase;
2968 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
2969 int iIdxCur = iBase++;
2970 assert( pIdx->pSchema==pTab->pSchema );
2971 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
2972 *piDataCur = iIdxCur;
2973 p5 = 0;
2974 }
2975 if( aToOpen==0 || aToOpen[i+1] ){
2976 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
2977 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2978 sqlite3VdbeChangeP5(v, p5);
2979 VdbeComment((v, "%s", pIdx->zName));
2980 }
2981 }
2982 if( iBase>pParse->nTab ) pParse->nTab = iBase;
2983 return i;
2984}
2985
2986
2987#ifdef SQLITE_TEST
2988/*
2989** The following global variable is incremented whenever the
2990** transfer optimization is used. This is used for testing
2991** purposes only - to make sure the transfer optimization really
2992** is happening when it is supposed to.
2993*/
2994int sqlite3_xferopt_count;
2995#endif /* SQLITE_TEST */
2996
2997
2998#ifndef SQLITE_OMIT_XFER_OPT
2999/*
3000** Check to see if index pSrc is compatible as a source of data
3001** for index pDest in an insert transfer optimization. The rules
3002** for a compatible index:
3003**
3004** * The index is over the same set of columns
3005** * The same DESC and ASC markings occurs on all columns
3006** * The same onError processing (OE_Abort, OE_Ignore, etc)
3007** * The same collating sequence on each column
3008** * The index has the exact same WHERE clause
3009*/
3010static int xferCompatibleIndex(Index *pDest, Index *pSrc){
3011 int i;
3012 assert( pDest && pSrc );
3013 assert( pDest->pTable!=pSrc->pTable );
3014 if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
3015 return 0; /* Different number of columns */
3016 }
3017 if( pDest->onError!=pSrc->onError ){
3018 return 0; /* Different conflict resolution strategies */
3019 }
3020 for(i=0; i<pSrc->nKeyCol; i++){
3021 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
3022 return 0; /* Different columns indexed */
3023 }
3024 if( pSrc->aiColumn[i]==XN_EXPR ){
3025 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
3026 if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
3027 pDest->aColExpr->a[i].pExpr, -1)!=0 ){
3028 return 0; /* Different expressions in the index */
3029 }
3030 }
3031 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
3032 return 0; /* Different sort orders */
3033 }
3034 if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
3035 return 0; /* Different collating sequences */
3036 }
3037 }
3038 if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
3039 return 0; /* Different WHERE clauses */
3040 }
3041
3042 /* If no test above fails then the indices must be compatible */
3043 return 1;
3044}
3045
3046/*
3047** Examine an expression node and abort if it references the ROWID.
3048** This is a Walker callback used by xferCompatibleCheck()
3049*/
3050static int xferCheckRowid(Walker *pWalk, Expr *pExpr){
3051 if( pExpr->op==TK_COLUMN && pExpr->iColumn<0 ){
3052 pWalk->eCode = 1;
3053 return WRC_Abort;
3054 }else{
3055 return WRC_Continue;
3056 }
3057}
3058
3059/*
3060** Analyze CHECK constraints on the source and destination tables and
3061** return true if those CHECK constraints are compatible with the
3062** xfer-optimization.
3063**
3064** * The pDest and pSrc tables must have identical CHECK constraints.
3065**
3066** * If the destination table, pDest, does not have an
3067** INTEGER PRIMARY KEY column, then no CHECK constraint may
3068** referenced the ROWID. (See forum post 2026-05-11T13:15:57Z)
3069*/
3070static int xferCompatibleCheck(Table *pDest, Table *pSrc){
3071 if( sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
3072 return 0;
3073 }
3074 if( pDest->iPKey<0 ){
3075 Walker w;
3076 memset(&w, 0, sizeof(w));
3077 w.xExprCallback = xferCheckRowid;
3078 sqlite3WalkExprList(&w,pDest->pCheck);
3079 if( w.eCode ) return 0;
3080 }
3081 return 1;
3082}
3083
3084/*
3085** Attempt the transfer optimization on INSERTs of the form
3086**
3087** INSERT INTO tab1 SELECT * FROM tab2;
3088**
3089** The xfer optimization transfers raw records from tab2 over to tab1.
3090** Columns are not decoded and reassembled, which greatly improves
3091** performance. Raw index records are transferred in the same way.
3092**
3093** The xfer optimization is only attempted if tab1 and tab2 are compatible.
3094** There are lots of rules for determining compatibility - see comments
3095** embedded in the code for details.
3096**
3097** This routine returns TRUE if the optimization is guaranteed to be used.
3098** Sometimes the xfer optimization will only work if the destination table
3099** is empty - a factor that can only be determined at run-time. In that
3100** case, this routine generates code for the xfer optimization but also
3101** does a test to see if the destination table is empty and jumps over the
3102** xfer optimization code if the test fails. In that case, this routine
3103** returns FALSE so that the caller will know to go ahead and generate
3104** an unoptimized transfer. This routine also returns FALSE if there
3105** is no chance that the xfer optimization can be applied.
3106**
3107** This optimization is particularly useful at making VACUUM run faster.
3108*/
3109static int xferOptimization(
3110 Parse *pParse, /* Parser context */
3111 Table *pDest, /* The table we are inserting into */
3112 Select *pSelect, /* A SELECT statement to use as the data source */
3113 int onError, /* How to handle constraint errors */
3114 int iDbDest /* The database of pDest */
3115){
3116 sqlite3 *db = pParse->db;
3117 ExprList *pEList; /* The result set of the SELECT */
3118 Table *pSrc; /* The table in the FROM clause of SELECT */
3119 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
3120 SrcItem *pItem; /* An element of pSelect->pSrc */
3121 int i; /* Loop counter */
3122 int iDbSrc; /* The database of pSrc */
3123 int iSrc, iDest; /* Cursors from source and destination */
3124 int addr1, addr2; /* Loop addresses */
3125 int emptyDestTest = 0; /* Address of test for empty pDest */
3126 int emptySrcTest = 0; /* Address of test for empty pSrc */
3127 Vdbe *v; /* The VDBE we are building */
3128 int regAutoinc; /* Memory register used by AUTOINC */
3129 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
3130 int regData, regRowid; /* Registers holding data and rowid */
3131
3132 assert( pSelect!=0 );
3133 if( pParse->pWith || pSelect->pWith ){
3134 /* Do not attempt to process this query if there are an WITH clauses
3135 ** attached to it. Proceeding may generate a false "no such table: xxx"
3136 ** error if pSelect reads from a CTE named "xxx". */
3137 return 0;
3138 }
3139#ifndef SQLITE_OMIT_VIRTUALTABLE
3140 if( IsVirtual(pDest) ){
3141 return 0; /* tab1 must not be a virtual table */
3142 }
3143#endif
3144 if( onError==OE_Default ){
3145 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
3146 if( onError==OE_Default ) onError = OE_Abort;
3147 }
3148 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
3149 if( pSelect->pSrc->nSrc!=1 ){
3150 return 0; /* FROM clause must have exactly one term */
3151 }
3152 if( pSelect->pSrc->a[0].fg.isSubquery ){
3153 return 0; /* FROM clause cannot contain a subquery */
3154 }
3155 if( pSelect->pWhere ){
3156 return 0; /* SELECT may not have a WHERE clause */
3157 }
3158 if( pSelect->pOrderBy ){
3159 return 0; /* SELECT may not have an ORDER BY clause */
3160 }
3161 /* Do not need to test for a HAVING clause. If HAVING is present but
3162 ** there is no ORDER BY, we will get an error. */
3163 if( pSelect->pGroupBy ){
3164 return 0; /* SELECT may not have a GROUP BY clause */
3165 }
3166 if( pSelect->pLimit ){
3167 return 0; /* SELECT may not have a LIMIT clause */
3168 }
3169 if( pSelect->pPrior ){
3170 return 0; /* SELECT may not be a compound query */
3171 }
3172 if( pSelect->selFlags & SF_Distinct ){
3173 return 0; /* SELECT may not be DISTINCT */
3174 }
3175 pEList = pSelect->pEList;
3176 assert( pEList!=0 );
3177 if( pEList->nExpr!=1 ){
3178 return 0; /* The result set must have exactly one column */
3179 }
3180 assert( pEList->a[0].pExpr );
3181 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
3182 return 0; /* The result set must be the special operator "*" */
3183 }
3184
3185 /* At this point we have established that the statement is of the
3186 ** correct syntactic form to participate in this optimization. Now
3187 ** we have to check the semantics.
3188 */
3189 pItem = pSelect->pSrc->a;
3190 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
3191 if( pSrc==0 ){
3192 return 0; /* FROM clause does not contain a real table */
3193 }
3194 if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
3195 testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
3196 return 0; /* tab1 and tab2 may not be the same table */
3197 }
3198 if( HasRowid(pDest)!=HasRowid(pSrc) ){
3199 return 0; /* source and destination must both be WITHOUT ROWID or not */
3200 }
3201 if( !IsOrdinaryTable(pSrc) ){
3202 return 0; /* tab2 may not be a view or virtual table */
3203 }
3204 if( pDest->nCol!=pSrc->nCol ){
3205 return 0; /* Number of columns must be the same in tab1 and tab2 */
3206 }
3207 if( pDest->iPKey!=pSrc->iPKey ){
3208 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
3209 }
3210 if( (pDest->tabFlags & TF_Strict)!=0 ){
3211 if( (pSrc->tabFlags & TF_Strict)==0 ){
3212 return 0; /* Cannot feed from a non-strict into a strict table */
3213 }
3214 for(i=0; i<pDest->nCol; i++){
3215 unsigned eDestType = pDest->aCol[i].eCType;
3216 unsigned eSrcType = pSrc->aCol[i].eCType;
3217 if( eDestType==COLTYPE_ANY ) continue;
3218 if( eDestType==eSrcType ) continue;
3219 if( eDestType==COLTYPE_INT && eSrcType==COLTYPE_INTEGER ) continue;
3220 if( eDestType==COLTYPE_INTEGER && eSrcType==COLTYPE_INT ) continue;
3221 return 0; /* Incompatible types in source and destination */
3222 }
3223 }
3224 for(i=0; i<pDest->nCol; i++){
3225 Column *pDestCol = &pDest->aCol[i];
3226 Column *pSrcCol = &pSrc->aCol[i];
3227#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
3228 if( (db->mDbFlags & DBFLAG_Vacuum)==0
3229 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
3230 ){
3231 return 0; /* Neither table may have __hidden__ columns */
3232 }
3233#endif
3234#ifndef SQLITE_OMIT_GENERATED_COLUMNS
3235 /* Even if tables t1 and t2 have identical schemas, if they contain
3236 ** generated columns, then this statement is semantically incorrect:
3237 **
3238 ** INSERT INTO t2 SELECT * FROM t1;
3239 **
3240 ** The reason is that generated column values are returned by the
3241 ** the SELECT statement on the right but the INSERT statement on the
3242 ** left wants them to be omitted.
3243 **
3244 ** Nevertheless, this is a useful notational shorthand to tell SQLite
3245 ** to do a bulk transfer all of the content from t1 over to t2.
3246 **
3247 ** We could, in theory, disable this (except for internal use by the
3248 ** VACUUM command where it is actually needed). But why do that? It
3249 ** seems harmless enough, and provides a useful service.
3250 */
3251 if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
3252 (pSrcCol->colFlags & COLFLAG_GENERATED) ){
3253 return 0; /* Both columns have the same generated-column type */
3254 }
3255 /* But the transfer is only allowed if both the source and destination
3256 ** tables have the exact same expressions for generated columns.
3257 ** This requirement could be relaxed for VIRTUAL columns, I suppose.
3258 */
3259 if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
3260 if( sqlite3ExprCompare(0,
3261 sqlite3ColumnExpr(pSrc, pSrcCol),
3262 sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
3263 testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
3264 testcase( pDestCol->colFlags & COLFLAG_STORED );
3265 return 0; /* Different generator expressions */
3266 }
3267 }
3268#endif
3269 if( pDestCol->affinity!=pSrcCol->affinity ){
3270 return 0; /* Affinity must be the same on all columns */
3271 }
3272 if( sqlite3_stricmp(sqlite3ColumnColl(pDestCol),
3273 sqlite3ColumnColl(pSrcCol))!=0 ){
3274 return 0; /* Collating sequence must be the same on all columns */
3275 }
3276 if( pDestCol->notNull && !pSrcCol->notNull ){
3277 return 0; /* tab2 must be NOT NULL if tab1 is */
3278 }
3279 /* Default values for second and subsequent columns need to match. */
3280 if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
3281 Expr *pDestExpr = sqlite3ColumnExpr(pDest, pDestCol);
3282 Expr *pSrcExpr = sqlite3ColumnExpr(pSrc, pSrcCol);
3283 assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
3284 assert( pDestExpr==0 || !ExprHasProperty(pDestExpr, EP_IntValue) );
3285 assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
3286 assert( pSrcExpr==0 || !ExprHasProperty(pSrcExpr, EP_IntValue) );
3287 if( (pDestExpr==0)!=(pSrcExpr==0)
3288 || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
3289 pSrcExpr->u.zToken)!=0)
3290 ){
3291 return 0; /* Default values must be the same for all columns */
3292 }
3293 }
3294 }
3295 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
3296 if( IsUniqueIndex(pDestIdx) ){
3297 destHasUniqueIdx = 1;
3298 }
3299 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
3300 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
3301 }
3302 if( pSrcIdx==0 ){
3303 return 0; /* pDestIdx has no corresponding index in pSrc */
3304 }
3305 if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
3306 && sqlite3FaultSim(411)==SQLITE_OK ){
3307 /* The sqlite3FaultSim() call allows this corruption test to be
3308 ** bypassed during testing, in order to exercise other corruption tests
3309 ** further downstream. */
3310 return 0; /* Corrupt schema - two indexes on the same btree */
3311 }
3312 }
3313#ifndef SQLITE_OMIT_CHECK
3314 if( pDest->pCheck
3315 && (db->mDbFlags & DBFLAG_Vacuum)==0
3316 && !xferCompatibleCheck(pDest,pSrc)
3317 ){
3318 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
3319 }
3320#endif
3321#ifndef SQLITE_OMIT_FOREIGN_KEY
3322 /* Disallow the transfer optimization if the destination table contains
3323 ** any foreign key constraints. This is more restrictive than necessary.
3324 ** But the main beneficiary of the transfer optimization is the VACUUM
3325 ** command, and the VACUUM command disables foreign key constraints. So
3326 ** the extra complication to make this rule less restrictive is probably
3327 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
3328 */
3329 assert( IsOrdinaryTable(pDest) );
3330 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
3331 return 0;
3332 }
3333#endif
3334 if( (db->flags & SQLITE_CountRows)!=0 ){
3335 return 0; /* xfer opt does not play well with PRAGMA count_changes */
3336 }
3337#ifndef SQLITE_OMIT_AUTHORIZATION
3338 if( db->xAuth ){
3339 int iDb = sqlite3SchemaToIndex(db, pSrc->pSchema);
3340 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 0;
3341 for(i=0; i<pSrc->nCol; i++){
3342 Column *pSrcCol = &pSrc->aCol[i];
3343 if( sqlite3AuthReadCol(pParse, pSrc->zName, pSrcCol->zCnName, iDb) ){
3344 return 0;
3345 }
3346 }
3347 }
3348#endif
3349
3350 /* If we get this far, it means that the xfer optimization is at
3351 ** least a possibility, though it might only work if the destination
3352 ** table (tab1) is initially empty.
3353 */
3354#ifdef SQLITE_TEST
3355 sqlite3_xferopt_count++;
3356#endif
3357 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
3358 v = sqlite3GetVdbe(pParse);
3359 sqlite3CodeVerifySchema(pParse, iDbSrc);
3360 iSrc = pParse->nTab++;
3361 iDest = pParse->nTab++;
3362 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
3363 regData = sqlite3GetTempReg(pParse);
3364 sqlite3VdbeAddOp2(v, OP_Null, 0, regData);
3365 regRowid = sqlite3GetTempReg(pParse);
3366 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
3367 assert( HasRowid(pDest) || destHasUniqueIdx );
3368 if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
3369 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
3370 || destHasUniqueIdx /* (2) */
3371 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
3372 )){
3373 /* In some circumstances, we are able to run the xfer optimization
3374 ** only if the destination table is initially empty. Unless the
3375 ** DBFLAG_Vacuum flag is set, this block generates code to make
3376 ** that determination. If DBFLAG_Vacuum is set, then the destination
3377 ** table is always empty.
3378 **
3379 ** Conditions under which the destination must be empty:
3380 **
3381 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
3382 ** (If the destination is not initially empty, the rowid fields
3383 ** of index entries might need to change.)
3384 **
3385 ** (2) The destination has a unique index. (The xfer optimization
3386 ** is unable to test uniqueness.)
3387 **
3388 ** (3) onError is something other than OE_Abort and OE_Rollback.
3389 */
3390 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
3391 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
3392 sqlite3VdbeJumpHere(v, addr1);
3393 }
3394 if( HasRowid(pSrc) ){
3395 u8 insFlags;
3396 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
3397 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
3398 if( pDest->iPKey>=0 ){
3399 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3400 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3401 sqlite3VdbeVerifyAbortable(v, onError);
3402 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
3403 VdbeCoverage(v);
3404 sqlite3RowidConstraint(pParse, onError, pDest);
3405 sqlite3VdbeJumpHere(v, addr2);
3406 }
3407 autoIncStep(pParse, regAutoinc, regRowid);
3408 }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
3409 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
3410 }else{
3411 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3412 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
3413 }
3414
3415 if( db->mDbFlags & DBFLAG_Vacuum ){
3416 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3417 insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3418 }else{
3419 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT;
3420 }
3421#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
3422 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3423 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3424 insFlags &= ~OPFLAG_PREFORMAT;
3425 }else
3426#endif
3427 {
3428 sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid);
3429 }
3430 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
3431 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3432 sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
3433 }
3434 sqlite3VdbeChangeP5(v, insFlags);
3435
3436 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
3437 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
3438 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3439 }else{
3440 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
3441 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
3442 }
3443 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
3444 u8 idxInsFlags = 0;
3445 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
3446 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
3447 }
3448 assert( pSrcIdx );
3449 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
3450 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
3451 VdbeComment((v, "%s", pSrcIdx->zName));
3452 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
3453 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
3454 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
3455 VdbeComment((v, "%s", pDestIdx->zName));
3456 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
3457 if( db->mDbFlags & DBFLAG_Vacuum ){
3458 /* This INSERT command is part of a VACUUM operation, which guarantees
3459 ** that the destination table is empty. If all indexed columns use
3460 ** collation sequence BINARY, then it can also be assumed that the
3461 ** index will be populated by inserting keys in strictly sorted
3462 ** order. In this case, instead of seeking within the b-tree as part
3463 ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
3464 ** OP_IdxInsert to seek to the point within the b-tree where each key
3465 ** should be inserted. This is faster.
3466 **
3467 ** If any of the indexed columns use a collation sequence other than
3468 ** BINARY, this optimization is disabled. This is because the user
3469 ** might change the definition of a collation sequence and then run
3470 ** a VACUUM command. In that case keys may not be written in strictly
3471 ** sorted order. */
3472 for(i=0; i<pSrcIdx->nColumn; i++){
3473 const char *zColl = pSrcIdx->azColl[i];
3474 if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
3475 }
3476 if( i==pSrcIdx->nColumn ){
3477 idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3478 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3479 sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc);
3480 }
3481 }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
3482 idxInsFlags |= OPFLAG_NCHANGE;
3483 }
3484 if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){
3485 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3486 if( (db->mDbFlags & DBFLAG_Vacuum)==0
3487 && !HasRowid(pDest)
3488 && IsPrimaryKeyIndex(pDestIdx)
3489 ){
3490 codeWithoutRowidPreupdate(pParse, pDest, iDest, regData);
3491 }
3492 }
3493 sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
3494 sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
3495 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
3496 sqlite3VdbeJumpHere(v, addr1);
3497 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
3498 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3499 }
3500 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
3501 sqlite3ReleaseTempReg(pParse, regRowid);
3502 sqlite3ReleaseTempReg(pParse, regData);
3503 if( emptyDestTest ){
3504 sqlite3AutoincrementEnd(pParse);
3505 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
3506 sqlite3VdbeJumpHere(v, emptyDestTest);
3507 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
3508 return 0;
3509 }else{
3510 return 1;
3511 }
3512}
3513#endif /* SQLITE_OMIT_XFER_OPT */