Thanks to visit codestin.com
Credit goes to chromium.googlesource.com

blob: f0c56a7a8f4a233c2d1086059501059a5ea39f8e [file] [log] [blame]
drhcce7d172000-05-31 15:34:511/*
drhb19a2bc2001-09-16 00:13:262** 2001 September 15
drhcce7d172000-05-31 15:34:513**
drhb19a2bc2001-09-16 00:13:264** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drhcce7d172000-05-31 15:34:516**
drhb19a2bc2001-09-16 00:13:267** 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.
drhcce7d172000-05-31 15:34:5110**
11*************************************************************************
12** This file contains C code routines that are called by the parser
drhb19a2bc2001-09-16 00:13:2613** to handle INSERT statements in SQLite.
drhcce7d172000-05-31 15:34:5114*/
15#include "sqliteInt.h"
16
17/*
larrybrbc917382023-06-07 08:40:3118** Generate code that will
drhdd9930e2013-10-23 23:37:0219**
drh26198bb2013-10-31 11:15:0920** (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.
drhbbb5e4e2009-04-30 00:11:0925*/
26void sqlite3OpenTable(
drh2ec2fb22013-11-06 19:59:2327 Parse *pParse, /* Generate code into this VDBE */
drhbbb5e4e2009-04-30 00:11:0928 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;
drh5f53aac2012-12-03 19:42:3934 assert( !IsVirtual(pTab) );
drh289a0c82020-08-15 22:23:0035 assert( pParse->pVdbe!=0 );
36 v = pParse->pVdbe;
drhbbb5e4e2009-04-30 00:11:0937 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
drh40ee7292023-06-20 17:45:1938 if( !pParse->db->noSharedCache ){
39 sqlite3TableLock(pParse, iDb, pTab->tnum,
40 (opcode==OP_OpenWrite)?1:0, pTab->zName);
41 }
drhec95c442013-10-23 01:57:3242 if( HasRowid(pTab) ){
drh0b0b3a92019-10-17 18:35:5743 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
drhdd9930e2013-10-23 23:37:0244 VdbeComment((v, "%s", pTab->zName));
drh26198bb2013-10-31 11:15:0945 }else{
drhdd9930e2013-10-23 23:37:0246 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
47 assert( pPk!=0 );
drh39075602022-01-01 12:26:0148 assert( pPk->tnum==pTab->tnum || CORRUPT_DB );
drh2ec2fb22013-11-06 19:59:2349 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
50 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
drhec95c442013-10-23 01:57:3251 VdbeComment((v, "%s", pTab->zName));
52 }
drhbbb5e4e2009-04-30 00:11:0953}
54
55/*
dan69f8bb92009-08-13 19:21:1656** Return a pointer to the column affinity string associated with index
larrybrbc917382023-06-07 08:40:3157** pIdx. A column affinity string has one character for each column in
dan69f8bb92009-08-13 19:21:1658** the table, according to the affinity of the column:
danielk19773d1bfea2004-05-14 11:00:5359**
60** Character Column affinity
61** ------------------------------
drh05883a32015-06-02 15:32:0862** 'A' BLOB
drh4583c372014-09-19 20:13:2563** 'B' TEXT
64** 'C' NUMERIC
65** 'D' INTEGER
66** 'F' REAL
drh2d401ab2008-01-10 23:50:1167**
drh4583c372014-09-19 20:13:2568** An extra 'D' is appended to the end of the string to cover the
drh2d401ab2008-01-10 23:50:1169** rowid that appears as the last column in every index.
dan69f8bb92009-08-13 19:21:1670**
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.
danielk19773d1bfea2004-05-14 11:00:5374*/
drhca4cf122023-02-27 18:55:3775static 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);
danielk1977a37cdde2004-05-16 11:15:3687 if( !pIdx->zColAff ){
drhca4cf122023-02-27 18:55:3788 sqlite3OomFault(db);
89 return 0;
danielk1977a37cdde2004-05-16 11:15:3690 }
drhca4cf122023-02-27 18:55:3791 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;
dan69f8bb92009-08-13 19:21:16109 return pIdx->zColAff;
danielk1977a37cdde2004-05-16 11:15:36110}
drhca4cf122023-02-27 18:55:37111const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
112 if( !pIdx->zColAff ) return computeIndexAffStr(db, pIdx);
113 return pIdx->zColAff;
114}
115
danielk1977a37cdde2004-05-16 11:15:36116
117/*
drh5fdb9a32022-11-01 00:52:22118** 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 }
larrybrbc917382023-06-07 08:40:31136 return zColAff;
drh5fdb9a32022-11-01 00:52:22137}
138
139/*
drh71c770f2021-08-19 16:29:33140** 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**
drh57bf4a82014-02-17 14:59:22146** Compute the affinity string for table pTab, if it has not already been
drh05883a32015-06-02 15:32:08147** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
drh57bf4a82014-02-17 14:59:22148**
drh71c770f2021-08-19 16:29:33149** 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,
drh57bf4a82014-02-17 14:59:22154** then just set the P4 operand of the previous opcode (which should be
155** an OP_MakeRecord) to the affinity string.
156**
drhb6e8fd12014-03-06 01:56:33157** A column affinity string has one character per column:
danielk1977a37cdde2004-05-16 11:15:36158**
drh71c770f2021-08-19 16:29:33159** 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**
larrybrbc917382023-06-07 08:40:31170** Generate an appropriate OP_TypeCheck opcode that will verify the
drh71c770f2021-08-19 16:29:33171** 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.
danielk1977a37cdde2004-05-16 11:15:36178*/
drh57bf4a82014-02-17 14:59:22179void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
drh5fdb9a32022-11-01 00:52:22180 int i;
drh72532f52021-08-18 19:22:27181 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;
drhbcf25e72025-06-18 16:17:00188 int p3;
drh72532f52021-08-18 19:22:27189 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
drh058e9952022-07-25 19:05:24190 pPrev = sqlite3VdbeGetLastOp(v);
drh71c770f2021-08-19 16:29:33191 assert( pPrev!=0 );
192 assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );
drh72532f52021-08-18 19:22:27193 pPrev->opcode = OP_TypeCheck;
drhbcf25e72025-06-18 16:17:00194 p3 = pPrev->p3;
195 pPrev->p3 = 0;
196 sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, p3);
drh72532f52021-08-18 19:22:27197 }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;
drh57bf4a82014-02-17 14:59:22205 if( zColAff==0 ){
drh5fdb9a32022-11-01 00:52:22206 zColAff = sqlite3TableAffinityStr(0, pTab);
danielk19773d1bfea2004-05-14 11:00:53207 if( !zColAff ){
drh5fdb9a32022-11-01 00:52:22208 sqlite3OomFault(sqlite3VdbeDb(v));
danielk1977a37cdde2004-05-16 11:15:36209 return;
danielk19773d1bfea2004-05-14 11:00:53210 }
danielk19773d1bfea2004-05-14 11:00:53211 pTab->zColAff = zColAff;
212 }
drh7301e772018-10-31 20:52:00213 assert( zColAff!=0 );
214 i = sqlite3Strlen30NN(zColAff);
drh57bf4a82014-02-17 14:59:22215 if( i ){
216 if( iReg ){
217 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
218 }else{
drh058e9952022-07-25 19:05:24219 assert( sqlite3VdbeGetLastOp(v)->opcode==OP_MakeRecord
drh71c770f2021-08-19 16:29:33220 || sqlite3VdbeDb(v)->mallocFailed );
drh57bf4a82014-02-17 14:59:22221 sqlite3VdbeChangeP4(v, -1, zColAff, i);
222 }
223 }
danielk19773d1bfea2004-05-14 11:00:53224}
225
danielk19774d887782005-02-08 08:42:27226/*
drh48d11782007-11-23 15:02:19227** Return non-zero if the table pTab in database iDb or any of its indices
larrybrbc917382023-06-07 08:40:31228** 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.
danielk19774d887782005-02-08 08:42:27231*/
drh05a86c52014-02-16 01:55:49232static int readsTable(Parse *p, int iDb, Table *pTab){
danielk1977595a5232009-07-24 17:58:53233 Vdbe *v = sqlite3GetVdbe(p);
danielk19774d887782005-02-08 08:42:27234 int i;
drh48d11782007-11-23 15:02:19235 int iEnd = sqlite3VdbeCurrentAddr(v);
danielk1977595a5232009-07-24 17:58:53236#ifndef SQLITE_OMIT_VIRTUALTABLE
237 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
238#endif
239
drh05a86c52014-02-16 01:55:49240 for(i=1; i<iEnd; i++){
drh48d11782007-11-23 15:02:19241 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
drhef0bea92007-12-14 16:11:09242 assert( pOp!=0 );
danielk1977207872a2008-01-03 07:54:23243 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
244 Index *pIndex;
drh8deae5a2020-07-29 12:23:20245 Pgno tnum = pOp->p2;
danielk1977207872a2008-01-03 07:54:23246 if( tnum==pTab->tnum ){
247 return 1;
248 }
249 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
250 if( tnum==pIndex->tnum ){
drh48d11782007-11-23 15:02:19251 return 1;
252 }
drh48d11782007-11-23 15:02:19253 }
254 }
drh543165e2007-11-27 14:46:41255#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977595a5232009-07-24 17:58:53256 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
danielk19772dca4ac2008-01-03 11:50:29257 assert( pOp->p4.pVtab!=0 );
drh66a51672008-01-03 00:01:23258 assert( pOp->p4type==P4_VTAB );
drh48d11782007-11-23 15:02:19259 return 1;
danielk19774d887782005-02-08 08:42:27260 }
drh543165e2007-11-27 14:46:41261#endif
danielk19774d887782005-02-08 08:42:27262 }
263 return 0;
264}
danielk19773d1bfea2004-05-14 11:00:53265
drhdfa15272019-11-06 22:19:07266/* This walker callback will compute the union of colFlags flags for all
drh7dc76d82019-11-21 20:10:31267** referenced columns in a CHECK constraint or generated column expression.
drhdfa15272019-11-06 22:19:07268*/
269static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
drh7dc76d82019-11-21 20:10:31270 if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
271 assert( pExpr->iColumn < pWalker->u.pTab->nCol );
drhdfa15272019-11-06 22:19:07272 pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
273 }
274 return WRC_Continue;
275}
276
drhc1431142019-10-17 17:54:05277#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
drhdd6cc9b2019-10-19 18:47:27281** 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.
drhc1431142019-10-17 17:54:05284*/
drhdd6cc9b2019-10-19 18:47:27285void sqlite3ComputeGeneratedColumns(
drhc1431142019-10-17 17:54:05286 Parse *pParse, /* Parsing context */
287 int iRegStore, /* Register holding the first column */
288 Table *pTab /* The table */
289){
290 int i;
drhdfa15272019-11-06 22:19:07291 Walker w;
292 Column *pRedo;
293 int eProgress;
drhb5f62432019-12-10 02:48:41294 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);
drh926aac52021-11-03 14:02:48304 if( (pTab->tabFlags & TF_HasStored)!=0 ){
drh058e9952022-07-25 19:05:24305 pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
drh926aac52021-11-03 14:02:48306 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 );
drh926aac52021-11-03 14:02:48314 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++;
drhb5f62432019-12-10 02:48:41322 }
drh926aac52021-11-03 14:02:48323 }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 */
drh926aac52021-11-03 14:02:48327 pOp->p3 = 1;
drhb5f62432019-12-10 02:48:41328 }
329 }
drhdfa15272019-11-06 22:19:07330
drhdd6cc9b2019-10-19 18:47:27331 /* 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".
drh9942ef02019-10-18 02:19:18334 */
335 for(i=0; i<pTab->nCol; i++){
drhdd6cc9b2019-10-19 18:47:27336 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
drhab0992f2019-10-23 03:53:10337 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
338 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
drh9942ef02019-10-18 02:19:18339 pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
340 }
341 }
drhdfa15272019-11-06 22:19:07342
343 w.u.pTab = pTab;
344 w.xExprCallback = exprColumnFlagUnion;
345 w.xSelectCallback = 0;
346 w.xSelectCallback2 = 0;
347
drh9942ef02019-10-18 02:19:18348 /* 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 */
drhc1431142019-10-17 17:54:05353 pParse->iSelfTab = -iRegStore;
drhdfa15272019-11-06 22:19:07354 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;
drh79cf2b72021-07-31 20:30:41363 sqlite3WalkExpr(&w, sqlite3ColumnExpr(pTab, pCol));
drhdfa15272019-11-06 22:19:07364 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;
drh79cf2b72021-07-31 20:30:41372 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, x);
drhdfa15272019-11-06 22:19:07373 pCol->colFlags &= ~COLFLAG_NOTAVAIL;
drhdd6cc9b2019-10-19 18:47:27374 }
drhc1431142019-10-17 17:54:05375 }
drhdfa15272019-11-06 22:19:07376 }while( pRedo && eProgress );
377 if( pRedo ){
drhcf9d36d2021-08-02 18:03:43378 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zCnName);
drhc1431142019-10-17 17:54:05379 }
380 pParse->iSelfTab = 0;
381}
382#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
383
384
drh9d9cf222007-02-13 15:01:11385#ifndef SQLITE_OMIT_AUTOINCREMENT
386/*
drh0b9f50d2009-06-23 20:28:53387** Locate or create an AutoincInfo structure associated with table pTab
388** which is in database iDb. Return the register number for the register
drh9ef5e772016-08-19 14:20:56389** 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.)
drh9d9cf222007-02-13 15:01:11392**
drh0b9f50d2009-06-23 20:28:53393** 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.
drh9d9cf222007-02-13 15:01:11398**
drhc8abbc12018-03-16 18:46:30399** Four consecutive registers are allocated:
drh0b9f50d2009-06-23 20:28:53400**
drhc8abbc12018-03-16 18:46:30401** (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
drh0b9f50d2009-06-23 20:28:53405**
406** The 2nd register is the one that is returned. That is all the
407** insert routine needs to know about.
drh9d9cf222007-02-13 15:01:11408*/
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){
drh6a288a32008-01-07 19:20:24414 int memId = 0; /* Register holding maximum rowid */
drh186ebd42018-05-23 16:50:21415 assert( pParse->db->aDb[iDb].pSchema!=0 );
drh9ef5e772016-08-19 14:20:56416 if( (pTab->tabFlags & TF_Autoincrement)!=0
drh8257aa82017-07-26 19:59:13417 && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
drh9ef5e772016-08-19 14:20:56418 ){
dan65a7cd12009-09-01 12:16:01419 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh0b9f50d2009-06-23 20:28:53420 AutoincInfo *pInfo;
drh186ebd42018-05-23 16:50:21421 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)
drh0003d872021-04-11 00:11:56428 || NEVER(IsVirtual(pSeqTab))
drh186ebd42018-05-23 16:50:21429 || pSeqTab->nCol!=2
430 ){
431 pParse->nErr++;
432 pParse->rc = SQLITE_CORRUPT_SEQUENCE;
433 return 0;
434 }
drh0b9f50d2009-06-23 20:28:53435
dan65a7cd12009-09-01 12:16:01436 pInfo = pToplevel->pAinc;
drh0b9f50d2009-06-23 20:28:53437 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
438 if( pInfo==0 ){
drh575fad62016-02-05 13:38:36439 pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
drh21d4f5b2021-01-12 15:30:01440 sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
441 testcase( pParse->earlyCleanup );
442 if( pParse->db->mallocFailed ) return 0;
dan65a7cd12009-09-01 12:16:01443 pInfo->pNext = pToplevel->pAinc;
444 pToplevel->pAinc = pInfo;
drh0b9f50d2009-06-23 20:28:53445 pInfo->pTab = pTab;
446 pInfo->iDb = iDb;
dan65a7cd12009-09-01 12:16:01447 pToplevel->nMem++; /* Register to hold name of table */
448 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
drhc8abbc12018-03-16 18:46:30449 pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
drh0b9f50d2009-06-23 20:28:53450 }
451 memId = pInfo->regCtr;
drh9d9cf222007-02-13 15:01:11452 }
453 return memId;
454}
455
456/*
drh0b9f50d2009-06-23 20:28:53457** This routine generates code that will initialize all of the
larrybrbc917382023-06-07 08:40:31458** register used by the autoincrement tracker.
drh0b9f50d2009-06-23 20:28:53459*/
460void sqlite3AutoincrementBegin(Parse *pParse){
461 AutoincInfo *p; /* Information about an AUTOINCREMENT */
462 sqlite3 *db = pParse->db; /* The database connection */
463 Db *pDb; /* Database only autoinc table */
464 int memId; /* Register holding max rowid */
drh0b9f50d2009-06-23 20:28:53465 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
466
drh345ba7d2009-09-08 13:40:16467 /* This routine is never called during trigger-generation. It is
468 ** only called from the top-level */
469 assert( pParse->pTriggerTab==0 );
drhc149f182015-09-29 13:25:15470 assert( sqlite3IsToplevel(pParse) );
dan76d462e2009-08-30 11:42:51471
drh0b9f50d2009-06-23 20:28:53472 assert( v ); /* We failed long ago if this is not so */
473 for(p = pParse->pAinc; p; p = p->pNext){
drh1b325542016-02-03 01:55:44474 static const int iLn = VDBE_OFFSET_LINENO(2);
475 static const VdbeOpList autoInc[] = {
476 /* 0 */ {OP_Null, 0, 0, 0},
drhc8abbc12018-03-16 18:46:30477 /* 1 */ {OP_Rewind, 0, 10, 0},
drh1b325542016-02-03 01:55:44478 /* 2 */ {OP_Column, 0, 0, 0},
drhc8abbc12018-03-16 18:46:30479 /* 3 */ {OP_Ne, 0, 9, 0},
drh1b325542016-02-03 01:55:44480 /* 4 */ {OP_Rowid, 0, 0, 0},
481 /* 5 */ {OP_Column, 0, 1, 0},
drhc8abbc12018-03-16 18:46:30482 /* 6 */ {OP_AddImm, 0, 0, 0},
483 /* 7 */ {OP_Copy, 0, 0, 0},
484 /* 8 */ {OP_Goto, 0, 11, 0},
485 /* 9 */ {OP_Next, 0, 2, 0},
486 /* 10 */ {OP_Integer, 0, 0, 0},
larrybrbc917382023-06-07 08:40:31487 /* 11 */ {OP_Close, 0, 0, 0}
drh1b325542016-02-03 01:55:44488 };
489 VdbeOp *aOp;
drh0b9f50d2009-06-23 20:28:53490 pDb = &db->aDb[p->iDb];
491 memId = p->regCtr;
drh21206082011-04-04 18:22:02492 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
drh0b9f50d2009-06-23 20:28:53493 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
drh076e85f2015-09-03 13:46:12494 sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
drh1b325542016-02-03 01:55:44495 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
496 if( aOp==0 ) break;
497 aOp[0].p2 = memId;
drhc8abbc12018-03-16 18:46:30498 aOp[0].p3 = memId+2;
drh1b325542016-02-03 01:55:44499 aOp[2].p3 = memId;
500 aOp[3].p1 = memId-1;
501 aOp[3].p3 = memId;
502 aOp[3].p5 = SQLITE_JUMPIFNULL;
503 aOp[4].p2 = memId+1;
504 aOp[5].p3 = memId;
drhc8abbc12018-03-16 18:46:30505 aOp[6].p1 = memId;
506 aOp[7].p2 = memId+2;
507 aOp[7].p1 = memId;
508 aOp[10].p2 = memId;
drh04ab5862018-12-01 21:13:41509 if( pParse->nTab==0 ) pParse->nTab = 1;
drh0b9f50d2009-06-23 20:28:53510 }
511}
512
513/*
drh9d9cf222007-02-13 15:01:11514** Update the maximum rowid for an autoincrement calculation.
515**
drh1b325542016-02-03 01:55:44516** This routine should be called when the regRowid register holds a
drh9d9cf222007-02-13 15:01:11517** new rowid that is about to be inserted. If that new rowid is
518** larger than the maximum rowid in the memId memory cell, then the
drh1b325542016-02-03 01:55:44519** memory cell is updated.
drh9d9cf222007-02-13 15:01:11520*/
drh6a288a32008-01-07 19:20:24521static void autoIncStep(Parse *pParse, int memId, int regRowid){
drh9d9cf222007-02-13 15:01:11522 if( memId>0 ){
drh6a288a32008-01-07 19:20:24523 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
drh9d9cf222007-02-13 15:01:11524 }
525}
526
527/*
drh0b9f50d2009-06-23 20:28:53528** This routine generates the code needed to write autoincrement
529** maximum rowid values back into the sqlite_sequence register.
530** Every statement that might do an INSERT into an autoincrement
531** table (either directly or through triggers) needs to call this
532** routine just before the "exit" code.
drh9d9cf222007-02-13 15:01:11533*/
drh1b325542016-02-03 01:55:44534static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
drh0b9f50d2009-06-23 20:28:53535 AutoincInfo *p;
536 Vdbe *v = pParse->pVdbe;
537 sqlite3 *db = pParse->db;
drh6a288a32008-01-07 19:20:24538
drh0b9f50d2009-06-23 20:28:53539 assert( v );
540 for(p = pParse->pAinc; p; p = p->pNext){
drh1b325542016-02-03 01:55:44541 static const int iLn = VDBE_OFFSET_LINENO(2);
542 static const VdbeOpList autoIncEnd[] = {
543 /* 0 */ {OP_NotNull, 0, 2, 0},
544 /* 1 */ {OP_NewRowid, 0, 0, 0},
545 /* 2 */ {OP_MakeRecord, 0, 2, 0},
546 /* 3 */ {OP_Insert, 0, 0, 0},
547 /* 4 */ {OP_Close, 0, 0, 0}
548 };
549 VdbeOp *aOp;
drh0b9f50d2009-06-23 20:28:53550 Db *pDb = &db->aDb[p->iDb];
drh0b9f50d2009-06-23 20:28:53551 int iRec;
552 int memId = p->regCtr;
553
554 iRec = sqlite3GetTempReg(pParse);
drh21206082011-04-04 18:22:02555 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
drhc8abbc12018-03-16 18:46:30556 sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
557 VdbeCoverage(v);
drh0b9f50d2009-06-23 20:28:53558 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
drh1b325542016-02-03 01:55:44559 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
560 if( aOp==0 ) break;
561 aOp[0].p1 = memId+1;
562 aOp[1].p2 = memId+1;
563 aOp[2].p1 = memId-1;
564 aOp[2].p3 = iRec;
565 aOp[3].p2 = iRec;
566 aOp[3].p3 = memId+1;
567 aOp[3].p5 = OPFLAG_APPEND;
drh0b9f50d2009-06-23 20:28:53568 sqlite3ReleaseTempReg(pParse, iRec);
drh9d9cf222007-02-13 15:01:11569 }
570}
drh1b325542016-02-03 01:55:44571void sqlite3AutoincrementEnd(Parse *pParse){
572 if( pParse->pAinc ) autoIncrementEnd(pParse);
573}
drh9d9cf222007-02-13 15:01:11574#else
575/*
576** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
577** above are all no-ops
578*/
579# define autoIncBegin(A,B,C) (0)
danielk1977287fb612008-01-04 19:10:28580# define autoIncStep(A,B,C)
drh9d9cf222007-02-13 15:01:11581#endif /* SQLITE_OMIT_AUTOINCREMENT */
582
dan56be6f62024-03-13 20:04:11583/*
584** If argument pVal is a Select object returned by an sqlite3MultiValues()
585** that was able to use the co-routine optimization, finish coding the
586** co-routine.
587*/
dan815e0552024-03-11 17:27:19588void sqlite3MultiValuesEnd(Parse *pParse, Select *pVal){
drhe4a1b4d2024-03-17 00:13:12589 if( ALWAYS(pVal) && pVal->pSrc->nSrc>0 ){
dan815e0552024-03-11 17:27:19590 SrcItem *pItem = &pVal->pSrc->a[0];
drhff4ad292024-08-20 16:50:21591 assert( (pItem->fg.isSubquery && pItem->u4.pSubq!=0) || pParse->nErr );
592 if( pItem->fg.isSubquery ){
593 sqlite3VdbeEndCoroutine(pParse->pVdbe, pItem->u4.pSubq->regReturn);
594 sqlite3VdbeJumpHere(pParse->pVdbe, pItem->u4.pSubq->addrFillSub - 1);
595 }
dan815e0552024-03-11 17:27:19596 }
597}
598
dan56be6f62024-03-13 20:04:11599/*
600** Return true if all expressions in the expression-list passed as the
601** only argument are constant.
602*/
drhf6965912024-03-16 13:18:48603static int exprListIsConstant(Parse *pParse, ExprList *pRow){
dan815e0552024-03-11 17:27:19604 int ii;
605 for(ii=0; ii<pRow->nExpr; ii++){
drhf6965912024-03-16 13:18:48606 if( 0==sqlite3ExprIsConstant(pParse, pRow->a[ii].pExpr) ) return 0;
dan815e0552024-03-11 17:27:19607 }
608 return 1;
609}
610
dan56be6f62024-03-13 20:04:11611/*
612** Return true if all expressions in the expression-list passed as the
613** only argument are both constant and have no affinity.
614*/
drhf6965912024-03-16 13:18:48615static int exprListIsNoAffinity(Parse *pParse, ExprList *pRow){
dan609aba02024-03-13 15:34:44616 int ii;
drhf6965912024-03-16 13:18:48617 if( exprListIsConstant(pParse,pRow)==0 ) return 0;
dan609aba02024-03-13 15:34:44618 for(ii=0; ii<pRow->nExpr; ii++){
drha509a902024-03-25 20:35:14619 Expr *pExpr = pRow->a[ii].pExpr;
620 assert( pExpr->op!=TK_RAISE );
621 assert( pExpr->affExpr==0 );
622 if( 0!=sqlite3ExprAffinity(pExpr) ) return 0;
dan609aba02024-03-13 15:34:44623 }
624 return 1;
625
626}
627
danaa2e2442024-03-13 18:41:05628/*
629** This function is called by the parser for the second and subsequent
dan56be6f62024-03-13 20:04:11630** rows of a multi-row VALUES clause. Argument pLeft is the part of
631** the VALUES clause already parsed, argument pRow is the vector of values
632** for the new row. The Select object returned represents the complete
633** VALUES clause, including the new row.
634**
635** There are two ways in which this may be achieved - by incremental
636** coding of a co-routine (the "co-routine" method) or by returning a
637** Select object equivalent to the following (the "UNION ALL" method):
638**
639** "pLeft UNION ALL SELECT pRow"
640**
641** If the VALUES clause contains a lot of rows, this compound Select
642** object may consume a lot of memory.
643**
644** When the co-routine method is used, each row that will be returned
645** by the VALUES clause is coded into part of a co-routine as it is
646** passed to this function. The returned Select object is equivalent to:
647**
648** SELECT * FROM (
649** Select object to read co-routine
650** )
651**
652** The co-routine method is used in most cases. Exceptions are:
653**
654** a) If the current statement has a WITH clause. This is to avoid
655** statements like:
656**
657** WITH cte AS ( VALUES('x'), ('y') ... )
658** SELECT * FROM cte AS a, cte AS b;
659**
660** This will not work, as the co-routine uses a hard-coded register
661** for its OP_Yield instructions, and so it is not possible for two
662** cursors to iterate through it concurrently.
663**
664** b) The schema is currently being parsed (i.e. the VALUES clause is part
665** of a schema item like a VIEW or TRIGGER). In this case there is no VM
666** being generated when parsing is taking place, and so generating
667** a co-routine is not possible.
668**
669** c) There are non-constant expressions in the VALUES clause (e.g.
670** the VALUES clause is part of a correlated sub-query).
671**
672** d) One or more of the values in the first row of the VALUES clause
673** has an affinity (i.e. is a CAST expression). This causes problems
674** because the complex rules SQLite uses (see function
675** sqlite3SubqueryColumnTypes() in select.c) to determine the effective
676** affinity of such a column for all rows require access to all values in
677** the column simultaneously.
danaa2e2442024-03-13 18:41:05678*/
dan815e0552024-03-11 17:27:19679Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow){
dan815e0552024-03-11 17:27:19680
drhc195e232024-03-18 16:30:00681 if( pParse->bHasWith /* condition (a) above */
drhf6965912024-03-16 13:18:48682 || pParse->db->init.busy /* condition (b) above */
683 || exprListIsConstant(pParse,pRow)==0 /* condition (c) above */
684 || (pLeft->pSrc->nSrc==0 &&
685 exprListIsNoAffinity(pParse,pLeft->pEList)==0) /* condition (d) above */
dan26a3ef72024-03-14 19:31:06686 || IN_SPECIAL_PARSE
dan815e0552024-03-11 17:27:19687 ){
dan56be6f62024-03-13 20:04:11688 /* The co-routine method cannot be used. Fall back to UNION ALL. */
danaa2e2442024-03-13 18:41:05689 Select *pSelect = 0;
dan815e0552024-03-11 17:27:19690 int f = SF_Values | SF_MultiValue;
dane116fa12024-03-13 15:44:31691 if( pLeft->pSrc->nSrc ){
dan815e0552024-03-11 17:27:19692 sqlite3MultiValuesEnd(pParse, pLeft);
693 f = SF_Values;
dane116fa12024-03-13 15:44:31694 }else if( pLeft->pPrior ){
danaa2e2442024-03-13 18:41:05695 /* In this case set the SF_MultiValue flag only if it was set on pLeft */
dane116fa12024-03-13 15:44:31696 f = (f & pLeft->selFlags);
dan815e0552024-03-11 17:27:19697 }
danaa2e2442024-03-13 18:41:05698 pSelect = sqlite3SelectNew(pParse, pRow, 0, 0, 0, 0, 0, f, 0);
drhce250072025-02-21 17:03:22699 pLeft->selFlags &= ~(u32)SF_MultiValue;
dan815e0552024-03-11 17:27:19700 if( pSelect ){
701 pSelect->op = TK_ALL;
702 pSelect->pPrior = pLeft;
703 pLeft = pSelect;
704 }
705 }else{
dan56be6f62024-03-13 20:04:11706 SrcItem *p = 0; /* SrcItem that reads from co-routine */
dan815e0552024-03-11 17:27:19707
708 if( pLeft->pSrc->nSrc==0 ){
dan56be6f62024-03-13 20:04:11709 /* Co-routine has not yet been started and the special Select object
710 ** that accesses the co-routine has not yet been created. This block
711 ** does both those things. */
dan815e0552024-03-11 17:27:19712 Vdbe *v = sqlite3GetVdbe(pParse);
dan56be6f62024-03-13 20:04:11713 Select *pRet = sqlite3SelectNew(pParse, 0, 0, 0, 0, 0, 0, 0, 0);
dan75924d32024-03-18 11:12:22714
715 /* Ensure the database schema has been read. This is to ensure we have
716 ** the correct text encoding. */
717 if( (pParse->db->mDbFlags & DBFLAG_SchemaKnownOk)==0 ){
718 sqlite3ReadSchema(pParse);
719 }
720
dan35057fb2024-03-13 17:33:45721 if( pRet ){
danaa2e2442024-03-13 18:41:05722 SelectDest dest;
drh1521ca42024-08-19 22:48:30723 Subquery *pSubq;
dan35057fb2024-03-13 17:33:45724 pRet->pSrc->nSrc = 1;
drhc195e232024-03-18 16:30:00725 pRet->pPrior = pLeft->pPrior;
726 pRet->op = pLeft->op;
drh1193e462024-08-08 14:45:50727 if( pRet->pPrior ) pRet->selFlags |= SF_Values;
drhc195e232024-03-18 16:30:00728 pLeft->pPrior = 0;
729 pLeft->op = TK_SELECT;
730 assert( pLeft->pNext==0 );
731 assert( pRet->pNext==0 );
danaa2e2442024-03-13 18:41:05732 p = &pRet->pSrc->a[0];
dan35057fb2024-03-13 17:33:45733 p->fg.viaCoroutine = 1;
dan35057fb2024-03-13 17:33:45734 p->iCursor = -1;
drh692c1602024-08-20 19:09:59735 assert( !p->fg.isIndexedBy && !p->fg.isTabFunc );
drh27a5ee82024-03-18 12:49:30736 p->u1.nRow = 2;
drh1521ca42024-08-19 22:48:30737 if( sqlite3SrcItemAttachSubquery(pParse, p, pLeft, 0) ){
738 pSubq = p->u4.pSubq;
739 pSubq->addrFillSub = sqlite3VdbeCurrentAddr(v) + 1;
740 pSubq->regReturn = ++pParse->nMem;
741 sqlite3VdbeAddOp3(v, OP_InitCoroutine,
742 pSubq->regReturn, 0, pSubq->addrFillSub);
743 sqlite3SelectDestInit(&dest, SRT_Coroutine, pSubq->regReturn);
danf0f43232024-03-14 17:04:18744
drh1521ca42024-08-19 22:48:30745 /* Allocate registers for the output of the co-routine. Do so so
746 ** that there are two unused registers immediately before those
747 ** used by the co-routine. This allows the code in sqlite3Insert()
748 ** to use these registers directly, instead of copying the output
749 ** of the co-routine to a separate array for processing. */
750 dest.iSdst = pParse->nMem + 3;
751 dest.nSdst = pLeft->pEList->nExpr;
752 pParse->nMem += 2 + dest.nSdst;
danf0f43232024-03-14 17:04:18753
drh1521ca42024-08-19 22:48:30754 pLeft->selFlags |= SF_MultiValue;
755 sqlite3Select(pParse, pLeft, &dest);
756 pSubq->regResult = dest.iSdst;
757 assert( pParse->nErr || dest.iSdst>0 );
758 }
dan35057fb2024-03-13 17:33:45759 pLeft = pRet;
760 }
dan815e0552024-03-11 17:27:19761 }else{
762 p = &pLeft->pSrc->a[0];
drhac7c6f52024-03-18 13:31:24763 assert( !p->fg.isTabFunc && !p->fg.isIndexedBy );
drh27a5ee82024-03-18 12:49:30764 p->u1.nRow++;
dan815e0552024-03-11 17:27:19765 }
766
767 if( pParse->nErr==0 ){
drh1521ca42024-08-19 22:48:30768 Subquery *pSubq;
drh2ad25842024-03-18 17:13:52769 assert( p!=0 );
drh1521ca42024-08-19 22:48:30770 assert( p->fg.isSubquery );
771 pSubq = p->u4.pSubq;
772 assert( pSubq!=0 );
773 assert( pSubq->pSelect!=0 );
774 assert( pSubq->pSelect->pEList!=0 );
775 if( pSubq->pSelect->pEList->nExpr!=pRow->nExpr ){
776 sqlite3SelectWrongNumTermsError(pParse, pSubq->pSelect);
danaa2e2442024-03-13 18:41:05777 }else{
drh1521ca42024-08-19 22:48:30778 sqlite3ExprCodeExprList(pParse, pRow, pSubq->regResult, 0, 0);
779 sqlite3VdbeAddOp1(pParse->pVdbe, OP_Yield, pSubq->regReturn);
dan815e0552024-03-11 17:27:19780 }
781 }
danaa2e2442024-03-13 18:41:05782 sqlite3ExprListDelete(pParse->db, pRow);
dan815e0552024-03-11 17:27:19783 }
784
785 return pLeft;
786}
drh9d9cf222007-02-13 15:01:11787
788/* Forward declaration */
789static int xferOptimization(
790 Parse *pParse, /* Parser context */
791 Table *pDest, /* The table we are inserting into */
792 Select *pSelect, /* A SELECT statement to use as the data source */
793 int onError, /* How to handle constraint errors */
794 int iDbDest /* The database of pDest */
795);
796
danielk19773d1bfea2004-05-14 11:00:53797/*
drhd82b5022013-10-26 00:58:34798** This routine is called to handle SQL of the following forms:
drhcce7d172000-05-31 15:34:51799**
drha21f78b2015-04-19 18:32:43800** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
drh1ccde152000-06-17 13:12:39801** insert into TABLE (IDLIST) select
drha21f78b2015-04-19 18:32:43802** insert into TABLE (IDLIST) default values
drhcce7d172000-05-31 15:34:51803**
drh1ccde152000-06-17 13:12:39804** The IDLIST following the table name is always optional. If omitted,
drha21f78b2015-04-19 18:32:43805** then a list of all (non-hidden) columns for the table is substituted.
806** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
807** is omitted.
drh1ccde152000-06-17 13:12:39808**
drha21f78b2015-04-19 18:32:43809** For the pSelect parameter holds the values to be inserted for the
810** first two forms shown above. A VALUES clause is really just short-hand
811** for a SELECT statement that omits the FROM clause and everything else
812** that follows. If the pSelect parameter is NULL, that means that the
813** DEFAULT VALUES form of the INSERT statement is intended.
drh142e30d2002-08-28 03:00:58814**
drh9d9cf222007-02-13 15:01:11815** The code generated follows one of four templates. For a simple
drha21f78b2015-04-19 18:32:43816** insert with data coming from a single-row VALUES clause, the code executes
drhe00ee6e2008-06-20 15:24:01817** once straight down through. Pseudo-code follows (we call this
818** the "1st template"):
drh142e30d2002-08-28 03:00:58819**
820** open write cursor to <table> and its indices
drhec95c442013-10-23 01:57:32821** put VALUES clause expressions into registers
drh142e30d2002-08-28 03:00:58822** write the resulting record into <table>
823** cleanup
824**
drh9d9cf222007-02-13 15:01:11825** The three remaining templates assume the statement is of the form
drh142e30d2002-08-28 03:00:58826**
827** INSERT INTO <table> SELECT ...
828**
drh9d9cf222007-02-13 15:01:11829** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
830** in other words if the SELECT pulls all columns from a single table
831** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
832** if <table2> and <table1> are distinct tables but have identical
833** schemas, including all the same indices, then a special optimization
834** is invoked that copies raw records from <table2> over to <table1>.
835** See the xferOptimization() function for the implementation of this
drhe00ee6e2008-06-20 15:24:01836** template. This is the 2nd template.
drh9d9cf222007-02-13 15:01:11837**
838** open a write cursor to <table>
839** open read cursor on <table2>
840** transfer all records in <table2> over to <table>
841** close cursors
842** foreach index on <table>
843** open a write cursor on the <table> index
844** open a read cursor on the corresponding <table2> index
845** transfer all records from the read to the write cursors
846** close cursors
847** end foreach
848**
drhe00ee6e2008-06-20 15:24:01849** The 3rd template is for when the second template does not apply
drh9d9cf222007-02-13 15:01:11850** and the SELECT clause does not read from <table> at any time.
851** The generated code follows this template:
drh142e30d2002-08-28 03:00:58852**
drhe00ee6e2008-06-20 15:24:01853** X <- A
drh142e30d2002-08-28 03:00:58854** goto B
855** A: setup for the SELECT
drh9d9cf222007-02-13 15:01:11856** loop over the rows in the SELECT
drhe00ee6e2008-06-20 15:24:01857** load values into registers R..R+n
858** yield X
drh142e30d2002-08-28 03:00:58859** end loop
860** cleanup after the SELECT
drh81cf13e2014-02-07 18:27:53861** end-coroutine X
drhe00ee6e2008-06-20 15:24:01862** B: open write cursor to <table> and its indices
drh81cf13e2014-02-07 18:27:53863** C: yield X, at EOF goto D
drhe00ee6e2008-06-20 15:24:01864** insert the select result into <table> from R..R+n
865** goto C
drh142e30d2002-08-28 03:00:58866** D: cleanup
867**
drhe00ee6e2008-06-20 15:24:01868** The 4th template is used if the insert statement takes its
drh142e30d2002-08-28 03:00:58869** values from a SELECT but the data is being inserted into a table
870** that is also read as part of the SELECT. In the third form,
peter.d.reid60ec9142014-09-06 16:39:46871** we have to use an intermediate table to store the results of
drh142e30d2002-08-28 03:00:58872** the select. The template is like this:
873**
drhe00ee6e2008-06-20 15:24:01874** X <- A
drh142e30d2002-08-28 03:00:58875** goto B
876** A: setup for the SELECT
877** loop over the tables in the SELECT
drhe00ee6e2008-06-20 15:24:01878** load value into register R..R+n
879** yield X
drh142e30d2002-08-28 03:00:58880** end loop
881** cleanup after the SELECT
drh81cf13e2014-02-07 18:27:53882** end co-routine R
drhe00ee6e2008-06-20 15:24:01883** B: open temp table
drh81cf13e2014-02-07 18:27:53884** L: yield X, at EOF goto M
drhe00ee6e2008-06-20 15:24:01885** insert row from R..R+n into temp table
886** goto L
887** M: open write cursor to <table> and its indices
888** rewind temp table
889** C: loop over rows of intermediate table
drh142e30d2002-08-28 03:00:58890** transfer values form intermediate table into <table>
drhe00ee6e2008-06-20 15:24:01891** end loop
892** D: cleanup
drhcce7d172000-05-31 15:34:51893*/
danielk19774adee202004-05-08 08:23:19894void sqlite3Insert(
drhcce7d172000-05-31 15:34:51895 Parse *pParse, /* Parser context */
drh113088e2003-03-20 01:16:58896 SrcList *pTabList, /* Name of table into which we are inserting */
drh5974a302000-06-07 14:42:26897 Select *pSelect, /* A SELECT statement to use as the data source */
drhf5f19152019-10-21 01:04:11898 IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */
drh2c2e8442018-04-07 15:04:05899 int onError, /* How to handle constraint errors */
drh46d2e5c2018-04-12 13:15:43900 Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
drhcce7d172000-05-31 15:34:51901){
drh6a288a32008-01-07 19:20:24902 sqlite3 *db; /* The main database structure */
903 Table *pTab; /* The table to insert into. aka TABLE */
drh60ffc802016-11-21 21:33:46904 int i, j; /* Loop counters */
drh5974a302000-06-07 14:42:26905 Vdbe *v; /* Generate code into this virtual machine */
906 Index *pIdx; /* For looping over indices of the table */
drh967e8b72000-06-21 13:59:10907 int nColumn; /* Number of columns in the data */
drh6a288a32008-01-07 19:20:24908 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
drh26198bb2013-10-31 11:15:09909 int iDataCur = 0; /* VDBE cursor that is the main data repository */
910 int iIdxCur = 0; /* First index cursor */
drhd82b5022013-10-26 00:58:34911 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
drh0ca3e242002-01-29 23:07:02912 int endOfLoop; /* Label for the end of the insertion loop */
danielk1977cfe9a692004-06-16 12:00:29913 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
drhe00ee6e2008-06-20 15:24:01914 int addrInsTop = 0; /* Jump to label "D" */
915 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
drh2eb95372008-06-06 15:04:36916 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
drh6a288a32008-01-07 19:20:24917 int iDb; /* Index of database holding TABLE */
drh05a86c52014-02-16 01:55:49918 u8 useTempTable = 0; /* Store SELECT results in intermediate table */
919 u8 appendFlag = 0; /* True if the insert is likely to be an append */
920 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
drha21f78b2015-04-19 18:32:43921 u8 bIdListInOrder; /* True if IDLIST is in table order */
drh75593d92014-01-10 20:46:55922 ExprList *pList = 0; /* List of VALUES() to be inserted */
drhc27ea2a2019-10-16 20:05:56923 int iRegStore; /* Register in which to store next column */
drhcce7d172000-05-31 15:34:51924
drh6a288a32008-01-07 19:20:24925 /* Register allocations */
drh1bd10f82008-12-10 21:19:56926 int regFromSelect = 0;/* Base register for data coming from SELECT */
drh6a288a32008-01-07 19:20:24927 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
928 int regRowCount = 0; /* Memory cell used for the row counter */
929 int regIns; /* Block of regs holding rowid+data being inserted */
930 int regRowid; /* registers holding insert rowid */
931 int regData; /* register holding first column to insert */
drhaa9b8962008-01-08 02:57:55932 int *aRegIdx = 0; /* One register allocated to each index */
drh8b62a822025-01-28 12:50:17933 int *aTabColMap = 0; /* Mapping from pTab columns to pCol entries */
drh6a288a32008-01-07 19:20:24934
drh798da522004-11-04 04:42:28935#ifndef SQLITE_OMIT_TRIGGER
936 int isView; /* True if attempting to insert into a view */
danielk19772f886d12009-02-28 10:47:41937 Trigger *pTrigger; /* List of triggers on pTab, if required */
938 int tmask; /* Mask of trigger times */
drh798da522004-11-04 04:42:28939#endif
danielk1977c3f9bad2002-05-15 08:30:12940
drh17435752007-08-16 04:30:38941 db = pParse->db;
drh0c7d3d32022-01-24 16:47:12942 assert( db->pParse==pParse );
943 if( pParse->nErr ){
drh6f7adc82006-01-11 21:41:20944 goto insert_cleanup;
945 }
drh0c7d3d32022-01-24 16:47:12946 assert( db->mallocFailed==0 );
drh4c883482017-06-03 20:09:37947 dest.iSDParm = 0; /* Suppress a harmless compiler warning */
drhdaffd0e2001-04-11 14:28:42948
drh75593d92014-01-10 20:46:55949 /* If the Select object is really just a simple VALUES() list with a
drha21f78b2015-04-19 18:32:43950 ** single row (the common case) then keep that one row of values
951 ** and discard the other (unused) parts of the pSelect object
drh75593d92014-01-10 20:46:55952 */
953 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
954 pList = pSelect->pEList;
955 pSelect->pEList = 0;
956 sqlite3SelectDelete(db, pSelect);
957 pSelect = 0;
958 }
959
drh1ccde152000-06-17 13:12:39960 /* Locate the table into which we will be inserting new information.
961 */
drh113088e2003-03-20 01:16:58962 assert( pTabList->nSrc==1 );
danielk19774adee202004-05-08 08:23:19963 pTab = sqlite3SrcListLookup(pParse, pTabList);
danielk1977c3f9bad2002-05-15 08:30:12964 if( pTab==0 ){
danielk1977c3f9bad2002-05-15 08:30:12965 goto insert_cleanup;
966 }
danielk1977da184232006-01-05 11:34:32967 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
968 assert( iDb<db->nDb );
drha0daa752016-09-16 11:53:10969 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
970 db->aDb[iDb].zDbSName) ){
drh1962bda2003-01-12 19:33:52971 goto insert_cleanup;
972 }
drhec95c442013-10-23 01:57:32973 withoutRowid = !HasRowid(pTab);
danielk1977c3f9bad2002-05-15 08:30:12974
drhb7f91642004-10-31 02:22:47975 /* Figure out if we have any triggers and if the table being
976 ** inserted into is a view
977 */
978#ifndef SQLITE_OMIT_TRIGGER
danielk19772f886d12009-02-28 10:47:41979 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
drhf38524d2021-08-02 16:41:57980 isView = IsView(pTab);
drhb7f91642004-10-31 02:22:47981#else
danielk19772f886d12009-02-28 10:47:41982# define pTrigger 0
983# define tmask 0
drhb7f91642004-10-31 02:22:47984# define isView 0
985#endif
986#ifdef SQLITE_OMIT_VIEW
987# undef isView
988# define isView 0
989#endif
danielk19772f886d12009-02-28 10:47:41990 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
drhb7f91642004-10-31 02:22:47991
drh2a7dcbf2022-04-06 15:41:53992#if TREETRACE_ENABLED
993 if( sqlite3TreeTrace & 0x10000 ){
994 sqlite3TreeViewLine(0, "In sqlite3Insert() at %s:%d", __FILE__, __LINE__);
drhc2d0df92022-04-06 18:30:17995 sqlite3TreeViewInsert(pParse->pWith, pTabList, pColumn, pSelect, pList,
drh2a7dcbf2022-04-06 15:41:53996 onError, pUpsert, pTrigger);
997 }
998#endif
999
drhf573c992002-07-31 00:32:501000 /* If pTab is really a view, make sure it has been initialized.
drhd82b5022013-10-26 00:58:341001 ** ViewGetColumnNames() is a no-op if pTab is not a view.
drhf573c992002-07-31 00:32:501002 */
danielk1977b3d24bf2006-06-19 03:05:101003 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
drh5cf590c2003-04-24 01:45:041004 goto insert_cleanup;
drhf573c992002-07-31 00:32:501005 }
1006
drhd82b5022013-10-26 00:58:341007 /* Cannot insert into a read-only table.
danielk1977595a5232009-07-24 17:58:531008 */
drh3cbf38c2023-03-28 11:18:041009 if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
danielk1977595a5232009-07-24 17:58:531010 goto insert_cleanup;
1011 }
1012
drh1ccde152000-06-17 13:12:391013 /* Allocate a VDBE
1014 */
danielk19774adee202004-05-08 08:23:191015 v = sqlite3GetVdbe(pParse);
drh5974a302000-06-07 14:42:261016 if( v==0 ) goto insert_cleanup;
drh4794f732004-11-05 17:17:501017 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
danielk19772f886d12009-02-28 10:47:411018 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
drh1ccde152000-06-17 13:12:391019
drh9d9cf222007-02-13 15:01:111020#ifndef SQLITE_OMIT_XFER_OPT
1021 /* If the statement is of the form
1022 **
1023 ** INSERT INTO <table1> SELECT * FROM <table2>;
1024 **
1025 ** Then special optimizations can be applied that make the transfer
1026 ** very fast and which reduce fragmentation of indices.
drhe00ee6e2008-06-20 15:24:011027 **
1028 ** This is the 2nd template.
drh9d9cf222007-02-13 15:01:111029 */
larrybrbc917382023-06-07 08:40:311030 if( pColumn==0
drh935c3722022-02-28 16:44:581031 && pSelect!=0
1032 && pTrigger==0
1033 && xferOptimization(pParse, pTab, pSelect, onError, iDb)
1034 ){
danielk19772f886d12009-02-28 10:47:411035 assert( !pTrigger );
drh9d9cf222007-02-13 15:01:111036 assert( pList==0 );
drh0b9f50d2009-06-23 20:28:531037 goto insert_end;
drh9d9cf222007-02-13 15:01:111038 }
1039#endif /* SQLITE_OMIT_XFER_OPT */
1040
drh2958a4e2004-11-12 03:56:151041 /* If this is an AUTOINCREMENT table, look up the sequence number in the
drh6a288a32008-01-07 19:20:241042 ** sqlite_sequence table and store it in memory cell regAutoinc.
drh2958a4e2004-11-12 03:56:151043 */
drh6a288a32008-01-07 19:20:241044 regAutoinc = autoIncBegin(pParse, iDb, pTab);
drh2958a4e2004-11-12 03:56:151045
drhf5f19152019-10-21 01:04:111046 /* Allocate a block registers to hold the rowid and the values
1047 ** for all columns of the new row.
drh1ccde152000-06-17 13:12:391048 */
drh05a86c52014-02-16 01:55:491049 regRowid = regIns = pParse->nMem+1;
1050 pParse->nMem += pTab->nCol + 1;
danielk1977034ca142007-06-26 10:38:541051 if( IsVirtual(pTab) ){
drh05a86c52014-02-16 01:55:491052 regRowid++;
1053 pParse->nMem++;
danielk1977034ca142007-06-26 10:38:541054 }
drh05a86c52014-02-16 01:55:491055 regData = regRowid+1;
drh1ccde152000-06-17 13:12:391056
1057 /* If the INSERT statement included an IDLIST term, then make sure
larrybrbc917382023-06-07 08:40:311058 ** all elements of the IDLIST really are columns of the table and
drh1ccde152000-06-17 13:12:391059 ** remember the column indices.
drhc8392582001-12-31 02:48:511060 **
1061 ** If the table has an INTEGER PRIMARY KEY column and that column
drhd82b5022013-10-26 00:58:341062 ** is named in the IDLIST, then record in the ipkColumn variable
1063 ** the index into IDLIST of the primary key column. ipkColumn is
drhc8392582001-12-31 02:48:511064 ** the index of the primary key as it appears in IDLIST, not as
drhd82b5022013-10-26 00:58:341065 ** is appears in the original table. (The index of the INTEGER
drhf5f19152019-10-21 01:04:111066 ** PRIMARY KEY in the original table is pTab->iPKey.) After this
1067 ** loop, if ipkColumn==(-1), that means that integer primary key
1068 ** is unspecified, and hence the table is either WITHOUT ROWID or
1069 ** it will automatically generated an integer primary key.
1070 **
1071 ** bIdListInOrder is true if the columns in IDLIST are in storage
1072 ** order. This enables an optimization that avoids shuffling the
1073 ** columns into storage order. False negatives are harmless,
1074 ** but false positives will cause database corruption.
drh1ccde152000-06-17 13:12:391075 */
drhd4cd2922019-10-17 18:07:221076 bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
drh967e8b72000-06-21 13:59:101077 if( pColumn ){
drh8b62a822025-01-28 12:50:171078 aTabColMap = sqlite3DbMallocZero(db, pTab->nCol*sizeof(int));
1079 if( aTabColMap==0 ) goto insert_cleanup;
drh967e8b72000-06-21 13:59:101080 for(i=0; i<pColumn->nId; i++){
drh9d90a3a2025-02-08 14:15:421081 j = sqlite3ColumnIndex(pTab, pColumn->a[i].zName);
1082 if( j>=0 ){
1083 if( aTabColMap[j]==0 ) aTabColMap[j] = i+1;
1084 if( i!=j ) bIdListInOrder = 0;
1085 if( j==pTab->iPKey ){
1086 ipkColumn = i; assert( !withoutRowid );
drhcce7d172000-05-31 15:34:511087 }
drh9d90a3a2025-02-08 14:15:421088#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1089 if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
1090 sqlite3ErrorMsg(pParse,
1091 "cannot INSERT into generated column \"%s\"",
1092 pTab->aCol[j].zCnName);
1093 goto insert_cleanup;
1094 }
1095#endif
1096 }else{
drhec95c442013-10-23 01:57:321097 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
drhd82b5022013-10-26 00:58:341098 ipkColumn = i;
drhe48ae712014-05-23 11:48:571099 bIdListInOrder = 0;
drha0217ba2003-06-01 01:10:331100 }else{
danielk19774adee202004-05-08 08:23:191101 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
drha9799932021-03-19 13:00:281102 pTabList->a, pColumn->a[i].zName);
dan1db95102010-06-28 10:15:191103 pParse->checkSchema = 1;
drha0217ba2003-06-01 01:10:331104 goto insert_cleanup;
1105 }
drhcce7d172000-05-31 15:34:511106 }
1107 }
1108 }
drh1ccde152000-06-17 13:12:391109
drhcce7d172000-05-31 15:34:511110 /* Figure out how many columns of data are supplied. If the data
1111 ** is coming from a SELECT statement, then generate a co-routine that
1112 ** produces a single row of the SELECT on each invocation. The
1113 ** co-routine is the common header to the 3rd and 4th templates.
1114 */
drh5f085262012-09-15 13:29:231115 if( pSelect ){
drha21f78b2015-04-19 18:32:431116 /* Data is coming from a SELECT or from a multi-row VALUES clause.
1117 ** Generate a co-routine to run the SELECT. */
drh05a86c52014-02-16 01:55:491118 int rc; /* Result code */
drhcce7d172000-05-31 15:34:511119
dan400992b2024-03-14 19:01:171120 if( pSelect->pSrc->nSrc==1
1121 && pSelect->pSrc->a[0].fg.viaCoroutine
1122 && pSelect->pPrior==0
1123 ){
dan815e0552024-03-11 17:27:191124 SrcItem *pItem = &pSelect->pSrc->a[0];
drh1521ca42024-08-19 22:48:301125 Subquery *pSubq;
1126 assert( pItem->fg.isSubquery );
1127 pSubq = pItem->u4.pSubq;
1128 dest.iSDParm = pSubq->regReturn;
1129 regFromSelect = pSubq->regResult;
1130 assert( pSubq->pSelect!=0 );
1131 assert( pSubq->pSelect->pEList!=0 );
1132 nColumn = pSubq->pSelect->pEList->nExpr;
drh27a5ee82024-03-18 12:49:301133 ExplainQueryPlan((pParse, 0, "SCAN %S", pItem));
danf0f43232024-03-14 17:04:181134 if( bIdListInOrder && nColumn==pTab->nCol ){
1135 regData = regFromSelect;
1136 regRowid = regData - 1;
1137 regIns = regRowid - (IsVirtual(pTab) ? 1 : 0);
1138 }
dan815e0552024-03-11 17:27:191139 }else{
1140 int addrTop; /* Top of the co-routine */
drh2ad25842024-03-18 17:13:521141 int regYield = ++pParse->nMem;
dan815e0552024-03-11 17:27:191142 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
1143 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
1144 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
1145 dest.iSdst = bIdListInOrder ? regData : 0;
1146 dest.nSdst = pTab->nCol;
1147 rc = sqlite3Select(pParse, pSelect, &dest);
1148 regFromSelect = dest.iSdst;
1149 assert( db->pParse==pParse );
1150 if( rc || pParse->nErr ) goto insert_cleanup;
1151 assert( db->mallocFailed==0 );
1152 sqlite3VdbeEndCoroutine(v, regYield);
1153 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
1154 assert( pSelect->pEList );
1155 nColumn = pSelect->pEList->nExpr;
1156 }
drhcce7d172000-05-31 15:34:511157
1158 /* Set useTempTable to TRUE if the result of the SELECT statement
1159 ** should be written into a temporary table (template 4). Set to
1160 ** FALSE if each output row of the SELECT can be written directly into
1161 ** the destination table (template 3).
1162 **
1163 ** A temp table must be used if the table being updated is also one
larrybrbc917382023-06-07 08:40:311164 ** of the tables being read by the SELECT statement. Also use a
drhcce7d172000-05-31 15:34:511165 ** temp table in the case of row triggers.
1166 */
drh05a86c52014-02-16 01:55:491167 if( pTrigger || readsTable(pParse, iDb, pTab) ){
drhcce7d172000-05-31 15:34:511168 useTempTable = 1;
1169 }
1170
1171 if( useTempTable ){
1172 /* Invoke the coroutine to extract information from the SELECT
1173 ** and add it to a transient table srcTab. The code generated
1174 ** here is from the 4th template:
1175 **
1176 ** B: open temp table
drh81cf13e2014-02-07 18:27:531177 ** L: yield X, goto M at EOF
drhcce7d172000-05-31 15:34:511178 ** insert row from R..R+n into temp table
1179 ** goto L
1180 ** M: ...
1181 */
1182 int regRec; /* Register to hold packed record */
1183 int regTempRowid; /* Register to hold temp table ROWID */
drh06280ee2014-02-20 19:32:381184 int addrL; /* Label "L" */
drhcce7d172000-05-31 15:34:511185
1186 srcTab = pParse->nTab++;
1187 regRec = sqlite3GetTempReg(pParse);
1188 regTempRowid = sqlite3GetTempReg(pParse);
1189 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
drh06280ee2014-02-20 19:32:381190 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
drhcce7d172000-05-31 15:34:511191 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
1192 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
1193 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
drh076e85f2015-09-03 13:46:121194 sqlite3VdbeGoto(v, addrL);
drh06280ee2014-02-20 19:32:381195 sqlite3VdbeJumpHere(v, addrL);
drhcce7d172000-05-31 15:34:511196 sqlite3ReleaseTempReg(pParse, regRec);
1197 sqlite3ReleaseTempReg(pParse, regTempRowid);
1198 }
1199 }else{
larrybrbc917382023-06-07 08:40:311200 /* This is the case if the data for the INSERT is coming from a
drha21f78b2015-04-19 18:32:431201 ** single-row VALUES clause
drhcce7d172000-05-31 15:34:511202 */
1203 NameContext sNC;
1204 memset(&sNC, 0, sizeof(sNC));
1205 sNC.pParse = pParse;
1206 srcTab = -1;
1207 assert( useTempTable==0 );
drhfea870b2015-08-24 20:54:061208 if( pList ){
1209 nColumn = pList->nExpr;
1210 if( sqlite3ResolveExprListNames(&sNC, pList) ){
drhcce7d172000-05-31 15:34:511211 goto insert_cleanup;
1212 }
drhfea870b2015-08-24 20:54:061213 }else{
1214 nColumn = 0;
drhcce7d172000-05-31 15:34:511215 }
1216 }
1217
drhaacc5432002-01-06 17:07:401218 /* If there is no IDLIST term but the table has an integer primary
larrybrbc917382023-06-07 08:40:311219 ** key, the set the ipkColumn variable to the integer primary key
drhd82b5022013-10-26 00:58:341220 ** column index in the original table definition.
drh4a324312001-12-21 14:30:421221 */
drh147d0cc2006-08-25 23:42:531222 if( pColumn==0 && nColumn>0 ){
drhd82b5022013-10-26 00:58:341223 ipkColumn = pTab->iPKey;
drh427b96a2019-10-22 13:01:241224#ifndef SQLITE_OMIT_GENERATED_COLUMNS
drh6ab61d72019-10-23 15:47:331225 if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
drh427b96a2019-10-22 13:01:241226 testcase( pTab->tabFlags & TF_HasVirtual );
drh6ab61d72019-10-23 15:47:331227 testcase( pTab->tabFlags & TF_HasStored );
drh427b96a2019-10-22 13:01:241228 for(i=ipkColumn-1; i>=0; i--){
1229 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
1230 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
drh6ab61d72019-10-23 15:47:331231 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
drh427b96a2019-10-22 13:01:241232 ipkColumn--;
1233 }
1234 }
1235 }
1236#endif
drh05a86c52014-02-16 01:55:491237
drhc7e93f52021-02-18 00:26:111238 /* Make sure the number of columns in the source data matches the number
1239 ** of columns to be inserted into the table.
1240 */
drh6f6e60d2021-02-18 15:45:341241 assert( TF_HasHidden==COLFLAG_HIDDEN );
1242 assert( TF_HasGenerated==COLFLAG_GENERATED );
1243 assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) );
1244 if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
drhc7e93f52021-02-18 00:26:111245 for(i=0; i<pTab->nCol; i++){
1246 if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
1247 }
1248 }
1249 if( nColumn!=(pTab->nCol-nHidden) ){
larrybrbc917382023-06-07 08:40:311250 sqlite3ErrorMsg(pParse,
drhc7e93f52021-02-18 00:26:111251 "table %S has %d columns but %d values were supplied",
drha9799932021-03-19 13:00:281252 pTabList->a, pTab->nCol-nHidden, nColumn);
drhc7e93f52021-02-18 00:26:111253 goto insert_cleanup;
1254 }
drhcce7d172000-05-31 15:34:511255 }
1256 if( pColumn!=0 && nColumn!=pColumn->nId ){
1257 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
1258 goto insert_cleanup;
1259 }
larrybrbc917382023-06-07 08:40:311260
drhfeeb1392002-04-09 03:28:011261 /* Initialize the count of rows to be inserted
1262 */
drh79636912018-04-19 23:52:391263 if( (db->flags & SQLITE_CountRows)!=0
1264 && !pParse->nested
1265 && !pParse->pTriggerTab
drhd086aa02021-01-29 21:31:591266 && !pParse->bReturning
drh79636912018-04-19 23:52:391267 ){
drh6a288a32008-01-07 19:20:241268 regRowCount = ++pParse->nMem;
1269 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
drhfeeb1392002-04-09 03:28:011270 }
1271
danielk1977e448dc42008-01-02 11:50:511272 /* If this is not a view, open the table and and all indices */
1273 if( !isView ){
drhaa9b8962008-01-08 02:57:551274 int nIdx;
danfd261ec2015-10-22 20:54:331275 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
drh26198bb2013-10-31 11:15:091276 &iDataCur, &iIdxCur);
drha7c3b932019-05-07 19:13:421277 aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
drhaa9b8962008-01-08 02:57:551278 if( aRegIdx==0 ){
1279 goto insert_cleanup;
1280 }
drh2c4dfc32016-11-10 14:24:041281 for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
1282 assert( pIdx );
drhaa9b8962008-01-08 02:57:551283 aRegIdx[i] = ++pParse->nMem;
drh2c4dfc32016-11-10 14:24:041284 pParse->nMem += pIdx->nColumn;
drhaa9b8962008-01-08 02:57:551285 }
drha7c3b932019-05-07 19:13:421286 aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */
danielk1977c3f9bad2002-05-15 08:30:121287 }
drh788d55a2018-04-13 01:15:091288#ifndef SQLITE_OMIT_UPSERT
drh0b30a112018-04-13 21:55:221289 if( pUpsert ){
drh20b86322020-12-09 01:34:481290 Upsert *pNx;
drhb042d922019-01-04 23:39:371291 if( IsVirtual(pTab) ){
1292 sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
1293 pTab->zName);
1294 goto insert_cleanup;
1295 }
drhf38524d2021-08-02 16:41:571296 if( IsView(pTab) ){
drhc6b24ab2019-12-06 01:23:381297 sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
1298 goto insert_cleanup;
1299 }
dan9105fd52019-08-19 17:26:321300 if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
1301 goto insert_cleanup;
1302 }
drh788d55a2018-04-13 01:15:091303 pTabList->a[0].iCursor = iDataCur;
drh20b86322020-12-09 01:34:481304 pNx = pUpsert;
1305 do{
1306 pNx->pUpsertSrc = pTabList;
1307 pNx->regData = regData;
1308 pNx->iDataCur = iDataCur;
1309 pNx->iIdxCur = iIdxCur;
1310 if( pNx->pUpsertTarget ){
drh926fb602024-03-08 14:01:481311 if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx, pUpsert) ){
dan93eb9062021-03-19 14:26:241312 goto insert_cleanup;
1313 }
drh20b86322020-12-09 01:34:481314 }
1315 pNx = pNx->pNextUpsert;
1316 }while( pNx!=0 );
drh788d55a2018-04-13 01:15:091317 }
1318#endif
1319
danielk1977c3f9bad2002-05-15 08:30:121320
drhe00ee6e2008-06-20 15:24:011321 /* This is the top of the main insertion loop */
drh142e30d2002-08-28 03:00:581322 if( useTempTable ){
drhe00ee6e2008-06-20 15:24:011323 /* This block codes the top of loop only. The complete loop is the
1324 ** following pseudocode (template 4):
1325 **
drh81cf13e2014-02-07 18:27:531326 ** rewind temp table, if empty goto D
drhe00ee6e2008-06-20 15:24:011327 ** C: loop over rows of intermediate table
1328 ** transfer values form intermediate table into <table>
1329 ** end loop
1330 ** D: ...
1331 */
drh688852a2014-02-17 22:40:431332 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
drhe00ee6e2008-06-20 15:24:011333 addrCont = sqlite3VdbeCurrentAddr(v);
drh142e30d2002-08-28 03:00:581334 }else if( pSelect ){
drhe00ee6e2008-06-20 15:24:011335 /* This block codes the top of loop only. The complete loop is the
1336 ** following pseudocode (template 3):
1337 **
drh81cf13e2014-02-07 18:27:531338 ** C: yield X, at EOF goto D
drhe00ee6e2008-06-20 15:24:011339 ** insert the select result into <table> from R..R+n
1340 ** goto C
1341 ** D: ...
1342 */
drh3aef2fb2020-01-02 17:46:021343 sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
drh81cf13e2014-02-07 18:27:531344 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
drh688852a2014-02-17 22:40:431345 VdbeCoverage(v);
drhf5f19152019-10-21 01:04:111346 if( ipkColumn>=0 ){
1347 /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
1348 ** SELECT, go ahead and copy the value into the rowid slot now, so that
1349 ** the value does not get overwritten by a NULL at tag-20191021-002. */
1350 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
1351 }
drh5974a302000-06-07 14:42:261352 }
drh1ccde152000-06-17 13:12:391353
drhf5f19152019-10-21 01:04:111354 /* Compute data for ordinary columns of the new entry. Values
1355 ** are written in storage order into registers starting with regData.
1356 ** Only ordinary columns are computed in this loop. The rowid
1357 ** (if there is one) is computed later and generated columns are
1358 ** computed after the rowid since they might depend on the value
1359 ** of the rowid.
1360 */
1361 nHidden = 0;
1362 iRegStore = regData; assert( regData==regRowid+1 );
1363 for(i=0; i<pTab->nCol; i++, iRegStore++){
1364 int k;
1365 u32 colFlags;
1366 assert( i>=nHidden );
1367 if( i==pTab->iPKey ){
1368 /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
1369 ** using the rowid. So put a NULL in the IPK slot of the record to avoid
1370 ** using excess space. The file format definition requires this extra
1371 ** NULL - we cannot optimize further by skipping the column completely */
1372 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1373 continue;
1374 }
1375 if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
1376 nHidden++;
1377 if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
1378 /* Virtual columns do not participate in OP_MakeRecord. So back up
1379 ** iRegStore by one slot to compensate for the iRegStore++ in the
1380 ** outer for() loop */
1381 iRegStore--;
1382 continue;
1383 }else if( (colFlags & COLFLAG_STORED)!=0 ){
1384 /* Stored columns are computed later. But if there are BEFORE
1385 ** triggers, the slots used for stored columns will be OP_Copy-ed
1386 ** to a second block of registers, so the register needs to be
1387 ** initialized to NULL to avoid an uninitialized register read */
1388 if( tmask & TRIGGER_BEFORE ){
1389 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
1390 }
1391 continue;
1392 }else if( pColumn==0 ){
1393 /* Hidden columns that are not explicitly named in the INSERT
drh65552a72025-02-06 17:10:381394 ** get their default value */
larrybrbc917382023-06-07 08:40:311395 sqlite3ExprCodeFactorable(pParse,
drh79cf2b72021-07-31 20:30:411396 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1397 iRegStore);
drhf5f19152019-10-21 01:04:111398 continue;
1399 }
1400 }
1401 if( pColumn ){
drh8b62a822025-01-28 12:50:171402 j = aTabColMap[i];
1403 assert( j>=0 && j<=pColumn->nId );
1404 if( j==0 ){
drhf5f19152019-10-21 01:04:111405 /* A column not named in the insert column list gets its
1406 ** default value */
larrybrbc917382023-06-07 08:40:311407 sqlite3ExprCodeFactorable(pParse,
drh79cf2b72021-07-31 20:30:411408 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1409 iRegStore);
drhf5f19152019-10-21 01:04:111410 continue;
1411 }
drh8b62a822025-01-28 12:50:171412 k = j - 1;
drhf5f19152019-10-21 01:04:111413 }else if( nColumn==0 ){
1414 /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */
larrybrbc917382023-06-07 08:40:311415 sqlite3ExprCodeFactorable(pParse,
drh79cf2b72021-07-31 20:30:411416 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
1417 iRegStore);
drhf5f19152019-10-21 01:04:111418 continue;
1419 }else{
1420 k = i - nHidden;
1421 }
1422
1423 if( useTempTable ){
larrybrbc917382023-06-07 08:40:311424 sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
drhf5f19152019-10-21 01:04:111425 }else if( pSelect ){
1426 if( regFromSelect!=regData ){
1427 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
1428 }
1429 }else{
drh2d2e5282022-07-25 21:37:131430 Expr *pX = pList->a[k].pExpr;
1431 int y = sqlite3ExprCodeTarget(pParse, pX, iRegStore);
1432 if( y!=iRegStore ){
1433 sqlite3VdbeAddOp2(v,
1434 ExprHasProperty(pX, EP_Subquery) ? OP_Copy : OP_SCopy, y, iRegStore);
1435 }
drhf5f19152019-10-21 01:04:111436 }
1437 }
1438
1439
drh5cf590c2003-04-24 01:45:041440 /* Run the BEFORE and INSTEAD OF triggers, if there are any
drh70ce3f02003-04-15 19:22:221441 */
drhec4ccdb2018-12-29 02:26:591442 endOfLoop = sqlite3VdbeMakeLabel(pParse);
danielk19772f886d12009-02-28 10:47:411443 if( tmask & TRIGGER_BEFORE ){
dan76d462e2009-08-30 11:42:511444 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
danielk1977c3f9bad2002-05-15 08:30:121445
drh70ce3f02003-04-15 19:22:221446 /* build the NEW.* reference row. Note that if there is an INTEGER
1447 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
1448 ** translated into a unique ID for the row. But on a BEFORE trigger,
1449 ** we do not know what the unique ID will be (because the insert has
1450 ** not happened yet) so we substitute a rowid of -1
1451 */
drhd82b5022013-10-26 00:58:341452 if( ipkColumn<0 ){
dan76d462e2009-08-30 11:42:511453 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
drh70ce3f02003-04-15 19:22:221454 }else{
drh728e0f92015-10-10 14:41:281455 int addr1;
drhec95c442013-10-23 01:57:321456 assert( !withoutRowid );
drh7fe45902009-05-01 02:08:041457 if( useTempTable ){
drhd82b5022013-10-26 00:58:341458 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
drh7fe45902009-05-01 02:08:041459 }else{
1460 assert( pSelect==0 ); /* Otherwise useTempTable is true */
drhd82b5022013-10-26 00:58:341461 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
drh7fe45902009-05-01 02:08:041462 }
drh728e0f92015-10-10 14:41:281463 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
dan76d462e2009-08-30 11:42:511464 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
drh728e0f92015-10-10 14:41:281465 sqlite3VdbeJumpHere(v, addr1);
drh688852a2014-02-17 22:40:431466 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
drh70ce3f02003-04-15 19:22:221467 }
1468
drhf5f19152019-10-21 01:04:111469 /* Copy the new data already generated. */
drh3cbf38c2023-03-28 11:18:041470 assert( pTab->nNVCol>0 || pParse->nErr>0 );
drhf5f19152019-10-21 01:04:111471 sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
1472
1473#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1474 /* Compute the new value for generated columns after all other
1475 ** columns have already been computed. This must be done after
1476 ** computing the ROWID in case one of the generated columns
1477 ** refers to the ROWID. */
drh427b96a2019-10-22 13:01:241478 if( pTab->tabFlags & TF_HasGenerated ){
1479 testcase( pTab->tabFlags & TF_HasVirtual );
1480 testcase( pTab->tabFlags & TF_HasStored );
drhf5f19152019-10-21 01:04:111481 sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
danielk1977c3f9bad2002-05-15 08:30:121482 }
drhf5f19152019-10-21 01:04:111483#endif
danielk1977a37cdde2004-05-16 11:15:361484
1485 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
1486 ** do not attempt any conversions before assembling the record.
1487 ** If this is a real table, attempt conversions as required by the
1488 ** table column affinities.
1489 */
1490 if( !isView ){
drh57bf4a82014-02-17 14:59:221491 sqlite3TableAffinity(v, pTab, regCols+1);
danielk1977a37cdde2004-05-16 11:15:361492 }
danielk1977c3f9bad2002-05-15 08:30:121493
drh5cf590c2003-04-24 01:45:041494 /* Fire BEFORE or INSTEAD OF triggers */
larrybrbc917382023-06-07 08:40:311495 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
dan94d7f502009-09-24 09:05:491496 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
dan165921a2009-08-28 18:53:451497
dan76d462e2009-08-30 11:42:511498 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
drh70ce3f02003-04-15 19:22:221499 }
danielk1977c3f9bad2002-05-15 08:30:121500
drh5cf590c2003-04-24 01:45:041501 if( !isView ){
drh4cbdda92006-06-14 19:00:201502 if( IsVirtual(pTab) ){
danielk1977287fb612008-01-04 19:10:281503 /* The row that the VUpdate opcode will delete: none */
drh6a288a32008-01-07 19:20:241504 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
drh4cbdda92006-06-14 19:00:201505 }
drhd82b5022013-10-26 00:58:341506 if( ipkColumn>=0 ){
drhf5f19152019-10-21 01:04:111507 /* Compute the new rowid */
drh142e30d2002-08-28 03:00:581508 if( useTempTable ){
drhd82b5022013-10-26 00:58:341509 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
drh142e30d2002-08-28 03:00:581510 }else if( pSelect ){
drhf5f19152019-10-21 01:04:111511 /* Rowid already initialized at tag-20191021-001 */
danielk1977c3f9bad2002-05-15 08:30:121512 }else{
drh04fcef02019-01-17 04:40:041513 Expr *pIpk = pList->a[ipkColumn].pExpr;
1514 if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
1515 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:491516 appendFlag = 1;
drh04fcef02019-01-17 04:40:041517 }else{
1518 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
drhe4d90812007-03-29 05:51:491519 }
danielk1977c3f9bad2002-05-15 08:30:121520 }
drhf0863fe2005-06-12 21:35:511521 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
drh27a32782002-06-19 20:32:431522 ** to generate a unique primary key value.
1523 */
drhe4d90812007-03-29 05:51:491524 if( !appendFlag ){
drh728e0f92015-10-10 14:41:281525 int addr1;
danielk1977bb50e7a2008-07-04 10:56:071526 if( !IsVirtual(pTab) ){
drh728e0f92015-10-10 14:41:281527 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
drh26198bb2013-10-31 11:15:091528 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
drh728e0f92015-10-10 14:41:281529 sqlite3VdbeJumpHere(v, addr1);
danielk1977bb50e7a2008-07-04 10:56:071530 }else{
drh728e0f92015-10-10 14:41:281531 addr1 = sqlite3VdbeCurrentAddr(v);
1532 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
danielk1977bb50e7a2008-07-04 10:56:071533 }
drh688852a2014-02-17 22:40:431534 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
drhe4d90812007-03-29 05:51:491535 }
drhec95c442013-10-23 01:57:321536 }else if( IsVirtual(pTab) || withoutRowid ){
drh6a288a32008-01-07 19:20:241537 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
danielk1977c3f9bad2002-05-15 08:30:121538 }else{
drh26198bb2013-10-31 11:15:091539 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
drhe4d90812007-03-29 05:51:491540 appendFlag = 1;
drh4a324312001-12-21 14:30:421541 }
drh6a288a32008-01-07 19:20:241542 autoIncStep(pParse, regAutoinc, regRowid);
drh4a324312001-12-21 14:30:421543
drhc1431142019-10-17 17:54:051544#ifndef SQLITE_OMIT_GENERATED_COLUMNS
drhdd6cc9b2019-10-19 18:47:271545 /* Compute the new value for generated columns after all other
drhf5f19152019-10-21 01:04:111546 ** columns have already been computed. This must be done after
1547 ** computing the ROWID in case one of the generated columns
drhb5f62432019-12-10 02:48:411548 ** is derived from the INTEGER PRIMARY KEY. */
drh427b96a2019-10-22 13:01:241549 if( pTab->tabFlags & TF_HasGenerated ){
drhdd6cc9b2019-10-19 18:47:271550 sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
drhbed86902000-06-02 13:27:591551 }
drhc1431142019-10-17 17:54:051552#endif
danielk1977c3f9bad2002-05-15 08:30:121553
1554 /* Generate code to check constraints and generate index keys and
danielk1977f29ce552002-05-19 23:43:121555 ** do the insertion.
1556 */
drh4cbdda92006-06-14 19:00:201557#ifndef SQLITE_OMIT_VIRTUALTABLE
1558 if( IsVirtual(pTab) ){
danielk1977595a5232009-07-24 17:58:531559 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
drh4f3dd152008-04-28 18:46:431560 sqlite3VtabMakeWritable(pParse, pTab);
danielk1977595a5232009-07-24 17:58:531561 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
danb061d052011-04-25 18:49:571562 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
dane0af83a2009-09-08 19:15:011563 sqlite3MayAbort(pParse);
drh4cbdda92006-06-14 19:00:201564 }else
1565#endif
1566 {
dan11fbee22021-04-06 16:42:051567 int isReplace = 0;/* Set to true if constraints may cause a replace */
dan3b908d42016-11-08 19:22:321568 int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
drhf8ffb272013-11-01 17:08:561569 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
drh788d55a2018-04-13 01:15:091570 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
drh04adf412008-01-08 18:57:501571 );
drh509a6302022-07-25 23:01:411572 if( db->flags & SQLITE_ForeignKeys ){
1573 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
1574 }
dan3b908d42016-11-08 19:22:321575
1576 /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
1577 ** constraints or (b) there are no triggers and this table is not a
1578 ** parent table in a foreign key constraint. It is safe to set the
1579 ** flag in the second case as if any REPLACE constraint is hit, an
larrybrbc917382023-06-07 08:40:311580 ** OP_Delete or OP_IdxDelete instruction will be executed on each
dan3b908d42016-11-08 19:22:321581 ** cursor that is disturbed. And these instructions both clear the
1582 ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
1583 ** functionality. */
drh06baba52019-10-24 19:35:261584 bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
drh26198bb2013-10-31 11:15:091585 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
dan3b908d42016-11-08 19:22:321586 regIns, aRegIdx, 0, appendFlag, bUseSeek
1587 );
drh4cbdda92006-06-14 19:00:201588 }
drh6e5020e2021-04-07 15:45:011589#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
dan2a1aeaa2021-04-06 13:53:101590 }else if( pParse->bReturning ){
1591 /* If there is a RETURNING clause, populate the rowid register with
1592 ** constant value -1, in case one or more of the returned expressions
1593 ** refer to the "rowid" of the view. */
1594 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
drh6e5020e2021-04-07 15:45:011595#endif
drh5cf590c2003-04-24 01:45:041596 }
danielk1977c3f9bad2002-05-15 08:30:121597
drh5cf590c2003-04-24 01:45:041598 /* Update the count of rows that are inserted
1599 */
drh79636912018-04-19 23:52:391600 if( regRowCount ){
drh6a288a32008-01-07 19:20:241601 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
drh5974a302000-06-07 14:42:261602 }
drh1ccde152000-06-17 13:12:391603
danielk19772f886d12009-02-28 10:47:411604 if( pTrigger ){
danielk1977c3f9bad2002-05-15 08:30:121605 /* Code AFTER triggers */
larrybrbc917382023-06-07 08:40:311606 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
dan94d7f502009-09-24 09:05:491607 pTab, regData-2-pTab->nCol, onError, endOfLoop);
drh1bee3d72001-10-15 00:44:351608 }
1609
drhe00ee6e2008-06-20 15:24:011610 /* The bottom of the main insertion loop, if the data source
1611 ** is a SELECT statement.
danielk1977f29ce552002-05-19 23:43:121612 */
danielk19774adee202004-05-08 08:23:191613 sqlite3VdbeResolveLabel(v, endOfLoop);
drh142e30d2002-08-28 03:00:581614 if( useTempTable ){
drh688852a2014-02-17 22:40:431615 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
drhe00ee6e2008-06-20 15:24:011616 sqlite3VdbeJumpHere(v, addrInsTop);
drh2eb95372008-06-06 15:04:361617 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
drh142e30d2002-08-28 03:00:581618 }else if( pSelect ){
drh076e85f2015-09-03 13:46:121619 sqlite3VdbeGoto(v, addrCont);
drhd9670ab2019-12-28 01:52:461620#ifdef SQLITE_DEBUG
1621 /* If we are jumping back to an OP_Yield that is preceded by an
1622 ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
1623 ** OP_ReleaseReg will be included in the loop. */
1624 if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
1625 assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
1626 sqlite3VdbeChangeP5(v, 1);
1627 }
1628#endif
drhe00ee6e2008-06-20 15:24:011629 sqlite3VdbeJumpHere(v, addrInsTop);
drh6b563442001-11-07 16:48:261630 }
danielk1977c3f9bad2002-05-15 08:30:121631
mistachkind6665c52021-01-18 19:28:561632#ifndef SQLITE_OMIT_XFER_OPT
drh0b9f50d2009-06-23 20:28:531633insert_end:
mistachkind6665c52021-01-18 19:28:561634#endif /* SQLITE_OMIT_XFER_OPT */
drhf3388142004-11-13 03:48:061635 /* Update the sqlite_sequence table by storing the content of the
drh0b9f50d2009-06-23 20:28:531636 ** maximum rowid counter values recorded while inserting into
1637 ** autoincrement tables.
drh2958a4e2004-11-12 03:56:151638 */
dan165921a2009-08-28 18:53:451639 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
drh0b9f50d2009-06-23 20:28:531640 sqlite3AutoincrementEnd(pParse);
1641 }
drh2958a4e2004-11-12 03:56:151642
drh1bee3d72001-10-15 00:44:351643 /*
larrybrbc917382023-06-07 08:40:311644 ** Return the number of rows inserted. If this routine is
danielk1977e7de6f22004-11-05 06:02:061645 ** generating code because of a call to sqlite3NestedParse(), do not
1646 ** invoke the callback function.
drh1bee3d72001-10-15 00:44:351647 */
drh79636912018-04-19 23:52:391648 if( regRowCount ){
drh3b26b2b2021-12-01 19:17:141649 sqlite3CodeChangeCount(v, regRowCount, "rows inserted");
drh1bee3d72001-10-15 00:44:351650 }
drhcce7d172000-05-31 15:34:511651
1652insert_cleanup:
drh633e6d52008-07-28 19:34:531653 sqlite3SrcListDelete(db, pTabList);
1654 sqlite3ExprListDelete(db, pList);
drh46d2e5c2018-04-12 13:15:431655 sqlite3UpsertDelete(db, pUpsert);
drh633e6d52008-07-28 19:34:531656 sqlite3SelectDelete(db, pSelect);
drh8b62a822025-01-28 12:50:171657 if( pColumn ){
1658 sqlite3IdListDelete(db, pColumn);
1659 sqlite3DbFree(db, aTabColMap);
1660 }
drh41ce47c2022-08-22 02:00:261661 if( aRegIdx ) sqlite3DbNNFreeNN(db, aRegIdx);
drhcce7d172000-05-31 15:34:511662}
drh9cfcf5d2002-01-29 18:41:241663
dan75cbd982009-09-21 16:06:031664/* Make sure "isView" and other macros defined above are undefined. Otherwise
peter.d.reid60ec9142014-09-06 16:39:461665** they may interfere with compilation of other functions in this file
dan75cbd982009-09-21 16:06:031666** (or in another file, if this file becomes part of the amalgamation). */
1667#ifdef isView
1668 #undef isView
1669#endif
1670#ifdef pTrigger
1671 #undef pTrigger
1672#endif
1673#ifdef tmask
1674 #undef tmask
1675#endif
1676
drh9cfcf5d2002-01-29 18:41:241677/*
larrybrbc917382023-06-07 08:40:311678** Meanings of bits in of pWalker->eCode for
drhe9816d82018-09-15 21:38:481679** sqlite3ExprReferencesUpdatedColumn()
drh98bfa162016-02-10 18:24:051680*/
1681#define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
1682#define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
1683
drhe9816d82018-09-15 21:38:481684/* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
1685* Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
1686** expression node references any of the
larrybrbc917382023-06-07 08:40:311687** columns that are being modified by an UPDATE statement.
drh2a0b5272016-02-10 16:52:241688*/
1689static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
drh98bfa162016-02-10 18:24:051690 if( pExpr->op==TK_COLUMN ){
1691 assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
1692 if( pExpr->iColumn>=0 ){
1693 if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
1694 pWalker->eCode |= CKCNSTRNT_COLUMN;
1695 }
1696 }else{
1697 pWalker->eCode |= CKCNSTRNT_ROWID;
1698 }
drh2a0b5272016-02-10 16:52:241699 }
1700 return WRC_Continue;
1701}
1702
1703/*
1704** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
1705** only columns that are modified by the UPDATE are those for which
drh98bfa162016-02-10 18:24:051706** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
1707**
drhe9816d82018-09-15 21:38:481708** Return true if CHECK constraint pExpr uses any of the
drh98bfa162016-02-10 18:24:051709** changing columns (or the rowid if it is changing). In other words,
drhe9816d82018-09-15 21:38:481710** return true if this CHECK constraint must be validated for
drh98bfa162016-02-10 18:24:051711** the new row in the UPDATE statement.
drhe9816d82018-09-15 21:38:481712**
1713** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
1714** The operation of this routine is the same - return true if an only if
1715** the expression uses one or more of columns identified by the second and
1716** third arguments.
drh2a0b5272016-02-10 16:52:241717*/
drhe9816d82018-09-15 21:38:481718int sqlite3ExprReferencesUpdatedColumn(
1719 Expr *pExpr, /* The expression to be checked */
1720 int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */
1721 int chngRowid /* True if UPDATE changes the rowid */
1722){
drh2a0b5272016-02-10 16:52:241723 Walker w;
1724 memset(&w, 0, sizeof(w));
drh98bfa162016-02-10 18:24:051725 w.eCode = 0;
drh2a0b5272016-02-10 16:52:241726 w.xExprCallback = checkConstraintExprNode;
1727 w.u.aiCol = aiChng;
1728 sqlite3WalkExpr(&w, pExpr);
drh05723a92016-02-10 19:10:501729 if( !chngRowid ){
1730 testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
1731 w.eCode &= ~CKCNSTRNT_ROWID;
1732 }
1733 testcase( w.eCode==0 );
1734 testcase( w.eCode==CKCNSTRNT_COLUMN );
1735 testcase( w.eCode==CKCNSTRNT_ROWID );
1736 testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
drhe9816d82018-09-15 21:38:481737 return w.eCode!=0;
drh2a0b5272016-02-10 16:52:241738}
1739
drh11e85272013-10-26 15:40:481740/*
drhdaf27612020-12-10 20:31:251741** The sqlite3GenerateConstraintChecks() routine usually wants to visit
1742** the indexes of a table in the order provided in the Table->pIndex list.
1743** However, sometimes (rarely - when there is an upsert) it wants to visit
1744** the indexes in a different order. The following data structures accomplish
1745** this.
1746**
1747** The IndexIterator object is used to walk through all of the indexes
1748** of a table in either Index.pNext order, or in some other order established
1749** by an array of IndexListTerm objects.
1750*/
1751typedef struct IndexListTerm IndexListTerm;
1752typedef struct IndexIterator IndexIterator;
1753struct IndexIterator {
1754 int eType; /* 0 for Index.pNext list. 1 for an array of IndexListTerm */
1755 int i; /* Index of the current item from the list */
1756 union {
1757 struct { /* Use this object for eType==0: A Index.pNext list */
1758 Index *pIdx; /* The current Index */
larrybrbc917382023-06-07 08:40:311759 } lx;
drhdaf27612020-12-10 20:31:251760 struct { /* Use this object for eType==1; Array of IndexListTerm */
1761 int nIdx; /* Size of the array */
1762 IndexListTerm *aIdx; /* Array of IndexListTerms */
1763 } ax;
1764 } u;
1765};
1766
1767/* When IndexIterator.eType==1, then each index is an array of instances
1768** of the following object
1769*/
1770struct IndexListTerm {
1771 Index *p; /* The index */
1772 int ix; /* Which entry in the original Table.pIndex list is this index*/
1773};
1774
1775/* Return the first index on the list */
1776static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){
drhed4c5462020-12-11 16:49:511777 assert( pIter->i==0 );
1778 if( pIter->eType ){
1779 *pIx = pIter->u.ax.aIdx[0].ix;
1780 return pIter->u.ax.aIdx[0].p;
1781 }else{
1782 *pIx = 0;
1783 return pIter->u.lx.pIdx;
1784 }
drhdaf27612020-12-10 20:31:251785}
1786
1787/* Return the next index from the list. Return NULL when out of indexes */
1788static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){
drhdaf27612020-12-10 20:31:251789 if( pIter->eType ){
drhd3e21a12020-12-11 17:11:561790 int i = ++pIter->i;
drh61e280a2020-12-11 01:17:061791 if( i>=pIter->u.ax.nIdx ){
1792 *pIx = i;
1793 return 0;
1794 }
drhdaf27612020-12-10 20:31:251795 *pIx = pIter->u.ax.aIdx[i].ix;
1796 return pIter->u.ax.aIdx[i].p;
1797 }else{
drhd3e21a12020-12-11 17:11:561798 ++(*pIx);
drhdaf27612020-12-10 20:31:251799 pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
1800 return pIter->u.lx.pIdx;
1801 }
1802}
larrybrbc917382023-06-07 08:40:311803
drhdaf27612020-12-10 20:31:251804/*
drh6934fc72013-10-31 15:37:491805** Generate code to do constraint checks prior to an INSERT or an UPDATE
1806** on table pTab.
drh9cfcf5d2002-01-29 18:41:241807**
drh6934fc72013-10-31 15:37:491808** The regNewData parameter is the first register in a range that contains
1809** the data to be inserted or the data after the update. There will be
1810** pTab->nCol+1 registers in this range. The first register (the one
1811** that regNewData points to) will contain the new rowid, or NULL in the
1812** case of a WITHOUT ROWID table. The second register in the range will
1813** contain the content of the first table column. The third register will
1814** contain the content of the second table column. And so forth.
drh0ca3e242002-01-29 23:07:021815**
drhf8ffb272013-11-01 17:08:561816** The regOldData parameter is similar to regNewData except that it contains
1817** the data prior to an UPDATE rather than afterwards. regOldData is zero
1818** for an INSERT. This routine can distinguish between UPDATE and INSERT by
1819** checking regOldData for zero.
drh0ca3e242002-01-29 23:07:021820**
drhf8ffb272013-11-01 17:08:561821** For an UPDATE, the pkChng boolean is true if the true primary key (the
1822** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
1823** might be modified by the UPDATE. If pkChng is false, then the key of
1824** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
drh0ca3e242002-01-29 23:07:021825**
drhf8ffb272013-11-01 17:08:561826** For an INSERT, the pkChng boolean indicates whether or not the rowid
1827** was explicitly specified as part of the INSERT statement. If pkChng
1828** is zero, it means that the either rowid is computed automatically or
1829** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
1830** pkChng will only be true if the INSERT statement provides an integer
1831** value for either the rowid column or its INTEGER PRIMARY KEY alias.
drh0ca3e242002-01-29 23:07:021832**
drh6934fc72013-10-31 15:37:491833** The code generated by this routine will store new index entries into
drhaa9b8962008-01-08 02:57:551834** registers identified by aRegIdx[]. No index entry is created for
1835** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1836** the same as the order of indices on the linked list of indices
drh6934fc72013-10-31 15:37:491837** at pTab->pIndex.
1838**
drha7c3b932019-05-07 19:13:421839** (2019-05-07) The generated code also creates a new record for the
1840** main table, if pTab is a rowid table, and stores that record in the
1841** register identified by aRegIdx[nIdx] - in other words in the first
1842** entry of aRegIdx[] past the last index. It is important that the
1843** record be generated during constraint checks to avoid affinity changes
1844** to the register content that occur after constraint checks but before
1845** the new record is inserted.
1846**
drh6934fc72013-10-31 15:37:491847** The caller must have already opened writeable cursors on the main
1848** table and all applicable indices (that is to say, all indices for which
1849** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
1850** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
1851** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
1852** for the first index in the pTab->pIndex list. Cursors for other indices
1853** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
drh9cfcf5d2002-01-29 18:41:241854**
1855** This routine also generates code to check constraints. NOT NULL,
1856** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
drh1c928532002-01-31 15:54:211857** then the appropriate action is performed. There are five possible
1858** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
drh9cfcf5d2002-01-29 18:41:241859**
1860** Constraint type Action What Happens
1861** --------------- ---------- ----------------------------------------
drh1c928532002-01-31 15:54:211862** any ROLLBACK The current transaction is rolled back and
drh6934fc72013-10-31 15:37:491863** sqlite3_step() returns immediately with a
drh9cfcf5d2002-01-29 18:41:241864** return code of SQLITE_CONSTRAINT.
1865**
drh1c928532002-01-31 15:54:211866** any ABORT Back out changes from the current command
1867** only (do not do a complete rollback) then
drh6934fc72013-10-31 15:37:491868** cause sqlite3_step() to return immediately
drh1c928532002-01-31 15:54:211869** with SQLITE_CONSTRAINT.
1870**
drh6934fc72013-10-31 15:37:491871** any FAIL Sqlite3_step() returns immediately with a
drh1c928532002-01-31 15:54:211872** return code of SQLITE_CONSTRAINT. The
1873** transaction is not rolled back and any
drh6934fc72013-10-31 15:37:491874** changes to prior rows are retained.
drh1c928532002-01-31 15:54:211875**
drh6934fc72013-10-31 15:37:491876** any IGNORE The attempt in insert or update the current
1877** row is skipped, without throwing an error.
1878** Processing continues with the next row.
1879** (There is an immediate jump to ignoreDest.)
drh9cfcf5d2002-01-29 18:41:241880**
1881** NOT NULL REPLACE The NULL value is replace by the default
1882** value for that column. If the default value
1883** is NULL, the action is the same as ABORT.
1884**
1885** UNIQUE REPLACE The other row that conflicts with the row
1886** being inserted is removed.
1887**
1888** CHECK REPLACE Illegal. The results in an exception.
1889**
drh1c928532002-01-31 15:54:211890** Which action to take is determined by the overrideError parameter.
1891** Or if overrideError==OE_Default, then the pParse->onError parameter
1892** is used. Or if pParse->onError==OE_Default then the onError value
1893** for the constraint is used.
drh9cfcf5d2002-01-29 18:41:241894*/
danielk19774adee202004-05-08 08:23:191895void sqlite3GenerateConstraintChecks(
drh6934fc72013-10-31 15:37:491896 Parse *pParse, /* The parser context */
1897 Table *pTab, /* The table being inserted or updated */
drhf8ffb272013-11-01 17:08:561898 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
drh6934fc72013-10-31 15:37:491899 int iDataCur, /* Canonical data cursor (main table or PK index) */
1900 int iIdxCur, /* First index cursor */
1901 int regNewData, /* First register in a range holding values to insert */
drhf8ffb272013-11-01 17:08:561902 int regOldData, /* Previous content. 0 for INSERTs */
1903 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
1904 u8 overrideError, /* Override onError to this if not OE_Default */
drh6934fc72013-10-31 15:37:491905 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
drhbdb00222016-02-10 16:03:201906 int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
drh788d55a2018-04-13 01:15:091907 int *aiChng, /* column i is unchanged if aiChng[i]<0 */
1908 Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
drh9cfcf5d2002-01-29 18:41:241909){
larrybrbc917382023-06-07 08:40:311910 Vdbe *v; /* VDBE under construction */
drh1b7ecbb2009-05-03 01:00:591911 Index *pIdx; /* Pointer to one of the indices */
drhe84ad922020-12-09 20:30:471912 Index *pPk = 0; /* The PRIMARY KEY index for WITHOUT ROWID tables */
drh2938f922012-03-07 19:13:291913 sqlite3 *db; /* Database connection */
drhf8ffb272013-11-01 17:08:561914 int i; /* loop counter */
1915 int ix; /* Index loop counter */
1916 int nCol; /* Number of columns */
1917 int onError; /* Conflict resolution strategy */
drh1b7ecbb2009-05-03 01:00:591918 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
drh6fbe41a2013-10-30 20:22:551919 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
drh61e280a2020-12-11 01:17:061920 Upsert *pUpsertClause = 0; /* The specific ON CONFLICT clause for pIdx */
1921 u8 isUpdate; /* True if this is an UPDATE operation */
drh57bf4a82014-02-17 14:59:221922 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
drh61e280a2020-12-11 01:17:061923 int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */
1924 int upsertIpkDelay = 0; /* Address of Goto to bypass initial IPK check */
drh84304502018-08-14 15:12:521925 int ipkTop = 0; /* Top of the IPK uniqueness check */
1926 int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */
drha407ecc2019-10-26 00:04:211927 /* Variables associated with retesting uniqueness constraints after
1928 ** replace triggers fire have run */
1929 int regTrigCnt; /* Register used to count replace trigger invocations */
1930 int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */
1931 int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
1932 Trigger *pTrigger; /* List of DELETE triggers on the table pTab */
1933 int nReplaceTrig = 0; /* Number of replace triggers coded */
drh61e280a2020-12-11 01:17:061934 IndexIterator sIdxIter; /* Index iterator */
drh9cfcf5d2002-01-29 18:41:241935
drhf8ffb272013-11-01 17:08:561936 isUpdate = regOldData!=0;
drh2938f922012-03-07 19:13:291937 db = pParse->db;
drhf0b41742020-08-15 21:55:141938 v = pParse->pVdbe;
drh9cfcf5d2002-01-29 18:41:241939 assert( v!=0 );
drhf38524d2021-08-02 16:41:571940 assert( !IsView(pTab) ); /* This table is not a VIEW */
drh9cfcf5d2002-01-29 18:41:241941 nCol = pTab->nCol;
larrybrbc917382023-06-07 08:40:311942
drh6934fc72013-10-31 15:37:491943 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
larrybrbc917382023-06-07 08:40:311944 ** normal rowid tables. nPkField is the number of key fields in the
drh6934fc72013-10-31 15:37:491945 ** pPk index or 1 for a rowid table. In other words, nPkField is the
1946 ** number of fields in the true primary key of the table. */
drh26198bb2013-10-31 11:15:091947 if( HasRowid(pTab) ){
1948 pPk = 0;
1949 nPkField = 1;
1950 }else{
1951 pPk = sqlite3PrimaryKeyIndex(pTab);
1952 nPkField = pPk->nKeyCol;
1953 }
drh6fbe41a2013-10-30 20:22:551954
1955 /* Record that this module has started */
1956 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
drh6934fc72013-10-31 15:37:491957 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
drh9cfcf5d2002-01-29 18:41:241958
1959 /* Test all NOT NULL constraints.
1960 */
drhcbda9c72019-10-26 17:08:061961 if( pTab->tabFlags & TF_HasNotNull ){
drhad5f1572019-12-28 00:36:511962 int b2ndPass = 0; /* True if currently running 2nd pass */
1963 int nSeenReplace = 0; /* Number of ON CONFLICT REPLACE operations */
1964 int nGenerated = 0; /* Number of generated columns with NOT NULL */
1965 while(1){ /* Make 2 passes over columns. Exit loop via "break" */
1966 for(i=0; i<nCol; i++){
1967 int iReg; /* Register holding column value */
1968 Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */
1969 int isGenerated; /* non-zero if column is generated */
1970 onError = pCol->notNull;
1971 if( onError==OE_None ) continue; /* No NOT NULL on this column */
1972 if( i==pTab->iPKey ){
1973 continue; /* ROWID is never NULL */
1974 }
1975 isGenerated = pCol->colFlags & COLFLAG_GENERATED;
1976 if( isGenerated && !b2ndPass ){
1977 nGenerated++;
1978 continue; /* Generated columns processed on 2nd pass */
1979 }
1980 if( aiChng && aiChng[i]<0 && !isGenerated ){
1981 /* Do not check NOT NULL on columns that do not change */
1982 continue;
1983 }
1984 if( overrideError!=OE_Default ){
1985 onError = overrideError;
1986 }else if( onError==OE_Default ){
drhcbda9c72019-10-26 17:08:061987 onError = OE_Abort;
drhcbda9c72019-10-26 17:08:061988 }
drhad5f1572019-12-28 00:36:511989 if( onError==OE_Replace ){
1990 if( b2ndPass /* REPLACE becomes ABORT on the 2nd pass */
drh79cf2b72021-07-31 20:30:411991 || pCol->iDflt==0 /* REPLACE is ABORT if no DEFAULT value */
drhad5f1572019-12-28 00:36:511992 ){
1993 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1994 testcase( pCol->colFlags & COLFLAG_STORED );
1995 testcase( pCol->colFlags & COLFLAG_GENERATED );
1996 onError = OE_Abort;
1997 }else{
1998 assert( !isGenerated );
1999 }
2000 }else if( b2ndPass && !isGenerated ){
2001 continue;
drhcbda9c72019-10-26 17:08:062002 }
drhad5f1572019-12-28 00:36:512003 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
2004 || onError==OE_Ignore || onError==OE_Replace );
2005 testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
2006 iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
2007 switch( onError ){
2008 case OE_Replace: {
2009 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
2010 VdbeCoverage(v);
2011 assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
2012 nSeenReplace++;
drh79cf2b72021-07-31 20:30:412013 sqlite3ExprCodeCopy(pParse,
2014 sqlite3ColumnExpr(pTab, pCol), iReg);
drhad5f1572019-12-28 00:36:512015 sqlite3VdbeJumpHere(v, addr1);
2016 break;
2017 }
2018 case OE_Abort:
2019 sqlite3MayAbort(pParse);
drh08b92082020-08-10 14:18:002020 /* no break */ deliberate_fall_through
drhad5f1572019-12-28 00:36:512021 case OE_Rollback:
2022 case OE_Fail: {
2023 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
drhcf9d36d2021-08-02 18:03:432024 pCol->zCnName);
drh85ec20a2022-11-30 21:18:232025 testcase( zMsg==0 && db->mallocFailed==0 );
drhad5f1572019-12-28 00:36:512026 sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
2027 onError, iReg);
2028 sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
2029 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
2030 VdbeCoverage(v);
2031 break;
2032 }
2033 default: {
2034 assert( onError==OE_Ignore );
2035 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
2036 VdbeCoverage(v);
2037 break;
2038 }
2039 } /* end switch(onError) */
2040 } /* end loop i over columns */
2041 if( nGenerated==0 && nSeenReplace==0 ){
2042 /* If there are no generated columns with NOT NULL constraints
2043 ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
2044 ** pass is sufficient */
2045 break;
drh9cfcf5d2002-01-29 18:41:242046 }
drhad5f1572019-12-28 00:36:512047 if( b2ndPass ) break; /* Never need more than 2 passes */
2048 b2ndPass = 1;
drhef9f7192020-01-17 19:14:082049#ifndef SQLITE_OMIT_GENERATED_COLUMNS
drhad5f1572019-12-28 00:36:512050 if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
2051 /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
2052 ** first pass, recomputed values for all generated columns, as
2053 ** those values might depend on columns affected by the REPLACE.
2054 */
2055 sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
2056 }
drhef9f7192020-01-17 19:14:082057#endif
drhad5f1572019-12-28 00:36:512058 } /* end of 2-pass loop */
2059 } /* end if( has-not-null-constraints ) */
drh9cfcf5d2002-01-29 18:41:242060
2061 /* Test all CHECK constraints
2062 */
drhffe07b22005-11-03 00:41:172063#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:292064 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
2065 ExprList *pCheck = pTab->pCheck;
drh6e97f8e2017-07-20 13:17:082066 pParse->iSelfTab = -(regNewData+1);
drhaa01c7e2006-03-15 16:26:102067 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
drh2938f922012-03-07 19:13:292068 for(i=0; i<pCheck->nExpr; i++){
drh05723a92016-02-10 19:10:502069 int allOk;
drh5cf1b612020-03-10 18:55:412070 Expr *pCopy;
drh2a0b5272016-02-10 16:52:242071 Expr *pExpr = pCheck->a[i].pExpr;
drhe9816d82018-09-15 21:38:482072 if( aiChng
2073 && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
2074 ){
2075 /* The check constraints do not reference any of the columns being
2076 ** updated so there is no point it verifying the check constraint */
2077 continue;
2078 }
drh9dce0ef2020-02-01 21:03:272079 if( bAffinityDone==0 ){
2080 sqlite3TableAffinity(v, pTab, regNewData+1);
2081 bAffinityDone = 1;
2082 }
drhec4ccdb2018-12-29 02:26:592083 allOk = sqlite3VdbeMakeLabel(pParse);
drh4031baf2018-05-28 17:31:202084 sqlite3VdbeVerifyAbortable(v, onError);
drh5cf1b612020-03-10 18:55:412085 pCopy = sqlite3ExprDup(db, pExpr, 0);
2086 if( !db->mallocFailed ){
2087 sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
2088 }
2089 sqlite3ExprDelete(db, pCopy);
drh2d8e9202012-12-08 04:10:442090 if( onError==OE_Ignore ){
drh076e85f2015-09-03 13:46:122091 sqlite3VdbeGoto(v, ignoreDest);
drh2d8e9202012-12-08 04:10:442092 }else{
drh41cee662019-12-12 20:22:342093 char *zName = pCheck->a[i].zEName;
drhe2678b92020-08-28 12:58:212094 assert( zName!=0 || pParse->db->mallocFailed );
drh0ce974d2019-06-12 22:46:042095 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
drhd91c1a12013-02-09 13:58:252096 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
drhf9c8ce32013-11-05 13:33:552097 onError, zName, P4_TRANSIENT,
2098 P5_ConstraintCheck);
drh2938f922012-03-07 19:13:292099 }
drh2d8e9202012-12-08 04:10:442100 sqlite3VdbeResolveLabel(v, allOk);
drhaa01c7e2006-03-15 16:26:102101 }
drh6e97f8e2017-07-20 13:17:082102 pParse->iSelfTab = 0;
drhffe07b22005-11-03 00:41:172103 }
2104#endif /* !defined(SQLITE_OMIT_CHECK) */
drh9cfcf5d2002-01-29 18:41:242105
drh096fd472018-04-14 20:24:362106 /* UNIQUE and PRIMARY KEY constraints should be handled in the following
2107 ** order:
2108 **
drh84304502018-08-14 15:12:522109 ** (1) OE_Update
2110 ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
drh096fd472018-04-14 20:24:362111 ** (3) OE_Replace
2112 **
2113 ** OE_Fail and OE_Ignore must happen before any changes are made.
2114 ** OE_Update guarantees that only a single row will change, so it
2115 ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
2116 ** could happen in any order, but they are grouped up front for
2117 ** convenience.
2118 **
drh8a6f89c2025-04-10 10:18:072119 ** 2018-08-14: Ticket https://sqlite.org/src/info/908f001483982c43
drh84304502018-08-14 15:12:522120 ** The order of constraints used to have OE_Update as (2) and OE_Abort
2121 ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
2122 ** constraint before any others, so it had to be moved.
2123 **
drh096fd472018-04-14 20:24:362124 ** Constraint checking code is generated in this order:
2125 ** (A) The rowid constraint
2126 ** (B) Unique index constraints that do not have OE_Replace as their
2127 ** default conflict resolution strategy
2128 ** (C) Unique index that do use OE_Replace by default.
2129 **
2130 ** The ordering of (2) and (3) is accomplished by making sure the linked
2131 ** list of indexes attached to a table puts all OE_Replace indexes last
2132 ** in the list. See sqlite3CreateIndex() for where that happens.
2133 */
drh61e280a2020-12-11 01:17:062134 sIdxIter.eType = 0;
2135 sIdxIter.i = 0;
drhd3e21a12020-12-11 17:11:562136 sIdxIter.u.ax.aIdx = 0; /* Silence harmless compiler warning */
drh61e280a2020-12-11 01:17:062137 sIdxIter.u.lx.pIdx = pTab->pIndex;
drh096fd472018-04-14 20:24:362138 if( pUpsert ){
2139 if( pUpsert->pUpsertTarget==0 ){
drh61e280a2020-12-11 01:17:062140 /* There is just on ON CONFLICT clause and it has no constraint-target */
2141 assert( pUpsert->pNextUpsert==0 );
drh255c1c12020-12-12 00:28:152142 if( pUpsert->isDoUpdate==0 ){
drh61e280a2020-12-11 01:17:062143 /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
2144 ** Make all unique constraint resolution be OE_Ignore */
2145 overrideError = OE_Ignore;
2146 pUpsert = 0;
2147 }else{
2148 /* A single ON CONFLICT DO UPDATE. Make all resolutions OE_Update */
2149 overrideError = OE_Update;
2150 }
2151 }else if( pTab->pIndex!=0 ){
2152 /* Otherwise, we'll need to run the IndexListTerm array version of the
2153 ** iterator to ensure that all of the ON CONFLICT conditions are
2154 ** checked first and in order. */
2155 int nIdx, jj;
2156 u64 nByte;
2157 Upsert *pTerm;
2158 u8 *bUsed;
2159 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
2160 assert( aRegIdx[nIdx]>0 );
2161 }
2162 sIdxIter.eType = 1;
2163 sIdxIter.u.ax.nIdx = nIdx;
2164 nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx;
2165 sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte);
2166 if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */
2167 bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx];
2168 pUpsert->pToFree = sIdxIter.u.ax.aIdx;
2169 for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
2170 if( pTerm->pUpsertTarget==0 ) break;
2171 if( pTerm->pUpsertIdx==0 ) continue; /* Skip ON CONFLICT for the IPK */
2172 jj = 0;
2173 pIdx = pTab->pIndex;
2174 while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
2175 pIdx = pIdx->pNext;
2176 jj++;
2177 }
2178 if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */
2179 bUsed[jj] = 1;
2180 sIdxIter.u.ax.aIdx[i].p = pIdx;
2181 sIdxIter.u.ax.aIdx[i].ix = jj;
2182 i++;
2183 }
2184 for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
2185 if( bUsed[jj] ) continue;
2186 sIdxIter.u.ax.aIdx[i].p = pIdx;
2187 sIdxIter.u.ax.aIdx[i].ix = jj;
2188 i++;
2189 }
2190 assert( i==nIdx );
drh096fd472018-04-14 20:24:362191 }
2192 }
2193
drha407ecc2019-10-26 00:04:212194 /* Determine if it is possible that triggers (either explicitly coded
2195 ** triggers or FK resolution actions) might run as a result of deletes
2196 ** that happen when OE_Replace conflict resolution occurs. (Call these
2197 ** "replace triggers".) If any replace triggers run, we will need to
2198 ** recheck all of the uniqueness constraints after they have all run.
2199 ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
2200 **
2201 ** If replace triggers are a possibility, then
2202 **
2203 ** (1) Allocate register regTrigCnt and initialize it to zero.
2204 ** That register will count the number of replace triggers that
drhd3c468b2019-10-26 16:38:492205 ** fire. Constraint recheck only occurs if the number is positive.
2206 ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
drha407ecc2019-10-26 00:04:212207 ** (3) Initialize addrRecheck and lblRecheckOk
2208 **
2209 ** The uniqueness rechecking code will create a series of tests to run
2210 ** in a second pass. The addrRecheck and lblRecheckOk variables are
2211 ** used to link together these tests which are separated from each other
2212 ** in the generate bytecode.
2213 */
2214 if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
2215 /* There are not DELETE triggers nor FK constraints. No constraint
2216 ** rechecks are needed. */
2217 pTrigger = 0;
2218 regTrigCnt = 0;
2219 }else{
2220 if( db->flags&SQLITE_RecTriggers ){
2221 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
2222 regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
2223 }else{
2224 pTrigger = 0;
2225 regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
2226 }
2227 if( regTrigCnt ){
2228 /* Replace triggers might exist. Allocate the counter and
2229 ** initialize it to zero. */
2230 regTrigCnt = ++pParse->nMem;
2231 sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
2232 VdbeComment((v, "trigger count"));
2233 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2234 addrRecheck = lblRecheckOk;
2235 }
2236 }
2237
drhf8ffb272013-11-01 17:08:562238 /* If rowid is changing, make sure the new rowid does not previously
2239 ** exist in the table.
drh9cfcf5d2002-01-29 18:41:242240 */
drh6fbe41a2013-10-30 20:22:552241 if( pkChng && pPk==0 ){
drhec4ccdb2018-12-29 02:26:592242 int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
drh11e85272013-10-26 15:40:482243
drhf8ffb272013-11-01 17:08:562244 /* Figure out what action to take in case of a rowid collision */
drh0ca3e242002-01-29 23:07:022245 onError = pTab->keyConf;
2246 if( overrideError!=OE_Default ){
2247 onError = overrideError;
drha996e472003-05-16 02:30:272248 }else if( onError==OE_Default ){
2249 onError = OE_Abort;
drh0ca3e242002-01-29 23:07:022250 }
drh11e85272013-10-26 15:40:482251
drhc8a0c902018-04-13 15:14:332252 /* figure out whether or not upsert applies in this case */
drh61e280a2020-12-11 01:17:062253 if( pUpsert ){
2254 pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0);
2255 if( pUpsertClause!=0 ){
drh255c1c12020-12-12 00:28:152256 if( pUpsertClause->isDoUpdate==0 ){
drh61e280a2020-12-11 01:17:062257 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
2258 }else{
2259 onError = OE_Update; /* DO UPDATE */
2260 }
2261 }
2262 if( pUpsertClause!=pUpsert ){
2263 /* The first ON CONFLICT clause has a conflict target other than
2264 ** the IPK. We have to jump ahead to that first ON CONFLICT clause
2265 ** and then come back here and deal with the IPK afterwards */
2266 upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto);
drhc8a0c902018-04-13 15:14:332267 }
2268 }
2269
drh8d1b82e2013-11-05 19:41:322270 /* If the response to a rowid conflict is REPLACE but the response
2271 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
2272 ** to defer the running of the rowid conflict checking until after
2273 ** the UNIQUE constraints have run.
2274 */
drh84304502018-08-14 15:12:522275 if( onError==OE_Replace /* IPK rule is REPLACE */
mistachkin9a60e712020-12-22 19:57:532276 && onError!=overrideError /* Rules for other constraints are different */
drh84304502018-08-14 15:12:522277 && pTab->pIndex /* There exist other constraints */
drh66306d82021-12-30 02:38:432278 && !upsertIpkDelay /* IPK check already deferred by UPSERT */
drh096fd472018-04-14 20:24:362279 ){
drh84304502018-08-14 15:12:522280 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
2281 VdbeComment((v, "defer IPK REPLACE until last"));
drh8d1b82e2013-11-05 19:41:322282 }
2283
drhbb6b1ca2018-04-19 13:52:392284 if( isUpdate ){
2285 /* pkChng!=0 does not mean that the rowid has changed, only that
2286 ** it might have changed. Skip the conflict logic below if the rowid
2287 ** is unchanged. */
2288 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
2289 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2290 VdbeCoverage(v);
2291 }
2292
drhf8ffb272013-11-01 17:08:562293 /* Check to see if the new rowid already exists in the table. Skip
2294 ** the following conflict logic if it does not. */
drh7f5f3062018-04-17 20:06:242295 VdbeNoopComment((v, "uniqueness check for ROWID"));
drh4031baf2018-05-28 17:31:202296 sqlite3VdbeVerifyAbortable(v, onError);
drh6934fc72013-10-31 15:37:492297 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
drh688852a2014-02-17 22:40:432298 VdbeCoverage(v);
drhf8ffb272013-11-01 17:08:562299
dane1e2ae22009-09-24 16:52:282300 switch( onError ){
2301 default: {
2302 onError = OE_Abort;
drh08b92082020-08-10 14:18:002303 /* no break */ deliberate_fall_through
drh79b0c952002-05-21 12:56:432304 }
dane1e2ae22009-09-24 16:52:282305 case OE_Rollback:
2306 case OE_Abort:
2307 case OE_Fail: {
drh99160482018-04-18 01:34:392308 testcase( onError==OE_Rollback );
2309 testcase( onError==OE_Abort );
2310 testcase( onError==OE_Fail );
drhf9c8ce32013-11-05 13:33:552311 sqlite3RowidConstraint(pParse, onError, pTab);
dane1e2ae22009-09-24 16:52:282312 break;
drh0ca3e242002-01-29 23:07:022313 }
dane1e2ae22009-09-24 16:52:282314 case OE_Replace: {
2315 /* If there are DELETE triggers on this table and the
2316 ** recursive-triggers flag is set, call GenerateRowDelete() to
mistachkind5578432012-08-25 10:01:292317 ** remove the conflicting row from the table. This will fire
dane1e2ae22009-09-24 16:52:282318 ** the triggers and remove both the table and index b-tree entries.
2319 **
2320 ** Otherwise, if there are no triggers or the recursive-triggers
larrybrbc917382023-06-07 08:40:312321 ** flag is not set, but the table has one or more indexes, call
2322 ** GenerateRowIndexDelete(). This removes the index b-tree entries
2323 ** only. The table b-tree entry will be replaced by the new entry
2324 ** when it is inserted.
danda730f62010-02-18 08:19:192325 **
2326 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
2327 ** also invoke MultiWrite() to indicate that this VDBE may require
2328 ** statement rollback (if the statement is aborted after the delete
2329 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
2330 ** but being more selective here allows statements like:
2331 **
2332 ** REPLACE INTO t(rowid) VALUES($newrowid)
2333 **
2334 ** to run without a statement journal if there are no indexes on the
2335 ** table.
2336 */
drha407ecc2019-10-26 00:04:212337 if( regTrigCnt ){
danda730f62010-02-18 08:19:192338 sqlite3MultiWrite(pParse);
drh26198bb2013-10-31 11:15:092339 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
dan438b8812015-09-15 15:55:152340 regNewData, 1, 0, OE_Replace, 1, -1);
drha407ecc2019-10-26 00:04:212341 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2342 nReplaceTrig++;
dan46c47d42011-03-01 18:42:072343 }else{
drh9b1c62d2011-03-30 21:04:432344#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
drh54f2cd92018-04-13 16:23:222345 assert( HasRowid(pTab) );
2346 /* This OP_Delete opcode fires the pre-update-hook only. It does
2347 ** not modify the b-tree. It is more efficient to let the coming
2348 ** OP_Insert replace the existing entry than it is to delete the
2349 ** existing entry and then insert a new one. */
2350 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
2351 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
drh9b1c62d2011-03-30 21:04:432352#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
dan46c47d42011-03-01 18:42:072353 if( pTab->pIndex ){
2354 sqlite3MultiWrite(pParse);
drhb77ebd82015-09-15 13:42:162355 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
dan46c47d42011-03-01 18:42:072356 }
dane1e2ae22009-09-24 16:52:282357 }
2358 seenReplace = 1;
2359 break;
drh5383ae52003-06-04 12:23:302360 }
drh9eddaca2018-04-13 18:59:172361#ifndef SQLITE_OMIT_UPSERT
2362 case OE_Update: {
dan2cc00422018-04-17 18:16:102363 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
drh08b92082020-08-10 14:18:002364 /* no break */ deliberate_fall_through
drh9eddaca2018-04-13 18:59:172365 }
2366#endif
dane1e2ae22009-09-24 16:52:282367 case OE_Ignore: {
drh99160482018-04-18 01:34:392368 testcase( onError==OE_Ignore );
drh076e85f2015-09-03 13:46:122369 sqlite3VdbeGoto(v, ignoreDest);
dane1e2ae22009-09-24 16:52:282370 break;
2371 }
2372 }
drh11e85272013-10-26 15:40:482373 sqlite3VdbeResolveLabel(v, addrRowidOk);
drh61e280a2020-12-11 01:17:062374 if( pUpsert && pUpsertClause!=pUpsert ){
2375 upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
2376 }else if( ipkTop ){
drh84304502018-08-14 15:12:522377 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
2378 sqlite3VdbeJumpHere(v, ipkTop-1);
drh5383ae52003-06-04 12:23:302379 }
drh0ca3e242002-01-29 23:07:022380 }
drh0bd1f4e2002-06-06 18:54:392381
2382 /* Test all UNIQUE constraints by creating entries for each UNIQUE
2383 ** index and making sure that duplicate entries do not already exist.
drh11e85272013-10-26 15:40:482384 ** Compute the revised record entries for indices as we go.
drhf8ffb272013-11-01 17:08:562385 **
2386 ** This loop also handles the case of the PRIMARY KEY index for a
2387 ** WITHOUT ROWID table.
drh0bd1f4e2002-06-06 18:54:392388 */
drh61e280a2020-12-11 01:17:062389 for(pIdx = indexIteratorFirst(&sIdxIter, &ix);
drhdaf27612020-12-10 20:31:252390 pIdx;
drh61e280a2020-12-11 01:17:062391 pIdx = indexIteratorNext(&sIdxIter, &ix)
drhdaf27612020-12-10 20:31:252392 ){
larrybrbc917382023-06-07 08:40:312393 int regIdx; /* Range of registers holding content for pIdx */
drh6934fc72013-10-31 15:37:492394 int regR; /* Range of registers holding conflicting PK */
2395 int iThisCur; /* Cursor for this UNIQUE index */
2396 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
drha407ecc2019-10-26 00:04:212397 int addrConflictCk; /* First opcode in the conflict check logic */
drh2184fc72011-04-09 03:04:132398
drh26198bb2013-10-31 11:15:092399 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
drh61e280a2020-12-11 01:17:062400 if( pUpsert ){
2401 pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
2402 if( upsertIpkDelay && pUpsertClause==pUpsert ){
2403 sqlite3VdbeJumpHere(v, upsertIpkDelay);
2404 }
drh7f5f3062018-04-17 20:06:242405 }
drh61e280a2020-12-11 01:17:062406 addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
2407 if( bAffinityDone==0 ){
drh84304502018-08-14 15:12:522408 sqlite3TableAffinity(v, pTab, regNewData+1);
2409 bAffinityDone = 1;
2410 }
drh8e50d652020-05-23 17:56:492411 VdbeNoopComment((v, "prep index %s", pIdx->zName));
drh6934fc72013-10-31 15:37:492412 iThisCur = iIdxCur+ix;
drh7f5f3062018-04-17 20:06:242413
drhb2fe7d82003-04-20 17:29:232414
drhf8ffb272013-11-01 17:08:562415 /* Skip partial indices for which the WHERE clause is not true */
drhb2b9d3d2013-08-01 01:14:432416 if( pIdx->pPartIdxWhere ){
drh26198bb2013-10-31 11:15:092417 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
drh6e97f8e2017-07-20 13:17:082418 pParse->iSelfTab = -(regNewData+1);
drh72bc8202015-06-11 13:58:352419 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
2420 SQLITE_JUMPIFNULL);
drh6e97f8e2017-07-20 13:17:082421 pParse->iSelfTab = 0;
drhb2b9d3d2013-08-01 01:14:432422 }
2423
drh6934fc72013-10-31 15:37:492424 /* Create a record for this index entry as it should appear after
drhf8ffb272013-11-01 17:08:562425 ** the insert or update. Store that record in the aRegIdx[ix] register
2426 */
drhbf2f5732016-11-10 16:07:432427 regIdx = aRegIdx[ix]+1;
drh9cfcf5d2002-01-29 18:41:242428 for(i=0; i<pIdx->nColumn; i++){
drh6934fc72013-10-31 15:37:492429 int iField = pIdx->aiColumn[i];
drhf82b9af2013-11-01 14:03:202430 int x;
drh4b92f982015-09-29 17:20:142431 if( iField==XN_EXPR ){
drh6e97f8e2017-07-20 13:17:082432 pParse->iSelfTab = -(regNewData+1);
drh1c75c9d2015-12-21 15:22:132433 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
drh6e97f8e2017-07-20 13:17:082434 pParse->iSelfTab = 0;
drh1f9ca2c2015-08-25 16:57:522435 VdbeComment((v, "%s column %d", pIdx->zName, i));
drh463e76f2019-10-18 10:05:062436 }else if( iField==XN_ROWID || iField==pTab->iPKey ){
2437 x = regNewData;
2438 sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
2439 VdbeComment((v, "rowid"));
drh9cfcf5d2002-01-29 18:41:242440 }else{
drhc5f808d2019-10-19 15:01:522441 testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
drhb9bcf7c2019-10-19 13:29:102442 x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
drh463e76f2019-10-18 10:05:062443 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
drhcf9d36d2021-08-02 18:03:432444 VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
drh9cfcf5d2002-01-29 18:41:242445 }
2446 }
drh26198bb2013-10-31 11:15:092447 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
drh26198bb2013-10-31 11:15:092448 VdbeComment((v, "for %s", pIdx->zName));
drh7e4acf72017-02-14 20:00:162449#ifdef SQLITE_ENABLE_NULL_TRIM
drh9df385e2019-02-19 13:08:352450 if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
2451 sqlite3SetMakeRecordP5(v, pIdx->pTable);
2452 }
drh7e4acf72017-02-14 20:00:162453#endif
drh3aef2fb2020-01-02 17:46:022454 sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
drhb2fe7d82003-04-20 17:29:232455
larrybrbc917382023-06-07 08:40:312456 /* In an UPDATE operation, if this index is the PRIMARY KEY index
drhf8ffb272013-11-01 17:08:562457 ** of a WITHOUT ROWID table and there has been no change the
2458 ** primary key, then no collision is possible. The collision detection
2459 ** logic below can all be skipped. */
drh00012df2013-11-05 01:59:072460 if( isUpdate && pPk==pIdx && pkChng==0 ){
drhda475b82013-11-04 21:44:542461 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2462 continue;
2463 }
drhf8ffb272013-11-01 17:08:562464
drh6934fc72013-10-31 15:37:492465 /* Find out what action to take in case there is a uniqueness conflict */
drh9cfcf5d2002-01-29 18:41:242466 onError = pIdx->onError;
larrybrbc917382023-06-07 08:40:312467 if( onError==OE_None ){
drh11e85272013-10-26 15:40:482468 sqlite3VdbeResolveLabel(v, addrUniqueOk);
danielk1977de630352009-05-04 11:42:292469 continue; /* pIdx is not a UNIQUE index */
2470 }
drh9cfcf5d2002-01-29 18:41:242471 if( overrideError!=OE_Default ){
2472 onError = overrideError;
drha996e472003-05-16 02:30:272473 }else if( onError==OE_Default ){
2474 onError = OE_Abort;
drh9cfcf5d2002-01-29 18:41:242475 }
drhc6c9e152016-11-10 17:01:362476
drhc8a0c902018-04-13 15:14:332477 /* Figure out if the upsert clause applies to this index */
drh61e280a2020-12-11 01:17:062478 if( pUpsertClause ){
drh255c1c12020-12-12 00:28:152479 if( pUpsertClause->isDoUpdate==0 ){
drhc8a0c902018-04-13 15:14:332480 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
2481 }else{
2482 onError = OE_Update; /* DO UPDATE */
2483 }
2484 }
2485
drh801f55d2017-01-04 22:02:562486 /* Collision detection may be omitted if all of the following are true:
2487 ** (1) The conflict resolution algorithm is REPLACE
2488 ** (2) The table is a WITHOUT ROWID table
2489 ** (3) There are no secondary indexes on the table
2490 ** (4) No delete triggers need to be fired if there is a conflict
danf9a12a12017-01-05 06:57:422491 ** (5) No FK constraint counters need to be updated if a conflict occurs.
dan418454c2019-01-07 15:57:352492 **
2493 ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
2494 ** must be explicitly deleted in order to ensure any pre-update hook
drh78b2fa82021-10-07 12:11:202495 ** is invoked. */
2496 assert( IsOrdinaryTable(pTab) );
dan418454c2019-01-07 15:57:352497#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
drh801f55d2017-01-04 22:02:562498 if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
2499 && pPk==pIdx /* Condition 2 */
2500 && onError==OE_Replace /* Condition 1 */
2501 && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
2502 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
danf9a12a12017-01-05 06:57:422503 && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
drhf38524d2021-08-02 16:41:572504 (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
drh801f55d2017-01-04 22:02:562505 ){
2506 sqlite3VdbeResolveLabel(v, addrUniqueOk);
2507 continue;
drhc6c9e152016-11-10 17:01:362508 }
dan418454c2019-01-07 15:57:352509#endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
drhc6c9e152016-11-10 17:01:362510
drhb2fe7d82003-04-20 17:29:232511 /* Check to see if the new index entry will be unique */
drh4031baf2018-05-28 17:31:202512 sqlite3VdbeVerifyAbortable(v, onError);
larrybrbc917382023-06-07 08:40:312513 addrConflictCk =
drha407ecc2019-10-26 00:04:212514 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
2515 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
drhf8ffb272013-11-01 17:08:562516
2517 /* Generate code to handle collisions */
drhd3e21a12020-12-11 17:11:562518 regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField);
drh46d03fc2013-12-19 02:23:452519 if( isUpdate || onError==OE_Replace ){
2520 if( HasRowid(pTab) ){
2521 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
2522 /* Conflict only if the rowid of the existing index entry
2523 ** is different from old-rowid */
2524 if( isUpdate ){
2525 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
drh3d77dee2014-02-19 14:20:492526 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
drh688852a2014-02-17 22:40:432527 VdbeCoverage(v);
drhda475b82013-11-04 21:44:542528 }
drh46d03fc2013-12-19 02:23:452529 }else{
2530 int x;
2531 /* Extract the PRIMARY KEY from the end of the index entry and
2532 ** store it in registers regR..regR+nPk-1 */
drha021f122013-12-19 14:34:342533 if( pIdx!=pPk ){
drh46d03fc2013-12-19 02:23:452534 for(i=0; i<pPk->nKeyCol; i++){
drh4b92f982015-09-29 17:20:142535 assert( pPk->aiColumn[i]>=0 );
drhb9bcf7c2019-10-19 13:29:102536 x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
drh46d03fc2013-12-19 02:23:452537 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
2538 VdbeComment((v, "%s.%s", pTab->zName,
drhcf9d36d2021-08-02 18:03:432539 pTab->aCol[pPk->aiColumn[i]].zCnName));
drhda475b82013-11-04 21:44:542540 }
drh46d03fc2013-12-19 02:23:452541 }
2542 if( isUpdate ){
larrybrbc917382023-06-07 08:40:312543 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
drh46d03fc2013-12-19 02:23:452544 ** table, only conflict if the new PRIMARY KEY values are actually
drh5a1f7612022-03-11 15:42:052545 ** different from the old. See TH3 withoutrowid04.test.
drh46d03fc2013-12-19 02:23:452546 **
2547 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
2548 ** of the matched index row are different from the original PRIMARY
2549 ** KEY values of this row before the update. */
2550 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
2551 int op = OP_Ne;
drh48dd1d82014-05-27 18:18:582552 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
larrybrbc917382023-06-07 08:40:312553
drh46d03fc2013-12-19 02:23:452554 for(i=0; i<pPk->nKeyCol; i++){
2555 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
2556 x = pPk->aiColumn[i];
drh4b92f982015-09-29 17:20:142557 assert( x>=0 );
drh46d03fc2013-12-19 02:23:452558 if( i==(pPk->nKeyCol-1) ){
2559 addrJump = addrUniqueOk;
2560 op = OP_Eq;
2561 }
drhb6d861e2019-10-29 03:30:262562 x = sqlite3TableColumnToStorage(pTab, x);
larrybrbc917382023-06-07 08:40:312563 sqlite3VdbeAddOp4(v, op,
drh46d03fc2013-12-19 02:23:452564 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
2565 );
drh3d77dee2014-02-19 14:20:492566 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2567 VdbeCoverageIf(v, op==OP_Eq);
2568 VdbeCoverageIf(v, op==OP_Ne);
drh46d03fc2013-12-19 02:23:452569 }
drh26198bb2013-10-31 11:15:092570 }
drh26198bb2013-10-31 11:15:092571 }
drh11e85272013-10-26 15:40:482572 }
drhb2fe7d82003-04-20 17:29:232573
2574 /* Generate code that executes if the new index entry is not unique */
danielk1977b84f96f2005-01-20 11:32:232575 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
drh9eddaca2018-04-13 18:59:172576 || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
drh9cfcf5d2002-01-29 18:41:242577 switch( onError ){
drh1c928532002-01-31 15:54:212578 case OE_Rollback:
2579 case OE_Abort:
2580 case OE_Fail: {
drh99160482018-04-18 01:34:392581 testcase( onError==OE_Rollback );
2582 testcase( onError==OE_Abort );
2583 testcase( onError==OE_Fail );
drhf9c8ce32013-11-05 13:33:552584 sqlite3UniqueConstraint(pParse, onError, pIdx);
drh9cfcf5d2002-01-29 18:41:242585 break;
2586 }
drh9eddaca2018-04-13 18:59:172587#ifndef SQLITE_OMIT_UPSERT
2588 case OE_Update: {
dan2cc00422018-04-17 18:16:102589 sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
drh08b92082020-08-10 14:18:002590 /* no break */ deliberate_fall_through
drh9eddaca2018-04-13 18:59:172591 }
2592#endif
drh9cfcf5d2002-01-29 18:41:242593 case OE_Ignore: {
drh99160482018-04-18 01:34:392594 testcase( onError==OE_Ignore );
drh076e85f2015-09-03 13:46:122595 sqlite3VdbeGoto(v, ignoreDest);
drh9cfcf5d2002-01-29 18:41:242596 break;
2597 }
drh098d1682009-05-02 15:46:462598 default: {
drha407ecc2019-10-26 00:04:212599 int nConflictCk; /* Number of opcodes in conflict check logic */
2600
drh098d1682009-05-02 15:46:462601 assert( onError==OE_Replace );
drha407ecc2019-10-26 00:04:212602 nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
drh362c1812021-10-30 18:17:592603 assert( nConflictCk>0 || db->mallocFailed );
2604 testcase( nConflictCk<=0 );
drhd3c468b2019-10-26 16:38:492605 testcase( nConflictCk>1 );
drha407ecc2019-10-26 00:04:212606 if( regTrigCnt ){
danfecfb312018-05-28 18:29:462607 sqlite3MultiWrite(pParse);
drha407ecc2019-10-26 00:04:212608 nReplaceTrig++;
danfecfb312018-05-28 18:29:462609 }
drh7b14b652019-12-29 22:08:202610 if( pTrigger && isUpdate ){
2611 sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
2612 }
drh26198bb2013-10-31 11:15:092613 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
drhb0264ee2015-09-14 14:45:502614 regR, nPkField, 0, OE_Replace,
drh68116932017-01-07 14:47:032615 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
drh7b14b652019-12-29 22:08:202616 if( pTrigger && isUpdate ){
2617 sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
2618 }
drha407ecc2019-10-26 00:04:212619 if( regTrigCnt ){
drha407ecc2019-10-26 00:04:212620 int addrBypass; /* Jump destination to bypass recheck logic */
2621
2622 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
2623 addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
2624 VdbeComment((v, "bypass recheck"));
2625
2626 /* Here we insert code that will be invoked after all constraint
2627 ** checks have run, if and only if one or more replace triggers
2628 ** fired. */
2629 sqlite3VdbeResolveLabel(v, lblRecheckOk);
2630 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
2631 if( pIdx->pPartIdxWhere ){
2632 /* Bypass the recheck if this partial index is not defined
2633 ** for the current row */
drh06608842019-10-26 01:43:142634 sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
drha407ecc2019-10-26 00:04:212635 VdbeCoverage(v);
2636 }
2637 /* Copy the constraint check code from above, except change
2638 ** the constraint-ok jump destination to be the address of
2639 ** the next retest block */
drhd3c468b2019-10-26 16:38:492640 while( nConflictCk>0 ){
drhd901b162019-10-26 12:27:552641 VdbeOp x; /* Conflict check opcode to copy */
2642 /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
2643 ** Hence, make a complete copy of the opcode, rather than using
2644 ** a pointer to the opcode. */
2645 x = *sqlite3VdbeGetOp(v, addrConflictCk);
2646 if( x.opcode!=OP_IdxRowid ){
2647 int p2; /* New P2 value for copied conflict check opcode */
drhb9f2e5f2020-01-28 15:02:232648 const char *zP4;
drhd901b162019-10-26 12:27:552649 if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
2650 p2 = lblRecheckOk;
2651 }else{
2652 p2 = x.p2;
2653 }
drhb9f2e5f2020-01-28 15:02:232654 zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
2655 sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
drhd901b162019-10-26 12:27:552656 sqlite3VdbeChangeP5(v, x.p5);
2657 VdbeCoverageIf(v, p2!=x.p2);
drha407ecc2019-10-26 00:04:212658 }
2659 nConflictCk--;
drhd901b162019-10-26 12:27:552660 addrConflictCk++;
drha407ecc2019-10-26 00:04:212661 }
2662 /* If the retest fails, issue an abort */
drh2da8d6f2019-10-16 14:56:032663 sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
drha407ecc2019-10-26 00:04:212664
2665 sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
drh2da8d6f2019-10-16 14:56:032666 }
drh0ca3e242002-01-29 23:07:022667 seenReplace = 1;
drh9cfcf5d2002-01-29 18:41:242668 break;
2669 }
drh9cfcf5d2002-01-29 18:41:242670 }
drh61e280a2020-12-11 01:17:062671 sqlite3VdbeResolveLabel(v, addrUniqueOk);
drh392ee212013-11-08 16:54:562672 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
larrybrbc917382023-06-07 08:40:312673 if( pUpsertClause
drhed4c5462020-12-11 16:49:512674 && upsertIpkReturn
2675 && sqlite3UpsertNextIsIPK(pUpsertClause)
2676 ){
drh61e280a2020-12-11 01:17:062677 sqlite3VdbeGoto(v, upsertIpkDelay+1);
2678 sqlite3VdbeJumpHere(v, upsertIpkReturn);
drh58b18a42020-12-11 19:36:192679 upsertIpkReturn = 0;
drh61e280a2020-12-11 01:17:062680 }
drh9cfcf5d2002-01-29 18:41:242681 }
drh84304502018-08-14 15:12:522682
2683 /* If the IPK constraint is a REPLACE, run it last */
2684 if( ipkTop ){
drh6214d932019-01-12 16:19:232685 sqlite3VdbeGoto(v, ipkTop);
drh84304502018-08-14 15:12:522686 VdbeComment((v, "Do IPK REPLACE"));
drh66306d82021-12-30 02:38:432687 assert( ipkBottom>0 );
drh84304502018-08-14 15:12:522688 sqlite3VdbeJumpHere(v, ipkBottom);
2689 }
2690
drha407ecc2019-10-26 00:04:212691 /* Recheck all uniqueness constraints after replace triggers have run */
2692 testcase( regTrigCnt!=0 && nReplaceTrig==0 );
drhd3c468b2019-10-26 16:38:492693 assert( regTrigCnt!=0 || nReplaceTrig==0 );
drha407ecc2019-10-26 00:04:212694 if( nReplaceTrig ){
2695 sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
2696 if( !pPk ){
2697 if( isUpdate ){
2698 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
2699 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
2700 VdbeCoverage(v);
2701 }
2702 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
2703 VdbeCoverage(v);
2704 sqlite3RowidConstraint(pParse, OE_Abort, pTab);
2705 }else{
2706 sqlite3VdbeGoto(v, addrRecheck);
2707 }
2708 sqlite3VdbeResolveLabel(v, lblRecheckOk);
2709 }
2710
drha7c3b932019-05-07 19:13:422711 /* Generate the table record */
2712 if( HasRowid(pTab) ){
2713 int regRec = aRegIdx[ix];
drh0b0b3a92019-10-17 18:35:572714 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
drha7c3b932019-05-07 19:13:422715 sqlite3SetMakeRecordP5(v, pTab);
2716 if( !bAffinityDone ){
2717 sqlite3TableAffinity(v, pTab, 0);
2718 }
2719 }
2720
drh4308e342013-11-11 16:55:522721 *pbMayReplace = seenReplace;
drhce60aa42013-11-08 01:09:152722 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
drh9cfcf5d2002-01-29 18:41:242723}
drh0ca3e242002-01-29 23:07:022724
drhd447dce2017-01-25 20:55:112725#ifdef SQLITE_ENABLE_NULL_TRIM
drh0ca3e242002-01-29 23:07:022726/*
drh585ce192017-01-25 14:58:272727** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
2728** to be the number of columns in table pTab that must not be NULL-trimmed.
2729**
2730** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
2731*/
2732void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
2733 u16 i;
2734
2735 /* Records with omitted columns are only allowed for schema format
2736 ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
2737 if( pTab->pSchema->file_format<2 ) return;
2738
drh7e4acf72017-02-14 20:00:162739 for(i=pTab->nCol-1; i>0; i--){
drh79cf2b72021-07-31 20:30:412740 if( pTab->aCol[i].iDflt!=0 ) break;
drh7e4acf72017-02-14 20:00:162741 if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
2742 }
2743 sqlite3VdbeChangeP5(v, i+1);
drh585ce192017-01-25 14:58:272744}
drhd447dce2017-01-25 20:55:112745#endif
drh585ce192017-01-25 14:58:272746
drh0ca3e242002-01-29 23:07:022747/*
danfadc0e32021-02-18 12:18:102748** Table pTab is a WITHOUT ROWID table that is being written to. The cursor
2749** number is iCur, and register regData contains the new record for the
2750** PK index. This function adds code to invoke the pre-update hook,
2751** if one is registered.
2752*/
2753#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2754static void codeWithoutRowidPreupdate(
2755 Parse *pParse, /* Parse context */
2756 Table *pTab, /* Table being updated */
2757 int iCur, /* Cursor number for table */
2758 int regData /* Data containing new record */
2759){
2760 Vdbe *v = pParse->pVdbe;
2761 int r = sqlite3GetTempReg(pParse);
2762 assert( !HasRowid(pTab) );
drhd01206f2021-03-21 18:23:482763 assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
danfadc0e32021-02-18 12:18:102764 sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
2765 sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE);
2766 sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
2767 sqlite3ReleaseTempReg(pParse, r);
2768}
2769#else
2770# define codeWithoutRowidPreupdate(a,b,c,d)
2771#endif
2772
2773/*
drh0ca3e242002-01-29 23:07:022774** This routine generates code to finish the INSERT or UPDATE operation
danielk19774adee202004-05-08 08:23:192775** that was started by a prior call to sqlite3GenerateConstraintChecks.
drh6934fc72013-10-31 15:37:492776** A consecutive range of registers starting at regNewData contains the
drh04adf412008-01-08 18:57:502777** rowid and the content to be inserted.
drh0ca3e242002-01-29 23:07:022778**
drhb419a922002-01-30 16:17:232779** The arguments to this routine should be the same as the first six
danielk19774adee202004-05-08 08:23:192780** arguments to sqlite3GenerateConstraintChecks.
drh0ca3e242002-01-29 23:07:022781*/
danielk19774adee202004-05-08 08:23:192782void sqlite3CompleteInsertion(
drh0ca3e242002-01-29 23:07:022783 Parse *pParse, /* The parser context */
2784 Table *pTab, /* the table into which we are inserting */
drh26198bb2013-10-31 11:15:092785 int iDataCur, /* Cursor of the canonical data source */
2786 int iIdxCur, /* First index cursor */
drh6934fc72013-10-31 15:37:492787 int regNewData, /* Range of content */
drhaa9b8962008-01-08 02:57:552788 int *aRegIdx, /* Register used by each index. 0 for unused indices */
danf91c1312017-01-10 20:04:382789 int update_flags, /* True for UPDATE, False for INSERT */
danielk1977de630352009-05-04 11:42:292790 int appendBias, /* True if this is likely to be an append */
2791 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
drh0ca3e242002-01-29 23:07:022792){
drh6934fc72013-10-31 15:37:492793 Vdbe *v; /* Prepared statements under construction */
2794 Index *pIdx; /* An index being inserted or updated */
2795 u8 pik_flags; /* flag values passed to the btree insert */
drh6934fc72013-10-31 15:37:492796 int i; /* Loop counter */
drh0ca3e242002-01-29 23:07:022797
danf91c1312017-01-10 20:04:382798 assert( update_flags==0
2799 || update_flags==OPFLAG_ISUPDATE
2800 || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
2801 );
2802
drhf0b41742020-08-15 21:55:142803 v = pParse->pVdbe;
drh0ca3e242002-01-29 23:07:022804 assert( v!=0 );
drhf38524d2021-08-02 16:41:572805 assert( !IsView(pTab) ); /* This table is not a VIEW */
drhb2b9d3d2013-08-01 01:14:432806 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
drhd35bdd62019-12-15 02:49:322807 /* All REPLACE indexes are at the end of the list */
2808 assert( pIdx->onError!=OE_Replace
2809 || pIdx->pNext==0
2810 || pIdx->pNext->onError==OE_Replace );
drhaa9b8962008-01-08 02:57:552811 if( aRegIdx[i]==0 ) continue;
drhb2b9d3d2013-08-01 01:14:432812 if( pIdx->pPartIdxWhere ){
2813 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
drh688852a2014-02-17 22:40:432814 VdbeCoverage(v);
drhb2b9d3d2013-08-01 01:14:432815 }
dancb9a3642017-01-30 19:44:532816 pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
drh48dd1d82014-05-27 18:18:582817 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
drh6546af12013-11-04 15:23:252818 pik_flags |= OPFLAG_NCHANGE;
danf91c1312017-01-10 20:04:382819 pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
dancb9a3642017-01-30 19:44:532820 if( update_flags==0 ){
danfadc0e32021-02-18 12:18:102821 codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]);
dancb9a3642017-01-30 19:44:532822 }
danielk1977de630352009-05-04 11:42:292823 }
dancb9a3642017-01-30 19:44:532824 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
2825 aRegIdx[i]+1,
2826 pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
drh9b34abe2016-01-16 15:12:352827 sqlite3VdbeChangeP5(v, pik_flags);
drh0ca3e242002-01-29 23:07:022828 }
drhec95c442013-10-23 01:57:322829 if( !HasRowid(pTab) ) return;
drh4794f732004-11-05 17:17:502830 if( pParse->nested ){
2831 pik_flags = 0;
2832 }else{
danielk197794eb6a12005-12-15 15:22:082833 pik_flags = OPFLAG_NCHANGE;
danf91c1312017-01-10 20:04:382834 pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
drh4794f732004-11-05 17:17:502835 }
drhe4d90812007-03-29 05:51:492836 if( appendBias ){
2837 pik_flags |= OPFLAG_APPEND;
2838 }
danielk1977de630352009-05-04 11:42:292839 if( useSeekResult ){
2840 pik_flags |= OPFLAG_USESEEKRESULT;
2841 }
drha7c3b932019-05-07 19:13:422842 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
danielk197794eb6a12005-12-15 15:22:082843 if( !pParse->nested ){
drhf14b7fb2016-12-07 21:35:552844 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
danielk197794eb6a12005-12-15 15:22:082845 }
drhb7654112008-01-12 12:48:072846 sqlite3VdbeChangeP5(v, pik_flags);
drh0ca3e242002-01-29 23:07:022847}
drhcd446902004-02-24 01:05:312848
2849/*
drh26198bb2013-10-31 11:15:092850** Allocate cursors for the pTab table and all its indices and generate
2851** code to open and initialized those cursors.
drhaa9b8962008-01-08 02:57:552852**
drh26198bb2013-10-31 11:15:092853** The cursor for the object that contains the complete data (normally
2854** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
2855** ROWID table) is returned in *piDataCur. The first index cursor is
2856** returned in *piIdxCur. The number of indices is returned.
2857**
2858** Use iBase as the first cursor (either the *piDataCur for rowid tables
2859** or the first index for WITHOUT ROWID tables) if it is non-negative.
2860** If iBase is negative, then allocate the next available cursor.
2861**
2862** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
2863** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
2864** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
2865** pTab->pIndex list.
drhb6b4b792014-08-21 14:10:232866**
2867** If pTab is a virtual table, then this routine is a no-op and the
2868** *piDataCur and *piIdxCur values are left uninitialized.
drhcd446902004-02-24 01:05:312869*/
drhaa9b8962008-01-08 02:57:552870int sqlite3OpenTableAndIndices(
drh290c1942004-08-21 17:54:452871 Parse *pParse, /* Parsing context */
2872 Table *pTab, /* Table to be opened */
drh26198bb2013-10-31 11:15:092873 int op, /* OP_OpenRead or OP_OpenWrite */
drhb89aeb62016-01-27 15:49:322874 u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
drh26198bb2013-10-31 11:15:092875 int iBase, /* Use this for the table cursor, if there is one */
drh6a534992013-11-16 20:13:392876 u8 *aToOpen, /* If not NULL: boolean for each table and index */
drh26198bb2013-10-31 11:15:092877 int *piDataCur, /* Write the database source cursor number here */
2878 int *piIdxCur /* Write the first index cursor number here */
drh290c1942004-08-21 17:54:452879){
drhcd446902004-02-24 01:05:312880 int i;
drh4cbdda92006-06-14 19:00:202881 int iDb;
drh6a534992013-11-16 20:13:392882 int iDataCur;
drhcd446902004-02-24 01:05:312883 Index *pIdx;
drh4cbdda92006-06-14 19:00:202884 Vdbe *v;
2885
drh26198bb2013-10-31 11:15:092886 assert( op==OP_OpenRead || op==OP_OpenWrite );
danfd261ec2015-10-22 20:54:332887 assert( op==OP_OpenWrite || p5==0 );
drh56a41072023-06-16 14:39:212888 assert( piDataCur!=0 );
2889 assert( piIdxCur!=0 );
drh26198bb2013-10-31 11:15:092890 if( IsVirtual(pTab) ){
drhb6b4b792014-08-21 14:10:232891 /* This routine is a no-op for virtual tables. Leave the output
drh33d28ab2021-10-28 12:07:432892 ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
2893 ** for improved error detection. */
2894 *piDataCur = *piIdxCur = -999;
drh26198bb2013-10-31 11:15:092895 return 0;
2896 }
drh4cbdda92006-06-14 19:00:202897 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drhf0b41742020-08-15 21:55:142898 v = pParse->pVdbe;
drhcd446902004-02-24 01:05:312899 assert( v!=0 );
drh26198bb2013-10-31 11:15:092900 if( iBase<0 ) iBase = pParse->nTab;
drh6a534992013-11-16 20:13:392901 iDataCur = iBase++;
drh56a41072023-06-16 14:39:212902 *piDataCur = iDataCur;
drh6a534992013-11-16 20:13:392903 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
2904 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
drh40ee7292023-06-20 17:45:192905 }else if( pParse->db->noSharedCache==0 ){
drh26198bb2013-10-31 11:15:092906 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
drh6fbe41a2013-10-30 20:22:552907 }
drh56a41072023-06-16 14:39:212908 *piIdxCur = iBase;
drh26198bb2013-10-31 11:15:092909 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
drh26198bb2013-10-31 11:15:092910 int iIdxCur = iBase++;
danielk1977da184232006-01-05 11:34:322911 assert( pIdx->pSchema==pTab->pSchema );
dan61441c32016-08-26 12:00:502912 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
drh56a41072023-06-16 14:39:212913 *piDataCur = iIdxCur;
dan61441c32016-08-26 12:00:502914 p5 = 0;
2915 }
drh6a534992013-11-16 20:13:392916 if( aToOpen==0 || aToOpen[i+1] ){
2917 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
2918 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
drhb89aeb62016-01-27 15:49:322919 sqlite3VdbeChangeP5(v, p5);
dan61441c32016-08-26 12:00:502920 VdbeComment((v, "%s", pIdx->zName));
drhb89aeb62016-01-27 15:49:322921 }
drhcd446902004-02-24 01:05:312922 }
drh26198bb2013-10-31 11:15:092923 if( iBase>pParse->nTab ) pParse->nTab = iBase;
2924 return i;
drhcd446902004-02-24 01:05:312925}
drh9d9cf222007-02-13 15:01:112926
drh91c58e22007-03-27 12:04:042927
2928#ifdef SQLITE_TEST
2929/*
2930** The following global variable is incremented whenever the
2931** transfer optimization is used. This is used for testing
2932** purposes only - to make sure the transfer optimization really
peter.d.reid60ec9142014-09-06 16:39:462933** is happening when it is supposed to.
drh91c58e22007-03-27 12:04:042934*/
2935int sqlite3_xferopt_count;
2936#endif /* SQLITE_TEST */
2937
2938
drh9d9cf222007-02-13 15:01:112939#ifndef SQLITE_OMIT_XFER_OPT
2940/*
drh9d9cf222007-02-13 15:01:112941** Check to see if index pSrc is compatible as a source of data
2942** for index pDest in an insert transfer optimization. The rules
2943** for a compatible index:
2944**
2945** * The index is over the same set of columns
2946** * The same DESC and ASC markings occurs on all columns
2947** * The same onError processing (OE_Abort, OE_Ignore, etc)
2948** * The same collating sequence on each column
drhb2b9d3d2013-08-01 01:14:432949** * The index has the exact same WHERE clause
drh9d9cf222007-02-13 15:01:112950*/
2951static int xferCompatibleIndex(Index *pDest, Index *pSrc){
2952 int i;
2953 assert( pDest && pSrc );
2954 assert( pDest->pTable!=pSrc->pTable );
drh1e7c00e2019-11-07 14:51:242955 if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
drh9d9cf222007-02-13 15:01:112956 return 0; /* Different number of columns */
2957 }
2958 if( pDest->onError!=pSrc->onError ){
2959 return 0; /* Different conflict resolution strategies */
2960 }
drhbbbdc832013-10-22 18:01:402961 for(i=0; i<pSrc->nKeyCol; i++){
drh9d9cf222007-02-13 15:01:112962 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
2963 return 0; /* Different columns indexed */
2964 }
drh4b92f982015-09-29 17:20:142965 if( pSrc->aiColumn[i]==XN_EXPR ){
drh1f9ca2c2015-08-25 16:57:522966 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
dan5aa550c2017-06-24 18:10:292967 if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
drh1f9ca2c2015-08-25 16:57:522968 pDest->aColExpr->a[i].pExpr, -1)!=0 ){
2969 return 0; /* Different expressions in the index */
2970 }
2971 }
drh9d9cf222007-02-13 15:01:112972 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
2973 return 0; /* Different sort orders */
2974 }
drh0472af92015-12-30 15:18:162975 if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
drh60a713c2008-01-21 16:22:452976 return 0; /* Different collating sequences */
drh9d9cf222007-02-13 15:01:112977 }
2978 }
dan5aa550c2017-06-24 18:10:292979 if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
drhb2b9d3d2013-08-01 01:14:432980 return 0; /* Different WHERE clauses */
2981 }
drh9d9cf222007-02-13 15:01:112982
2983 /* If no test above fails then the indices must be compatible */
2984 return 1;
2985}
2986
2987/*
2988** Attempt the transfer optimization on INSERTs of the form
2989**
2990** INSERT INTO tab1 SELECT * FROM tab2;
2991**
larrybrbc917382023-06-07 08:40:312992** The xfer optimization transfers raw records from tab2 over to tab1.
peter.d.reid60ec9142014-09-06 16:39:462993** Columns are not decoded and reassembled, which greatly improves
drhccdf1ba2011-11-04 14:36:022994** performance. Raw index records are transferred in the same way.
drh9d9cf222007-02-13 15:01:112995**
drhccdf1ba2011-11-04 14:36:022996** The xfer optimization is only attempted if tab1 and tab2 are compatible.
2997** There are lots of rules for determining compatibility - see comments
2998** embedded in the code for details.
drh9d9cf222007-02-13 15:01:112999**
drhccdf1ba2011-11-04 14:36:023000** This routine returns TRUE if the optimization is guaranteed to be used.
3001** Sometimes the xfer optimization will only work if the destination table
3002** is empty - a factor that can only be determined at run-time. In that
3003** case, this routine generates code for the xfer optimization but also
3004** does a test to see if the destination table is empty and jumps over the
3005** xfer optimization code if the test fails. In that case, this routine
3006** returns FALSE so that the caller will know to go ahead and generate
3007** an unoptimized transfer. This routine also returns FALSE if there
3008** is no chance that the xfer optimization can be applied.
drh9d9cf222007-02-13 15:01:113009**
drhccdf1ba2011-11-04 14:36:023010** This optimization is particularly useful at making VACUUM run faster.
drh9d9cf222007-02-13 15:01:113011*/
3012static int xferOptimization(
3013 Parse *pParse, /* Parser context */
3014 Table *pDest, /* The table we are inserting into */
3015 Select *pSelect, /* A SELECT statement to use as the data source */
3016 int onError, /* How to handle constraint errors */
3017 int iDbDest /* The database of pDest */
3018){
dane34162b2015-04-01 18:20:253019 sqlite3 *db = pParse->db;
drh9d9cf222007-02-13 15:01:113020 ExprList *pEList; /* The result set of the SELECT */
3021 Table *pSrc; /* The table in the FROM clause of SELECT */
3022 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
drh76012942021-02-21 21:04:543023 SrcItem *pItem; /* An element of pSelect->pSrc */
drh9d9cf222007-02-13 15:01:113024 int i; /* Loop counter */
3025 int iDbSrc; /* The database of pSrc */
3026 int iSrc, iDest; /* Cursors from source and destination */
3027 int addr1, addr2; /* Loop addresses */
drhda475b82013-11-04 21:44:543028 int emptyDestTest = 0; /* Address of test for empty pDest */
3029 int emptySrcTest = 0; /* Address of test for empty pSrc */
drh9d9cf222007-02-13 15:01:113030 Vdbe *v; /* The VDBE we are building */
drh6a288a32008-01-07 19:20:243031 int regAutoinc; /* Memory register used by AUTOINC */
drhf33c9fa2007-04-10 18:17:553032 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
drhb7654112008-01-12 12:48:073033 int regData, regRowid; /* Registers holding data and rowid */
drh9d9cf222007-02-13 15:01:113034
drh935c3722022-02-28 16:44:583035 assert( pSelect!=0 );
danebbf08a2014-01-18 08:27:023036 if( pParse->pWith || pSelect->pWith ){
3037 /* Do not attempt to process this query if there are an WITH clauses
3038 ** attached to it. Proceeding may generate a false "no such table: xxx"
3039 ** error if pSelect reads from a CTE named "xxx". */
3040 return 0;
3041 }
drh9d9cf222007-02-13 15:01:113042#ifndef SQLITE_OMIT_VIRTUALTABLE
drh44266ec2017-02-16 14:48:083043 if( IsVirtual(pDest) ){
drh9d9cf222007-02-13 15:01:113044 return 0; /* tab1 must not be a virtual table */
3045 }
3046#endif
3047 if( onError==OE_Default ){
drhe7224a02011-11-04 00:23:533048 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
3049 if( onError==OE_Default ) onError = OE_Abort;
drh9d9cf222007-02-13 15:01:113050 }
danielk19775ce240a2007-09-03 17:30:063051 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
drh9d9cf222007-02-13 15:01:113052 if( pSelect->pSrc->nSrc!=1 ){
3053 return 0; /* FROM clause must have exactly one term */
3054 }
drh1521ca42024-08-19 22:48:303055 if( pSelect->pSrc->a[0].fg.isSubquery ){
drh9d9cf222007-02-13 15:01:113056 return 0; /* FROM clause cannot contain a subquery */
3057 }
3058 if( pSelect->pWhere ){
3059 return 0; /* SELECT may not have a WHERE clause */
3060 }
3061 if( pSelect->pOrderBy ){
3062 return 0; /* SELECT may not have an ORDER BY clause */
3063 }
drh8103b7d2007-02-24 13:23:513064 /* Do not need to test for a HAVING clause. If HAVING is present but
3065 ** there is no ORDER BY, we will get an error. */
drh9d9cf222007-02-13 15:01:113066 if( pSelect->pGroupBy ){
3067 return 0; /* SELECT may not have a GROUP BY clause */
3068 }
3069 if( pSelect->pLimit ){
3070 return 0; /* SELECT may not have a LIMIT clause */
3071 }
drh9d9cf222007-02-13 15:01:113072 if( pSelect->pPrior ){
3073 return 0; /* SELECT may not be a compound query */
3074 }
drh7d10d5a2008-08-20 16:35:103075 if( pSelect->selFlags & SF_Distinct ){
drh9d9cf222007-02-13 15:01:113076 return 0; /* SELECT may not be DISTINCT */
3077 }
3078 pEList = pSelect->pEList;
3079 assert( pEList!=0 );
3080 if( pEList->nExpr!=1 ){
3081 return 0; /* The result set must have exactly one column */
3082 }
3083 assert( pEList->a[0].pExpr );
drh1a1d3cd2015-11-19 16:33:313084 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
drh9d9cf222007-02-13 15:01:113085 return 0; /* The result set must be the special operator "*" */
3086 }
3087
3088 /* At this point we have established that the statement is of the
3089 ** correct syntactic form to participate in this optimization. Now
3090 ** we have to check the semantics.
3091 */
3092 pItem = pSelect->pSrc->a;
dan41fb5cd2012-10-04 19:33:003093 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
drh9d9cf222007-02-13 15:01:113094 if( pSrc==0 ){
3095 return 0; /* FROM clause does not contain a real table */
3096 }
drh21908b22019-01-17 20:19:353097 if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
drh1e32bed2020-06-19 13:33:533098 testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
drh9d9cf222007-02-13 15:01:113099 return 0; /* tab1 and tab2 may not be the same table */
3100 }
drh55548272013-10-23 16:03:073101 if( HasRowid(pDest)!=HasRowid(pSrc) ){
3102 return 0; /* source and destination must both be WITHOUT ROWID or not */
3103 }
drhf38524d2021-08-02 16:41:573104 if( !IsOrdinaryTable(pSrc) ){
3105 return 0; /* tab2 may not be a view or virtual table */
drh9d9cf222007-02-13 15:01:113106 }
3107 if( pDest->nCol!=pSrc->nCol ){
3108 return 0; /* Number of columns must be the same in tab1 and tab2 */
3109 }
3110 if( pDest->iPKey!=pSrc->iPKey ){
3111 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
3112 }
drh7b4b74a2021-08-20 01:12:393113 if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
3114 return 0; /* Cannot feed from a non-strict into a strict table */
3115 }
drh9d9cf222007-02-13 15:01:113116 for(i=0; i<pDest->nCol; i++){
dan9940e2a2014-04-26 14:07:573117 Column *pDestCol = &pDest->aCol[i];
3118 Column *pSrcCol = &pSrc->aCol[i];
danba68f8f2015-11-19 16:46:463119#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
larrybrbc917382023-06-07 08:40:313120 if( (db->mDbFlags & DBFLAG_Vacuum)==0
3121 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
danaaea3142015-11-19 18:09:053122 ){
danba68f8f2015-11-19 16:46:463123 return 0; /* Neither table may have __hidden__ columns */
3124 }
3125#endif
drh6ab61d72019-10-23 15:47:333126#ifndef SQLITE_OMIT_GENERATED_COLUMNS
3127 /* Even if tables t1 and t2 have identical schemas, if they contain
3128 ** generated columns, then this statement is semantically incorrect:
3129 **
3130 ** INSERT INTO t2 SELECT * FROM t1;
3131 **
3132 ** The reason is that generated column values are returned by the
3133 ** the SELECT statement on the right but the INSERT statement on the
3134 ** left wants them to be omitted.
3135 **
3136 ** Nevertheless, this is a useful notational shorthand to tell SQLite
3137 ** to do a bulk transfer all of the content from t1 over to t2.
larrybrbc917382023-06-07 08:40:313138 **
drh6ab61d72019-10-23 15:47:333139 ** We could, in theory, disable this (except for internal use by the
3140 ** VACUUM command where it is actually needed). But why do that? It
3141 ** seems harmless enough, and provides a useful service.
3142 */
drhae3977a2019-10-17 16:16:343143 if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
3144 (pSrcCol->colFlags & COLFLAG_GENERATED) ){
drh6ab61d72019-10-23 15:47:333145 return 0; /* Both columns have the same generated-column type */
drhae3977a2019-10-17 16:16:343146 }
drh6ab61d72019-10-23 15:47:333147 /* But the transfer is only allowed if both the source and destination
3148 ** tables have the exact same expressions for generated columns.
3149 ** This requirement could be relaxed for VIRTUAL columns, I suppose.
3150 */
3151 if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
drh79cf2b72021-07-31 20:30:413152 if( sqlite3ExprCompare(0,
3153 sqlite3ColumnExpr(pSrc, pSrcCol),
3154 sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
drh6ab61d72019-10-23 15:47:333155 testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
3156 testcase( pDestCol->colFlags & COLFLAG_STORED );
3157 return 0; /* Different generator expressions */
3158 }
3159 }
3160#endif
dan9940e2a2014-04-26 14:07:573161 if( pDestCol->affinity!=pSrcCol->affinity ){
drh9d9cf222007-02-13 15:01:113162 return 0; /* Affinity must be the same on all columns */
3163 }
larrybrbc917382023-06-07 08:40:313164 if( sqlite3_stricmp(sqlite3ColumnColl(pDestCol),
drh65b40092021-08-05 15:27:193165 sqlite3ColumnColl(pSrcCol))!=0 ){
drh9d9cf222007-02-13 15:01:113166 return 0; /* Collating sequence must be the same on all columns */
3167 }
dan9940e2a2014-04-26 14:07:573168 if( pDestCol->notNull && !pSrcCol->notNull ){
drh9d9cf222007-02-13 15:01:113169 return 0; /* tab2 must be NOT NULL if tab1 is */
3170 }
drh453e0262014-04-26 17:52:083171 /* Default values for second and subsequent columns need to match. */
drhae3977a2019-10-17 16:16:343172 if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
drh79cf2b72021-07-31 20:30:413173 Expr *pDestExpr = sqlite3ColumnExpr(pDest, pDestCol);
3174 Expr *pSrcExpr = sqlite3ColumnExpr(pSrc, pSrcCol);
3175 assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
drhf9751072021-10-07 13:40:293176 assert( pDestExpr==0 || !ExprHasProperty(pDestExpr, EP_IntValue) );
drh79cf2b72021-07-31 20:30:413177 assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
drhf9751072021-10-07 13:40:293178 assert( pSrcExpr==0 || !ExprHasProperty(pSrcExpr, EP_IntValue) );
larrybrbc917382023-06-07 08:40:313179 if( (pDestExpr==0)!=(pSrcExpr==0)
drh79cf2b72021-07-31 20:30:413180 || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
3181 pSrcExpr->u.zToken)!=0)
drh94fa9c42016-02-27 21:16:043182 ){
3183 return 0; /* Default values must be the same for all columns */
3184 }
dan9940e2a2014-04-26 14:07:573185 }
drh9d9cf222007-02-13 15:01:113186 }
3187 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drh5f1d1d92014-07-31 22:59:043188 if( IsUniqueIndex(pDestIdx) ){
drhf33c9fa2007-04-10 18:17:553189 destHasUniqueIdx = 1;
3190 }
drh9d9cf222007-02-13 15:01:113191 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
3192 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
3193 }
3194 if( pSrcIdx==0 ){
3195 return 0; /* pDestIdx has no corresponding index in pSrc */
3196 }
drhe3bd2322019-04-05 16:38:123197 if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
3198 && sqlite3FaultSim(411)==SQLITE_OK ){
3199 /* The sqlite3FaultSim() call allows this corruption test to be
3200 ** bypassed during testing, in order to exercise other corruption tests
3201 ** further downstream. */
drh86223e82019-04-05 15:44:553202 return 0; /* Corrupt schema - two indexes on the same btree */
3203 }
drh9d9cf222007-02-13 15:01:113204 }
drh7fc2f412007-03-29 00:08:243205#ifndef SQLITE_OMIT_CHECK
drhd21d5b22024-04-09 13:57:273206 if( pDest->pCheck
3207 && (db->mDbFlags & DBFLAG_Vacuum)==0
3208 && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1)
3209 ){
drh8103b7d2007-02-24 13:23:513210 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
3211 }
drh7fc2f412007-03-29 00:08:243212#endif
drh713de342011-04-24 22:56:073213#ifndef SQLITE_OMIT_FOREIGN_KEY
larrybrbc917382023-06-07 08:40:313214 /* Disallow the transfer optimization if the destination table contains
drh713de342011-04-24 22:56:073215 ** any foreign key constraints. This is more restrictive than necessary.
larrybrbc917382023-06-07 08:40:313216 ** But the main beneficiary of the transfer optimization is the VACUUM
drh713de342011-04-24 22:56:073217 ** command, and the VACUUM command disables foreign key constraints. So
3218 ** the extra complication to make this rule less restrictive is probably
3219 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
3220 */
drh78b2fa82021-10-07 12:11:203221 assert( IsOrdinaryTable(pDest) );
drhf38524d2021-08-02 16:41:573222 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
drh713de342011-04-24 22:56:073223 return 0;
3224 }
3225#endif
dane34162b2015-04-01 18:20:253226 if( (db->flags & SQLITE_CountRows)!=0 ){
drhccdf1ba2011-11-04 14:36:023227 return 0; /* xfer opt does not play well with PRAGMA count_changes */
dan16961242011-09-30 12:01:013228 }
drh9d9cf222007-02-13 15:01:113229
drhccdf1ba2011-11-04 14:36:023230 /* If we get this far, it means that the xfer optimization is at
3231 ** least a possibility, though it might only work if the destination
3232 ** table (tab1) is initially empty.
drh9d9cf222007-02-13 15:01:113233 */
drhdd735212007-02-24 13:53:053234#ifdef SQLITE_TEST
3235 sqlite3_xferopt_count++;
3236#endif
dane34162b2015-04-01 18:20:253237 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
drh9d9cf222007-02-13 15:01:113238 v = sqlite3GetVdbe(pParse);
drhf53e9b52007-08-29 13:45:583239 sqlite3CodeVerifySchema(pParse, iDbSrc);
drh9d9cf222007-02-13 15:01:113240 iSrc = pParse->nTab++;
3241 iDest = pParse->nTab++;
drh6a288a32008-01-07 19:20:243242 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
drhb7654112008-01-12 12:48:073243 regData = sqlite3GetTempReg(pParse);
dan7aae7352020-12-10 18:06:243244 sqlite3VdbeAddOp2(v, OP_Null, 0, regData);
drhb7654112008-01-12 12:48:073245 regRowid = sqlite3GetTempReg(pParse);
drh9d9cf222007-02-13 15:01:113246 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
dan427ebba2013-11-05 16:39:313247 assert( HasRowid(pDest) || destHasUniqueIdx );
drh8257aa82017-07-26 19:59:133248 if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
dane34162b2015-04-01 18:20:253249 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
drh9d9cf222007-02-13 15:01:113250 || destHasUniqueIdx /* (2) */
3251 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
dane34162b2015-04-01 18:20:253252 )){
drh9d9cf222007-02-13 15:01:113253 /* In some circumstances, we are able to run the xfer optimization
dane34162b2015-04-01 18:20:253254 ** only if the destination table is initially empty. Unless the
drh8257aa82017-07-26 19:59:133255 ** DBFLAG_Vacuum flag is set, this block generates code to make
3256 ** that determination. If DBFLAG_Vacuum is set, then the destination
dane34162b2015-04-01 18:20:253257 ** table is always empty.
3258 **
3259 ** Conditions under which the destination must be empty:
drhbd36ba62007-03-31 13:00:263260 **
drh9d9cf222007-02-13 15:01:113261 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
3262 ** (If the destination is not initially empty, the rowid fields
3263 ** of index entries might need to change.)
3264 **
larrybrbc917382023-06-07 08:40:313265 ** (2) The destination has a unique index. (The xfer optimization
drh9d9cf222007-02-13 15:01:113266 ** is unable to test uniqueness.)
drhbd36ba62007-03-31 13:00:263267 **
3268 ** (3) onError is something other than OE_Abort and OE_Rollback.
drhf33c9fa2007-04-10 18:17:553269 */
drh688852a2014-02-17 22:40:433270 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
drh2991ba02015-09-02 18:19:003271 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
drh66a51672008-01-03 00:01:233272 sqlite3VdbeJumpHere(v, addr1);
drh9d9cf222007-02-13 15:01:113273 }
drh55548272013-10-23 16:03:073274 if( HasRowid(pSrc) ){
drhc9b9dea2016-11-15 02:46:393275 u8 insFlags;
drh55548272013-10-23 16:03:073276 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
drh688852a2014-02-17 22:40:433277 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
drh55548272013-10-23 16:03:073278 if( pDest->iPKey>=0 ){
3279 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
dan036e0672020-12-08 20:19:073280 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3281 sqlite3VdbeVerifyAbortable(v, onError);
3282 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
3283 VdbeCoverage(v);
3284 sqlite3RowidConstraint(pParse, onError, pDest);
3285 sqlite3VdbeJumpHere(v, addr2);
3286 }
drh55548272013-10-23 16:03:073287 autoIncStep(pParse, regAutoinc, regRowid);
drh4e61e882019-04-04 14:00:233288 }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
drh55548272013-10-23 16:03:073289 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
3290 }else{
3291 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
3292 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
3293 }
dan7aae7352020-12-10 18:06:243294
drh8257aa82017-07-26 19:59:133295 if( db->mDbFlags & DBFLAG_Vacuum ){
drh86b40df2017-08-01 19:53:433296 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
dan7aae7352020-12-10 18:06:243297 insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
drhc9b9dea2016-11-15 02:46:393298 }else{
dan7aae7352020-12-10 18:06:243299 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT;
drhc9b9dea2016-11-15 02:46:393300 }
dan7aae7352020-12-10 18:06:243301#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
dana55a8392021-02-18 15:59:373302 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3303 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
3304 insFlags &= ~OPFLAG_PREFORMAT;
3305 }else
dan7aae7352020-12-10 18:06:243306#endif
dana55a8392021-02-18 15:59:373307 {
3308 sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid);
3309 }
3310 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
3311 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
3312 sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
3313 }
dan7aae7352020-12-10 18:06:243314 sqlite3VdbeChangeP5(v, insFlags);
3315
drh688852a2014-02-17 22:40:433316 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
drh55548272013-10-23 16:03:073317 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
3318 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh95bad4c2007-03-28 18:04:103319 }else{
drhda475b82013-11-04 21:44:543320 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
3321 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
drh95bad4c2007-03-28 18:04:103322 }
drh9d9cf222007-02-13 15:01:113323 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
drh41b9ca22015-07-28 18:53:373324 u8 idxInsFlags = 0;
drh1b7ecbb2009-05-03 01:00:593325 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
drh9d9cf222007-02-13 15:01:113326 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
3327 }
3328 assert( pSrcIdx );
drh2ec2fb22013-11-06 19:59:233329 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
3330 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
drhd4e70eb2008-01-02 00:34:363331 VdbeComment((v, "%s", pSrcIdx->zName));
drh2ec2fb22013-11-06 19:59:233332 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
3333 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
dan59885722013-10-04 18:17:183334 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
danielk1977207872a2008-01-03 07:54:233335 VdbeComment((v, "%s", pDestIdx->zName));
drh688852a2014-02-17 22:40:433336 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
drh8257aa82017-07-26 19:59:133337 if( db->mDbFlags & DBFLAG_Vacuum ){
dane34162b2015-04-01 18:20:253338 /* This INSERT command is part of a VACUUM operation, which guarantees
3339 ** that the destination table is empty. If all indexed columns use
3340 ** collation sequence BINARY, then it can also be assumed that the
larrybrbc917382023-06-07 08:40:313341 ** index will be populated by inserting keys in strictly sorted
dane34162b2015-04-01 18:20:253342 ** order. In this case, instead of seeking within the b-tree as part
drh86b40df2017-08-01 19:53:433343 ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
larrybrbc917382023-06-07 08:40:313344 ** OP_IdxInsert to seek to the point within the b-tree where each key
dane34162b2015-04-01 18:20:253345 ** should be inserted. This is faster.
3346 **
3347 ** If any of the indexed columns use a collation sequence other than
larrybrbc917382023-06-07 08:40:313348 ** BINARY, this optimization is disabled. This is because the user
dane34162b2015-04-01 18:20:253349 ** might change the definition of a collation sequence and then run
3350 ** a VACUUM command. In that case keys may not be written in strictly
3351 ** sorted order. */
dana55a8392021-02-18 15:59:373352 for(i=0; i<pSrcIdx->nColumn; i++){
3353 const char *zColl = pSrcIdx->azColl[i];
3354 if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
3355 }
3356 if( i==pSrcIdx->nColumn ){
3357 idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
3358 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
3359 sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc);
dane34162b2015-04-01 18:20:253360 }
drhc84ad312020-02-06 20:46:083361 }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
drh41b9ca22015-07-28 18:53:373362 idxInsFlags |= OPFLAG_NCHANGE;
3363 }
dan7aae7352020-12-10 18:06:243364 if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){
dancd1b2d02020-12-09 20:33:513365 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
larrybrbc917382023-06-07 08:40:313366 if( (db->mDbFlags & DBFLAG_Vacuum)==0
3367 && !HasRowid(pDest)
3368 && IsPrimaryKeyIndex(pDestIdx)
dana55a8392021-02-18 15:59:373369 ){
danfadc0e32021-02-18 12:18:103370 codeWithoutRowidPreupdate(pParse, pDest, iDest, regData);
3371 }
dancd1b2d02020-12-09 20:33:513372 }
dan7aae7352020-12-10 18:06:243373 sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
3374 sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
drh688852a2014-02-17 22:40:433375 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
drh9d9cf222007-02-13 15:01:113376 sqlite3VdbeJumpHere(v, addr1);
drh55548272013-10-23 16:03:073377 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
3378 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:113379 }
drhaceb31b2014-02-08 01:40:273380 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
drhb7654112008-01-12 12:48:073381 sqlite3ReleaseTempReg(pParse, regRowid);
3382 sqlite3ReleaseTempReg(pParse, regData);
drh9d9cf222007-02-13 15:01:113383 if( emptyDestTest ){
drh1dd518c2016-10-03 02:59:333384 sqlite3AutoincrementEnd(pParse);
drh66a51672008-01-03 00:01:233385 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
drh9d9cf222007-02-13 15:01:113386 sqlite3VdbeJumpHere(v, emptyDestTest);
drh66a51672008-01-03 00:01:233387 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
drh9d9cf222007-02-13 15:01:113388 return 0;
3389 }else{
3390 return 1;
3391 }
3392}
3393#endif /* SQLITE_OMIT_XFER_OPT */