1.1 --- a/extensions/sqlite/sqlite-source/insert.c Fri Jul 11 06:51:21 2008 +0000
1.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
1.3 @@ -1,1605 +0,0 @@
1.4 -/*
1.5 -** 2001 September 15
1.6 -**
1.7 -** The author disclaims copyright to this source code. In place of
1.8 -** a legal notice, here is a blessing:
1.9 -**
1.10 -** May you do good and not evil.
1.11 -** May you find forgiveness for yourself and forgive others.
1.12 -** May you share freely, never taking more than you give.
1.13 -**
1.14 -*************************************************************************
1.15 -** This file contains C code routines that are called by the parser
1.16 -** to handle INSERT statements in SQLite.
1.17 -**
1.18 -** $Id$
1.19 -*/
1.20 -#include "sqliteInt.h"
1.21 -
1.22 -/*
1.23 -** Set P3 of the most recently inserted opcode to a column affinity
1.24 -** string for index pIdx. A column affinity string has one character
1.25 -** for each column in the table, according to the affinity of the column:
1.26 -**
1.27 -** Character Column affinity
1.28 -** ------------------------------
1.29 -** 'a' TEXT
1.30 -** 'b' NONE
1.31 -** 'c' NUMERIC
1.32 -** 'd' INTEGER
1.33 -** 'e' REAL
1.34 -*/
1.35 -void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
1.36 - if( !pIdx->zColAff ){
1.37 - /* The first time a column affinity string for a particular index is
1.38 - ** required, it is allocated and populated here. It is then stored as
1.39 - ** a member of the Index structure for subsequent use.
1.40 - **
1.41 - ** The column affinity string will eventually be deleted by
1.42 - ** sqliteDeleteIndex() when the Index structure itself is cleaned
1.43 - ** up.
1.44 - */
1.45 - int n;
1.46 - Table *pTab = pIdx->pTable;
1.47 - sqlite3 *db = sqlite3VdbeDb(v);
1.48 - pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+1);
1.49 - if( !pIdx->zColAff ){
1.50 - return;
1.51 - }
1.52 - for(n=0; n<pIdx->nColumn; n++){
1.53 - pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
1.54 - }
1.55 - pIdx->zColAff[pIdx->nColumn] = '\0';
1.56 - }
1.57 -
1.58 - sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
1.59 -}
1.60 -
1.61 -/*
1.62 -** Set P3 of the most recently inserted opcode to a column affinity
1.63 -** string for table pTab. A column affinity string has one character
1.64 -** for each column indexed by the index, according to the affinity of the
1.65 -** column:
1.66 -**
1.67 -** Character Column affinity
1.68 -** ------------------------------
1.69 -** 'a' TEXT
1.70 -** 'b' NONE
1.71 -** 'c' NUMERIC
1.72 -** 'd' INTEGER
1.73 -** 'e' REAL
1.74 -*/
1.75 -void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
1.76 - /* The first time a column affinity string for a particular table
1.77 - ** is required, it is allocated and populated here. It is then
1.78 - ** stored as a member of the Table structure for subsequent use.
1.79 - **
1.80 - ** The column affinity string will eventually be deleted by
1.81 - ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
1.82 - */
1.83 - if( !pTab->zColAff ){
1.84 - char *zColAff;
1.85 - int i;
1.86 - sqlite3 *db = sqlite3VdbeDb(v);
1.87 -
1.88 - zColAff = (char *)sqlite3DbMallocZero(db, pTab->nCol+1);
1.89 - if( !zColAff ){
1.90 - return;
1.91 - }
1.92 -
1.93 - for(i=0; i<pTab->nCol; i++){
1.94 - zColAff[i] = pTab->aCol[i].affinity;
1.95 - }
1.96 - zColAff[pTab->nCol] = '\0';
1.97 -
1.98 - pTab->zColAff = zColAff;
1.99 - }
1.100 -
1.101 - sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
1.102 -}
1.103 -
1.104 -/*
1.105 -** Return non-zero if SELECT statement p opens the table with rootpage
1.106 -** iTab in database iDb. This is used to see if a statement of the form
1.107 -** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
1.108 -** table for the results of the SELECT.
1.109 -**
1.110 -** No checking is done for sub-selects that are part of expressions.
1.111 -*/
1.112 -static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
1.113 - int i;
1.114 - struct SrcList_item *pItem;
1.115 - if( p->pSrc==0 ) return 0;
1.116 - for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
1.117 - if( pItem->pSelect ){
1.118 - if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
1.119 - }else{
1.120 - if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
1.121 - }
1.122 - }
1.123 - return 0;
1.124 -}
1.125 -
1.126 -#ifndef SQLITE_OMIT_AUTOINCREMENT
1.127 -/*
1.128 -** Write out code to initialize the autoincrement logic. This code
1.129 -** looks up the current autoincrement value in the sqlite_sequence
1.130 -** table and stores that value in a memory cell. Code generated by
1.131 -** autoIncStep() will keep that memory cell holding the largest
1.132 -** rowid value. Code generated by autoIncEnd() will write the new
1.133 -** largest value of the counter back into the sqlite_sequence table.
1.134 -**
1.135 -** This routine returns the index of the mem[] cell that contains
1.136 -** the maximum rowid counter.
1.137 -**
1.138 -** Two memory cells are allocated. The next memory cell after the
1.139 -** one returned holds the rowid in sqlite_sequence where we will
1.140 -** write back the revised maximum rowid.
1.141 -*/
1.142 -static int autoIncBegin(
1.143 - Parse *pParse, /* Parsing context */
1.144 - int iDb, /* Index of the database holding pTab */
1.145 - Table *pTab /* The table we are writing to */
1.146 -){
1.147 - int memId = 0;
1.148 - if( pTab->autoInc ){
1.149 - Vdbe *v = pParse->pVdbe;
1.150 - Db *pDb = &pParse->db->aDb[iDb];
1.151 - int iCur = pParse->nTab;
1.152 - int addr;
1.153 - assert( v );
1.154 - addr = sqlite3VdbeCurrentAddr(v);
1.155 - memId = pParse->nMem+1;
1.156 - pParse->nMem += 2;
1.157 - sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
1.158 - sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
1.159 - sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
1.160 - sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
1.161 - sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
1.162 - sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
1.163 - sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
1.164 - sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
1.165 - sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
1.166 - sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
1.167 - sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
1.168 - sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
1.169 - }
1.170 - return memId;
1.171 -}
1.172 -
1.173 -/*
1.174 -** Update the maximum rowid for an autoincrement calculation.
1.175 -**
1.176 -** This routine should be called when the top of the stack holds a
1.177 -** new rowid that is about to be inserted. If that new rowid is
1.178 -** larger than the maximum rowid in the memId memory cell, then the
1.179 -** memory cell is updated. The stack is unchanged.
1.180 -*/
1.181 -static void autoIncStep(Parse *pParse, int memId){
1.182 - if( memId>0 ){
1.183 - sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
1.184 - }
1.185 -}
1.186 -
1.187 -/*
1.188 -** After doing one or more inserts, the maximum rowid is stored
1.189 -** in mem[memId]. Generate code to write this value back into the
1.190 -** the sqlite_sequence table.
1.191 -*/
1.192 -static void autoIncEnd(
1.193 - Parse *pParse, /* The parsing context */
1.194 - int iDb, /* Index of the database holding pTab */
1.195 - Table *pTab, /* Table we are inserting into */
1.196 - int memId /* Memory cell holding the maximum rowid */
1.197 -){
1.198 - if( pTab->autoInc ){
1.199 - int iCur = pParse->nTab;
1.200 - Vdbe *v = pParse->pVdbe;
1.201 - Db *pDb = &pParse->db->aDb[iDb];
1.202 - int addr;
1.203 - assert( v );
1.204 - addr = sqlite3VdbeCurrentAddr(v);
1.205 - sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
1.206 - sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
1.207 - sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
1.208 - sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1.209 - sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
1.210 - sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
1.211 - sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
1.212 - sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
1.213 - sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
1.214 - sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
1.215 - }
1.216 -}
1.217 -#else
1.218 -/*
1.219 -** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
1.220 -** above are all no-ops
1.221 -*/
1.222 -# define autoIncBegin(A,B,C) (0)
1.223 -# define autoIncStep(A,B)
1.224 -# define autoIncEnd(A,B,C,D)
1.225 -#endif /* SQLITE_OMIT_AUTOINCREMENT */
1.226 -
1.227 -
1.228 -/* Forward declaration */
1.229 -static int xferOptimization(
1.230 - Parse *pParse, /* Parser context */
1.231 - Table *pDest, /* The table we are inserting into */
1.232 - Select *pSelect, /* A SELECT statement to use as the data source */
1.233 - int onError, /* How to handle constraint errors */
1.234 - int iDbDest /* The database of pDest */
1.235 -);
1.236 -
1.237 -/*
1.238 -** This routine is call to handle SQL of the following forms:
1.239 -**
1.240 -** insert into TABLE (IDLIST) values(EXPRLIST)
1.241 -** insert into TABLE (IDLIST) select
1.242 -**
1.243 -** The IDLIST following the table name is always optional. If omitted,
1.244 -** then a list of all columns for the table is substituted. The IDLIST
1.245 -** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
1.246 -**
1.247 -** The pList parameter holds EXPRLIST in the first form of the INSERT
1.248 -** statement above, and pSelect is NULL. For the second form, pList is
1.249 -** NULL and pSelect is a pointer to the select statement used to generate
1.250 -** data for the insert.
1.251 -**
1.252 -** The code generated follows one of four templates. For a simple
1.253 -** select with data coming from a VALUES clause, the code executes
1.254 -** once straight down through. The template looks like this:
1.255 -**
1.256 -** open write cursor to <table> and its indices
1.257 -** puts VALUES clause expressions onto the stack
1.258 -** write the resulting record into <table>
1.259 -** cleanup
1.260 -**
1.261 -** The three remaining templates assume the statement is of the form
1.262 -**
1.263 -** INSERT INTO <table> SELECT ...
1.264 -**
1.265 -** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
1.266 -** in other words if the SELECT pulls all columns from a single table
1.267 -** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
1.268 -** if <table2> and <table1> are distinct tables but have identical
1.269 -** schemas, including all the same indices, then a special optimization
1.270 -** is invoked that copies raw records from <table2> over to <table1>.
1.271 -** See the xferOptimization() function for the implementation of this
1.272 -** template. This is the second template.
1.273 -**
1.274 -** open a write cursor to <table>
1.275 -** open read cursor on <table2>
1.276 -** transfer all records in <table2> over to <table>
1.277 -** close cursors
1.278 -** foreach index on <table>
1.279 -** open a write cursor on the <table> index
1.280 -** open a read cursor on the corresponding <table2> index
1.281 -** transfer all records from the read to the write cursors
1.282 -** close cursors
1.283 -** end foreach
1.284 -**
1.285 -** The third template is for when the second template does not apply
1.286 -** and the SELECT clause does not read from <table> at any time.
1.287 -** The generated code follows this template:
1.288 -**
1.289 -** goto B
1.290 -** A: setup for the SELECT
1.291 -** loop over the rows in the SELECT
1.292 -** gosub C
1.293 -** end loop
1.294 -** cleanup after the SELECT
1.295 -** goto D
1.296 -** B: open write cursor to <table> and its indices
1.297 -** goto A
1.298 -** C: insert the select result into <table>
1.299 -** return
1.300 -** D: cleanup
1.301 -**
1.302 -** The fourth template is used if the insert statement takes its
1.303 -** values from a SELECT but the data is being inserted into a table
1.304 -** that is also read as part of the SELECT. In the third form,
1.305 -** we have to use a intermediate table to store the results of
1.306 -** the select. The template is like this:
1.307 -**
1.308 -** goto B
1.309 -** A: setup for the SELECT
1.310 -** loop over the tables in the SELECT
1.311 -** gosub C
1.312 -** end loop
1.313 -** cleanup after the SELECT
1.314 -** goto D
1.315 -** C: insert the select result into the intermediate table
1.316 -** return
1.317 -** B: open a cursor to an intermediate table
1.318 -** goto A
1.319 -** D: open write cursor to <table> and its indices
1.320 -** loop over the intermediate table
1.321 -** transfer values form intermediate table into <table>
1.322 -** end the loop
1.323 -** cleanup
1.324 -*/
1.325 -void sqlite3Insert(
1.326 - Parse *pParse, /* Parser context */
1.327 - SrcList *pTabList, /* Name of table into which we are inserting */
1.328 - ExprList *pList, /* List of values to be inserted */
1.329 - Select *pSelect, /* A SELECT statement to use as the data source */
1.330 - IdList *pColumn, /* Column names corresponding to IDLIST. */
1.331 - int onError /* How to handle constraint errors */
1.332 -){
1.333 - Table *pTab; /* The table to insert into */
1.334 - char *zTab; /* Name of the table into which we are inserting */
1.335 - const char *zDb; /* Name of the database holding this table */
1.336 - int i, j, idx; /* Loop counters */
1.337 - Vdbe *v; /* Generate code into this virtual machine */
1.338 - Index *pIdx; /* For looping over indices of the table */
1.339 - int nColumn; /* Number of columns in the data */
1.340 - int base = 0; /* VDBE Cursor number for pTab */
1.341 - int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
1.342 - sqlite3 *db; /* The main database structure */
1.343 - int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
1.344 - int endOfLoop; /* Label for the end of the insertion loop */
1.345 - int useTempTable = 0; /* Store SELECT results in intermediate table */
1.346 - int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
1.347 - int iSelectLoop = 0; /* Address of code that implements the SELECT */
1.348 - int iCleanup = 0; /* Address of the cleanup code */
1.349 - int iInsertBlock = 0; /* Address of the subroutine used to insert data */
1.350 - int iCntMem = 0; /* Memory cell used for the row counter */
1.351 - int newIdx = -1; /* Cursor for the NEW table */
1.352 - Db *pDb; /* The database containing table being inserted into */
1.353 - int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */
1.354 - int appendFlag = 0; /* True if the insert is likely to be an append */
1.355 - int iDb;
1.356 -
1.357 - int nHidden = 0;
1.358 -
1.359 -#ifndef SQLITE_OMIT_TRIGGER
1.360 - int isView; /* True if attempting to insert into a view */
1.361 - int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
1.362 -#endif
1.363 -
1.364 - db = pParse->db;
1.365 - if( pParse->nErr || db->mallocFailed ){
1.366 - goto insert_cleanup;
1.367 - }
1.368 -
1.369 - /* Locate the table into which we will be inserting new information.
1.370 - */
1.371 - assert( pTabList->nSrc==1 );
1.372 - zTab = pTabList->a[0].zName;
1.373 - if( zTab==0 ) goto insert_cleanup;
1.374 - pTab = sqlite3SrcListLookup(pParse, pTabList);
1.375 - if( pTab==0 ){
1.376 - goto insert_cleanup;
1.377 - }
1.378 - iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1.379 - assert( iDb<db->nDb );
1.380 - pDb = &db->aDb[iDb];
1.381 - zDb = pDb->zName;
1.382 - if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
1.383 - goto insert_cleanup;
1.384 - }
1.385 -
1.386 - /* Figure out if we have any triggers and if the table being
1.387 - ** inserted into is a view
1.388 - */
1.389 -#ifndef SQLITE_OMIT_TRIGGER
1.390 - triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
1.391 - isView = pTab->pSelect!=0;
1.392 -#else
1.393 -# define triggers_exist 0
1.394 -# define isView 0
1.395 -#endif
1.396 -#ifdef SQLITE_OMIT_VIEW
1.397 -# undef isView
1.398 -# define isView 0
1.399 -#endif
1.400 -
1.401 - /* Ensure that:
1.402 - * (a) the table is not read-only,
1.403 - * (b) that if it is a view then ON INSERT triggers exist
1.404 - */
1.405 - if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
1.406 - goto insert_cleanup;
1.407 - }
1.408 - assert( pTab!=0 );
1.409 -
1.410 - /* If pTab is really a view, make sure it has been initialized.
1.411 - ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
1.412 - ** module table).
1.413 - */
1.414 - if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1.415 - goto insert_cleanup;
1.416 - }
1.417 -
1.418 - /* Allocate a VDBE
1.419 - */
1.420 - v = sqlite3GetVdbe(pParse);
1.421 - if( v==0 ) goto insert_cleanup;
1.422 - if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
1.423 - sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
1.424 -
1.425 - /* if there are row triggers, allocate a temp table for new.* references. */
1.426 - if( triggers_exist ){
1.427 - newIdx = pParse->nTab++;
1.428 - }
1.429 -
1.430 -#ifndef SQLITE_OMIT_XFER_OPT
1.431 - /* If the statement is of the form
1.432 - **
1.433 - ** INSERT INTO <table1> SELECT * FROM <table2>;
1.434 - **
1.435 - ** Then special optimizations can be applied that make the transfer
1.436 - ** very fast and which reduce fragmentation of indices.
1.437 - */
1.438 - if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
1.439 - assert( !triggers_exist );
1.440 - assert( pList==0 );
1.441 - goto insert_cleanup;
1.442 - }
1.443 -#endif /* SQLITE_OMIT_XFER_OPT */
1.444 -
1.445 - /* If this is an AUTOINCREMENT table, look up the sequence number in the
1.446 - ** sqlite_sequence table and store it in memory cell counterMem. Also
1.447 - ** remember the rowid of the sqlite_sequence table entry in memory cell
1.448 - ** counterRowid.
1.449 - */
1.450 - counterMem = autoIncBegin(pParse, iDb, pTab);
1.451 -
1.452 - /* Figure out how many columns of data are supplied. If the data
1.453 - ** is coming from a SELECT statement, then this step also generates
1.454 - ** all the code to implement the SELECT statement and invoke a subroutine
1.455 - ** to process each row of the result. (Template 2.) If the SELECT
1.456 - ** statement uses the the table that is being inserted into, then the
1.457 - ** subroutine is also coded here. That subroutine stores the SELECT
1.458 - ** results in a temporary table. (Template 3.)
1.459 - */
1.460 - if( pSelect ){
1.461 - /* Data is coming from a SELECT. Generate code to implement that SELECT
1.462 - */
1.463 - int rc, iInitCode;
1.464 - iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
1.465 - iSelectLoop = sqlite3VdbeCurrentAddr(v);
1.466 - iInsertBlock = sqlite3VdbeMakeLabel(v);
1.467 -
1.468 - /* Resolve the expressions in the SELECT statement and execute it. */
1.469 - rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
1.470 - if( rc || pParse->nErr || db->mallocFailed ){
1.471 - goto insert_cleanup;
1.472 - }
1.473 -
1.474 - iCleanup = sqlite3VdbeMakeLabel(v);
1.475 - sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
1.476 - assert( pSelect->pEList );
1.477 - nColumn = pSelect->pEList->nExpr;
1.478 -
1.479 - /* Set useTempTable to TRUE if the result of the SELECT statement
1.480 - ** should be written into a temporary table. Set to FALSE if each
1.481 - ** row of the SELECT can be written directly into the result table.
1.482 - **
1.483 - ** A temp table must be used if the table being updated is also one
1.484 - ** of the tables being read by the SELECT statement. Also use a
1.485 - ** temp table in the case of row triggers.
1.486 - */
1.487 - if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
1.488 - useTempTable = 1;
1.489 - }
1.490 -
1.491 - if( useTempTable ){
1.492 - /* Generate the subroutine that SELECT calls to process each row of
1.493 - ** the result. Store the result in a temporary table
1.494 - */
1.495 - srcTab = pParse->nTab++;
1.496 - sqlite3VdbeResolveLabel(v, iInsertBlock);
1.497 - sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
1.498 - sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
1.499 - sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
1.500 - sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
1.501 - sqlite3VdbeAddOp(v, OP_Return, 0, 0);
1.502 -
1.503 - /* The following code runs first because the GOTO at the very top
1.504 - ** of the program jumps to it. Create the temporary table, then jump
1.505 - ** back up and execute the SELECT code above.
1.506 - */
1.507 - sqlite3VdbeJumpHere(v, iInitCode);
1.508 - sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
1.509 - sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
1.510 - sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
1.511 - sqlite3VdbeResolveLabel(v, iCleanup);
1.512 - }else{
1.513 - sqlite3VdbeJumpHere(v, iInitCode);
1.514 - }
1.515 - }else{
1.516 - /* This is the case if the data for the INSERT is coming from a VALUES
1.517 - ** clause
1.518 - */
1.519 - NameContext sNC;
1.520 - memset(&sNC, 0, sizeof(sNC));
1.521 - sNC.pParse = pParse;
1.522 - srcTab = -1;
1.523 - useTempTable = 0;
1.524 - nColumn = pList ? pList->nExpr : 0;
1.525 - for(i=0; i<nColumn; i++){
1.526 - if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
1.527 - goto insert_cleanup;
1.528 - }
1.529 - }
1.530 - }
1.531 -
1.532 - /* Make sure the number of columns in the source data matches the number
1.533 - ** of columns to be inserted into the table.
1.534 - */
1.535 - if( IsVirtual(pTab) ){
1.536 - for(i=0; i<pTab->nCol; i++){
1.537 - nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
1.538 - }
1.539 - }
1.540 - if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
1.541 - sqlite3ErrorMsg(pParse,
1.542 - "table %S has %d columns but %d values were supplied",
1.543 - pTabList, 0, pTab->nCol, nColumn);
1.544 - goto insert_cleanup;
1.545 - }
1.546 - if( pColumn!=0 && nColumn!=pColumn->nId ){
1.547 - sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
1.548 - goto insert_cleanup;
1.549 - }
1.550 -
1.551 - /* If the INSERT statement included an IDLIST term, then make sure
1.552 - ** all elements of the IDLIST really are columns of the table and
1.553 - ** remember the column indices.
1.554 - **
1.555 - ** If the table has an INTEGER PRIMARY KEY column and that column
1.556 - ** is named in the IDLIST, then record in the keyColumn variable
1.557 - ** the index into IDLIST of the primary key column. keyColumn is
1.558 - ** the index of the primary key as it appears in IDLIST, not as
1.559 - ** is appears in the original table. (The index of the primary
1.560 - ** key in the original table is pTab->iPKey.)
1.561 - */
1.562 - if( pColumn ){
1.563 - for(i=0; i<pColumn->nId; i++){
1.564 - pColumn->a[i].idx = -1;
1.565 - }
1.566 - for(i=0; i<pColumn->nId; i++){
1.567 - for(j=0; j<pTab->nCol; j++){
1.568 - if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
1.569 - pColumn->a[i].idx = j;
1.570 - if( j==pTab->iPKey ){
1.571 - keyColumn = i;
1.572 - }
1.573 - break;
1.574 - }
1.575 - }
1.576 - if( j>=pTab->nCol ){
1.577 - if( sqlite3IsRowid(pColumn->a[i].zName) ){
1.578 - keyColumn = i;
1.579 - }else{
1.580 - sqlite3ErrorMsg(pParse, "table %S has no column named %s",
1.581 - pTabList, 0, pColumn->a[i].zName);
1.582 - pParse->nErr++;
1.583 - goto insert_cleanup;
1.584 - }
1.585 - }
1.586 - }
1.587 - }
1.588 -
1.589 - /* If there is no IDLIST term but the table has an integer primary
1.590 - ** key, the set the keyColumn variable to the primary key column index
1.591 - ** in the original table definition.
1.592 - */
1.593 - if( pColumn==0 && nColumn>0 ){
1.594 - keyColumn = pTab->iPKey;
1.595 - }
1.596 -
1.597 - /* Open the temp table for FOR EACH ROW triggers
1.598 - */
1.599 - if( triggers_exist ){
1.600 - sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
1.601 - sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
1.602 - }
1.603 -
1.604 - /* Initialize the count of rows to be inserted
1.605 - */
1.606 - if( db->flags & SQLITE_CountRows ){
1.607 - iCntMem = pParse->nMem++;
1.608 - sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
1.609 - }
1.610 -
1.611 - /* Open tables and indices if there are no row triggers */
1.612 - if( !triggers_exist ){
1.613 - base = pParse->nTab;
1.614 - sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
1.615 - }
1.616 -
1.617 - /* If the data source is a temporary table, then we have to create
1.618 - ** a loop because there might be multiple rows of data. If the data
1.619 - ** source is a subroutine call from the SELECT statement, then we need
1.620 - ** to launch the SELECT statement processing.
1.621 - */
1.622 - if( useTempTable ){
1.623 - iBreak = sqlite3VdbeMakeLabel(v);
1.624 - sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
1.625 - iCont = sqlite3VdbeCurrentAddr(v);
1.626 - }else if( pSelect ){
1.627 - sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
1.628 - sqlite3VdbeResolveLabel(v, iInsertBlock);
1.629 - }
1.630 -
1.631 - /* Run the BEFORE and INSTEAD OF triggers, if there are any
1.632 - */
1.633 - endOfLoop = sqlite3VdbeMakeLabel(v);
1.634 - if( triggers_exist & TRIGGER_BEFORE ){
1.635 -
1.636 - /* build the NEW.* reference row. Note that if there is an INTEGER
1.637 - ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
1.638 - ** translated into a unique ID for the row. But on a BEFORE trigger,
1.639 - ** we do not know what the unique ID will be (because the insert has
1.640 - ** not happened yet) so we substitute a rowid of -1
1.641 - */
1.642 - if( keyColumn<0 ){
1.643 - sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
1.644 - }else if( useTempTable ){
1.645 - sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
1.646 - }else{
1.647 - assert( pSelect==0 ); /* Otherwise useTempTable is true */
1.648 - sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
1.649 - sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
1.650 - sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1.651 - sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
1.652 - sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1.653 - }
1.654 -
1.655 - /* Cannot have triggers on a virtual table. If it were possible,
1.656 - ** this block would have to account for hidden column.
1.657 - */
1.658 - assert(!IsVirtual(pTab));
1.659 -
1.660 - /* Create the new column data
1.661 - */
1.662 - for(i=0; i<pTab->nCol; i++){
1.663 - if( pColumn==0 ){
1.664 - j = i;
1.665 - }else{
1.666 - for(j=0; j<pColumn->nId; j++){
1.667 - if( pColumn->a[j].idx==i ) break;
1.668 - }
1.669 - }
1.670 - if( pColumn && j>=pColumn->nId ){
1.671 - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
1.672 - }else if( useTempTable ){
1.673 - sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
1.674 - }else{
1.675 - assert( pSelect==0 ); /* Otherwise useTempTable is true */
1.676 - sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
1.677 - }
1.678 - }
1.679 - sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
1.680 -
1.681 - /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
1.682 - ** do not attempt any conversions before assembling the record.
1.683 - ** If this is a real table, attempt conversions as required by the
1.684 - ** table column affinities.
1.685 - */
1.686 - if( !isView ){
1.687 - sqlite3TableAffinityStr(v, pTab);
1.688 - }
1.689 - sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
1.690 -
1.691 - /* Fire BEFORE or INSTEAD OF triggers */
1.692 - if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
1.693 - newIdx, -1, onError, endOfLoop) ){
1.694 - goto insert_cleanup;
1.695 - }
1.696 - }
1.697 -
1.698 - /* If any triggers exists, the opening of tables and indices is deferred
1.699 - ** until now.
1.700 - */
1.701 - if( triggers_exist && !isView ){
1.702 - base = pParse->nTab;
1.703 - sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
1.704 - }
1.705 -
1.706 - /* Push the record number for the new entry onto the stack. The
1.707 - ** record number is a randomly generate integer created by NewRowid
1.708 - ** except when the table has an INTEGER PRIMARY KEY column, in which
1.709 - ** case the record number is the same as that column.
1.710 - */
1.711 - if( !isView ){
1.712 - if( IsVirtual(pTab) ){
1.713 - /* The row that the VUpdate opcode will delete: none */
1.714 - sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1.715 - }
1.716 - if( keyColumn>=0 ){
1.717 - if( useTempTable ){
1.718 - sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
1.719 - }else if( pSelect ){
1.720 - sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
1.721 - }else{
1.722 - VdbeOp *pOp;
1.723 - sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
1.724 - pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
1.725 - if( pOp && pOp->opcode==OP_Null ){
1.726 - appendFlag = 1;
1.727 - pOp->opcode = OP_NewRowid;
1.728 - pOp->p1 = base;
1.729 - pOp->p2 = counterMem;
1.730 - }
1.731 - }
1.732 - /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
1.733 - ** to generate a unique primary key value.
1.734 - */
1.735 - if( !appendFlag ){
1.736 - sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
1.737 - sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1.738 - sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
1.739 - sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1.740 - }
1.741 - }else if( IsVirtual(pTab) ){
1.742 - sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1.743 - }else{
1.744 - sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
1.745 - appendFlag = 1;
1.746 - }
1.747 - autoIncStep(pParse, counterMem);
1.748 -
1.749 - /* Push onto the stack, data for all columns of the new entry, beginning
1.750 - ** with the first column.
1.751 - */
1.752 - nHidden = 0;
1.753 - for(i=0; i<pTab->nCol; i++){
1.754 - if( i==pTab->iPKey ){
1.755 - /* The value of the INTEGER PRIMARY KEY column is always a NULL.
1.756 - ** Whenever this column is read, the record number will be substituted
1.757 - ** in its place. So will fill this column with a NULL to avoid
1.758 - ** taking up data space with information that will never be used. */
1.759 - sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1.760 - continue;
1.761 - }
1.762 - if( pColumn==0 ){
1.763 - if( IsHiddenColumn(&pTab->aCol[i]) ){
1.764 - assert( IsVirtual(pTab) );
1.765 - j = -1;
1.766 - nHidden++;
1.767 - }else{
1.768 - j = i - nHidden;
1.769 - }
1.770 - }else{
1.771 - for(j=0; j<pColumn->nId; j++){
1.772 - if( pColumn->a[j].idx==i ) break;
1.773 - }
1.774 - }
1.775 - if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
1.776 - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
1.777 - }else if( useTempTable ){
1.778 - sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
1.779 - }else if( pSelect ){
1.780 - sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
1.781 - }else{
1.782 - sqlite3ExprCode(pParse, pList->a[j].pExpr);
1.783 - }
1.784 - }
1.785 -
1.786 - /* Generate code to check constraints and generate index keys and
1.787 - ** do the insertion.
1.788 - */
1.789 -#ifndef SQLITE_OMIT_VIRTUALTABLE
1.790 - if( IsVirtual(pTab) ){
1.791 - pParse->pVirtualLock = pTab;
1.792 - sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
1.793 - (const char*)pTab->pVtab, P3_VTAB);
1.794 - }else
1.795 -#endif
1.796 - {
1.797 - sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
1.798 - 0, onError, endOfLoop);
1.799 - sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
1.800 - (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
1.801 - appendFlag);
1.802 - }
1.803 - }
1.804 -
1.805 - /* Update the count of rows that are inserted
1.806 - */
1.807 - if( (db->flags & SQLITE_CountRows)!=0 ){
1.808 - sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
1.809 - }
1.810 -
1.811 - if( triggers_exist ){
1.812 - /* Close all tables opened */
1.813 - if( !isView ){
1.814 - sqlite3VdbeAddOp(v, OP_Close, base, 0);
1.815 - for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
1.816 - sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
1.817 - }
1.818 - }
1.819 -
1.820 - /* Code AFTER triggers */
1.821 - if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
1.822 - newIdx, -1, onError, endOfLoop) ){
1.823 - goto insert_cleanup;
1.824 - }
1.825 - }
1.826 -
1.827 - /* The bottom of the loop, if the data source is a SELECT statement
1.828 - */
1.829 - sqlite3VdbeResolveLabel(v, endOfLoop);
1.830 - if( useTempTable ){
1.831 - sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
1.832 - sqlite3VdbeResolveLabel(v, iBreak);
1.833 - sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
1.834 - }else if( pSelect ){
1.835 - sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
1.836 - sqlite3VdbeAddOp(v, OP_Return, 0, 0);
1.837 - sqlite3VdbeResolveLabel(v, iCleanup);
1.838 - }
1.839 -
1.840 - if( !triggers_exist && !IsVirtual(pTab) ){
1.841 - /* Close all tables opened */
1.842 - sqlite3VdbeAddOp(v, OP_Close, base, 0);
1.843 - for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
1.844 - sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
1.845 - }
1.846 - }
1.847 -
1.848 - /* Update the sqlite_sequence table by storing the content of the
1.849 - ** counter value in memory counterMem back into the sqlite_sequence
1.850 - ** table.
1.851 - */
1.852 - autoIncEnd(pParse, iDb, pTab, counterMem);
1.853 -
1.854 - /*
1.855 - ** Return the number of rows inserted. If this routine is
1.856 - ** generating code because of a call to sqlite3NestedParse(), do not
1.857 - ** invoke the callback function.
1.858 - */
1.859 - if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
1.860 - sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
1.861 - sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
1.862 - sqlite3VdbeSetNumCols(v, 1);
1.863 - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
1.864 - }
1.865 -
1.866 -insert_cleanup:
1.867 - sqlite3SrcListDelete(pTabList);
1.868 - sqlite3ExprListDelete(pList);
1.869 - sqlite3SelectDelete(pSelect);
1.870 - sqlite3IdListDelete(pColumn);
1.871 -}
1.872 -
1.873 -/*
1.874 -** Generate code to do a constraint check prior to an INSERT or an UPDATE.
1.875 -**
1.876 -** When this routine is called, the stack contains (from bottom to top)
1.877 -** the following values:
1.878 -**
1.879 -** 1. The rowid of the row to be updated before the update. This
1.880 -** value is omitted unless we are doing an UPDATE that involves a
1.881 -** change to the record number.
1.882 -**
1.883 -** 2. The rowid of the row after the update.
1.884 -**
1.885 -** 3. The data in the first column of the entry after the update.
1.886 -**
1.887 -** i. Data from middle columns...
1.888 -**
1.889 -** N. The data in the last column of the entry after the update.
1.890 -**
1.891 -** The old rowid shown as entry (1) above is omitted unless both isUpdate
1.892 -** and rowidChng are 1. isUpdate is true for UPDATEs and false for
1.893 -** INSERTs and rowidChng is true if the record number is being changed.
1.894 -**
1.895 -** The code generated by this routine pushes additional entries onto
1.896 -** the stack which are the keys for new index entries for the new record.
1.897 -** The order of index keys is the same as the order of the indices on
1.898 -** the pTable->pIndex list. A key is only created for index i if
1.899 -** aIdxUsed!=0 and aIdxUsed[i]!=0.
1.900 -**
1.901 -** This routine also generates code to check constraints. NOT NULL,
1.902 -** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
1.903 -** then the appropriate action is performed. There are five possible
1.904 -** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
1.905 -**
1.906 -** Constraint type Action What Happens
1.907 -** --------------- ---------- ----------------------------------------
1.908 -** any ROLLBACK The current transaction is rolled back and
1.909 -** sqlite3_exec() returns immediately with a
1.910 -** return code of SQLITE_CONSTRAINT.
1.911 -**
1.912 -** any ABORT Back out changes from the current command
1.913 -** only (do not do a complete rollback) then
1.914 -** cause sqlite3_exec() to return immediately
1.915 -** with SQLITE_CONSTRAINT.
1.916 -**
1.917 -** any FAIL Sqlite_exec() returns immediately with a
1.918 -** return code of SQLITE_CONSTRAINT. The
1.919 -** transaction is not rolled back and any
1.920 -** prior changes are retained.
1.921 -**
1.922 -** any IGNORE The record number and data is popped from
1.923 -** the stack and there is an immediate jump
1.924 -** to label ignoreDest.
1.925 -**
1.926 -** NOT NULL REPLACE The NULL value is replace by the default
1.927 -** value for that column. If the default value
1.928 -** is NULL, the action is the same as ABORT.
1.929 -**
1.930 -** UNIQUE REPLACE The other row that conflicts with the row
1.931 -** being inserted is removed.
1.932 -**
1.933 -** CHECK REPLACE Illegal. The results in an exception.
1.934 -**
1.935 -** Which action to take is determined by the overrideError parameter.
1.936 -** Or if overrideError==OE_Default, then the pParse->onError parameter
1.937 -** is used. Or if pParse->onError==OE_Default then the onError value
1.938 -** for the constraint is used.
1.939 -**
1.940 -** The calling routine must open a read/write cursor for pTab with
1.941 -** cursor number "base". All indices of pTab must also have open
1.942 -** read/write cursors with cursor number base+i for the i-th cursor.
1.943 -** Except, if there is no possibility of a REPLACE action then
1.944 -** cursors do not need to be open for indices where aIdxUsed[i]==0.
1.945 -**
1.946 -** If the isUpdate flag is true, it means that the "base" cursor is
1.947 -** initially pointing to an entry that is being updated. The isUpdate
1.948 -** flag causes extra code to be generated so that the "base" cursor
1.949 -** is still pointing at the same entry after the routine returns.
1.950 -** Without the isUpdate flag, the "base" cursor might be moved.
1.951 -*/
1.952 -void sqlite3GenerateConstraintChecks(
1.953 - Parse *pParse, /* The parser context */
1.954 - Table *pTab, /* the table into which we are inserting */
1.955 - int base, /* Index of a read/write cursor pointing at pTab */
1.956 - char *aIdxUsed, /* Which indices are used. NULL means all are used */
1.957 - int rowidChng, /* True if the record number will change */
1.958 - int isUpdate, /* True for UPDATE, False for INSERT */
1.959 - int overrideError, /* Override onError to this if not OE_Default */
1.960 - int ignoreDest /* Jump to this label on an OE_Ignore resolution */
1.961 -){
1.962 - int i;
1.963 - Vdbe *v;
1.964 - int nCol;
1.965 - int onError;
1.966 - int addr;
1.967 - int extra;
1.968 - int iCur;
1.969 - Index *pIdx;
1.970 - int seenReplace = 0;
1.971 - int jumpInst1=0, jumpInst2;
1.972 - int hasTwoRowids = (isUpdate && rowidChng);
1.973 -
1.974 - v = sqlite3GetVdbe(pParse);
1.975 - assert( v!=0 );
1.976 - assert( pTab->pSelect==0 ); /* This table is not a VIEW */
1.977 - nCol = pTab->nCol;
1.978 -
1.979 - /* Test all NOT NULL constraints.
1.980 - */
1.981 - for(i=0; i<nCol; i++){
1.982 - if( i==pTab->iPKey ){
1.983 - continue;
1.984 - }
1.985 - onError = pTab->aCol[i].notNull;
1.986 - if( onError==OE_None ) continue;
1.987 - if( overrideError!=OE_Default ){
1.988 - onError = overrideError;
1.989 - }else if( onError==OE_Default ){
1.990 - onError = OE_Abort;
1.991 - }
1.992 - if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
1.993 - onError = OE_Abort;
1.994 - }
1.995 - sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
1.996 - addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
1.997 - assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1.998 - || onError==OE_Ignore || onError==OE_Replace );
1.999 - switch( onError ){
1.1000 - case OE_Rollback:
1.1001 - case OE_Abort:
1.1002 - case OE_Fail: {
1.1003 - char *zMsg = 0;
1.1004 - sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1.1005 - sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
1.1006 - " may not be NULL", (char*)0);
1.1007 - sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
1.1008 - break;
1.1009 - }
1.1010 - case OE_Ignore: {
1.1011 - sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1.1012 - sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1.1013 - break;
1.1014 - }
1.1015 - case OE_Replace: {
1.1016 - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
1.1017 - sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
1.1018 - break;
1.1019 - }
1.1020 - }
1.1021 - sqlite3VdbeJumpHere(v, addr);
1.1022 - }
1.1023 -
1.1024 - /* Test all CHECK constraints
1.1025 - */
1.1026 -#ifndef SQLITE_OMIT_CHECK
1.1027 - if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
1.1028 - int allOk = sqlite3VdbeMakeLabel(v);
1.1029 - assert( pParse->ckOffset==0 );
1.1030 - pParse->ckOffset = nCol;
1.1031 - sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
1.1032 - assert( pParse->ckOffset==nCol );
1.1033 - pParse->ckOffset = 0;
1.1034 - onError = overrideError!=OE_Default ? overrideError : OE_Abort;
1.1035 - if( onError==OE_Ignore ){
1.1036 - sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1.1037 - sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1.1038 - }else{
1.1039 - sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1.1040 - }
1.1041 - sqlite3VdbeResolveLabel(v, allOk);
1.1042 - }
1.1043 -#endif /* !defined(SQLITE_OMIT_CHECK) */
1.1044 -
1.1045 - /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1.1046 - ** of the new record does not previously exist. Except, if this
1.1047 - ** is an UPDATE and the primary key is not changing, that is OK.
1.1048 - */
1.1049 - if( rowidChng ){
1.1050 - onError = pTab->keyConf;
1.1051 - if( overrideError!=OE_Default ){
1.1052 - onError = overrideError;
1.1053 - }else if( onError==OE_Default ){
1.1054 - onError = OE_Abort;
1.1055 - }
1.1056 -
1.1057 - if( isUpdate ){
1.1058 - sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1.1059 - sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1.1060 - jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
1.1061 - }
1.1062 - sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
1.1063 - jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
1.1064 - switch( onError ){
1.1065 - default: {
1.1066 - onError = OE_Abort;
1.1067 - /* Fall thru into the next case */
1.1068 - }
1.1069 - case OE_Rollback:
1.1070 - case OE_Abort:
1.1071 - case OE_Fail: {
1.1072 - sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1.1073 - "PRIMARY KEY must be unique", P3_STATIC);
1.1074 - break;
1.1075 - }
1.1076 - case OE_Replace: {
1.1077 - sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
1.1078 - if( isUpdate ){
1.1079 - sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
1.1080 - sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
1.1081 - }
1.1082 - seenReplace = 1;
1.1083 - break;
1.1084 - }
1.1085 - case OE_Ignore: {
1.1086 - assert( seenReplace==0 );
1.1087 - sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
1.1088 - sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1.1089 - break;
1.1090 - }
1.1091 - }
1.1092 - sqlite3VdbeJumpHere(v, jumpInst2);
1.1093 - if( isUpdate ){
1.1094 - sqlite3VdbeJumpHere(v, jumpInst1);
1.1095 - sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
1.1096 - sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
1.1097 - }
1.1098 - }
1.1099 -
1.1100 - /* Test all UNIQUE constraints by creating entries for each UNIQUE
1.1101 - ** index and making sure that duplicate entries do not already exist.
1.1102 - ** Add the new records to the indices as we go.
1.1103 - */
1.1104 - extra = -1;
1.1105 - for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
1.1106 - if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
1.1107 - extra++;
1.1108 -
1.1109 - /* Create a key for accessing the index entry */
1.1110 - sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
1.1111 - for(i=0; i<pIdx->nColumn; i++){
1.1112 - int idx = pIdx->aiColumn[i];
1.1113 - if( idx==pTab->iPKey ){
1.1114 - sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
1.1115 - }else{
1.1116 - sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
1.1117 - }
1.1118 - }
1.1119 - jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
1.1120 - sqlite3IndexAffinityStr(v, pIdx);
1.1121 -
1.1122 - /* Find out what action to take in case there is an indexing conflict */
1.1123 - onError = pIdx->onError;
1.1124 - if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
1.1125 - if( overrideError!=OE_Default ){
1.1126 - onError = overrideError;
1.1127 - }else if( onError==OE_Default ){
1.1128 - onError = OE_Abort;
1.1129 - }
1.1130 - if( seenReplace ){
1.1131 - if( onError==OE_Ignore ) onError = OE_Replace;
1.1132 - else if( onError==OE_Fail ) onError = OE_Abort;
1.1133 - }
1.1134 -
1.1135 -
1.1136 - /* Check to see if the new index entry will be unique */
1.1137 - sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
1.1138 - jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
1.1139 -
1.1140 - /* Generate code that executes if the new index entry is not unique */
1.1141 - assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1.1142 - || onError==OE_Ignore || onError==OE_Replace );
1.1143 - switch( onError ){
1.1144 - case OE_Rollback:
1.1145 - case OE_Abort:
1.1146 - case OE_Fail: {
1.1147 - int j, n1, n2;
1.1148 - char zErrMsg[200];
1.1149 - sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
1.1150 - pIdx->nColumn>1 ? "columns " : "column ");
1.1151 - n1 = strlen(zErrMsg);
1.1152 - for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
1.1153 - char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1.1154 - n2 = strlen(zCol);
1.1155 - if( j>0 ){
1.1156 - sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
1.1157 - n1 += 2;
1.1158 - }
1.1159 - if( n1+n2>sizeof(zErrMsg)-30 ){
1.1160 - sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
1.1161 - n1 += 3;
1.1162 - break;
1.1163 - }else{
1.1164 - sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
1.1165 - n1 += n2;
1.1166 - }
1.1167 - }
1.1168 - sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
1.1169 - pIdx->nColumn>1 ? " are not unique" : " is not unique");
1.1170 - sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
1.1171 - break;
1.1172 - }
1.1173 - case OE_Ignore: {
1.1174 - assert( seenReplace==0 );
1.1175 - sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
1.1176 - sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1.1177 - break;
1.1178 - }
1.1179 - case OE_Replace: {
1.1180 - sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
1.1181 - if( isUpdate ){
1.1182 - sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
1.1183 - sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
1.1184 - }
1.1185 - seenReplace = 1;
1.1186 - break;
1.1187 - }
1.1188 - }
1.1189 -#if NULL_DISTINCT_FOR_UNIQUE
1.1190 - sqlite3VdbeJumpHere(v, jumpInst1);
1.1191 -#endif
1.1192 - sqlite3VdbeJumpHere(v, jumpInst2);
1.1193 - }
1.1194 -}
1.1195 -
1.1196 -/*
1.1197 -** This routine generates code to finish the INSERT or UPDATE operation
1.1198 -** that was started by a prior call to sqlite3GenerateConstraintChecks.
1.1199 -** The stack must contain keys for all active indices followed by data
1.1200 -** and the rowid for the new entry. This routine creates the new
1.1201 -** entries in all indices and in the main table.
1.1202 -**
1.1203 -** The arguments to this routine should be the same as the first six
1.1204 -** arguments to sqlite3GenerateConstraintChecks.
1.1205 -*/
1.1206 -void sqlite3CompleteInsertion(
1.1207 - Parse *pParse, /* The parser context */
1.1208 - Table *pTab, /* the table into which we are inserting */
1.1209 - int base, /* Index of a read/write cursor pointing at pTab */
1.1210 - char *aIdxUsed, /* Which indices are used. NULL means all are used */
1.1211 - int rowidChng, /* True if the record number will change */
1.1212 - int isUpdate, /* True for UPDATE, False for INSERT */
1.1213 - int newIdx, /* Index of NEW table for triggers. -1 if none */
1.1214 - int appendBias /* True if this is likely to be an append */
1.1215 -){
1.1216 - int i;
1.1217 - Vdbe *v;
1.1218 - int nIdx;
1.1219 - Index *pIdx;
1.1220 - int pik_flags;
1.1221 -
1.1222 - v = sqlite3GetVdbe(pParse);
1.1223 - assert( v!=0 );
1.1224 - assert( pTab->pSelect==0 ); /* This table is not a VIEW */
1.1225 - for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1.1226 - for(i=nIdx-1; i>=0; i--){
1.1227 - if( aIdxUsed && aIdxUsed[i]==0 ) continue;
1.1228 - sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
1.1229 - }
1.1230 - sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
1.1231 - sqlite3TableAffinityStr(v, pTab);
1.1232 -#ifndef SQLITE_OMIT_TRIGGER
1.1233 - if( newIdx>=0 ){
1.1234 - sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1.1235 - sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1.1236 - sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
1.1237 - }
1.1238 -#endif
1.1239 - if( pParse->nested ){
1.1240 - pik_flags = 0;
1.1241 - }else{
1.1242 - pik_flags = OPFLAG_NCHANGE;
1.1243 - pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
1.1244 - }
1.1245 - if( appendBias ){
1.1246 - pik_flags |= OPFLAG_APPEND;
1.1247 - }
1.1248 - sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
1.1249 - if( !pParse->nested ){
1.1250 - sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
1.1251 - }
1.1252 -
1.1253 - if( isUpdate && rowidChng ){
1.1254 - sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1.1255 - }
1.1256 -}
1.1257 -
1.1258 -/*
1.1259 -** Generate code that will open cursors for a table and for all
1.1260 -** indices of that table. The "base" parameter is the cursor number used
1.1261 -** for the table. Indices are opened on subsequent cursors.
1.1262 -*/
1.1263 -void sqlite3OpenTableAndIndices(
1.1264 - Parse *pParse, /* Parsing context */
1.1265 - Table *pTab, /* Table to be opened */
1.1266 - int base, /* Cursor number assigned to the table */
1.1267 - int op /* OP_OpenRead or OP_OpenWrite */
1.1268 -){
1.1269 - int i;
1.1270 - int iDb;
1.1271 - Index *pIdx;
1.1272 - Vdbe *v;
1.1273 -
1.1274 - if( IsVirtual(pTab) ) return;
1.1275 - iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1.1276 - v = sqlite3GetVdbe(pParse);
1.1277 - assert( v!=0 );
1.1278 - sqlite3OpenTable(pParse, base, iDb, pTab, op);
1.1279 - for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1.1280 - KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1.1281 - assert( pIdx->pSchema==pTab->pSchema );
1.1282 - sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
1.1283 - VdbeComment((v, "# %s", pIdx->zName));
1.1284 - sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
1.1285 - }
1.1286 - if( pParse->nTab<=base+i ){
1.1287 - pParse->nTab = base+i;
1.1288 - }
1.1289 -}
1.1290 -
1.1291 -
1.1292 -#ifdef SQLITE_TEST
1.1293 -/*
1.1294 -** The following global variable is incremented whenever the
1.1295 -** transfer optimization is used. This is used for testing
1.1296 -** purposes only - to make sure the transfer optimization really
1.1297 -** is happening when it is suppose to.
1.1298 -*/
1.1299 -int sqlite3_xferopt_count;
1.1300 -#endif /* SQLITE_TEST */
1.1301 -
1.1302 -
1.1303 -#ifndef SQLITE_OMIT_XFER_OPT
1.1304 -/*
1.1305 -** Check to collation names to see if they are compatible.
1.1306 -*/
1.1307 -static int xferCompatibleCollation(const char *z1, const char *z2){
1.1308 - if( z1==0 ){
1.1309 - return z2==0;
1.1310 - }
1.1311 - if( z2==0 ){
1.1312 - return 0;
1.1313 - }
1.1314 - return sqlite3StrICmp(z1, z2)==0;
1.1315 -}
1.1316 -
1.1317 -
1.1318 -/*
1.1319 -** Check to see if index pSrc is compatible as a source of data
1.1320 -** for index pDest in an insert transfer optimization. The rules
1.1321 -** for a compatible index:
1.1322 -**
1.1323 -** * The index is over the same set of columns
1.1324 -** * The same DESC and ASC markings occurs on all columns
1.1325 -** * The same onError processing (OE_Abort, OE_Ignore, etc)
1.1326 -** * The same collating sequence on each column
1.1327 -*/
1.1328 -static int xferCompatibleIndex(Index *pDest, Index *pSrc){
1.1329 - int i;
1.1330 - assert( pDest && pSrc );
1.1331 - assert( pDest->pTable!=pSrc->pTable );
1.1332 - if( pDest->nColumn!=pSrc->nColumn ){
1.1333 - return 0; /* Different number of columns */
1.1334 - }
1.1335 - if( pDest->onError!=pSrc->onError ){
1.1336 - return 0; /* Different conflict resolution strategies */
1.1337 - }
1.1338 - for(i=0; i<pSrc->nColumn; i++){
1.1339 - if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
1.1340 - return 0; /* Different columns indexed */
1.1341 - }
1.1342 - if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
1.1343 - return 0; /* Different sort orders */
1.1344 - }
1.1345 - if( pSrc->azColl[i]!=pDest->azColl[i] ){
1.1346 - return 0; /* Different sort orders */
1.1347 - }
1.1348 - }
1.1349 -
1.1350 - /* If no test above fails then the indices must be compatible */
1.1351 - return 1;
1.1352 -}
1.1353 -
1.1354 -/*
1.1355 -** Attempt the transfer optimization on INSERTs of the form
1.1356 -**
1.1357 -** INSERT INTO tab1 SELECT * FROM tab2;
1.1358 -**
1.1359 -** This optimization is only attempted if
1.1360 -**
1.1361 -** (1) tab1 and tab2 have identical schemas including all the
1.1362 -** same indices and constraints
1.1363 -**
1.1364 -** (2) tab1 and tab2 are different tables
1.1365 -**
1.1366 -** (3) There must be no triggers on tab1
1.1367 -**
1.1368 -** (4) The result set of the SELECT statement is "*"
1.1369 -**
1.1370 -** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1.1371 -** or LIMIT clause.
1.1372 -**
1.1373 -** (6) The SELECT statement is a simple (not a compound) select that
1.1374 -** contains only tab2 in its FROM clause
1.1375 -**
1.1376 -** This method for implementing the INSERT transfers raw records from
1.1377 -** tab2 over to tab1. The columns are not decoded. Raw records from
1.1378 -** the indices of tab2 are transfered to tab1 as well. In so doing,
1.1379 -** the resulting tab1 has much less fragmentation.
1.1380 -**
1.1381 -** This routine returns TRUE if the optimization is attempted. If any
1.1382 -** of the conditions above fail so that the optimization should not
1.1383 -** be attempted, then this routine returns FALSE.
1.1384 -*/
1.1385 -static int xferOptimization(
1.1386 - Parse *pParse, /* Parser context */
1.1387 - Table *pDest, /* The table we are inserting into */
1.1388 - Select *pSelect, /* A SELECT statement to use as the data source */
1.1389 - int onError, /* How to handle constraint errors */
1.1390 - int iDbDest /* The database of pDest */
1.1391 -){
1.1392 - ExprList *pEList; /* The result set of the SELECT */
1.1393 - Table *pSrc; /* The table in the FROM clause of SELECT */
1.1394 - Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
1.1395 - struct SrcList_item *pItem; /* An element of pSelect->pSrc */
1.1396 - int i; /* Loop counter */
1.1397 - int iDbSrc; /* The database of pSrc */
1.1398 - int iSrc, iDest; /* Cursors from source and destination */
1.1399 - int addr1, addr2; /* Loop addresses */
1.1400 - int emptyDestTest; /* Address of test for empty pDest */
1.1401 - int emptySrcTest; /* Address of test for empty pSrc */
1.1402 - Vdbe *v; /* The VDBE we are building */
1.1403 - KeyInfo *pKey; /* Key information for an index */
1.1404 - int counterMem; /* Memory register used by AUTOINC */
1.1405 - int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
1.1406 -
1.1407 - if( pSelect==0 ){
1.1408 - return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1.1409 - }
1.1410 - if( pDest->pTrigger ){
1.1411 - return 0; /* tab1 must not have triggers */
1.1412 - }
1.1413 -#ifndef SQLITE_OMIT_VIRTUALTABLE
1.1414 - if( pDest->isVirtual ){
1.1415 - return 0; /* tab1 must not be a virtual table */
1.1416 - }
1.1417 -#endif
1.1418 - if( onError==OE_Default ){
1.1419 - onError = OE_Abort;
1.1420 - }
1.1421 - if( onError!=OE_Abort && onError!=OE_Rollback ){
1.1422 - return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1.1423 - }
1.1424 - assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
1.1425 - if( pSelect->pSrc->nSrc!=1 ){
1.1426 - return 0; /* FROM clause must have exactly one term */
1.1427 - }
1.1428 - if( pSelect->pSrc->a[0].pSelect ){
1.1429 - return 0; /* FROM clause cannot contain a subquery */
1.1430 - }
1.1431 - if( pSelect->pWhere ){
1.1432 - return 0; /* SELECT may not have a WHERE clause */
1.1433 - }
1.1434 - if( pSelect->pOrderBy ){
1.1435 - return 0; /* SELECT may not have an ORDER BY clause */
1.1436 - }
1.1437 - /* Do not need to test for a HAVING clause. If HAVING is present but
1.1438 - ** there is no ORDER BY, we will get an error. */
1.1439 - if( pSelect->pGroupBy ){
1.1440 - return 0; /* SELECT may not have a GROUP BY clause */
1.1441 - }
1.1442 - if( pSelect->pLimit ){
1.1443 - return 0; /* SELECT may not have a LIMIT clause */
1.1444 - }
1.1445 - assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
1.1446 - if( pSelect->pPrior ){
1.1447 - return 0; /* SELECT may not be a compound query */
1.1448 - }
1.1449 - if( pSelect->isDistinct ){
1.1450 - return 0; /* SELECT may not be DISTINCT */
1.1451 - }
1.1452 - pEList = pSelect->pEList;
1.1453 - assert( pEList!=0 );
1.1454 - if( pEList->nExpr!=1 ){
1.1455 - return 0; /* The result set must have exactly one column */
1.1456 - }
1.1457 - assert( pEList->a[0].pExpr );
1.1458 - if( pEList->a[0].pExpr->op!=TK_ALL ){
1.1459 - return 0; /* The result set must be the special operator "*" */
1.1460 - }
1.1461 -
1.1462 - /* At this point we have established that the statement is of the
1.1463 - ** correct syntactic form to participate in this optimization. Now
1.1464 - ** we have to check the semantics.
1.1465 - */
1.1466 - pItem = pSelect->pSrc->a;
1.1467 - pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
1.1468 - if( pSrc==0 ){
1.1469 - return 0; /* FROM clause does not contain a real table */
1.1470 - }
1.1471 - if( pSrc==pDest ){
1.1472 - return 0; /* tab1 and tab2 may not be the same table */
1.1473 - }
1.1474 -#ifndef SQLITE_OMIT_VIRTUALTABLE
1.1475 - if( pSrc->isVirtual ){
1.1476 - return 0; /* tab2 must not be a virtual table */
1.1477 - }
1.1478 -#endif
1.1479 - if( pSrc->pSelect ){
1.1480 - return 0; /* tab2 may not be a view */
1.1481 - }
1.1482 - if( pDest->nCol!=pSrc->nCol ){
1.1483 - return 0; /* Number of columns must be the same in tab1 and tab2 */
1.1484 - }
1.1485 - if( pDest->iPKey!=pSrc->iPKey ){
1.1486 - return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
1.1487 - }
1.1488 - for(i=0; i<pDest->nCol; i++){
1.1489 - if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
1.1490 - return 0; /* Affinity must be the same on all columns */
1.1491 - }
1.1492 - if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
1.1493 - return 0; /* Collating sequence must be the same on all columns */
1.1494 - }
1.1495 - if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
1.1496 - return 0; /* tab2 must be NOT NULL if tab1 is */
1.1497 - }
1.1498 - }
1.1499 - for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1.1500 - if( pDestIdx->onError!=OE_None ){
1.1501 - destHasUniqueIdx = 1;
1.1502 - }
1.1503 - for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1.1504 - if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1.1505 - }
1.1506 - if( pSrcIdx==0 ){
1.1507 - return 0; /* pDestIdx has no corresponding index in pSrc */
1.1508 - }
1.1509 - }
1.1510 -#ifndef SQLITE_OMIT_CHECK
1.1511 - if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
1.1512 - return 0; /* Tables have different CHECK constraints. Ticket #2252 */
1.1513 - }
1.1514 -#endif
1.1515 -
1.1516 - /* If we get this far, it means either:
1.1517 - **
1.1518 - ** * We can always do the transfer if the table contains an
1.1519 - ** an integer primary key
1.1520 - **
1.1521 - ** * We can conditionally do the transfer if the destination
1.1522 - ** table is empty.
1.1523 - */
1.1524 -#ifdef SQLITE_TEST
1.1525 - sqlite3_xferopt_count++;
1.1526 -#endif
1.1527 - iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
1.1528 - v = sqlite3GetVdbe(pParse);
1.1529 - sqlite3CodeVerifySchema(pParse, iDbSrc);
1.1530 - iSrc = pParse->nTab++;
1.1531 - iDest = pParse->nTab++;
1.1532 - counterMem = autoIncBegin(pParse, iDbDest, pDest);
1.1533 - sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1.1534 - if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
1.1535 - /* If tables do not have an INTEGER PRIMARY KEY and there
1.1536 - ** are indices to be copied and the destination is not empty,
1.1537 - ** we have to disallow the transfer optimization because the
1.1538 - ** the rowids might change which will mess up indexing.
1.1539 - **
1.1540 - ** Or if the destination has a UNIQUE index and is not empty,
1.1541 - ** we also disallow the transfer optimization because we cannot
1.1542 - ** insure that all entries in the union of DEST and SRC will be
1.1543 - ** unique.
1.1544 - */
1.1545 - addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
1.1546 - emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
1.1547 - sqlite3VdbeJumpHere(v, addr1);
1.1548 - }else{
1.1549 - emptyDestTest = 0;
1.1550 - }
1.1551 - sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
1.1552 - emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
1.1553 - if( pDest->iPKey>=0 ){
1.1554 - addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
1.1555 - sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1.1556 - addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
1.1557 - sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
1.1558 - "PRIMARY KEY must be unique", P3_STATIC);
1.1559 - sqlite3VdbeJumpHere(v, addr2);
1.1560 - autoIncStep(pParse, counterMem);
1.1561 - }else if( pDest->pIndex==0 ){
1.1562 - addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
1.1563 - }else{
1.1564 - addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
1.1565 - assert( pDest->autoInc==0 );
1.1566 - }
1.1567 - sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
1.1568 - sqlite3VdbeOp3(v, OP_Insert, iDest,
1.1569 - OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
1.1570 - pDest->zName, 0);
1.1571 - sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
1.1572 - autoIncEnd(pParse, iDbDest, pDest, counterMem);
1.1573 - for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1.1574 - for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
1.1575 - if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
1.1576 - }
1.1577 - assert( pSrcIdx );
1.1578 - sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1.1579 - sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1.1580 - sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
1.1581 - pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1.1582 - VdbeComment((v, "# %s", pSrcIdx->zName));
1.1583 - sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
1.1584 - (char*)pKey, P3_KEYINFO_HANDOFF);
1.1585 - sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
1.1586 - pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1.1587 - VdbeComment((v, "# %s", pDestIdx->zName));
1.1588 - sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
1.1589 - (char*)pKey, P3_KEYINFO_HANDOFF);
1.1590 - addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
1.1591 - sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
1.1592 - sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
1.1593 - sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
1.1594 - sqlite3VdbeJumpHere(v, addr1);
1.1595 - }
1.1596 - sqlite3VdbeJumpHere(v, emptySrcTest);
1.1597 - sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
1.1598 - sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1.1599 - if( emptyDestTest ){
1.1600 - sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
1.1601 - sqlite3VdbeJumpHere(v, emptyDestTest);
1.1602 - sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
1.1603 - return 0;
1.1604 - }else{
1.1605 - return 1;
1.1606 - }
1.1607 -}
1.1608 -#endif /* SQLITE_OMIT_XFER_OPT */