| OLD | NEW | 
 | (Empty) | 
|     1 /* |  | 
|     2 ** 2001 September 15 |  | 
|     3 ** |  | 
|     4 ** The author disclaims copyright to this source code.  In place of |  | 
|     5 ** a legal notice, here is a blessing: |  | 
|     6 ** |  | 
|     7 **    May you do good and not evil. |  | 
|     8 **    May you find forgiveness for yourself and forgive others. |  | 
|     9 **    May you share freely, never taking more than you give. |  | 
|    10 ** |  | 
|    11 ************************************************************************* |  | 
|    12 ** This file contains C code routines that are called by the parser |  | 
|    13 ** to handle INSERT statements in SQLite. |  | 
|    14 ** |  | 
|    15 ** $Id: insert.c,v 1.270 2009/07/24 17:58:53 danielk1977 Exp $ |  | 
|    16 */ |  | 
|    17 #include "sqliteInt.h" |  | 
|    18  |  | 
|    19 /* |  | 
|    20 ** Generate code that will open a table for reading. |  | 
|    21 */ |  | 
|    22 void sqlite3OpenTable( |  | 
|    23   Parse *p,       /* Generate code into this VDBE */ |  | 
|    24   int iCur,       /* The cursor number of the table */ |  | 
|    25   int iDb,        /* The database index in sqlite3.aDb[] */ |  | 
|    26   Table *pTab,    /* The table to be opened */ |  | 
|    27   int opcode      /* OP_OpenRead or OP_OpenWrite */ |  | 
|    28 ){ |  | 
|    29   Vdbe *v; |  | 
|    30   if( IsVirtual(pTab) ) return; |  | 
|    31   v = sqlite3GetVdbe(p); |  | 
|    32   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); |  | 
|    33   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName); |  | 
|    34   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb); |  | 
|    35   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32); |  | 
|    36   VdbeComment((v, "%s", pTab->zName)); |  | 
|    37 } |  | 
|    38  |  | 
|    39 /* |  | 
|    40 ** Return a pointer to the column affinity string associated with index |  | 
|    41 ** pIdx. A column affinity string has one character for each column in  |  | 
|    42 ** the table, according to the affinity of the column: |  | 
|    43 ** |  | 
|    44 **  Character      Column affinity |  | 
|    45 **  ------------------------------ |  | 
|    46 **  'a'            TEXT |  | 
|    47 **  'b'            NONE |  | 
|    48 **  'c'            NUMERIC |  | 
|    49 **  'd'            INTEGER |  | 
|    50 **  'e'            REAL |  | 
|    51 ** |  | 
|    52 ** An extra 'b' is appended to the end of the string to cover the |  | 
|    53 ** rowid that appears as the last column in every index. |  | 
|    54 ** |  | 
|    55 ** Memory for the buffer containing the column index affinity string |  | 
|    56 ** is managed along with the rest of the Index structure. It will be |  | 
|    57 ** released when sqlite3DeleteIndex() is called. |  | 
|    58 */ |  | 
|    59 const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ |  | 
|    60   if( !pIdx->zColAff ){ |  | 
|    61     /* The first time a column affinity string for a particular index is |  | 
|    62     ** required, it is allocated and populated here. It is then stored as |  | 
|    63     ** a member of the Index structure for subsequent use. |  | 
|    64     ** |  | 
|    65     ** The column affinity string will eventually be deleted by |  | 
|    66     ** sqliteDeleteIndex() when the Index structure itself is cleaned |  | 
|    67     ** up. |  | 
|    68     */ |  | 
|    69     int n; |  | 
|    70     Table *pTab = pIdx->pTable; |  | 
|    71     sqlite3 *db = sqlite3VdbeDb(v); |  | 
|    72     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2); |  | 
|    73     if( !pIdx->zColAff ){ |  | 
|    74       db->mallocFailed = 1; |  | 
|    75       return 0; |  | 
|    76     } |  | 
|    77     for(n=0; n<pIdx->nColumn; n++){ |  | 
|    78       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity; |  | 
|    79     } |  | 
|    80     pIdx->zColAff[n++] = SQLITE_AFF_NONE; |  | 
|    81     pIdx->zColAff[n] = 0; |  | 
|    82   } |  | 
|    83   |  | 
|    84   return pIdx->zColAff; |  | 
|    85 } |  | 
|    86  |  | 
|    87 /* |  | 
|    88 ** Set P4 of the most recently inserted opcode to a column affinity |  | 
|    89 ** string for table pTab. A column affinity string has one character |  | 
|    90 ** for each column indexed by the index, according to the affinity of the |  | 
|    91 ** column: |  | 
|    92 ** |  | 
|    93 **  Character      Column affinity |  | 
|    94 **  ------------------------------ |  | 
|    95 **  'a'            TEXT |  | 
|    96 **  'b'            NONE |  | 
|    97 **  'c'            NUMERIC |  | 
|    98 **  'd'            INTEGER |  | 
|    99 **  'e'            REAL |  | 
|   100 */ |  | 
|   101 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){ |  | 
|   102   /* The first time a column affinity string for a particular table |  | 
|   103   ** is required, it is allocated and populated here. It is then  |  | 
|   104   ** stored as a member of the Table structure for subsequent use. |  | 
|   105   ** |  | 
|   106   ** The column affinity string will eventually be deleted by |  | 
|   107   ** sqlite3DeleteTable() when the Table structure itself is cleaned up. |  | 
|   108   */ |  | 
|   109   if( !pTab->zColAff ){ |  | 
|   110     char *zColAff; |  | 
|   111     int i; |  | 
|   112     sqlite3 *db = sqlite3VdbeDb(v); |  | 
|   113  |  | 
|   114     zColAff = (char *)sqlite3Malloc(pTab->nCol+1); |  | 
|   115     if( !zColAff ){ |  | 
|   116       db->mallocFailed = 1; |  | 
|   117       return; |  | 
|   118     } |  | 
|   119  |  | 
|   120     for(i=0; i<pTab->nCol; i++){ |  | 
|   121       zColAff[i] = pTab->aCol[i].affinity; |  | 
|   122     } |  | 
|   123     zColAff[pTab->nCol] = '\0'; |  | 
|   124  |  | 
|   125     pTab->zColAff = zColAff; |  | 
|   126   } |  | 
|   127  |  | 
|   128   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0); |  | 
|   129 } |  | 
|   130  |  | 
|   131 /* |  | 
|   132 ** Return non-zero if the table pTab in database iDb or any of its indices |  | 
|   133 ** have been opened at any point in the VDBE program beginning at location |  | 
|   134 ** iStartAddr throught the end of the program.  This is used to see if  |  | 
|   135 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can  |  | 
|   136 ** run without using temporary table for the results of the SELECT.  |  | 
|   137 */ |  | 
|   138 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){ |  | 
|   139   Vdbe *v = sqlite3GetVdbe(p); |  | 
|   140   int i; |  | 
|   141   int iEnd = sqlite3VdbeCurrentAddr(v); |  | 
|   142 #ifndef SQLITE_OMIT_VIRTUALTABLE |  | 
|   143   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; |  | 
|   144 #endif |  | 
|   145  |  | 
|   146   for(i=iStartAddr; i<iEnd; i++){ |  | 
|   147     VdbeOp *pOp = sqlite3VdbeGetOp(v, i); |  | 
|   148     assert( pOp!=0 ); |  | 
|   149     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ |  | 
|   150       Index *pIndex; |  | 
|   151       int tnum = pOp->p2; |  | 
|   152       if( tnum==pTab->tnum ){ |  | 
|   153         return 1; |  | 
|   154       } |  | 
|   155       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ |  | 
|   156         if( tnum==pIndex->tnum ){ |  | 
|   157           return 1; |  | 
|   158         } |  | 
|   159       } |  | 
|   160     } |  | 
|   161 #ifndef SQLITE_OMIT_VIRTUALTABLE |  | 
|   162     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){ |  | 
|   163       assert( pOp->p4.pVtab!=0 ); |  | 
|   164       assert( pOp->p4type==P4_VTAB ); |  | 
|   165       return 1; |  | 
|   166     } |  | 
|   167 #endif |  | 
|   168   } |  | 
|   169   return 0; |  | 
|   170 } |  | 
|   171  |  | 
|   172 #ifndef SQLITE_OMIT_AUTOINCREMENT |  | 
|   173 /* |  | 
|   174 ** Locate or create an AutoincInfo structure associated with table pTab |  | 
|   175 ** which is in database iDb.  Return the register number for the register |  | 
|   176 ** that holds the maximum rowid. |  | 
|   177 ** |  | 
|   178 ** There is at most one AutoincInfo structure per table even if the |  | 
|   179 ** same table is autoincremented multiple times due to inserts within |  | 
|   180 ** triggers.  A new AutoincInfo structure is created if this is the |  | 
|   181 ** first use of table pTab.  On 2nd and subsequent uses, the original |  | 
|   182 ** AutoincInfo structure is used. |  | 
|   183 ** |  | 
|   184 ** Three memory locations are allocated: |  | 
|   185 ** |  | 
|   186 **   (1)  Register to hold the name of the pTab table. |  | 
|   187 **   (2)  Register to hold the maximum ROWID of pTab. |  | 
|   188 **   (3)  Register to hold the rowid in sqlite_sequence of pTab |  | 
|   189 ** |  | 
|   190 ** The 2nd register is the one that is returned.  That is all the |  | 
|   191 ** insert routine needs to know about. |  | 
|   192 */ |  | 
|   193 static int autoIncBegin( |  | 
|   194   Parse *pParse,      /* Parsing context */ |  | 
|   195   int iDb,            /* Index of the database holding pTab */ |  | 
|   196   Table *pTab         /* The table we are writing to */ |  | 
|   197 ){ |  | 
|   198   int memId = 0;      /* Register holding maximum rowid */ |  | 
|   199   if( pTab->tabFlags & TF_Autoincrement ){ |  | 
|   200     Parse *pToplevel = sqlite3ParseToplevel(pParse); |  | 
|   201     AutoincInfo *pInfo; |  | 
|   202  |  | 
|   203     pInfo = pToplevel->pAinc; |  | 
|   204     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } |  | 
|   205     if( pInfo==0 ){ |  | 
|   206       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo)); |  | 
|   207       if( pInfo==0 ) return 0; |  | 
|   208       pInfo->pNext = pToplevel->pAinc; |  | 
|   209       pToplevel->pAinc = pInfo; |  | 
|   210       pInfo->pTab = pTab; |  | 
|   211       pInfo->iDb = iDb; |  | 
|   212       pToplevel->nMem++;                  /* Register to hold name of table */ |  | 
|   213       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */ |  | 
|   214       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */ |  | 
|   215     } |  | 
|   216     memId = pInfo->regCtr; |  | 
|   217   } |  | 
|   218   return memId; |  | 
|   219 } |  | 
|   220  |  | 
|   221 /* |  | 
|   222 ** This routine generates code that will initialize all of the |  | 
|   223 ** register used by the autoincrement tracker.   |  | 
|   224 */ |  | 
|   225 void sqlite3AutoincrementBegin(Parse *pParse){ |  | 
|   226   AutoincInfo *p;            /* Information about an AUTOINCREMENT */ |  | 
|   227   sqlite3 *db = pParse->db;  /* The database connection */ |  | 
|   228   Db *pDb;                   /* Database only autoinc table */ |  | 
|   229   int memId;                 /* Register holding max rowid */ |  | 
|   230   int addr;                  /* A VDBE address */ |  | 
|   231   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */ |  | 
|   232  |  | 
|   233   /* This routine is never called during trigger-generation.  It is |  | 
|   234   ** only called from the top-level */ |  | 
|   235   assert( pParse->pTriggerTab==0 ); |  | 
|   236   assert( pParse==sqlite3ParseToplevel(pParse) ); |  | 
|   237  |  | 
|   238   assert( v );   /* We failed long ago if this is not so */ |  | 
|   239   for(p = pParse->pAinc; p; p = p->pNext){ |  | 
|   240     pDb = &db->aDb[p->iDb]; |  | 
|   241     memId = p->regCtr; |  | 
|   242     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); |  | 
|   243     addr = sqlite3VdbeCurrentAddr(v); |  | 
|   244     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0); |  | 
|   245     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); |  | 
|   246     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId); |  | 
|   247     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); |  | 
|   248     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); |  | 
|   249     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1); |  | 
|   250     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId); |  | 
|   251     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9); |  | 
|   252     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); |  | 
|   253     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId); |  | 
|   254     sqlite3VdbeAddOp0(v, OP_Close); |  | 
|   255   } |  | 
|   256 } |  | 
|   257  |  | 
|   258 /* |  | 
|   259 ** Update the maximum rowid for an autoincrement calculation. |  | 
|   260 ** |  | 
|   261 ** This routine should be called when the top of the stack holds a |  | 
|   262 ** new rowid that is about to be inserted.  If that new rowid is |  | 
|   263 ** larger than the maximum rowid in the memId memory cell, then the |  | 
|   264 ** memory cell is updated.  The stack is unchanged. |  | 
|   265 */ |  | 
|   266 static void autoIncStep(Parse *pParse, int memId, int regRowid){ |  | 
|   267   if( memId>0 ){ |  | 
|   268     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); |  | 
|   269   } |  | 
|   270 } |  | 
|   271  |  | 
|   272 /* |  | 
|   273 ** This routine generates the code needed to write autoincrement |  | 
|   274 ** maximum rowid values back into the sqlite_sequence register. |  | 
|   275 ** Every statement that might do an INSERT into an autoincrement |  | 
|   276 ** table (either directly or through triggers) needs to call this |  | 
|   277 ** routine just before the "exit" code. |  | 
|   278 */ |  | 
|   279 void sqlite3AutoincrementEnd(Parse *pParse){ |  | 
|   280   AutoincInfo *p; |  | 
|   281   Vdbe *v = pParse->pVdbe; |  | 
|   282   sqlite3 *db = pParse->db; |  | 
|   283  |  | 
|   284   assert( v ); |  | 
|   285   for(p = pParse->pAinc; p; p = p->pNext){ |  | 
|   286     Db *pDb = &db->aDb[p->iDb]; |  | 
|   287     int j1, j2, j3, j4, j5; |  | 
|   288     int iRec; |  | 
|   289     int memId = p->regCtr; |  | 
|   290  |  | 
|   291     iRec = sqlite3GetTempReg(pParse); |  | 
|   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); |  | 
|   310   } |  | 
|   311 } |  | 
|   312 #else |  | 
|   313 /* |  | 
|   314 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines |  | 
|   315 ** above are all no-ops |  | 
|   316 */ |  | 
|   317 # define autoIncBegin(A,B,C) (0) |  | 
|   318 # define autoIncStep(A,B,C) |  | 
|   319 #endif /* SQLITE_OMIT_AUTOINCREMENT */ |  | 
|   320  |  | 
|   321  |  | 
|   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 */ |  | 
|   329 ); |  | 
|   330  |  | 
|   331 /* |  | 
|   332 ** This routine is call to handle SQL of the following forms: |  | 
|   333 ** |  | 
|   334 **    insert into TABLE (IDLIST) values(EXPRLIST) |  | 
|   335 **    insert into TABLE (IDLIST) select |  | 
|   336 ** |  | 
|   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. |  | 
|   340 ** |  | 
|   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. |  | 
|   345 ** |  | 
|   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"): |  | 
|   350 ** |  | 
|   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 |  | 
|   355 ** |  | 
|   356 ** The three remaining templates assume the statement is of the form |  | 
|   357 ** |  | 
|   358 **   INSERT INTO <table> SELECT ... |  | 
|   359 ** |  | 
|   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. |  | 
|   368 ** |  | 
|   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 |  | 
|   379 ** |  | 
|   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: |  | 
|   383 ** |  | 
|   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 |  | 
|   402 ** |  | 
|   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: |  | 
|   408 ** |  | 
|   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 |  | 
|   432 */ |  | 
|   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 */ |  | 
|   440 ){ |  | 
|   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 */ |  | 
|   462  |  | 
|   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 regRecord;        /* Holds the assemblied row record */ |  | 
|   471   int regEof = 0;       /* Register recording end of SELECT data */ |  | 
|   472   int *aRegIdx = 0;     /* One register allocated to each index */ |  | 
|   473  |  | 
|   474 #ifndef SQLITE_OMIT_TRIGGER |  | 
|   475   int isView;                 /* True if attempting to insert into a view */ |  | 
|   476   Trigger *pTrigger;          /* List of triggers on pTab, if required */ |  | 
|   477   int tmask;                  /* Mask of trigger times */ |  | 
|   478 #endif |  | 
|   479  |  | 
|   480   db = pParse->db; |  | 
|   481   memset(&dest, 0, sizeof(dest)); |  | 
|   482   if( pParse->nErr || db->mallocFailed ){ |  | 
|   483     goto insert_cleanup; |  | 
|   484   } |  | 
|   485  |  | 
|   486   /* Locate the table into which we will be inserting new information. |  | 
|   487   */ |  | 
|   488   assert( pTabList->nSrc==1 ); |  | 
|   489   zTab = pTabList->a[0].zName; |  | 
|   490   if( NEVER(zTab==0) ) goto insert_cleanup; |  | 
|   491   pTab = sqlite3SrcListLookup(pParse, pTabList); |  | 
|   492   if( pTab==0 ){ |  | 
|   493     goto insert_cleanup; |  | 
|   494   } |  | 
|   495   iDb = sqlite3SchemaToIndex(db, pTab->pSchema); |  | 
|   496   assert( iDb<db->nDb ); |  | 
|   497   pDb = &db->aDb[iDb]; |  | 
|   498   zDb = pDb->zName; |  | 
|   499   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ |  | 
|   500     goto insert_cleanup; |  | 
|   501   } |  | 
|   502  |  | 
|   503   /* Figure out if we have any triggers and if the table being |  | 
|   504   ** inserted into is a view |  | 
|   505   */ |  | 
|   506 #ifndef SQLITE_OMIT_TRIGGER |  | 
|   507   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); |  | 
|   508   isView = pTab->pSelect!=0; |  | 
|   509 #else |  | 
|   510 # define pTrigger 0 |  | 
|   511 # define tmask 0 |  | 
|   512 # define isView 0 |  | 
|   513 #endif |  | 
|   514 #ifdef SQLITE_OMIT_VIEW |  | 
|   515 # undef isView |  | 
|   516 # define isView 0 |  | 
|   517 #endif |  | 
|   518   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); |  | 
|   519  |  | 
|   520   /* If pTab is really a view, make sure it has been initialized. |  | 
|   521   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual  |  | 
|   522   ** module table). |  | 
|   523   */ |  | 
|   524   if( sqlite3ViewGetColumnNames(pParse, pTab) ){ |  | 
|   525     goto insert_cleanup; |  | 
|   526   } |  | 
|   527  |  | 
|   528   /* Ensure that: |  | 
|   529   *  (a) the table is not read-only,  |  | 
|   530   *  (b) that if it is a view then ON INSERT triggers exist |  | 
|   531   */ |  | 
|   532   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ |  | 
|   533     goto insert_cleanup; |  | 
|   534   } |  | 
|   535  |  | 
|   536   /* Allocate a VDBE |  | 
|   537   */ |  | 
|   538   v = sqlite3GetVdbe(pParse); |  | 
|   539   if( v==0 ) goto insert_cleanup; |  | 
|   540   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); |  | 
|   541   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); |  | 
|   542  |  | 
|   543 #ifndef SQLITE_OMIT_XFER_OPT |  | 
|   544   /* If the statement is of the form |  | 
|   545   ** |  | 
|   546   **       INSERT INTO <table1> SELECT * FROM <table2>; |  | 
|   547   ** |  | 
|   548   ** Then special optimizations can be applied that make the transfer |  | 
|   549   ** very fast and which reduce fragmentation of indices. |  | 
|   550   ** |  | 
|   551   ** This is the 2nd template. |  | 
|   552   */ |  | 
|   553   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ |  | 
|   554     assert( !pTrigger ); |  | 
|   555     assert( pList==0 ); |  | 
|   556     goto insert_end; |  | 
|   557   } |  | 
|   558 #endif /* SQLITE_OMIT_XFER_OPT */ |  | 
|   559  |  | 
|   560   /* If this is an AUTOINCREMENT table, look up the sequence number in the |  | 
|   561   ** sqlite_sequence table and store it in memory cell regAutoinc. |  | 
|   562   */ |  | 
|   563   regAutoinc = autoIncBegin(pParse, iDb, pTab); |  | 
|   564  |  | 
|   565   /* Figure out how many columns of data are supplied.  If the data |  | 
|   566   ** is coming from a SELECT statement, then generate a co-routine that |  | 
|   567   ** produces a single row of the SELECT on each invocation.  The |  | 
|   568   ** co-routine is the common header to the 3rd and 4th templates. |  | 
|   569   */ |  | 
|   570   if( pSelect ){ |  | 
|   571     /* Data is coming from a SELECT.  Generate code to implement that SELECT |  | 
|   572     ** as a co-routine.  The code is common to both the 3rd and 4th |  | 
|   573     ** templates: |  | 
|   574     ** |  | 
|   575     **         EOF <- 0 |  | 
|   576     **         X <- A |  | 
|   577     **         goto B |  | 
|   578     **      A: setup for the SELECT |  | 
|   579     **         loop over the tables in the SELECT |  | 
|   580     **           load value into register R..R+n |  | 
|   581     **           yield X |  | 
|   582     **         end loop |  | 
|   583     **         cleanup after the SELECT |  | 
|   584     **         EOF <- 1 |  | 
|   585     **         yield X |  | 
|   586     **         halt-error |  | 
|   587     ** |  | 
|   588     ** On each invocation of the co-routine, it puts a single row of the |  | 
|   589     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1. |  | 
|   590     ** (These output registers are allocated by sqlite3Select().)  When |  | 
|   591     ** the SELECT completes, it sets the EOF flag stored in regEof. |  | 
|   592     */ |  | 
|   593     int rc, j1; |  | 
|   594  |  | 
|   595     regEof = ++pParse->nMem; |  | 
|   596     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */ |  | 
|   597     VdbeComment((v, "SELECT eof flag")); |  | 
|   598     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem); |  | 
|   599     addrSelect = sqlite3VdbeCurrentAddr(v)+2; |  | 
|   600     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm); |  | 
|   601     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); |  | 
|   602     VdbeComment((v, "Jump over SELECT coroutine")); |  | 
|   603  |  | 
|   604     /* Resolve the expressions in the SELECT statement and execute it. */ |  | 
|   605     rc = sqlite3Select(pParse, pSelect, &dest); |  | 
|   606     assert( pParse->nErr==0 || rc ); |  | 
|   607     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){ |  | 
|   608       goto insert_cleanup; |  | 
|   609     } |  | 
|   610     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */ |  | 
|   611     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */ |  | 
|   612     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort); |  | 
|   613     VdbeComment((v, "End of SELECT coroutine")); |  | 
|   614     sqlite3VdbeJumpHere(v, j1);                          /* label B: */ |  | 
|   615  |  | 
|   616     regFromSelect = dest.iMem; |  | 
|   617     assert( pSelect->pEList ); |  | 
|   618     nColumn = pSelect->pEList->nExpr; |  | 
|   619     assert( dest.nMem==nColumn ); |  | 
|   620  |  | 
|   621     /* Set useTempTable to TRUE if the result of the SELECT statement |  | 
|   622     ** should be written into a temporary table (template 4).  Set to |  | 
|   623     ** FALSE if each* row of the SELECT can be written directly into |  | 
|   624     ** the destination table (template 3). |  | 
|   625     ** |  | 
|   626     ** A temp table must be used if the table being updated is also one |  | 
|   627     ** of the tables being read by the SELECT statement.  Also use a  |  | 
|   628     ** temp table in the case of row triggers. |  | 
|   629     */ |  | 
|   630     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){ |  | 
|   631       useTempTable = 1; |  | 
|   632     } |  | 
|   633  |  | 
|   634     if( useTempTable ){ |  | 
|   635       /* Invoke the coroutine to extract information from the SELECT |  | 
|   636       ** and add it to a transient table srcTab.  The code generated |  | 
|   637       ** here is from the 4th template: |  | 
|   638       ** |  | 
|   639       **      B: open temp table |  | 
|   640       **      L: yield X |  | 
|   641       **         if EOF goto M |  | 
|   642       **         insert row from R..R+n into temp table |  | 
|   643       **         goto L |  | 
|   644       **      M: ... |  | 
|   645       */ |  | 
|   646       int regRec;          /* Register to hold packed record */ |  | 
|   647       int regTempRowid;    /* Register to hold temp table ROWID */ |  | 
|   648       int addrTop;         /* Label "L" */ |  | 
|   649       int addrIf;          /* Address of jump to M */ |  | 
|   650  |  | 
|   651       srcTab = pParse->nTab++; |  | 
|   652       regRec = sqlite3GetTempReg(pParse); |  | 
|   653       regTempRowid = sqlite3GetTempReg(pParse); |  | 
|   654       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); |  | 
|   655       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); |  | 
|   656       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof); |  | 
|   657       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); |  | 
|   658       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); |  | 
|   659       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); |  | 
|   660       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop); |  | 
|   661       sqlite3VdbeJumpHere(v, addrIf); |  | 
|   662       sqlite3ReleaseTempReg(pParse, regRec); |  | 
|   663       sqlite3ReleaseTempReg(pParse, regTempRowid); |  | 
|   664     } |  | 
|   665   }else{ |  | 
|   666     /* This is the case if the data for the INSERT is coming from a VALUES |  | 
|   667     ** clause |  | 
|   668     */ |  | 
|   669     NameContext sNC; |  | 
|   670     memset(&sNC, 0, sizeof(sNC)); |  | 
|   671     sNC.pParse = pParse; |  | 
|   672     srcTab = -1; |  | 
|   673     assert( useTempTable==0 ); |  | 
|   674     nColumn = pList ? pList->nExpr : 0; |  | 
|   675     for(i=0; i<nColumn; i++){ |  | 
|   676       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){ |  | 
|   677         goto insert_cleanup; |  | 
|   678       } |  | 
|   679     } |  | 
|   680   } |  | 
|   681  |  | 
|   682   /* Make sure the number of columns in the source data matches the number |  | 
|   683   ** of columns to be inserted into the table. |  | 
|   684   */ |  | 
|   685   if( IsVirtual(pTab) ){ |  | 
|   686     for(i=0; i<pTab->nCol; i++){ |  | 
|   687       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); |  | 
|   688     } |  | 
|   689   } |  | 
|   690   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ |  | 
|   691     sqlite3ErrorMsg(pParse,  |  | 
|   692        "table %S has %d columns but %d values were supplied", |  | 
|   693        pTabList, 0, pTab->nCol-nHidden, nColumn); |  | 
|   694     goto insert_cleanup; |  | 
|   695   } |  | 
|   696   if( pColumn!=0 && nColumn!=pColumn->nId ){ |  | 
|   697     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); |  | 
|   698     goto insert_cleanup; |  | 
|   699   } |  | 
|   700  |  | 
|   701   /* If the INSERT statement included an IDLIST term, then make sure |  | 
|   702   ** all elements of the IDLIST really are columns of the table and  |  | 
|   703   ** remember the column indices. |  | 
|   704   ** |  | 
|   705   ** If the table has an INTEGER PRIMARY KEY column and that column |  | 
|   706   ** is named in the IDLIST, then record in the keyColumn variable |  | 
|   707   ** the index into IDLIST of the primary key column.  keyColumn is |  | 
|   708   ** the index of the primary key as it appears in IDLIST, not as |  | 
|   709   ** is appears in the original table.  (The index of the primary |  | 
|   710   ** key in the original table is pTab->iPKey.) |  | 
|   711   */ |  | 
|   712   if( pColumn ){ |  | 
|   713     for(i=0; i<pColumn->nId; i++){ |  | 
|   714       pColumn->a[i].idx = -1; |  | 
|   715     } |  | 
|   716     for(i=0; i<pColumn->nId; i++){ |  | 
|   717       for(j=0; j<pTab->nCol; j++){ |  | 
|   718         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ |  | 
|   719           pColumn->a[i].idx = j; |  | 
|   720           if( j==pTab->iPKey ){ |  | 
|   721             keyColumn = i; |  | 
|   722           } |  | 
|   723           break; |  | 
|   724         } |  | 
|   725       } |  | 
|   726       if( j>=pTab->nCol ){ |  | 
|   727         if( sqlite3IsRowid(pColumn->a[i].zName) ){ |  | 
|   728           keyColumn = i; |  | 
|   729         }else{ |  | 
|   730           sqlite3ErrorMsg(pParse, "table %S has no column named %s", |  | 
|   731               pTabList, 0, pColumn->a[i].zName); |  | 
|   732           pParse->nErr++; |  | 
|   733           goto insert_cleanup; |  | 
|   734         } |  | 
|   735       } |  | 
|   736     } |  | 
|   737   } |  | 
|   738  |  | 
|   739   /* If there is no IDLIST term but the table has an integer primary |  | 
|   740   ** key, the set the keyColumn variable to the primary key column index |  | 
|   741   ** in the original table definition. |  | 
|   742   */ |  | 
|   743   if( pColumn==0 && nColumn>0 ){ |  | 
|   744     keyColumn = pTab->iPKey; |  | 
|   745   } |  | 
|   746      |  | 
|   747   /* Initialize the count of rows to be inserted |  | 
|   748   */ |  | 
|   749   if( db->flags & SQLITE_CountRows ){ |  | 
|   750     regRowCount = ++pParse->nMem; |  | 
|   751     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); |  | 
|   752   } |  | 
|   753  |  | 
|   754   /* If this is not a view, open the table and and all indices */ |  | 
|   755   if( !isView ){ |  | 
|   756     int nIdx; |  | 
|   757  |  | 
|   758     baseCur = pParse->nTab; |  | 
|   759     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite); |  | 
|   760     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); |  | 
|   761     if( aRegIdx==0 ){ |  | 
|   762       goto insert_cleanup; |  | 
|   763     } |  | 
|   764     for(i=0; i<nIdx; i++){ |  | 
|   765       aRegIdx[i] = ++pParse->nMem; |  | 
|   766     } |  | 
|   767   } |  | 
|   768  |  | 
|   769   /* This is the top of the main insertion loop */ |  | 
|   770   if( useTempTable ){ |  | 
|   771     /* This block codes the top of loop only.  The complete loop is the |  | 
|   772     ** following pseudocode (template 4): |  | 
|   773     ** |  | 
|   774     **         rewind temp table |  | 
|   775     **      C: loop over rows of intermediate table |  | 
|   776     **           transfer values form intermediate table into <table> |  | 
|   777     **         end loop |  | 
|   778     **      D: ... |  | 
|   779     */ |  | 
|   780     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); |  | 
|   781     addrCont = sqlite3VdbeCurrentAddr(v); |  | 
|   782   }else if( pSelect ){ |  | 
|   783     /* This block codes the top of loop only.  The complete loop is the |  | 
|   784     ** following pseudocode (template 3): |  | 
|   785     ** |  | 
|   786     **      C: yield X |  | 
|   787     **         if EOF goto D |  | 
|   788     **         insert the select result into <table> from R..R+n |  | 
|   789     **         goto C |  | 
|   790     **      D: ... |  | 
|   791     */ |  | 
|   792     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); |  | 
|   793     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof); |  | 
|   794   } |  | 
|   795  |  | 
|   796   /* Allocate registers for holding the rowid of the new row, |  | 
|   797   ** the content of the new row, and the assemblied row record. |  | 
|   798   */ |  | 
|   799   regRecord = ++pParse->nMem; |  | 
|   800   regRowid = regIns = pParse->nMem+1; |  | 
|   801   pParse->nMem += pTab->nCol + 1; |  | 
|   802   if( IsVirtual(pTab) ){ |  | 
|   803     regRowid++; |  | 
|   804     pParse->nMem++; |  | 
|   805   } |  | 
|   806   regData = regRowid+1; |  | 
|   807  |  | 
|   808   /* Run the BEFORE and INSTEAD OF triggers, if there are any |  | 
|   809   */ |  | 
|   810   endOfLoop = sqlite3VdbeMakeLabel(v); |  | 
|   811   if( tmask & TRIGGER_BEFORE ){ |  | 
|   812     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); |  | 
|   813  |  | 
|   814     /* build the NEW.* reference row.  Note that if there is an INTEGER |  | 
|   815     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be |  | 
|   816     ** translated into a unique ID for the row.  But on a BEFORE trigger, |  | 
|   817     ** we do not know what the unique ID will be (because the insert has |  | 
|   818     ** not happened yet) so we substitute a rowid of -1 |  | 
|   819     */ |  | 
|   820     if( keyColumn<0 ){ |  | 
|   821       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); |  | 
|   822     }else{ |  | 
|   823       int j1; |  | 
|   824       if( useTempTable ){ |  | 
|   825         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols); |  | 
|   826       }else{ |  | 
|   827         assert( pSelect==0 );  /* Otherwise useTempTable is true */ |  | 
|   828         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols); |  | 
|   829       } |  | 
|   830       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); |  | 
|   831       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); |  | 
|   832       sqlite3VdbeJumpHere(v, j1); |  | 
|   833       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); |  | 
|   834     } |  | 
|   835  |  | 
|   836     /* Cannot have triggers on a virtual table. If it were possible, |  | 
|   837     ** this block would have to account for hidden column. |  | 
|   838     */ |  | 
|   839     assert( !IsVirtual(pTab) ); |  | 
|   840  |  | 
|   841     /* Create the new column data |  | 
|   842     */ |  | 
|   843     for(i=0; i<pTab->nCol; i++){ |  | 
|   844       if( pColumn==0 ){ |  | 
|   845         j = i; |  | 
|   846       }else{ |  | 
|   847         for(j=0; j<pColumn->nId; j++){ |  | 
|   848           if( pColumn->a[j].idx==i ) break; |  | 
|   849         } |  | 
|   850       } |  | 
|   851       if( pColumn && j>=pColumn->nId ){ |  | 
|   852         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1); |  | 
|   853       }else if( useTempTable ){ |  | 
|   854         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);  |  | 
|   855       }else{ |  | 
|   856         assert( pSelect==0 ); /* Otherwise useTempTable is true */ |  | 
|   857         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); |  | 
|   858       } |  | 
|   859     } |  | 
|   860  |  | 
|   861     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, |  | 
|   862     ** do not attempt any conversions before assembling the record. |  | 
|   863     ** If this is a real table, attempt conversions as required by the |  | 
|   864     ** table column affinities. |  | 
|   865     */ |  | 
|   866     if( !isView ){ |  | 
|   867       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol); |  | 
|   868       sqlite3TableAffinityStr(v, pTab); |  | 
|   869     } |  | 
|   870  |  | 
|   871     /* Fire BEFORE or INSTEAD OF triggers */ |  | 
|   872     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,  |  | 
|   873         pTab, -1, regCols-pTab->nCol-1, onError, endOfLoop); |  | 
|   874  |  | 
|   875     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); |  | 
|   876   } |  | 
|   877  |  | 
|   878   /* Push the record number for the new entry onto the stack.  The |  | 
|   879   ** record number is a randomly generate integer created by NewRowid |  | 
|   880   ** except when the table has an INTEGER PRIMARY KEY column, in which |  | 
|   881   ** case the record number is the same as that column.  |  | 
|   882   */ |  | 
|   883   if( !isView ){ |  | 
|   884     if( IsVirtual(pTab) ){ |  | 
|   885       /* The row that the VUpdate opcode will delete: none */ |  | 
|   886       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); |  | 
|   887     } |  | 
|   888     if( keyColumn>=0 ){ |  | 
|   889       if( useTempTable ){ |  | 
|   890         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); |  | 
|   891       }else if( pSelect ){ |  | 
|   892         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid); |  | 
|   893       }else{ |  | 
|   894         VdbeOp *pOp; |  | 
|   895         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); |  | 
|   896         pOp = sqlite3VdbeGetOp(v, -1); |  | 
|   897         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ |  | 
|   898           appendFlag = 1; |  | 
|   899           pOp->opcode = OP_NewRowid; |  | 
|   900           pOp->p1 = baseCur; |  | 
|   901           pOp->p2 = regRowid; |  | 
|   902           pOp->p3 = regAutoinc; |  | 
|   903         } |  | 
|   904       } |  | 
|   905       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid |  | 
|   906       ** to generate a unique primary key value. |  | 
|   907       */ |  | 
|   908       if( !appendFlag ){ |  | 
|   909         int j1; |  | 
|   910         if( !IsVirtual(pTab) ){ |  | 
|   911           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); |  | 
|   912           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); |  | 
|   913           sqlite3VdbeJumpHere(v, j1); |  | 
|   914         }else{ |  | 
|   915           j1 = sqlite3VdbeCurrentAddr(v); |  | 
|   916           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); |  | 
|   917         } |  | 
|   918         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); |  | 
|   919       } |  | 
|   920     }else if( IsVirtual(pTab) ){ |  | 
|   921       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); |  | 
|   922     }else{ |  | 
|   923       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); |  | 
|   924       appendFlag = 1; |  | 
|   925     } |  | 
|   926     autoIncStep(pParse, regAutoinc, regRowid); |  | 
|   927  |  | 
|   928     /* Push onto the stack, data for all columns of the new entry, beginning |  | 
|   929     ** with the first column. |  | 
|   930     */ |  | 
|   931     nHidden = 0; |  | 
|   932     for(i=0; i<pTab->nCol; i++){ |  | 
|   933       int iRegStore = regRowid+1+i; |  | 
|   934       if( i==pTab->iPKey ){ |  | 
|   935         /* The value of the INTEGER PRIMARY KEY column is always a NULL. |  | 
|   936         ** Whenever this column is read, the record number will be substituted |  | 
|   937         ** in its place.  So will fill this column with a NULL to avoid |  | 
|   938         ** taking up data space with information that will never be used. */ |  | 
|   939         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore); |  | 
|   940         continue; |  | 
|   941       } |  | 
|   942       if( pColumn==0 ){ |  | 
|   943         if( IsHiddenColumn(&pTab->aCol[i]) ){ |  | 
|   944           assert( IsVirtual(pTab) ); |  | 
|   945           j = -1; |  | 
|   946           nHidden++; |  | 
|   947         }else{ |  | 
|   948           j = i - nHidden; |  | 
|   949         } |  | 
|   950       }else{ |  | 
|   951         for(j=0; j<pColumn->nId; j++){ |  | 
|   952           if( pColumn->a[j].idx==i ) break; |  | 
|   953         } |  | 
|   954       } |  | 
|   955       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ |  | 
|   956         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore); |  | 
|   957       }else if( useTempTable ){ |  | 
|   958         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);  |  | 
|   959       }else if( pSelect ){ |  | 
|   960         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); |  | 
|   961       }else{ |  | 
|   962         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); |  | 
|   963       } |  | 
|   964     } |  | 
|   965  |  | 
|   966     /* Generate code to check constraints and generate index keys and |  | 
|   967     ** do the insertion. |  | 
|   968     */ |  | 
|   969 #ifndef SQLITE_OMIT_VIRTUALTABLE |  | 
|   970     if( IsVirtual(pTab) ){ |  | 
|   971       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); |  | 
|   972       sqlite3VtabMakeWritable(pParse, pTab); |  | 
|   973       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); |  | 
|   974       sqlite3MayAbort(pParse); |  | 
|   975     }else |  | 
|   976 #endif |  | 
|   977     { |  | 
|   978       int isReplace;    /* Set to true if constraints may cause a replace */ |  | 
|   979       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx, |  | 
|   980           keyColumn>=0, 0, onError, endOfLoop, &isReplace |  | 
|   981       ); |  | 
|   982       sqlite3CompleteInsertion( |  | 
|   983           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0 |  | 
|   984       ); |  | 
|   985     } |  | 
|   986   } |  | 
|   987  |  | 
|   988   /* Update the count of rows that are inserted |  | 
|   989   */ |  | 
|   990   if( (db->flags & SQLITE_CountRows)!=0 ){ |  | 
|   991     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); |  | 
|   992   } |  | 
|   993  |  | 
|   994   if( pTrigger ){ |  | 
|   995     /* Code AFTER triggers */ |  | 
|   996     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,  |  | 
|   997         pTab, -1, regData-2-pTab->nCol, onError, endOfLoop); |  | 
|   998   } |  | 
|   999  |  | 
|  1000   /* The bottom of the main insertion loop, if the data source |  | 
|  1001   ** is a SELECT statement. |  | 
|  1002   */ |  | 
|  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); |  | 
|  1011   } |  | 
|  1012  |  | 
|  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); |  | 
|  1018     } |  | 
|  1019   } |  | 
|  1020  |  | 
|  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. |  | 
|  1025   */ |  | 
|  1026   if( pParse->nested==0 && pParse->pTriggerTab==0 ){ |  | 
|  1027     sqlite3AutoincrementEnd(pParse); |  | 
|  1028   } |  | 
|  1029  |  | 
|  1030   /* |  | 
|  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. |  | 
|  1034   */ |  | 
|  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); |  | 
|  1039   } |  | 
|  1040  |  | 
|  1041 insert_cleanup: |  | 
|  1042   sqlite3SrcListDelete(db, pTabList); |  | 
|  1043   sqlite3ExprListDelete(db, pList); |  | 
|  1044   sqlite3SelectDelete(db, pSelect); |  | 
|  1045   sqlite3IdListDelete(db, pColumn); |  | 
|  1046   sqlite3DbFree(db, aRegIdx); |  | 
|  1047 } |  | 
|  1048  |  | 
|  1049 /* |  | 
|  1050 ** Generate code to do constraint checks prior to an INSERT or an UPDATE. |  | 
|  1051 ** |  | 
|  1052 ** The input is a range of consecutive registers as follows: |  | 
|  1053 ** |  | 
|  1054 **    1.  The rowid of the row after the update. |  | 
|  1055 ** |  | 
|  1056 **    2.  The data in the first column of the entry after the update. |  | 
|  1057 ** |  | 
|  1058 **    i.  Data from middle columns... |  | 
|  1059 ** |  | 
|  1060 **    N.  The data in the last column of the entry after the update. |  | 
|  1061 ** |  | 
|  1062 ** The regRowid parameter is the index of the register containing (1). |  | 
|  1063 ** |  | 
|  1064 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains |  | 
|  1065 ** the address of a register containing the rowid before the update takes |  | 
|  1066 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate |  | 
|  1067 ** is false, indicating an INSERT statement, then a non-zero rowidChng  |  | 
|  1068 ** indicates that the rowid was explicitly specified as part of the |  | 
|  1069 ** INSERT statement. If rowidChng is false, it means that  the rowid is |  | 
|  1070 ** computed automatically in an insert or that the rowid value is not  |  | 
|  1071 ** modified by an update. |  | 
|  1072 ** |  | 
|  1073 ** The code generated by this routine store new index entries into |  | 
|  1074 ** registers identified by aRegIdx[].  No index entry is created for |  | 
|  1075 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is |  | 
|  1076 ** the same as the order of indices on the linked list of indices |  | 
|  1077 ** attached to the table. |  | 
|  1078 ** |  | 
|  1079 ** This routine also generates code to check constraints.  NOT NULL, |  | 
|  1080 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails, |  | 
|  1081 ** then the appropriate action is performed.  There are five possible |  | 
|  1082 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. |  | 
|  1083 ** |  | 
|  1084 **  Constraint type  Action       What Happens |  | 
|  1085 **  ---------------  ----------   ---------------------------------------- |  | 
|  1086 **  any              ROLLBACK     The current transaction is rolled back and |  | 
|  1087 **                                sqlite3_exec() returns immediately with a |  | 
|  1088 **                                return code of SQLITE_CONSTRAINT. |  | 
|  1089 ** |  | 
|  1090 **  any              ABORT        Back out changes from the current command |  | 
|  1091 **                                only (do not do a complete rollback) then |  | 
|  1092 **                                cause sqlite3_exec() to return immediately |  | 
|  1093 **                                with SQLITE_CONSTRAINT. |  | 
|  1094 ** |  | 
|  1095 **  any              FAIL         Sqlite_exec() returns immediately with a |  | 
|  1096 **                                return code of SQLITE_CONSTRAINT.  The |  | 
|  1097 **                                transaction is not rolled back and any |  | 
|  1098 **                                prior changes are retained. |  | 
|  1099 ** |  | 
|  1100 **  any              IGNORE       The record number and data is popped from |  | 
|  1101 **                                the stack and there is an immediate jump |  | 
|  1102 **                                to label ignoreDest. |  | 
|  1103 ** |  | 
|  1104 **  NOT NULL         REPLACE      The NULL value is replace by the default |  | 
|  1105 **                                value for that column.  If the default value |  | 
|  1106 **                                is NULL, the action is the same as ABORT. |  | 
|  1107 ** |  | 
|  1108 **  UNIQUE           REPLACE      The other row that conflicts with the row |  | 
|  1109 **                                being inserted is removed. |  | 
|  1110 ** |  | 
|  1111 **  CHECK            REPLACE      Illegal.  The results in an exception. |  | 
|  1112 ** |  | 
|  1113 ** Which action to take is determined by the overrideError parameter. |  | 
|  1114 ** Or if overrideError==OE_Default, then the pParse->onError parameter |  | 
|  1115 ** is used.  Or if pParse->onError==OE_Default then the onError value |  | 
|  1116 ** for the constraint is used. |  | 
|  1117 ** |  | 
|  1118 ** The calling routine must open a read/write cursor for pTab with |  | 
|  1119 ** cursor number "baseCur".  All indices of pTab must also have open |  | 
|  1120 ** read/write cursors with cursor number baseCur+i for the i-th cursor. |  | 
|  1121 ** Except, if there is no possibility of a REPLACE action then |  | 
|  1122 ** cursors do not need to be open for indices where aRegIdx[i]==0. |  | 
|  1123 */ |  | 
|  1124 void sqlite3GenerateConstraintChecks( |  | 
|  1125   Parse *pParse,      /* The parser context */ |  | 
|  1126   Table *pTab,        /* the table into which we are inserting */ |  | 
|  1127   int baseCur,        /* Index of a read/write cursor pointing at pTab */ |  | 
|  1128   int regRowid,       /* Index of the range of input registers */ |  | 
|  1129   int *aRegIdx,       /* Register used by each index.  0 for unused indices */ |  | 
|  1130   int rowidChng,      /* True if the rowid might collide with existing entry */ |  | 
|  1131   int isUpdate,       /* True for UPDATE, False for INSERT */ |  | 
|  1132   int overrideError,  /* Override onError to this if not OE_Default */ |  | 
|  1133   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */ |  | 
|  1134   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */ |  | 
|  1135 ){ |  | 
|  1136   int i;              /* loop counter */ |  | 
|  1137   Vdbe *v;            /* VDBE under constrution */ |  | 
|  1138   int nCol;           /* Number of columns */ |  | 
|  1139   int onError;        /* Conflict resolution strategy */ |  | 
|  1140   int j1;             /* Addresss of jump instruction */ |  | 
|  1141   int j2 = 0, j3;     /* Addresses of jump instructions */ |  | 
|  1142   int regData;        /* Register containing first data column */ |  | 
|  1143   int iCur;           /* Table cursor number */ |  | 
|  1144   Index *pIdx;         /* Pointer to one of the indices */ |  | 
|  1145   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ |  | 
|  1146   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid; |  | 
|  1147  |  | 
|  1148   v = sqlite3GetVdbe(pParse); |  | 
|  1149   assert( v!=0 ); |  | 
|  1150   assert( pTab->pSelect==0 );  /* This table is not a VIEW */ |  | 
|  1151   nCol = pTab->nCol; |  | 
|  1152   regData = regRowid + 1; |  | 
|  1153  |  | 
|  1154   /* Test all NOT NULL constraints. |  | 
|  1155   */ |  | 
|  1156   for(i=0; i<nCol; i++){ |  | 
|  1157     if( i==pTab->iPKey ){ |  | 
|  1158       continue; |  | 
|  1159     } |  | 
|  1160     onError = pTab->aCol[i].notNull; |  | 
|  1161     if( onError==OE_None ) continue; |  | 
|  1162     if( overrideError!=OE_Default ){ |  | 
|  1163       onError = overrideError; |  | 
|  1164     }else if( onError==OE_Default ){ |  | 
|  1165       onError = OE_Abort; |  | 
|  1166     } |  | 
|  1167     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ |  | 
|  1168       onError = OE_Abort; |  | 
|  1169     } |  | 
|  1170     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail |  | 
|  1171         || onError==OE_Ignore || onError==OE_Replace ); |  | 
|  1172     switch( onError ){ |  | 
|  1173       case OE_Abort: |  | 
|  1174         sqlite3MayAbort(pParse); |  | 
|  1175       case OE_Rollback: |  | 
|  1176       case OE_Fail: { |  | 
|  1177         char *zMsg; |  | 
|  1178         j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull, |  | 
|  1179                                   SQLITE_CONSTRAINT, onError, regData+i); |  | 
|  1180         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL", |  | 
|  1181                               pTab->zName, pTab->aCol[i].zName); |  | 
|  1182         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC); |  | 
|  1183         break; |  | 
|  1184       } |  | 
|  1185       case OE_Ignore: { |  | 
|  1186         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest); |  | 
|  1187         break; |  | 
|  1188       } |  | 
|  1189       default: { |  | 
|  1190         assert( onError==OE_Replace ); |  | 
|  1191         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i); |  | 
|  1192         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i); |  | 
|  1193         sqlite3VdbeJumpHere(v, j1); |  | 
|  1194         break; |  | 
|  1195       } |  | 
|  1196     } |  | 
|  1197   } |  | 
|  1198  |  | 
|  1199   /* Test all CHECK constraints |  | 
|  1200   */ |  | 
|  1201 #ifndef SQLITE_OMIT_CHECK |  | 
|  1202   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){ |  | 
|  1203     int allOk = sqlite3VdbeMakeLabel(v); |  | 
|  1204     pParse->ckBase = regData; |  | 
|  1205     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL); |  | 
|  1206     onError = overrideError!=OE_Default ? overrideError : OE_Abort; |  | 
|  1207     if( onError==OE_Ignore ){ |  | 
|  1208       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); |  | 
|  1209     }else{ |  | 
|  1210       sqlite3HaltConstraint(pParse, onError, 0, 0); |  | 
|  1211     } |  | 
|  1212     sqlite3VdbeResolveLabel(v, allOk); |  | 
|  1213   } |  | 
|  1214 #endif /* !defined(SQLITE_OMIT_CHECK) */ |  | 
|  1215  |  | 
|  1216   /* If we have an INTEGER PRIMARY KEY, make sure the primary key |  | 
|  1217   ** of the new record does not previously exist.  Except, if this |  | 
|  1218   ** is an UPDATE and the primary key is not changing, that is OK. |  | 
|  1219   */ |  | 
|  1220   if( rowidChng ){ |  | 
|  1221     onError = pTab->keyConf; |  | 
|  1222     if( overrideError!=OE_Default ){ |  | 
|  1223       onError = overrideError; |  | 
|  1224     }else if( onError==OE_Default ){ |  | 
|  1225       onError = OE_Abort; |  | 
|  1226     } |  | 
|  1227      |  | 
|  1228     if( onError!=OE_Replace || pTab->pIndex ){ |  | 
|  1229       if( isUpdate ){ |  | 
|  1230         j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng); |  | 
|  1231       } |  | 
|  1232       j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid); |  | 
|  1233       switch( onError ){ |  | 
|  1234         default: { |  | 
|  1235           onError = OE_Abort; |  | 
|  1236           /* Fall thru into the next case */ |  | 
|  1237         } |  | 
|  1238         case OE_Rollback: |  | 
|  1239         case OE_Abort: |  | 
|  1240         case OE_Fail: { |  | 
|  1241           sqlite3HaltConstraint( |  | 
|  1242             pParse, onError, "PRIMARY KEY must be unique", P4_STATIC); |  | 
|  1243           break; |  | 
|  1244         } |  | 
|  1245         case OE_Replace: { |  | 
|  1246           /* If there are DELETE triggers on this table and the |  | 
|  1247           ** recursive-triggers flag is set, call GenerateRowDelete() to |  | 
|  1248           ** remove the conflicting row from the the table. This will fire |  | 
|  1249           ** the triggers and remove both the table and index b-tree entries. |  | 
|  1250           ** |  | 
|  1251           ** Otherwise, if there are no triggers or the recursive-triggers |  | 
|  1252           ** flag is not set, call GenerateRowIndexDelete(). This removes |  | 
|  1253           ** the index b-tree entries only. The table b-tree entry will be  |  | 
|  1254           ** replaced by the new entry when it is inserted.  */ |  | 
|  1255           Trigger *pTrigger = 0; |  | 
|  1256           if( pParse->db->flags&SQLITE_RecTriggers ){ |  | 
|  1257             pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); |  | 
|  1258           } |  | 
|  1259           if( pTrigger ){ |  | 
|  1260             sqlite3GenerateRowDelete( |  | 
|  1261                 pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace |  | 
|  1262             ); |  | 
|  1263           }else{ |  | 
|  1264             sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0); |  | 
|  1265           } |  | 
|  1266           seenReplace = 1; |  | 
|  1267           break; |  | 
|  1268         } |  | 
|  1269         case OE_Ignore: { |  | 
|  1270           assert( seenReplace==0 ); |  | 
|  1271           sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); |  | 
|  1272           break; |  | 
|  1273         } |  | 
|  1274       } |  | 
|  1275       sqlite3VdbeJumpHere(v, j3); |  | 
|  1276       if( isUpdate ){ |  | 
|  1277         sqlite3VdbeJumpHere(v, j2); |  | 
|  1278       } |  | 
|  1279     } |  | 
|  1280   } |  | 
|  1281  |  | 
|  1282   /* Test all UNIQUE constraints by creating entries for each UNIQUE |  | 
|  1283   ** index and making sure that duplicate entries do not already exist. |  | 
|  1284   ** Add the new records to the indices as we go. |  | 
|  1285   */ |  | 
|  1286   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){ |  | 
|  1287     int regIdx; |  | 
|  1288     int regR; |  | 
|  1289  |  | 
|  1290     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */ |  | 
|  1291  |  | 
|  1292     /* Create a key for accessing the index entry */ |  | 
|  1293     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1); |  | 
|  1294     for(i=0; i<pIdx->nColumn; i++){ |  | 
|  1295       int idx = pIdx->aiColumn[i]; |  | 
|  1296       if( idx==pTab->iPKey ){ |  | 
|  1297         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); |  | 
|  1298       }else{ |  | 
|  1299         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i); |  | 
|  1300       } |  | 
|  1301     } |  | 
|  1302     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); |  | 
|  1303     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]); |  | 
|  1304     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0); |  | 
|  1305     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1); |  | 
|  1306  |  | 
|  1307     /* Find out what action to take in case there is an indexing conflict */ |  | 
|  1308     onError = pIdx->onError; |  | 
|  1309     if( onError==OE_None ){  |  | 
|  1310       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); |  | 
|  1311       continue;  /* pIdx is not a UNIQUE index */ |  | 
|  1312     } |  | 
|  1313     if( overrideError!=OE_Default ){ |  | 
|  1314       onError = overrideError; |  | 
|  1315     }else if( onError==OE_Default ){ |  | 
|  1316       onError = OE_Abort; |  | 
|  1317     } |  | 
|  1318     if( seenReplace ){ |  | 
|  1319       if( onError==OE_Ignore ) onError = OE_Replace; |  | 
|  1320       else if( onError==OE_Fail ) onError = OE_Abort; |  | 
|  1321     } |  | 
|  1322      |  | 
|  1323     /* Check to see if the new index entry will be unique */ |  | 
|  1324     regR = sqlite3GetTempReg(pParse); |  | 
|  1325     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR); |  | 
|  1326     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0, |  | 
|  1327                            regR, SQLITE_INT_TO_PTR(regIdx), |  | 
|  1328                            P4_INT32); |  | 
|  1329     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); |  | 
|  1330  |  | 
|  1331     /* Generate code that executes if the new index entry is not unique */ |  | 
|  1332     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail |  | 
|  1333         || onError==OE_Ignore || onError==OE_Replace ); |  | 
|  1334     switch( onError ){ |  | 
|  1335       case OE_Rollback: |  | 
|  1336       case OE_Abort: |  | 
|  1337       case OE_Fail: { |  | 
|  1338         int j; |  | 
|  1339         StrAccum errMsg; |  | 
|  1340         const char *zSep; |  | 
|  1341         char *zErr; |  | 
|  1342  |  | 
|  1343         sqlite3StrAccumInit(&errMsg, 0, 0, 200); |  | 
|  1344         errMsg.db = pParse->db; |  | 
|  1345         zSep = pIdx->nColumn>1 ? "columns " : "column "; |  | 
|  1346         for(j=0; j<pIdx->nColumn; j++){ |  | 
|  1347           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; |  | 
|  1348           sqlite3StrAccumAppend(&errMsg, zSep, -1); |  | 
|  1349           zSep = ", "; |  | 
|  1350           sqlite3StrAccumAppend(&errMsg, zCol, -1); |  | 
|  1351         } |  | 
|  1352         sqlite3StrAccumAppend(&errMsg, |  | 
|  1353             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1); |  | 
|  1354         zErr = sqlite3StrAccumFinish(&errMsg); |  | 
|  1355         sqlite3HaltConstraint(pParse, onError, zErr, 0); |  | 
|  1356         sqlite3DbFree(errMsg.db, zErr); |  | 
|  1357         break; |  | 
|  1358       } |  | 
|  1359       case OE_Ignore: { |  | 
|  1360         assert( seenReplace==0 ); |  | 
|  1361         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); |  | 
|  1362         break; |  | 
|  1363       } |  | 
|  1364       default: { |  | 
|  1365         Trigger *pTrigger = 0; |  | 
|  1366         assert( onError==OE_Replace ); |  | 
|  1367         if( pParse->db->flags&SQLITE_RecTriggers ){ |  | 
|  1368           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); |  | 
|  1369         } |  | 
|  1370         sqlite3GenerateRowDelete( |  | 
|  1371             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace |  | 
|  1372         ); |  | 
|  1373         seenReplace = 1; |  | 
|  1374         break; |  | 
|  1375       } |  | 
|  1376     } |  | 
|  1377     sqlite3VdbeJumpHere(v, j3); |  | 
|  1378     sqlite3ReleaseTempReg(pParse, regR); |  | 
|  1379   } |  | 
|  1380  |  | 
|  1381   if( pbMayReplace ){ |  | 
|  1382     *pbMayReplace = seenReplace; |  | 
|  1383   } |  | 
|  1384 } |  | 
|  1385  |  | 
|  1386 /* |  | 
|  1387 ** This routine generates code to finish the INSERT or UPDATE operation |  | 
|  1388 ** that was started by a prior call to sqlite3GenerateConstraintChecks. |  | 
|  1389 ** A consecutive range of registers starting at regRowid contains the |  | 
|  1390 ** rowid and the content to be inserted. |  | 
|  1391 ** |  | 
|  1392 ** The arguments to this routine should be the same as the first six |  | 
|  1393 ** arguments to sqlite3GenerateConstraintChecks. |  | 
|  1394 */ |  | 
|  1395 void sqlite3CompleteInsertion( |  | 
|  1396   Parse *pParse,      /* The parser context */ |  | 
|  1397   Table *pTab,        /* the table into which we are inserting */ |  | 
|  1398   int baseCur,        /* Index of a read/write cursor pointing at pTab */ |  | 
|  1399   int regRowid,       /* Range of content */ |  | 
|  1400   int *aRegIdx,       /* Register used by each index.  0 for unused indices */ |  | 
|  1401   int isUpdate,       /* True for UPDATE, False for INSERT */ |  | 
|  1402   int appendBias,     /* True if this is likely to be an append */ |  | 
|  1403   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ |  | 
|  1404 ){ |  | 
|  1405   int i; |  | 
|  1406   Vdbe *v; |  | 
|  1407   int nIdx; |  | 
|  1408   Index *pIdx; |  | 
|  1409   u8 pik_flags; |  | 
|  1410   int regData; |  | 
|  1411   int regRec; |  | 
|  1412  |  | 
|  1413   v = sqlite3GetVdbe(pParse); |  | 
|  1414   assert( v!=0 ); |  | 
|  1415   assert( pTab->pSelect==0 );  /* This table is not a VIEW */ |  | 
|  1416   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} |  | 
|  1417   for(i=nIdx-1; i>=0; i--){ |  | 
|  1418     if( aRegIdx[i]==0 ) continue; |  | 
|  1419     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]); |  | 
|  1420     if( useSeekResult ){ |  | 
|  1421       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); |  | 
|  1422     } |  | 
|  1423   } |  | 
|  1424   regData = regRowid + 1; |  | 
|  1425   regRec = sqlite3GetTempReg(pParse); |  | 
|  1426   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); |  | 
|  1427   sqlite3TableAffinityStr(v, pTab); |  | 
|  1428   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); |  | 
|  1429   if( pParse->nested ){ |  | 
|  1430     pik_flags = 0; |  | 
|  1431   }else{ |  | 
|  1432     pik_flags = OPFLAG_NCHANGE; |  | 
|  1433     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); |  | 
|  1434   } |  | 
|  1435   if( appendBias ){ |  | 
|  1436     pik_flags |= OPFLAG_APPEND; |  | 
|  1437   } |  | 
|  1438   if( useSeekResult ){ |  | 
|  1439     pik_flags |= OPFLAG_USESEEKRESULT; |  | 
|  1440   } |  | 
|  1441   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid); |  | 
|  1442   if( !pParse->nested ){ |  | 
|  1443     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); |  | 
|  1444   } |  | 
|  1445   sqlite3VdbeChangeP5(v, pik_flags); |  | 
|  1446 } |  | 
|  1447  |  | 
|  1448 /* |  | 
|  1449 ** Generate code that will open cursors for a table and for all |  | 
|  1450 ** indices of that table.  The "baseCur" parameter is the cursor number used |  | 
|  1451 ** for the table.  Indices are opened on subsequent cursors. |  | 
|  1452 ** |  | 
|  1453 ** Return the number of indices on the table. |  | 
|  1454 */ |  | 
|  1455 int sqlite3OpenTableAndIndices( |  | 
|  1456   Parse *pParse,   /* Parsing context */ |  | 
|  1457   Table *pTab,     /* Table to be opened */ |  | 
|  1458   int baseCur,     /* Cursor number assigned to the table */ |  | 
|  1459   int op           /* OP_OpenRead or OP_OpenWrite */ |  | 
|  1460 ){ |  | 
|  1461   int i; |  | 
|  1462   int iDb; |  | 
|  1463   Index *pIdx; |  | 
|  1464   Vdbe *v; |  | 
|  1465  |  | 
|  1466   if( IsVirtual(pTab) ) return 0; |  | 
|  1467   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); |  | 
|  1468   v = sqlite3GetVdbe(pParse); |  | 
|  1469   assert( v!=0 ); |  | 
|  1470   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op); |  | 
|  1471   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ |  | 
|  1472     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); |  | 
|  1473     assert( pIdx->pSchema==pTab->pSchema ); |  | 
|  1474     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb, |  | 
|  1475                       (char*)pKey, P4_KEYINFO_HANDOFF); |  | 
|  1476     VdbeComment((v, "%s", pIdx->zName)); |  | 
|  1477   } |  | 
|  1478   if( pParse->nTab<baseCur+i ){ |  | 
|  1479     pParse->nTab = baseCur+i; |  | 
|  1480   } |  | 
|  1481   return i-1; |  | 
|  1482 } |  | 
|  1483  |  | 
|  1484  |  | 
|  1485 #ifdef SQLITE_TEST |  | 
|  1486 /* |  | 
|  1487 ** The following global variable is incremented whenever the |  | 
|  1488 ** transfer optimization is used.  This is used for testing |  | 
|  1489 ** purposes only - to make sure the transfer optimization really |  | 
|  1490 ** is happening when it is suppose to. |  | 
|  1491 */ |  | 
|  1492 int sqlite3_xferopt_count; |  | 
|  1493 #endif /* SQLITE_TEST */ |  | 
|  1494  |  | 
|  1495  |  | 
|  1496 #ifndef SQLITE_OMIT_XFER_OPT |  | 
|  1497 /* |  | 
|  1498 ** Check to collation names to see if they are compatible. |  | 
|  1499 */ |  | 
|  1500 static int xferCompatibleCollation(const char *z1, const char *z2){ |  | 
|  1501   if( z1==0 ){ |  | 
|  1502     return z2==0; |  | 
|  1503   } |  | 
|  1504   if( z2==0 ){ |  | 
|  1505     return 0; |  | 
|  1506   } |  | 
|  1507   return sqlite3StrICmp(z1, z2)==0; |  | 
|  1508 } |  | 
|  1509  |  | 
|  1510  |  | 
|  1511 /* |  | 
|  1512 ** Check to see if index pSrc is compatible as a source of data |  | 
|  1513 ** for index pDest in an insert transfer optimization.  The rules |  | 
|  1514 ** for a compatible index: |  | 
|  1515 ** |  | 
|  1516 **    *   The index is over the same set of columns |  | 
|  1517 **    *   The same DESC and ASC markings occurs on all columns |  | 
|  1518 **    *   The same onError processing (OE_Abort, OE_Ignore, etc) |  | 
|  1519 **    *   The same collating sequence on each column |  | 
|  1520 */ |  | 
|  1521 static int xferCompatibleIndex(Index *pDest, Index *pSrc){ |  | 
|  1522   int i; |  | 
|  1523   assert( pDest && pSrc ); |  | 
|  1524   assert( pDest->pTable!=pSrc->pTable ); |  | 
|  1525   if( pDest->nColumn!=pSrc->nColumn ){ |  | 
|  1526     return 0;   /* Different number of columns */ |  | 
|  1527   } |  | 
|  1528   if( pDest->onError!=pSrc->onError ){ |  | 
|  1529     return 0;   /* Different conflict resolution strategies */ |  | 
|  1530   } |  | 
|  1531   for(i=0; i<pSrc->nColumn; i++){ |  | 
|  1532     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ |  | 
|  1533       return 0;   /* Different columns indexed */ |  | 
|  1534     } |  | 
|  1535     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ |  | 
|  1536       return 0;   /* Different sort orders */ |  | 
|  1537     } |  | 
|  1538     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){ |  | 
|  1539       return 0;   /* Different collating sequences */ |  | 
|  1540     } |  | 
|  1541   } |  | 
|  1542  |  | 
|  1543   /* If no test above fails then the indices must be compatible */ |  | 
|  1544   return 1; |  | 
|  1545 } |  | 
|  1546  |  | 
|  1547 /* |  | 
|  1548 ** Attempt the transfer optimization on INSERTs of the form |  | 
|  1549 ** |  | 
|  1550 **     INSERT INTO tab1 SELECT * FROM tab2; |  | 
|  1551 ** |  | 
|  1552 ** This optimization is only attempted if |  | 
|  1553 ** |  | 
|  1554 **    (1)  tab1 and tab2 have identical schemas including all the |  | 
|  1555 **         same indices and constraints |  | 
|  1556 ** |  | 
|  1557 **    (2)  tab1 and tab2 are different tables |  | 
|  1558 ** |  | 
|  1559 **    (3)  There must be no triggers on tab1 |  | 
|  1560 ** |  | 
|  1561 **    (4)  The result set of the SELECT statement is "*" |  | 
|  1562 ** |  | 
|  1563 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY, |  | 
|  1564 **         or LIMIT clause. |  | 
|  1565 ** |  | 
|  1566 **    (6)  The SELECT statement is a simple (not a compound) select that |  | 
|  1567 **         contains only tab2 in its FROM clause |  | 
|  1568 ** |  | 
|  1569 ** This method for implementing the INSERT transfers raw records from |  | 
|  1570 ** tab2 over to tab1.  The columns are not decoded.  Raw records from |  | 
|  1571 ** the indices of tab2 are transfered to tab1 as well.  In so doing, |  | 
|  1572 ** the resulting tab1 has much less fragmentation. |  | 
|  1573 ** |  | 
|  1574 ** This routine returns TRUE if the optimization is attempted.  If any |  | 
|  1575 ** of the conditions above fail so that the optimization should not |  | 
|  1576 ** be attempted, then this routine returns FALSE. |  | 
|  1577 */ |  | 
|  1578 static int xferOptimization( |  | 
|  1579   Parse *pParse,        /* Parser context */ |  | 
|  1580   Table *pDest,         /* The table we are inserting into */ |  | 
|  1581   Select *pSelect,      /* A SELECT statement to use as the data source */ |  | 
|  1582   int onError,          /* How to handle constraint errors */ |  | 
|  1583   int iDbDest           /* The database of pDest */ |  | 
|  1584 ){ |  | 
|  1585   ExprList *pEList;                /* The result set of the SELECT */ |  | 
|  1586   Table *pSrc;                     /* The table in the FROM clause of SELECT */ |  | 
|  1587   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */ |  | 
|  1588   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */ |  | 
|  1589   int i;                           /* Loop counter */ |  | 
|  1590   int iDbSrc;                      /* The database of pSrc */ |  | 
|  1591   int iSrc, iDest;                 /* Cursors from source and destination */ |  | 
|  1592   int addr1, addr2;                /* Loop addresses */ |  | 
|  1593   int emptyDestTest;               /* Address of test for empty pDest */ |  | 
|  1594   int emptySrcTest;                /* Address of test for empty pSrc */ |  | 
|  1595   Vdbe *v;                         /* The VDBE we are building */ |  | 
|  1596   KeyInfo *pKey;                   /* Key information for an index */ |  | 
|  1597   int regAutoinc;                  /* Memory register used by AUTOINC */ |  | 
|  1598   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */ |  | 
|  1599   int regData, regRowid;           /* Registers holding data and rowid */ |  | 
|  1600  |  | 
|  1601   if( pSelect==0 ){ |  | 
|  1602     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */ |  | 
|  1603   } |  | 
|  1604   if( sqlite3TriggerList(pParse, pDest) ){ |  | 
|  1605     return 0;   /* tab1 must not have triggers */ |  | 
|  1606   } |  | 
|  1607 #ifndef SQLITE_OMIT_VIRTUALTABLE |  | 
|  1608   if( pDest->tabFlags & TF_Virtual ){ |  | 
|  1609     return 0;   /* tab1 must not be a virtual table */ |  | 
|  1610   } |  | 
|  1611 #endif |  | 
|  1612   if( onError==OE_Default ){ |  | 
|  1613     onError = OE_Abort; |  | 
|  1614   } |  | 
|  1615   if( onError!=OE_Abort && onError!=OE_Rollback ){ |  | 
|  1616     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */ |  | 
|  1617   } |  | 
|  1618   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */ |  | 
|  1619   if( pSelect->pSrc->nSrc!=1 ){ |  | 
|  1620     return 0;   /* FROM clause must have exactly one term */ |  | 
|  1621   } |  | 
|  1622   if( pSelect->pSrc->a[0].pSelect ){ |  | 
|  1623     return 0;   /* FROM clause cannot contain a subquery */ |  | 
|  1624   } |  | 
|  1625   if( pSelect->pWhere ){ |  | 
|  1626     return 0;   /* SELECT may not have a WHERE clause */ |  | 
|  1627   } |  | 
|  1628   if( pSelect->pOrderBy ){ |  | 
|  1629     return 0;   /* SELECT may not have an ORDER BY clause */ |  | 
|  1630   } |  | 
|  1631   /* Do not need to test for a HAVING clause.  If HAVING is present but |  | 
|  1632   ** there is no ORDER BY, we will get an error. */ |  | 
|  1633   if( pSelect->pGroupBy ){ |  | 
|  1634     return 0;   /* SELECT may not have a GROUP BY clause */ |  | 
|  1635   } |  | 
|  1636   if( pSelect->pLimit ){ |  | 
|  1637     return 0;   /* SELECT may not have a LIMIT clause */ |  | 
|  1638   } |  | 
|  1639   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */ |  | 
|  1640   if( pSelect->pPrior ){ |  | 
|  1641     return 0;   /* SELECT may not be a compound query */ |  | 
|  1642   } |  | 
|  1643   if( pSelect->selFlags & SF_Distinct ){ |  | 
|  1644     return 0;   /* SELECT may not be DISTINCT */ |  | 
|  1645   } |  | 
|  1646   pEList = pSelect->pEList; |  | 
|  1647   assert( pEList!=0 ); |  | 
|  1648   if( pEList->nExpr!=1 ){ |  | 
|  1649     return 0;   /* The result set must have exactly one column */ |  | 
|  1650   } |  | 
|  1651   assert( pEList->a[0].pExpr ); |  | 
|  1652   if( pEList->a[0].pExpr->op!=TK_ALL ){ |  | 
|  1653     return 0;   /* The result set must be the special operator "*" */ |  | 
|  1654   } |  | 
|  1655  |  | 
|  1656   /* At this point we have established that the statement is of the |  | 
|  1657   ** correct syntactic form to participate in this optimization.  Now |  | 
|  1658   ** we have to check the semantics. |  | 
|  1659   */ |  | 
|  1660   pItem = pSelect->pSrc->a; |  | 
|  1661   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase); |  | 
|  1662   if( pSrc==0 ){ |  | 
|  1663     return 0;   /* FROM clause does not contain a real table */ |  | 
|  1664   } |  | 
|  1665   if( pSrc==pDest ){ |  | 
|  1666     return 0;   /* tab1 and tab2 may not be the same table */ |  | 
|  1667   } |  | 
|  1668 #ifndef SQLITE_OMIT_VIRTUALTABLE |  | 
|  1669   if( pSrc->tabFlags & TF_Virtual ){ |  | 
|  1670     return 0;   /* tab2 must not be a virtual table */ |  | 
|  1671   } |  | 
|  1672 #endif |  | 
|  1673   if( pSrc->pSelect ){ |  | 
|  1674     return 0;   /* tab2 may not be a view */ |  | 
|  1675   } |  | 
|  1676   if( pDest->nCol!=pSrc->nCol ){ |  | 
|  1677     return 0;   /* Number of columns must be the same in tab1 and tab2 */ |  | 
|  1678   } |  | 
|  1679   if( pDest->iPKey!=pSrc->iPKey ){ |  | 
|  1680     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */ |  | 
|  1681   } |  | 
|  1682   for(i=0; i<pDest->nCol; i++){ |  | 
|  1683     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){ |  | 
|  1684       return 0;    /* Affinity must be the same on all columns */ |  | 
|  1685     } |  | 
|  1686     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){ |  | 
|  1687       return 0;    /* Collating sequence must be the same on all columns */ |  | 
|  1688     } |  | 
|  1689     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){ |  | 
|  1690       return 0;    /* tab2 must be NOT NULL if tab1 is */ |  | 
|  1691     } |  | 
|  1692   } |  | 
|  1693   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ |  | 
|  1694     if( pDestIdx->onError!=OE_None ){ |  | 
|  1695       destHasUniqueIdx = 1; |  | 
|  1696     } |  | 
|  1697     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ |  | 
|  1698       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; |  | 
|  1699     } |  | 
|  1700     if( pSrcIdx==0 ){ |  | 
|  1701       return 0;    /* pDestIdx has no corresponding index in pSrc */ |  | 
|  1702     } |  | 
|  1703   } |  | 
|  1704 #ifndef SQLITE_OMIT_CHECK |  | 
|  1705   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){ |  | 
|  1706     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */ |  | 
|  1707   } |  | 
|  1708 #endif |  | 
|  1709  |  | 
|  1710   /* If we get this far, it means either: |  | 
|  1711   ** |  | 
|  1712   **    *   We can always do the transfer if the table contains an |  | 
|  1713   **        an integer primary key |  | 
|  1714   ** |  | 
|  1715   **    *   We can conditionally do the transfer if the destination |  | 
|  1716   **        table is empty. |  | 
|  1717   */ |  | 
|  1718 #ifdef SQLITE_TEST |  | 
|  1719   sqlite3_xferopt_count++; |  | 
|  1720 #endif |  | 
|  1721   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema); |  | 
|  1722   v = sqlite3GetVdbe(pParse); |  | 
|  1723   sqlite3CodeVerifySchema(pParse, iDbSrc); |  | 
|  1724   iSrc = pParse->nTab++; |  | 
|  1725   iDest = pParse->nTab++; |  | 
|  1726   regAutoinc = autoIncBegin(pParse, iDbDest, pDest); |  | 
|  1727   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); |  | 
|  1728   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){ |  | 
|  1729     /* If tables do not have an INTEGER PRIMARY KEY and there |  | 
|  1730     ** are indices to be copied and the destination is not empty, |  | 
|  1731     ** we have to disallow the transfer optimization because the |  | 
|  1732     ** the rowids might change which will mess up indexing. |  | 
|  1733     ** |  | 
|  1734     ** Or if the destination has a UNIQUE index and is not empty, |  | 
|  1735     ** we also disallow the transfer optimization because we cannot |  | 
|  1736     ** insure that all entries in the union of DEST and SRC will be |  | 
|  1737     ** unique. |  | 
|  1738     */ |  | 
|  1739     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); |  | 
|  1740     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); |  | 
|  1741     sqlite3VdbeJumpHere(v, addr1); |  | 
|  1742   }else{ |  | 
|  1743     emptyDestTest = 0; |  | 
|  1744   } |  | 
|  1745   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); |  | 
|  1746   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); |  | 
|  1747   regData = sqlite3GetTempReg(pParse); |  | 
|  1748   regRowid = sqlite3GetTempReg(pParse); |  | 
|  1749   if( pDest->iPKey>=0 ){ |  | 
|  1750     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); |  | 
|  1751     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); |  | 
|  1752     sqlite3HaltConstraint( |  | 
|  1753         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC); |  | 
|  1754     sqlite3VdbeJumpHere(v, addr2); |  | 
|  1755     autoIncStep(pParse, regAutoinc, regRowid); |  | 
|  1756   }else if( pDest->pIndex==0 ){ |  | 
|  1757     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); |  | 
|  1758   }else{ |  | 
|  1759     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); |  | 
|  1760     assert( (pDest->tabFlags & TF_Autoincrement)==0 ); |  | 
|  1761   } |  | 
|  1762   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); |  | 
|  1763   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); |  | 
|  1764   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); |  | 
|  1765   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); |  | 
|  1766   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); |  | 
|  1767   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ |  | 
|  1768     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ |  | 
|  1769       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; |  | 
|  1770     } |  | 
|  1771     assert( pSrcIdx ); |  | 
|  1772     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); |  | 
|  1773     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); |  | 
|  1774     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx); |  | 
|  1775     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc, |  | 
|  1776                       (char*)pKey, P4_KEYINFO_HANDOFF); |  | 
|  1777     VdbeComment((v, "%s", pSrcIdx->zName)); |  | 
|  1778     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx); |  | 
|  1779     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest, |  | 
|  1780                       (char*)pKey, P4_KEYINFO_HANDOFF); |  | 
|  1781     VdbeComment((v, "%s", pDestIdx->zName)); |  | 
|  1782     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); |  | 
|  1783     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); |  | 
|  1784     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); |  | 
|  1785     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); |  | 
|  1786     sqlite3VdbeJumpHere(v, addr1); |  | 
|  1787   } |  | 
|  1788   sqlite3VdbeJumpHere(v, emptySrcTest); |  | 
|  1789   sqlite3ReleaseTempReg(pParse, regRowid); |  | 
|  1790   sqlite3ReleaseTempReg(pParse, regData); |  | 
|  1791   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); |  | 
|  1792   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); |  | 
|  1793   if( emptyDestTest ){ |  | 
|  1794     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); |  | 
|  1795     sqlite3VdbeJumpHere(v, emptyDestTest); |  | 
|  1796     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); |  | 
|  1797     return 0; |  | 
|  1798   }else{ |  | 
|  1799     return 1; |  | 
|  1800   } |  | 
|  1801 } |  | 
|  1802 #endif /* SQLITE_OMIT_XFER_OPT */ |  | 
|  1803  |  | 
|  1804 /* Make sure "isView" gets undefined in case this file becomes part of |  | 
|  1805 ** the amalgamation - so that subsequent files do not see isView as a |  | 
|  1806 ** macro. */ |  | 
|  1807 #undef isView |  | 
| OLD | NEW |