add pragma cipher_default_use_hmac to toggle global HMAC setting
[sqlcipher.git] / src / insert.c
blob277a852cc7ed551c7cd501b676f9d497fb0f3f64
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains C code routines that are called by the parser
13 ** to handle INSERT statements in SQLite.
15 #include "sqliteInt.h"
18 ** Generate code that will open a table for reading.
20 void sqlite3OpenTable(
21 Parse *p, /* Generate code into this VDBE */
22 int iCur, /* The cursor number of the table */
23 int iDb, /* The database index in sqlite3.aDb[] */
24 Table *pTab, /* The table to be opened */
25 int opcode /* OP_OpenRead or OP_OpenWrite */
27 Vdbe *v;
28 if( IsVirtual(pTab) ) return;
29 v = sqlite3GetVdbe(p);
30 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
31 sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
32 sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
33 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
34 VdbeComment((v, "%s", pTab->zName));
38 ** Return a pointer to the column affinity string associated with index
39 ** pIdx. A column affinity string has one character for each column in
40 ** the table, according to the affinity of the column:
42 ** Character Column affinity
43 ** ------------------------------
44 ** 'a' TEXT
45 ** 'b' NONE
46 ** 'c' NUMERIC
47 ** 'd' INTEGER
48 ** 'e' REAL
50 ** An extra 'b' is appended to the end of the string to cover the
51 ** rowid that appears as the last column in every index.
53 ** Memory for the buffer containing the column index affinity string
54 ** is managed along with the rest of the Index structure. It will be
55 ** released when sqlite3DeleteIndex() is called.
57 const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
58 if( !pIdx->zColAff ){
59 /* The first time a column affinity string for a particular index is
60 ** required, it is allocated and populated here. It is then stored as
61 ** a member of the Index structure for subsequent use.
63 ** The column affinity string will eventually be deleted by
64 ** sqliteDeleteIndex() when the Index structure itself is cleaned
65 ** up.
67 int n;
68 Table *pTab = pIdx->pTable;
69 sqlite3 *db = sqlite3VdbeDb(v);
70 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
71 if( !pIdx->zColAff ){
72 db->mallocFailed = 1;
73 return 0;
75 for(n=0; n<pIdx->nColumn; n++){
76 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
78 pIdx->zColAff[n++] = SQLITE_AFF_NONE;
79 pIdx->zColAff[n] = 0;
82 return pIdx->zColAff;
86 ** Set P4 of the most recently inserted opcode to a column affinity
87 ** string for table pTab. A column affinity string has one character
88 ** for each column indexed by the index, according to the affinity of the
89 ** column:
91 ** Character Column affinity
92 ** ------------------------------
93 ** 'a' TEXT
94 ** 'b' NONE
95 ** 'c' NUMERIC
96 ** 'd' INTEGER
97 ** 'e' REAL
99 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
100 /* The first time a column affinity string for a particular table
101 ** is required, it is allocated and populated here. It is then
102 ** stored as a member of the Table structure for subsequent use.
104 ** The column affinity string will eventually be deleted by
105 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
107 if( !pTab->zColAff ){
108 char *zColAff;
109 int i;
110 sqlite3 *db = sqlite3VdbeDb(v);
112 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
113 if( !zColAff ){
114 db->mallocFailed = 1;
115 return;
118 for(i=0; i<pTab->nCol; i++){
119 zColAff[i] = pTab->aCol[i].affinity;
121 zColAff[pTab->nCol] = '\0';
123 pTab->zColAff = zColAff;
126 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
130 ** Return non-zero if the table pTab in database iDb or any of its indices
131 ** have been opened at any point in the VDBE program beginning at location
132 ** iStartAddr throught the end of the program. This is used to see if
133 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
134 ** run without using temporary table for the results of the SELECT.
136 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
137 Vdbe *v = sqlite3GetVdbe(p);
138 int i;
139 int iEnd = sqlite3VdbeCurrentAddr(v);
140 #ifndef SQLITE_OMIT_VIRTUALTABLE
141 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
142 #endif
144 for(i=iStartAddr; i<iEnd; i++){
145 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
146 assert( pOp!=0 );
147 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
148 Index *pIndex;
149 int tnum = pOp->p2;
150 if( tnum==pTab->tnum ){
151 return 1;
153 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
154 if( tnum==pIndex->tnum ){
155 return 1;
159 #ifndef SQLITE_OMIT_VIRTUALTABLE
160 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
161 assert( pOp->p4.pVtab!=0 );
162 assert( pOp->p4type==P4_VTAB );
163 return 1;
165 #endif
167 return 0;
170 #ifndef SQLITE_OMIT_AUTOINCREMENT
172 ** Locate or create an AutoincInfo structure associated with table pTab
173 ** which is in database iDb. Return the register number for the register
174 ** that holds the maximum rowid.
176 ** There is at most one AutoincInfo structure per table even if the
177 ** same table is autoincremented multiple times due to inserts within
178 ** triggers. A new AutoincInfo structure is created if this is the
179 ** first use of table pTab. On 2nd and subsequent uses, the original
180 ** AutoincInfo structure is used.
182 ** Three memory locations are allocated:
184 ** (1) Register to hold the name of the pTab table.
185 ** (2) Register to hold the maximum ROWID of pTab.
186 ** (3) Register to hold the rowid in sqlite_sequence of pTab
188 ** The 2nd register is the one that is returned. That is all the
189 ** insert routine needs to know about.
191 static int autoIncBegin(
192 Parse *pParse, /* Parsing context */
193 int iDb, /* Index of the database holding pTab */
194 Table *pTab /* The table we are writing to */
196 int memId = 0; /* Register holding maximum rowid */
197 if( pTab->tabFlags & TF_Autoincrement ){
198 Parse *pToplevel = sqlite3ParseToplevel(pParse);
199 AutoincInfo *pInfo;
201 pInfo = pToplevel->pAinc;
202 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
203 if( pInfo==0 ){
204 pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
205 if( pInfo==0 ) return 0;
206 pInfo->pNext = pToplevel->pAinc;
207 pToplevel->pAinc = pInfo;
208 pInfo->pTab = pTab;
209 pInfo->iDb = iDb;
210 pToplevel->nMem++; /* Register to hold name of table */
211 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
212 pToplevel->nMem++; /* Rowid in sqlite_sequence */
214 memId = pInfo->regCtr;
216 return memId;
220 ** This routine generates code that will initialize all of the
221 ** register used by the autoincrement tracker.
223 void sqlite3AutoincrementBegin(Parse *pParse){
224 AutoincInfo *p; /* Information about an AUTOINCREMENT */
225 sqlite3 *db = pParse->db; /* The database connection */
226 Db *pDb; /* Database only autoinc table */
227 int memId; /* Register holding max rowid */
228 int addr; /* A VDBE address */
229 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
231 /* This routine is never called during trigger-generation. It is
232 ** only called from the top-level */
233 assert( pParse->pTriggerTab==0 );
234 assert( pParse==sqlite3ParseToplevel(pParse) );
236 assert( v ); /* We failed long ago if this is not so */
237 for(p = pParse->pAinc; p; p = p->pNext){
238 pDb = &db->aDb[p->iDb];
239 memId = p->regCtr;
240 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
241 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
242 addr = sqlite3VdbeCurrentAddr(v);
243 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
244 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
245 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
246 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
247 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
248 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
249 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
250 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
251 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
252 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
253 sqlite3VdbeAddOp0(v, OP_Close);
258 ** Update the maximum rowid for an autoincrement calculation.
260 ** This routine should be called when the top of the stack holds a
261 ** new rowid that is about to be inserted. If that new rowid is
262 ** larger than the maximum rowid in the memId memory cell, then the
263 ** memory cell is updated. The stack is unchanged.
265 static void autoIncStep(Parse *pParse, int memId, int regRowid){
266 if( memId>0 ){
267 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
272 ** This routine generates the code needed to write autoincrement
273 ** maximum rowid values back into the sqlite_sequence register.
274 ** Every statement that might do an INSERT into an autoincrement
275 ** table (either directly or through triggers) needs to call this
276 ** routine just before the "exit" code.
278 void sqlite3AutoincrementEnd(Parse *pParse){
279 AutoincInfo *p;
280 Vdbe *v = pParse->pVdbe;
281 sqlite3 *db = pParse->db;
283 assert( v );
284 for(p = pParse->pAinc; p; p = p->pNext){
285 Db *pDb = &db->aDb[p->iDb];
286 int j1, j2, j3, j4, j5;
287 int iRec;
288 int memId = p->regCtr;
290 iRec = sqlite3GetTempReg(pParse);
291 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
292 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
293 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
294 j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
295 j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
296 j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
297 sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
298 sqlite3VdbeJumpHere(v, j2);
299 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
300 j5 = sqlite3VdbeAddOp0(v, OP_Goto);
301 sqlite3VdbeJumpHere(v, j4);
302 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
303 sqlite3VdbeJumpHere(v, j1);
304 sqlite3VdbeJumpHere(v, j5);
305 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
306 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
307 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
308 sqlite3VdbeAddOp0(v, OP_Close);
309 sqlite3ReleaseTempReg(pParse, iRec);
312 #else
314 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
315 ** above are all no-ops
317 # define autoIncBegin(A,B,C) (0)
318 # define autoIncStep(A,B,C)
319 #endif /* SQLITE_OMIT_AUTOINCREMENT */
322 /* Forward declaration */
323 static int xferOptimization(
324 Parse *pParse, /* Parser context */
325 Table *pDest, /* The table we are inserting into */
326 Select *pSelect, /* A SELECT statement to use as the data source */
327 int onError, /* How to handle constraint errors */
328 int iDbDest /* The database of pDest */
332 ** This routine is call to handle SQL of the following forms:
334 ** insert into TABLE (IDLIST) values(EXPRLIST)
335 ** insert into TABLE (IDLIST) select
337 ** The IDLIST following the table name is always optional. If omitted,
338 ** then a list of all columns for the table is substituted. The IDLIST
339 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
341 ** The pList parameter holds EXPRLIST in the first form of the INSERT
342 ** statement above, and pSelect is NULL. For the second form, pList is
343 ** NULL and pSelect is a pointer to the select statement used to generate
344 ** data for the insert.
346 ** The code generated follows one of four templates. For a simple
347 ** select with data coming from a VALUES clause, the code executes
348 ** once straight down through. Pseudo-code follows (we call this
349 ** the "1st template"):
351 ** open write cursor to <table> and its indices
352 ** puts VALUES clause expressions onto the stack
353 ** write the resulting record into <table>
354 ** cleanup
356 ** The three remaining templates assume the statement is of the form
358 ** INSERT INTO <table> SELECT ...
360 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
361 ** in other words if the SELECT pulls all columns from a single table
362 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
363 ** if <table2> and <table1> are distinct tables but have identical
364 ** schemas, including all the same indices, then a special optimization
365 ** is invoked that copies raw records from <table2> over to <table1>.
366 ** See the xferOptimization() function for the implementation of this
367 ** template. This is the 2nd template.
369 ** open a write cursor to <table>
370 ** open read cursor on <table2>
371 ** transfer all records in <table2> over to <table>
372 ** close cursors
373 ** foreach index on <table>
374 ** open a write cursor on the <table> index
375 ** open a read cursor on the corresponding <table2> index
376 ** transfer all records from the read to the write cursors
377 ** close cursors
378 ** end foreach
380 ** The 3rd template is for when the second template does not apply
381 ** and the SELECT clause does not read from <table> at any time.
382 ** The generated code follows this template:
384 ** EOF <- 0
385 ** X <- A
386 ** goto B
387 ** A: setup for the SELECT
388 ** loop over the rows in the SELECT
389 ** load values into registers R..R+n
390 ** yield X
391 ** end loop
392 ** cleanup after the SELECT
393 ** EOF <- 1
394 ** yield X
395 ** goto A
396 ** B: open write cursor to <table> and its indices
397 ** C: yield X
398 ** if EOF goto D
399 ** insert the select result into <table> from R..R+n
400 ** goto C
401 ** D: cleanup
403 ** The 4th template is used if the insert statement takes its
404 ** values from a SELECT but the data is being inserted into a table
405 ** that is also read as part of the SELECT. In the third form,
406 ** we have to use a intermediate table to store the results of
407 ** the select. The template is like this:
409 ** EOF <- 0
410 ** X <- A
411 ** goto B
412 ** A: setup for the SELECT
413 ** loop over the tables in the SELECT
414 ** load value into register R..R+n
415 ** yield X
416 ** end loop
417 ** cleanup after the SELECT
418 ** EOF <- 1
419 ** yield X
420 ** halt-error
421 ** B: open temp table
422 ** L: yield X
423 ** if EOF goto M
424 ** insert row from R..R+n into temp table
425 ** goto L
426 ** M: open write cursor to <table> and its indices
427 ** rewind temp table
428 ** C: loop over rows of intermediate table
429 ** transfer values form intermediate table into <table>
430 ** end loop
431 ** D: cleanup
433 void sqlite3Insert(
434 Parse *pParse, /* Parser context */
435 SrcList *pTabList, /* Name of table into which we are inserting */
436 ExprList *pList, /* List of values to be inserted */
437 Select *pSelect, /* A SELECT statement to use as the data source */
438 IdList *pColumn, /* Column names corresponding to IDLIST. */
439 int onError /* How to handle constraint errors */
441 sqlite3 *db; /* The main database structure */
442 Table *pTab; /* The table to insert into. aka TABLE */
443 char *zTab; /* Name of the table into which we are inserting */
444 const char *zDb; /* Name of the database holding this table */
445 int i, j, idx; /* Loop counters */
446 Vdbe *v; /* Generate code into this virtual machine */
447 Index *pIdx; /* For looping over indices of the table */
448 int nColumn; /* Number of columns in the data */
449 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
450 int baseCur = 0; /* VDBE Cursor number for pTab */
451 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
452 int endOfLoop; /* Label for the end of the insertion loop */
453 int useTempTable = 0; /* Store SELECT results in intermediate table */
454 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
455 int addrInsTop = 0; /* Jump to label "D" */
456 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
457 int addrSelect = 0; /* Address of coroutine that implements the SELECT */
458 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
459 int iDb; /* Index of database holding TABLE */
460 Db *pDb; /* The database containing table being inserted into */
461 int appendFlag = 0; /* True if the insert is likely to be an append */
463 /* Register allocations */
464 int regFromSelect = 0;/* Base register for data coming from SELECT */
465 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
466 int regRowCount = 0; /* Memory cell used for the row counter */
467 int regIns; /* Block of regs holding rowid+data being inserted */
468 int regRowid; /* registers holding insert rowid */
469 int regData; /* register holding first column to insert */
470 int regEof = 0; /* Register recording end of SELECT data */
471 int *aRegIdx = 0; /* One register allocated to each index */
473 #ifndef SQLITE_OMIT_TRIGGER
474 int isView; /* True if attempting to insert into a view */
475 Trigger *pTrigger; /* List of triggers on pTab, if required */
476 int tmask; /* Mask of trigger times */
477 #endif
479 db = pParse->db;
480 memset(&dest, 0, sizeof(dest));
481 if( pParse->nErr || db->mallocFailed ){
482 goto insert_cleanup;
485 /* Locate the table into which we will be inserting new information.
487 assert( pTabList->nSrc==1 );
488 zTab = pTabList->a[0].zName;
489 if( NEVER(zTab==0) ) goto insert_cleanup;
490 pTab = sqlite3SrcListLookup(pParse, pTabList);
491 if( pTab==0 ){
492 goto insert_cleanup;
494 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
495 assert( iDb<db->nDb );
496 pDb = &db->aDb[iDb];
497 zDb = pDb->zName;
498 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
499 goto insert_cleanup;
502 /* Figure out if we have any triggers and if the table being
503 ** inserted into is a view
505 #ifndef SQLITE_OMIT_TRIGGER
506 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
507 isView = pTab->pSelect!=0;
508 #else
509 # define pTrigger 0
510 # define tmask 0
511 # define isView 0
512 #endif
513 #ifdef SQLITE_OMIT_VIEW
514 # undef isView
515 # define isView 0
516 #endif
517 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
519 /* If pTab is really a view, make sure it has been initialized.
520 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
521 ** module table).
523 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
524 goto insert_cleanup;
527 /* Ensure that:
528 * (a) the table is not read-only,
529 * (b) that if it is a view then ON INSERT triggers exist
531 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
532 goto insert_cleanup;
535 /* Allocate a VDBE
537 v = sqlite3GetVdbe(pParse);
538 if( v==0 ) goto insert_cleanup;
539 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
540 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
542 #ifndef SQLITE_OMIT_XFER_OPT
543 /* If the statement is of the form
545 ** INSERT INTO <table1> SELECT * FROM <table2>;
547 ** Then special optimizations can be applied that make the transfer
548 ** very fast and which reduce fragmentation of indices.
550 ** This is the 2nd template.
552 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
553 assert( !pTrigger );
554 assert( pList==0 );
555 goto insert_end;
557 #endif /* SQLITE_OMIT_XFER_OPT */
559 /* If this is an AUTOINCREMENT table, look up the sequence number in the
560 ** sqlite_sequence table and store it in memory cell regAutoinc.
562 regAutoinc = autoIncBegin(pParse, iDb, pTab);
564 /* Figure out how many columns of data are supplied. If the data
565 ** is coming from a SELECT statement, then generate a co-routine that
566 ** produces a single row of the SELECT on each invocation. The
567 ** co-routine is the common header to the 3rd and 4th templates.
569 if( pSelect ){
570 /* Data is coming from a SELECT. Generate code to implement that SELECT
571 ** as a co-routine. The code is common to both the 3rd and 4th
572 ** templates:
574 ** EOF <- 0
575 ** X <- A
576 ** goto B
577 ** A: setup for the SELECT
578 ** loop over the tables in the SELECT
579 ** load value into register R..R+n
580 ** yield X
581 ** end loop
582 ** cleanup after the SELECT
583 ** EOF <- 1
584 ** yield X
585 ** halt-error
587 ** On each invocation of the co-routine, it puts a single row of the
588 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
589 ** (These output registers are allocated by sqlite3Select().) When
590 ** the SELECT completes, it sets the EOF flag stored in regEof.
592 int rc, j1;
594 regEof = ++pParse->nMem;
595 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
596 VdbeComment((v, "SELECT eof flag"));
597 sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
598 addrSelect = sqlite3VdbeCurrentAddr(v)+2;
599 sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
600 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
601 VdbeComment((v, "Jump over SELECT coroutine"));
603 /* Resolve the expressions in the SELECT statement and execute it. */
604 rc = sqlite3Select(pParse, pSelect, &dest);
605 assert( pParse->nErr==0 || rc );
606 if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
607 goto insert_cleanup;
609 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
610 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
611 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
612 VdbeComment((v, "End of SELECT coroutine"));
613 sqlite3VdbeJumpHere(v, j1); /* label B: */
615 regFromSelect = dest.iMem;
616 assert( pSelect->pEList );
617 nColumn = pSelect->pEList->nExpr;
618 assert( dest.nMem==nColumn );
620 /* Set useTempTable to TRUE if the result of the SELECT statement
621 ** should be written into a temporary table (template 4). Set to
622 ** FALSE if each* row of the SELECT can be written directly into
623 ** the destination table (template 3).
625 ** A temp table must be used if the table being updated is also one
626 ** of the tables being read by the SELECT statement. Also use a
627 ** temp table in the case of row triggers.
629 if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
630 useTempTable = 1;
633 if( useTempTable ){
634 /* Invoke the coroutine to extract information from the SELECT
635 ** and add it to a transient table srcTab. The code generated
636 ** here is from the 4th template:
638 ** B: open temp table
639 ** L: yield X
640 ** if EOF goto M
641 ** insert row from R..R+n into temp table
642 ** goto L
643 ** M: ...
645 int regRec; /* Register to hold packed record */
646 int regTempRowid; /* Register to hold temp table ROWID */
647 int addrTop; /* Label "L" */
648 int addrIf; /* Address of jump to M */
650 srcTab = pParse->nTab++;
651 regRec = sqlite3GetTempReg(pParse);
652 regTempRowid = sqlite3GetTempReg(pParse);
653 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
654 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
655 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
656 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
657 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
658 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
659 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
660 sqlite3VdbeJumpHere(v, addrIf);
661 sqlite3ReleaseTempReg(pParse, regRec);
662 sqlite3ReleaseTempReg(pParse, regTempRowid);
664 }else{
665 /* This is the case if the data for the INSERT is coming from a VALUES
666 ** clause
668 NameContext sNC;
669 memset(&sNC, 0, sizeof(sNC));
670 sNC.pParse = pParse;
671 srcTab = -1;
672 assert( useTempTable==0 );
673 nColumn = pList ? pList->nExpr : 0;
674 for(i=0; i<nColumn; i++){
675 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
676 goto insert_cleanup;
681 /* Make sure the number of columns in the source data matches the number
682 ** of columns to be inserted into the table.
684 if( IsVirtual(pTab) ){
685 for(i=0; i<pTab->nCol; i++){
686 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
689 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
690 sqlite3ErrorMsg(pParse,
691 "table %S has %d columns but %d values were supplied",
692 pTabList, 0, pTab->nCol-nHidden, nColumn);
693 goto insert_cleanup;
695 if( pColumn!=0 && nColumn!=pColumn->nId ){
696 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
697 goto insert_cleanup;
700 /* If the INSERT statement included an IDLIST term, then make sure
701 ** all elements of the IDLIST really are columns of the table and
702 ** remember the column indices.
704 ** If the table has an INTEGER PRIMARY KEY column and that column
705 ** is named in the IDLIST, then record in the keyColumn variable
706 ** the index into IDLIST of the primary key column. keyColumn is
707 ** the index of the primary key as it appears in IDLIST, not as
708 ** is appears in the original table. (The index of the primary
709 ** key in the original table is pTab->iPKey.)
711 if( pColumn ){
712 for(i=0; i<pColumn->nId; i++){
713 pColumn->a[i].idx = -1;
715 for(i=0; i<pColumn->nId; i++){
716 for(j=0; j<pTab->nCol; j++){
717 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
718 pColumn->a[i].idx = j;
719 if( j==pTab->iPKey ){
720 keyColumn = i;
722 break;
725 if( j>=pTab->nCol ){
726 if( sqlite3IsRowid(pColumn->a[i].zName) ){
727 keyColumn = i;
728 }else{
729 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
730 pTabList, 0, pColumn->a[i].zName);
731 pParse->checkSchema = 1;
732 goto insert_cleanup;
738 /* If there is no IDLIST term but the table has an integer primary
739 ** key, the set the keyColumn variable to the primary key column index
740 ** in the original table definition.
742 if( pColumn==0 && nColumn>0 ){
743 keyColumn = pTab->iPKey;
746 /* Initialize the count of rows to be inserted
748 if( db->flags & SQLITE_CountRows ){
749 regRowCount = ++pParse->nMem;
750 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
753 /* If this is not a view, open the table and and all indices */
754 if( !isView ){
755 int nIdx;
757 baseCur = pParse->nTab;
758 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
759 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
760 if( aRegIdx==0 ){
761 goto insert_cleanup;
763 for(i=0; i<nIdx; i++){
764 aRegIdx[i] = ++pParse->nMem;
768 /* This is the top of the main insertion loop */
769 if( useTempTable ){
770 /* This block codes the top of loop only. The complete loop is the
771 ** following pseudocode (template 4):
773 ** rewind temp table
774 ** C: loop over rows of intermediate table
775 ** transfer values form intermediate table into <table>
776 ** end loop
777 ** D: ...
779 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
780 addrCont = sqlite3VdbeCurrentAddr(v);
781 }else if( pSelect ){
782 /* This block codes the top of loop only. The complete loop is the
783 ** following pseudocode (template 3):
785 ** C: yield X
786 ** if EOF goto D
787 ** insert the select result into <table> from R..R+n
788 ** goto C
789 ** D: ...
791 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
792 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
795 /* Allocate registers for holding the rowid of the new row,
796 ** the content of the new row, and the assemblied row record.
798 regRowid = regIns = pParse->nMem+1;
799 pParse->nMem += pTab->nCol + 1;
800 if( IsVirtual(pTab) ){
801 regRowid++;
802 pParse->nMem++;
804 regData = regRowid+1;
806 /* Run the BEFORE and INSTEAD OF triggers, if there are any
808 endOfLoop = sqlite3VdbeMakeLabel(v);
809 if( tmask & TRIGGER_BEFORE ){
810 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
812 /* build the NEW.* reference row. Note that if there is an INTEGER
813 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
814 ** translated into a unique ID for the row. But on a BEFORE trigger,
815 ** we do not know what the unique ID will be (because the insert has
816 ** not happened yet) so we substitute a rowid of -1
818 if( keyColumn<0 ){
819 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
820 }else{
821 int j1;
822 if( useTempTable ){
823 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
824 }else{
825 assert( pSelect==0 ); /* Otherwise useTempTable is true */
826 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
828 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
829 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
830 sqlite3VdbeJumpHere(v, j1);
831 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
834 /* Cannot have triggers on a virtual table. If it were possible,
835 ** this block would have to account for hidden column.
837 assert( !IsVirtual(pTab) );
839 /* Create the new column data
841 for(i=0; i<pTab->nCol; i++){
842 if( pColumn==0 ){
843 j = i;
844 }else{
845 for(j=0; j<pColumn->nId; j++){
846 if( pColumn->a[j].idx==i ) break;
849 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
850 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
851 }else if( useTempTable ){
852 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
853 }else{
854 assert( pSelect==0 ); /* Otherwise useTempTable is true */
855 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
859 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
860 ** do not attempt any conversions before assembling the record.
861 ** If this is a real table, attempt conversions as required by the
862 ** table column affinities.
864 if( !isView ){
865 sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
866 sqlite3TableAffinityStr(v, pTab);
869 /* Fire BEFORE or INSTEAD OF triggers */
870 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
871 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
873 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
876 /* Push the record number for the new entry onto the stack. The
877 ** record number is a randomly generate integer created by NewRowid
878 ** except when the table has an INTEGER PRIMARY KEY column, in which
879 ** case the record number is the same as that column.
881 if( !isView ){
882 if( IsVirtual(pTab) ){
883 /* The row that the VUpdate opcode will delete: none */
884 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
886 if( keyColumn>=0 ){
887 if( useTempTable ){
888 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
889 }else if( pSelect ){
890 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
891 }else{
892 VdbeOp *pOp;
893 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
894 pOp = sqlite3VdbeGetOp(v, -1);
895 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
896 appendFlag = 1;
897 pOp->opcode = OP_NewRowid;
898 pOp->p1 = baseCur;
899 pOp->p2 = regRowid;
900 pOp->p3 = regAutoinc;
903 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
904 ** to generate a unique primary key value.
906 if( !appendFlag ){
907 int j1;
908 if( !IsVirtual(pTab) ){
909 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
910 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
911 sqlite3VdbeJumpHere(v, j1);
912 }else{
913 j1 = sqlite3VdbeCurrentAddr(v);
914 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
916 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
918 }else if( IsVirtual(pTab) ){
919 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
920 }else{
921 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
922 appendFlag = 1;
924 autoIncStep(pParse, regAutoinc, regRowid);
926 /* Push onto the stack, data for all columns of the new entry, beginning
927 ** with the first column.
929 nHidden = 0;
930 for(i=0; i<pTab->nCol; i++){
931 int iRegStore = regRowid+1+i;
932 if( i==pTab->iPKey ){
933 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
934 ** Whenever this column is read, the record number will be substituted
935 ** in its place. So will fill this column with a NULL to avoid
936 ** taking up data space with information that will never be used. */
937 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
938 continue;
940 if( pColumn==0 ){
941 if( IsHiddenColumn(&pTab->aCol[i]) ){
942 assert( IsVirtual(pTab) );
943 j = -1;
944 nHidden++;
945 }else{
946 j = i - nHidden;
948 }else{
949 for(j=0; j<pColumn->nId; j++){
950 if( pColumn->a[j].idx==i ) break;
953 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
954 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
955 }else if( useTempTable ){
956 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
957 }else if( pSelect ){
958 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
959 }else{
960 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
964 /* Generate code to check constraints and generate index keys and
965 ** do the insertion.
967 #ifndef SQLITE_OMIT_VIRTUALTABLE
968 if( IsVirtual(pTab) ){
969 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
970 sqlite3VtabMakeWritable(pParse, pTab);
971 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
972 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
973 sqlite3MayAbort(pParse);
974 }else
975 #endif
977 int isReplace; /* Set to true if constraints may cause a replace */
978 sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
979 keyColumn>=0, 0, onError, endOfLoop, &isReplace
981 sqlite3FkCheck(pParse, pTab, 0, regIns);
982 sqlite3CompleteInsertion(
983 pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
988 /* Update the count of rows that are inserted
990 if( (db->flags & SQLITE_CountRows)!=0 ){
991 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
994 if( pTrigger ){
995 /* Code AFTER triggers */
996 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
997 pTab, regData-2-pTab->nCol, onError, endOfLoop);
1000 /* The bottom of the main insertion loop, if the data source
1001 ** is a SELECT statement.
1003 sqlite3VdbeResolveLabel(v, endOfLoop);
1004 if( useTempTable ){
1005 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
1006 sqlite3VdbeJumpHere(v, addrInsTop);
1007 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
1008 }else if( pSelect ){
1009 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
1010 sqlite3VdbeJumpHere(v, addrInsTop);
1013 if( !IsVirtual(pTab) && !isView ){
1014 /* Close all tables opened */
1015 sqlite3VdbeAddOp1(v, OP_Close, baseCur);
1016 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
1017 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
1021 insert_end:
1022 /* Update the sqlite_sequence table by storing the content of the
1023 ** maximum rowid counter values recorded while inserting into
1024 ** autoincrement tables.
1026 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
1027 sqlite3AutoincrementEnd(pParse);
1031 ** Return the number of rows inserted. If this routine is
1032 ** generating code because of a call to sqlite3NestedParse(), do not
1033 ** invoke the callback function.
1035 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
1036 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
1037 sqlite3VdbeSetNumCols(v, 1);
1038 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
1041 insert_cleanup:
1042 sqlite3SrcListDelete(db, pTabList);
1043 sqlite3ExprListDelete(db, pList);
1044 sqlite3SelectDelete(db, pSelect);
1045 sqlite3IdListDelete(db, pColumn);
1046 sqlite3DbFree(db, aRegIdx);
1049 /* Make sure "isView" and other macros defined above are undefined. Otherwise
1050 ** thely may interfere with compilation of other functions in this file
1051 ** (or in another file, if this file becomes part of the amalgamation). */
1052 #ifdef isView
1053 #undef isView
1054 #endif
1055 #ifdef pTrigger
1056 #undef pTrigger
1057 #endif
1058 #ifdef tmask
1059 #undef tmask
1060 #endif
1064 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
1066 ** The input is a range of consecutive registers as follows:
1068 ** 1. The rowid of the row after the update.
1070 ** 2. The data in the first column of the entry after the update.
1072 ** i. Data from middle columns...
1074 ** N. The data in the last column of the entry after the update.
1076 ** The regRowid parameter is the index of the register containing (1).
1078 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
1079 ** the address of a register containing the rowid before the update takes
1080 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
1081 ** is false, indicating an INSERT statement, then a non-zero rowidChng
1082 ** indicates that the rowid was explicitly specified as part of the
1083 ** INSERT statement. If rowidChng is false, it means that the rowid is
1084 ** computed automatically in an insert or that the rowid value is not
1085 ** modified by an update.
1087 ** The code generated by this routine store new index entries into
1088 ** registers identified by aRegIdx[]. No index entry is created for
1089 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1090 ** the same as the order of indices on the linked list of indices
1091 ** attached to the table.
1093 ** This routine also generates code to check constraints. NOT NULL,
1094 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
1095 ** then the appropriate action is performed. There are five possible
1096 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
1098 ** Constraint type Action What Happens
1099 ** --------------- ---------- ----------------------------------------
1100 ** any ROLLBACK The current transaction is rolled back and
1101 ** sqlite3_exec() returns immediately with a
1102 ** return code of SQLITE_CONSTRAINT.
1104 ** any ABORT Back out changes from the current command
1105 ** only (do not do a complete rollback) then
1106 ** cause sqlite3_exec() to return immediately
1107 ** with SQLITE_CONSTRAINT.
1109 ** any FAIL Sqlite_exec() returns immediately with a
1110 ** return code of SQLITE_CONSTRAINT. The
1111 ** transaction is not rolled back and any
1112 ** prior changes are retained.
1114 ** any IGNORE The record number and data is popped from
1115 ** the stack and there is an immediate jump
1116 ** to label ignoreDest.
1118 ** NOT NULL REPLACE The NULL value is replace by the default
1119 ** value for that column. If the default value
1120 ** is NULL, the action is the same as ABORT.
1122 ** UNIQUE REPLACE The other row that conflicts with the row
1123 ** being inserted is removed.
1125 ** CHECK REPLACE Illegal. The results in an exception.
1127 ** Which action to take is determined by the overrideError parameter.
1128 ** Or if overrideError==OE_Default, then the pParse->onError parameter
1129 ** is used. Or if pParse->onError==OE_Default then the onError value
1130 ** for the constraint is used.
1132 ** The calling routine must open a read/write cursor for pTab with
1133 ** cursor number "baseCur". All indices of pTab must also have open
1134 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
1135 ** Except, if there is no possibility of a REPLACE action then
1136 ** cursors do not need to be open for indices where aRegIdx[i]==0.
1138 void sqlite3GenerateConstraintChecks(
1139 Parse *pParse, /* The parser context */
1140 Table *pTab, /* the table into which we are inserting */
1141 int baseCur, /* Index of a read/write cursor pointing at pTab */
1142 int regRowid, /* Index of the range of input registers */
1143 int *aRegIdx, /* Register used by each index. 0 for unused indices */
1144 int rowidChng, /* True if the rowid might collide with existing entry */
1145 int isUpdate, /* True for UPDATE, False for INSERT */
1146 int overrideError, /* Override onError to this if not OE_Default */
1147 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
1148 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
1150 int i; /* loop counter */
1151 Vdbe *v; /* VDBE under constrution */
1152 int nCol; /* Number of columns */
1153 int onError; /* Conflict resolution strategy */
1154 int j1; /* Addresss of jump instruction */
1155 int j2 = 0, j3; /* Addresses of jump instructions */
1156 int regData; /* Register containing first data column */
1157 int iCur; /* Table cursor number */
1158 Index *pIdx; /* Pointer to one of the indices */
1159 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
1160 int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
1162 v = sqlite3GetVdbe(pParse);
1163 assert( v!=0 );
1164 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
1165 nCol = pTab->nCol;
1166 regData = regRowid + 1;
1168 /* Test all NOT NULL constraints.
1170 for(i=0; i<nCol; i++){
1171 if( i==pTab->iPKey ){
1172 continue;
1174 onError = pTab->aCol[i].notNull;
1175 if( onError==OE_None ) continue;
1176 if( overrideError!=OE_Default ){
1177 onError = overrideError;
1178 }else if( onError==OE_Default ){
1179 onError = OE_Abort;
1181 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
1182 onError = OE_Abort;
1184 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1185 || onError==OE_Ignore || onError==OE_Replace );
1186 switch( onError ){
1187 case OE_Abort:
1188 sqlite3MayAbort(pParse);
1189 case OE_Rollback:
1190 case OE_Fail: {
1191 char *zMsg;
1192 sqlite3VdbeAddOp3(v, OP_HaltIfNull,
1193 SQLITE_CONSTRAINT, onError, regData+i);
1194 zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
1195 pTab->zName, pTab->aCol[i].zName);
1196 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
1197 break;
1199 case OE_Ignore: {
1200 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
1201 break;
1203 default: {
1204 assert( onError==OE_Replace );
1205 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
1206 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
1207 sqlite3VdbeJumpHere(v, j1);
1208 break;
1213 /* Test all CHECK constraints
1215 #ifndef SQLITE_OMIT_CHECK
1216 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
1217 int allOk = sqlite3VdbeMakeLabel(v);
1218 pParse->ckBase = regData;
1219 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
1220 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
1221 if( onError==OE_Ignore ){
1222 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1223 }else{
1224 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
1225 sqlite3HaltConstraint(pParse, onError, 0, 0);
1227 sqlite3VdbeResolveLabel(v, allOk);
1229 #endif /* !defined(SQLITE_OMIT_CHECK) */
1231 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1232 ** of the new record does not previously exist. Except, if this
1233 ** is an UPDATE and the primary key is not changing, that is OK.
1235 if( rowidChng ){
1236 onError = pTab->keyConf;
1237 if( overrideError!=OE_Default ){
1238 onError = overrideError;
1239 }else if( onError==OE_Default ){
1240 onError = OE_Abort;
1243 if( isUpdate ){
1244 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
1246 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
1247 switch( onError ){
1248 default: {
1249 onError = OE_Abort;
1250 /* Fall thru into the next case */
1252 case OE_Rollback:
1253 case OE_Abort:
1254 case OE_Fail: {
1255 sqlite3HaltConstraint(
1256 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
1257 break;
1259 case OE_Replace: {
1260 /* If there are DELETE triggers on this table and the
1261 ** recursive-triggers flag is set, call GenerateRowDelete() to
1262 ** remove the conflicting row from the the table. This will fire
1263 ** the triggers and remove both the table and index b-tree entries.
1265 ** Otherwise, if there are no triggers or the recursive-triggers
1266 ** flag is not set, but the table has one or more indexes, call
1267 ** GenerateRowIndexDelete(). This removes the index b-tree entries
1268 ** only. The table b-tree entry will be replaced by the new entry
1269 ** when it is inserted.
1271 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1272 ** also invoke MultiWrite() to indicate that this VDBE may require
1273 ** statement rollback (if the statement is aborted after the delete
1274 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1275 ** but being more selective here allows statements like:
1277 ** REPLACE INTO t(rowid) VALUES($newrowid)
1279 ** to run without a statement journal if there are no indexes on the
1280 ** table.
1282 Trigger *pTrigger = 0;
1283 if( pParse->db->flags&SQLITE_RecTriggers ){
1284 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1286 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
1287 sqlite3MultiWrite(pParse);
1288 sqlite3GenerateRowDelete(
1289 pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
1291 }else if( pTab->pIndex ){
1292 sqlite3MultiWrite(pParse);
1293 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
1295 seenReplace = 1;
1296 break;
1298 case OE_Ignore: {
1299 assert( seenReplace==0 );
1300 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1301 break;
1304 sqlite3VdbeJumpHere(v, j3);
1305 if( isUpdate ){
1306 sqlite3VdbeJumpHere(v, j2);
1310 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1311 ** index and making sure that duplicate entries do not already exist.
1312 ** Add the new records to the indices as we go.
1314 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1315 int regIdx;
1316 int regR;
1318 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
1320 /* Create a key for accessing the index entry */
1321 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
1322 for(i=0; i<pIdx->nColumn; i++){
1323 int idx = pIdx->aiColumn[i];
1324 if( idx==pTab->iPKey ){
1325 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
1326 }else{
1327 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
1330 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
1331 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
1332 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
1333 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
1335 /* Find out what action to take in case there is an indexing conflict */
1336 onError = pIdx->onError;
1337 if( onError==OE_None ){
1338 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
1339 continue; /* pIdx is not a UNIQUE index */
1341 if( overrideError!=OE_Default ){
1342 onError = overrideError;
1343 }else if( onError==OE_Default ){
1344 onError = OE_Abort;
1346 if( seenReplace ){
1347 if( onError==OE_Ignore ) onError = OE_Replace;
1348 else if( onError==OE_Fail ) onError = OE_Abort;
1351 /* Check to see if the new index entry will be unique */
1352 regR = sqlite3GetTempReg(pParse);
1353 sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
1354 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
1355 regR, SQLITE_INT_TO_PTR(regIdx),
1356 P4_INT32);
1357 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
1359 /* Generate code that executes if the new index entry is not unique */
1360 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1361 || onError==OE_Ignore || onError==OE_Replace );
1362 switch( onError ){
1363 case OE_Rollback:
1364 case OE_Abort:
1365 case OE_Fail: {
1366 int j;
1367 StrAccum errMsg;
1368 const char *zSep;
1369 char *zErr;
1371 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
1372 errMsg.db = pParse->db;
1373 zSep = pIdx->nColumn>1 ? "columns " : "column ";
1374 for(j=0; j<pIdx->nColumn; j++){
1375 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1376 sqlite3StrAccumAppend(&errMsg, zSep, -1);
1377 zSep = ", ";
1378 sqlite3StrAccumAppend(&errMsg, zCol, -1);
1380 sqlite3StrAccumAppend(&errMsg,
1381 pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
1382 zErr = sqlite3StrAccumFinish(&errMsg);
1383 sqlite3HaltConstraint(pParse, onError, zErr, 0);
1384 sqlite3DbFree(errMsg.db, zErr);
1385 break;
1387 case OE_Ignore: {
1388 assert( seenReplace==0 );
1389 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1390 break;
1392 default: {
1393 Trigger *pTrigger = 0;
1394 assert( onError==OE_Replace );
1395 sqlite3MultiWrite(pParse);
1396 if( pParse->db->flags&SQLITE_RecTriggers ){
1397 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
1399 sqlite3GenerateRowDelete(
1400 pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
1402 seenReplace = 1;
1403 break;
1406 sqlite3VdbeJumpHere(v, j3);
1407 sqlite3ReleaseTempReg(pParse, regR);
1410 if( pbMayReplace ){
1411 *pbMayReplace = seenReplace;
1416 ** This routine generates code to finish the INSERT or UPDATE operation
1417 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
1418 ** A consecutive range of registers starting at regRowid contains the
1419 ** rowid and the content to be inserted.
1421 ** The arguments to this routine should be the same as the first six
1422 ** arguments to sqlite3GenerateConstraintChecks.
1424 void sqlite3CompleteInsertion(
1425 Parse *pParse, /* The parser context */
1426 Table *pTab, /* the table into which we are inserting */
1427 int baseCur, /* Index of a read/write cursor pointing at pTab */
1428 int regRowid, /* Range of content */
1429 int *aRegIdx, /* Register used by each index. 0 for unused indices */
1430 int isUpdate, /* True for UPDATE, False for INSERT */
1431 int appendBias, /* True if this is likely to be an append */
1432 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
1434 int i;
1435 Vdbe *v;
1436 int nIdx;
1437 Index *pIdx;
1438 u8 pik_flags;
1439 int regData;
1440 int regRec;
1442 v = sqlite3GetVdbe(pParse);
1443 assert( v!=0 );
1444 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
1445 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1446 for(i=nIdx-1; i>=0; i--){
1447 if( aRegIdx[i]==0 ) continue;
1448 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
1449 if( useSeekResult ){
1450 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1453 regData = regRowid + 1;
1454 regRec = sqlite3GetTempReg(pParse);
1455 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1456 sqlite3TableAffinityStr(v, pTab);
1457 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
1458 if( pParse->nested ){
1459 pik_flags = 0;
1460 }else{
1461 pik_flags = OPFLAG_NCHANGE;
1462 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
1464 if( appendBias ){
1465 pik_flags |= OPFLAG_APPEND;
1467 if( useSeekResult ){
1468 pik_flags |= OPFLAG_USESEEKRESULT;
1470 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
1471 if( !pParse->nested ){
1472 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
1474 sqlite3VdbeChangeP5(v, pik_flags);
1478 ** Generate code that will open cursors for a table and for all
1479 ** indices of that table. The "baseCur" parameter is the cursor number used
1480 ** for the table. Indices are opened on subsequent cursors.
1482 ** Return the number of indices on the table.
1484 int sqlite3OpenTableAndIndices(
1485 Parse *pParse, /* Parsing context */
1486 Table *pTab, /* Table to be opened */
1487 int baseCur, /* Cursor number assigned to the table */
1488 int op /* OP_OpenRead or OP_OpenWrite */
1490 int i;
1491 int iDb;
1492 Index *pIdx;
1493 Vdbe *v;
1495 if( IsVirtual(pTab) ) return 0;
1496 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1497 v = sqlite3GetVdbe(pParse);
1498 assert( v!=0 );
1499 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
1500 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1501 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1502 assert( pIdx->pSchema==pTab->pSchema );
1503 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
1504 (char*)pKey, P4_KEYINFO_HANDOFF);
1505 VdbeComment((v, "%s", pIdx->zName));
1507 if( pParse->nTab<baseCur+i ){
1508 pParse->nTab = baseCur+i;
1510 return i-1;
1514 #ifdef SQLITE_TEST
1516 ** The following global variable is incremented whenever the
1517 ** transfer optimization is used. This is used for testing
1518 ** purposes only - to make sure the transfer optimization really
1519 ** is happening when it is suppose to.
1521 int sqlite3_xferopt_count;
1522 #endif /* SQLITE_TEST */
1525 #ifndef SQLITE_OMIT_XFER_OPT
1527 ** Check to collation names to see if they are compatible.
1529 static int xferCompatibleCollation(const char *z1, const char *z2){
1530 if( z1==0 ){
1531 return z2==0;
1533 if( z2==0 ){
1534 return 0;
1536 return sqlite3StrICmp(z1, z2)==0;
1541 ** Check to see if index pSrc is compatible as a source of data
1542 ** for index pDest in an insert transfer optimization. The rules
1543 ** for a compatible index:
1545 ** * The index is over the same set of columns
1546 ** * The same DESC and ASC markings occurs on all columns
1547 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
1548 ** * The same collating sequence on each column
1550 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1551 int i;
1552 assert( pDest && pSrc );
1553 assert( pDest->pTable!=pSrc->pTable );
1554 if( pDest->nColumn!=pSrc->nColumn ){
1555 return 0; /* Different number of columns */
1557 if( pDest->onError!=pSrc->onError ){
1558 return 0; /* Different conflict resolution strategies */
1560 for(i=0; i<pSrc->nColumn; i++){
1561 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1562 return 0; /* Different columns indexed */
1564 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1565 return 0; /* Different sort orders */
1567 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
1568 return 0; /* Different collating sequences */
1572 /* If no test above fails then the indices must be compatible */
1573 return 1;
1577 ** Attempt the transfer optimization on INSERTs of the form
1579 ** INSERT INTO tab1 SELECT * FROM tab2;
1581 ** This optimization is only attempted if
1583 ** (1) tab1 and tab2 have identical schemas including all the
1584 ** same indices and constraints
1586 ** (2) tab1 and tab2 are different tables
1588 ** (3) There must be no triggers on tab1
1590 ** (4) The result set of the SELECT statement is "*"
1592 ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1593 ** or LIMIT clause.
1595 ** (6) The SELECT statement is a simple (not a compound) select that
1596 ** contains only tab2 in its FROM clause
1598 ** This method for implementing the INSERT transfers raw records from
1599 ** tab2 over to tab1. The columns are not decoded. Raw records from
1600 ** the indices of tab2 are transfered to tab1 as well. In so doing,
1601 ** the resulting tab1 has much less fragmentation.
1603 ** This routine returns TRUE if the optimization is attempted. If any
1604 ** of the conditions above fail so that the optimization should not
1605 ** be attempted, then this routine returns FALSE.
1607 static int xferOptimization(
1608 Parse *pParse, /* Parser context */
1609 Table *pDest, /* The table we are inserting into */
1610 Select *pSelect, /* A SELECT statement to use as the data source */
1611 int onError, /* How to handle constraint errors */
1612 int iDbDest /* The database of pDest */
1614 ExprList *pEList; /* The result set of the SELECT */
1615 Table *pSrc; /* The table in the FROM clause of SELECT */
1616 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1617 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1618 int i; /* Loop counter */
1619 int iDbSrc; /* The database of pSrc */
1620 int iSrc, iDest; /* Cursors from source and destination */
1621 int addr1, addr2; /* Loop addresses */
1622 int emptyDestTest; /* Address of test for empty pDest */
1623 int emptySrcTest; /* Address of test for empty pSrc */
1624 Vdbe *v; /* The VDBE we are building */
1625 KeyInfo *pKey; /* Key information for an index */
1626 int regAutoinc; /* Memory register used by AUTOINC */
1627 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
1628 int regData, regRowid; /* Registers holding data and rowid */
1630 if( pSelect==0 ){
1631 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1633 if( sqlite3TriggerList(pParse, pDest) ){
1634 return 0; /* tab1 must not have triggers */
1636 #ifndef SQLITE_OMIT_VIRTUALTABLE
1637 if( pDest->tabFlags & TF_Virtual ){
1638 return 0; /* tab1 must not be a virtual table */
1640 #endif
1641 if( onError==OE_Default ){
1642 onError = OE_Abort;
1644 if( onError!=OE_Abort && onError!=OE_Rollback ){
1645 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1647 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
1648 if( pSelect->pSrc->nSrc!=1 ){
1649 return 0; /* FROM clause must have exactly one term */
1651 if( pSelect->pSrc->a[0].pSelect ){
1652 return 0; /* FROM clause cannot contain a subquery */
1654 if( pSelect->pWhere ){
1655 return 0; /* SELECT may not have a WHERE clause */
1657 if( pSelect->pOrderBy ){
1658 return 0; /* SELECT may not have an ORDER BY clause */
1660 /* Do not need to test for a HAVING clause. If HAVING is present but
1661 ** there is no ORDER BY, we will get an error. */
1662 if( pSelect->pGroupBy ){
1663 return 0; /* SELECT may not have a GROUP BY clause */
1665 if( pSelect->pLimit ){
1666 return 0; /* SELECT may not have a LIMIT clause */
1668 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
1669 if( pSelect->pPrior ){
1670 return 0; /* SELECT may not be a compound query */
1672 if( pSelect->selFlags & SF_Distinct ){
1673 return 0; /* SELECT may not be DISTINCT */
1675 pEList = pSelect->pEList;
1676 assert( pEList!=0 );
1677 if( pEList->nExpr!=1 ){
1678 return 0; /* The result set must have exactly one column */
1680 assert( pEList->a[0].pExpr );
1681 if( pEList->a[0].pExpr->op!=TK_ALL ){
1682 return 0; /* The result set must be the special operator "*" */
1685 /* At this point we have established that the statement is of the
1686 ** correct syntactic form to participate in this optimization. Now
1687 ** we have to check the semantics.
1689 pItem = pSelect->pSrc->a;
1690 pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
1691 if( pSrc==0 ){
1692 return 0; /* FROM clause does not contain a real table */
1694 if( pSrc==pDest ){
1695 return 0; /* tab1 and tab2 may not be the same table */
1697 #ifndef SQLITE_OMIT_VIRTUALTABLE
1698 if( pSrc->tabFlags & TF_Virtual ){
1699 return 0; /* tab2 must not be a virtual table */
1701 #endif
1702 if( pSrc->pSelect ){
1703 return 0; /* tab2 may not be a view */
1705 if( pDest->nCol!=pSrc->nCol ){
1706 return 0; /* Number of columns must be the same in tab1 and tab2 */
1708 if( pDest->iPKey!=pSrc->iPKey ){
1709 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1711 for(i=0; i<pDest->nCol; i++){
1712 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1713 return 0; /* Affinity must be the same on all columns */
1715 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1716 return 0; /* Collating sequence must be the same on all columns */
1718 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1719 return 0; /* tab2 must be NOT NULL if tab1 is */
1722 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1723 if( pDestIdx->onError!=OE_None ){
1724 destHasUniqueIdx = 1;
1726 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1727 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1729 if( pSrcIdx==0 ){
1730 return 0; /* pDestIdx has no corresponding index in pSrc */
1733 #ifndef SQLITE_OMIT_CHECK
1734 if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
1735 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1737 #endif
1738 #ifndef SQLITE_OMIT_FOREIGN_KEY
1739 /* Disallow the transfer optimization if the destination table constains
1740 ** any foreign key constraints. This is more restrictive than necessary.
1741 ** But the main beneficiary of the transfer optimization is the VACUUM
1742 ** command, and the VACUUM command disables foreign key constraints. So
1743 ** the extra complication to make this rule less restrictive is probably
1744 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
1746 if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
1747 return 0;
1749 #endif
1750 if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
1751 return 0;
1754 /* If we get this far, it means either:
1756 ** * We can always do the transfer if the table contains an
1757 ** an integer primary key
1759 ** * We can conditionally do the transfer if the destination
1760 ** table is empty.
1762 #ifdef SQLITE_TEST
1763 sqlite3_xferopt_count++;
1764 #endif
1765 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1766 v = sqlite3GetVdbe(pParse);
1767 sqlite3CodeVerifySchema(pParse, iDbSrc);
1768 iSrc = pParse->nTab++;
1769 iDest = pParse->nTab++;
1770 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
1771 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1772 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
1773 /* If tables do not have an INTEGER PRIMARY KEY and there
1774 ** are indices to be copied and the destination is not empty,
1775 ** we have to disallow the transfer optimization because the
1776 ** the rowids might change which will mess up indexing.
1778 ** Or if the destination has a UNIQUE index and is not empty,
1779 ** we also disallow the transfer optimization because we cannot
1780 ** insure that all entries in the union of DEST and SRC will be
1781 ** unique.
1783 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
1784 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
1785 sqlite3VdbeJumpHere(v, addr1);
1786 }else{
1787 emptyDestTest = 0;
1789 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
1790 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1791 regData = sqlite3GetTempReg(pParse);
1792 regRowid = sqlite3GetTempReg(pParse);
1793 if( pDest->iPKey>=0 ){
1794 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1795 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
1796 sqlite3HaltConstraint(
1797 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
1798 sqlite3VdbeJumpHere(v, addr2);
1799 autoIncStep(pParse, regAutoinc, regRowid);
1800 }else if( pDest->pIndex==0 ){
1801 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
1802 }else{
1803 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1804 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
1806 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1807 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1808 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
1809 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
1810 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
1811 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1812 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
1813 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1815 assert( pSrcIdx );
1816 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1817 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
1818 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1819 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1820 (char*)pKey, P4_KEYINFO_HANDOFF);
1821 VdbeComment((v, "%s", pSrcIdx->zName));
1822 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1823 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
1824 (char*)pKey, P4_KEYINFO_HANDOFF);
1825 VdbeComment((v, "%s", pDestIdx->zName));
1826 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1827 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1828 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
1829 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
1830 sqlite3VdbeJumpHere(v, addr1);
1832 sqlite3VdbeJumpHere(v, emptySrcTest);
1833 sqlite3ReleaseTempReg(pParse, regRowid);
1834 sqlite3ReleaseTempReg(pParse, regData);
1835 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
1836 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
1837 if( emptyDestTest ){
1838 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
1839 sqlite3VdbeJumpHere(v, emptyDestTest);
1840 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
1841 return 0;
1842 }else{
1843 return 1;
1846 #endif /* SQLITE_OMIT_XFER_OPT */