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.cpp 1282 2008-11-13 09:31:33Z LarsPson $ |
|
16 */ |
|
17 #include "sqliteInt.h" |
|
18 |
|
19 /* |
|
20 ** Set P3 of the most recently inserted opcode to a column affinity |
|
21 ** string for index pIdx. A column affinity string has one character |
|
22 ** for each column in the table, according to the affinity of the column: |
|
23 ** |
|
24 ** Character Column affinity |
|
25 ** ------------------------------ |
|
26 ** 'a' TEXT |
|
27 ** 'b' NONE |
|
28 ** 'c' NUMERIC |
|
29 ** 'd' INTEGER |
|
30 ** 'e' REAL |
|
31 */ |
|
32 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ |
|
33 if( !pIdx->zColAff ){ |
|
34 /* The first time a column affinity string for a particular index is |
|
35 ** required, it is allocated and populated here. It is then stored as |
|
36 ** a member of the Index structure for subsequent use. |
|
37 ** |
|
38 ** The column affinity string will eventually be deleted by |
|
39 ** sqliteDeleteIndex() when the Index structure itself is cleaned |
|
40 ** up. |
|
41 */ |
|
42 int n; |
|
43 Table *pTab = pIdx->pTable; |
|
44 sqlite3 *db = sqlite3VdbeDb(v); |
|
45 pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+1); |
|
46 if( !pIdx->zColAff ){ |
|
47 return; |
|
48 } |
|
49 for(n=0; n<pIdx->nColumn; n++){ |
|
50 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity; |
|
51 } |
|
52 pIdx->zColAff[pIdx->nColumn] = '\0'; |
|
53 } |
|
54 |
|
55 sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0); |
|
56 } |
|
57 |
|
58 /* |
|
59 ** Set P3 of the most recently inserted opcode to a column affinity |
|
60 ** string for table pTab. A column affinity string has one character |
|
61 ** for each column indexed by the index, according to the affinity of the |
|
62 ** column: |
|
63 ** |
|
64 ** Character Column affinity |
|
65 ** ------------------------------ |
|
66 ** 'a' TEXT |
|
67 ** 'b' NONE |
|
68 ** 'c' NUMERIC |
|
69 ** 'd' INTEGER |
|
70 ** 'e' REAL |
|
71 */ |
|
72 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){ |
|
73 /* The first time a column affinity string for a particular table |
|
74 ** is required, it is allocated and populated here. It is then |
|
75 ** stored as a member of the Table structure for subsequent use. |
|
76 ** |
|
77 ** The column affinity string will eventually be deleted by |
|
78 ** sqlite3DeleteTable() when the Table structure itself is cleaned up. |
|
79 */ |
|
80 if( !pTab->zColAff ){ |
|
81 char *zColAff; |
|
82 int i; |
|
83 sqlite3 *db = sqlite3VdbeDb(v); |
|
84 |
|
85 zColAff = (char *)sqlite3DbMallocZero(db, pTab->nCol+1); |
|
86 if( !zColAff ){ |
|
87 return; |
|
88 } |
|
89 |
|
90 for(i=0; i<pTab->nCol; i++){ |
|
91 zColAff[i] = pTab->aCol[i].affinity; |
|
92 } |
|
93 zColAff[pTab->nCol] = '\0'; |
|
94 |
|
95 pTab->zColAff = zColAff; |
|
96 } |
|
97 |
|
98 sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0); |
|
99 } |
|
100 |
|
101 /* |
|
102 ** Return non-zero if the table pTab in database iDb or any of its indices |
|
103 ** have been opened at any point in the VDBE program beginning at location |
|
104 ** iStartAddr throught the end of the program. This is used to see if |
|
105 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can |
|
106 ** run without using temporary table for the results of the SELECT. |
|
107 */ |
|
108 static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){ |
|
109 int i; |
|
110 int iEnd = sqlite3VdbeCurrentAddr(v); |
|
111 for(i=iStartAddr; i<iEnd; i++){ |
|
112 VdbeOp *pOp = sqlite3VdbeGetOp(v, i); |
|
113 assert( pOp!=0 ); |
|
114 if( pOp->opcode==OP_OpenRead ){ |
|
115 VdbeOp *pPrior = &pOp[-1]; |
|
116 int tnum = pOp->p2; |
|
117 assert( i>iStartAddr ); |
|
118 assert( pPrior->opcode==OP_Integer ); |
|
119 if( pPrior->p1==iDb ){ |
|
120 Index *pIndex; |
|
121 if( tnum==pTab->tnum ){ |
|
122 return 1; |
|
123 } |
|
124 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ |
|
125 if( tnum==pIndex->tnum ){ |
|
126 return 1; |
|
127 } |
|
128 } |
|
129 } |
|
130 } |
|
131 #ifndef SQLITE_OMIT_VIRTUALTABLE |
|
132 if( pOp->opcode==OP_VOpen && pOp->p3==(const char*)pTab->pVtab ){ |
|
133 assert( pOp->p3!=0 ); |
|
134 assert( pOp->p3type==P3_VTAB ); |
|
135 return 1; |
|
136 } |
|
137 #endif |
|
138 } |
|
139 return 0; |
|
140 } |
|
141 |
|
142 #ifndef SQLITE_OMIT_AUTOINCREMENT |
|
143 /* |
|
144 ** Write out code to initialize the autoincrement logic. This code |
|
145 ** looks up the current autoincrement value in the sqlite_sequence |
|
146 ** table and stores that value in a memory cell. Code generated by |
|
147 ** autoIncStep() will keep that memory cell holding the largest |
|
148 ** rowid value. Code generated by autoIncEnd() will write the new |
|
149 ** largest value of the counter back into the sqlite_sequence table. |
|
150 ** |
|
151 ** This routine returns the index of the mem[] cell that contains |
|
152 ** the maximum rowid counter. |
|
153 ** |
|
154 ** Two memory cells are allocated. The next memory cell after the |
|
155 ** one returned holds the rowid in sqlite_sequence where we will |
|
156 ** write back the revised maximum rowid. |
|
157 */ |
|
158 static int autoIncBegin( |
|
159 Parse *pParse, /* Parsing context */ |
|
160 int iDb, /* Index of the database holding pTab */ |
|
161 Table *pTab /* The table we are writing to */ |
|
162 ){ |
|
163 int memId = 0; |
|
164 if( pTab->autoInc ){ |
|
165 Vdbe *v = pParse->pVdbe; |
|
166 Db *pDb = &pParse->db->aDb[iDb]; |
|
167 int iCur = pParse->nTab; |
|
168 int addr; |
|
169 assert( v ); |
|
170 addr = sqlite3VdbeCurrentAddr(v); |
|
171 memId = pParse->nMem+1; |
|
172 pParse->nMem += 2; |
|
173 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead); |
|
174 sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13); |
|
175 sqlite3VdbeAddOp(v, OP_Column, iCur, 0); |
|
176 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0); |
|
177 sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12); |
|
178 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0); |
|
179 sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1); |
|
180 sqlite3VdbeAddOp(v, OP_Column, iCur, 1); |
|
181 sqlite3VdbeAddOp(v, OP_MemStore, memId, 1); |
|
182 sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13); |
|
183 sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4); |
|
184 sqlite3VdbeAddOp(v, OP_Close, iCur, 0); |
|
185 } |
|
186 return memId; |
|
187 } |
|
188 |
|
189 /* |
|
190 ** Update the maximum rowid for an autoincrement calculation. |
|
191 ** |
|
192 ** This routine should be called when the top of the stack holds a |
|
193 ** new rowid that is about to be inserted. If that new rowid is |
|
194 ** larger than the maximum rowid in the memId memory cell, then the |
|
195 ** memory cell is updated. The stack is unchanged. |
|
196 */ |
|
197 static void autoIncStep(Parse *pParse, int memId){ |
|
198 if( memId>0 ){ |
|
199 sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0); |
|
200 } |
|
201 } |
|
202 |
|
203 /* |
|
204 ** After doing one or more inserts, the maximum rowid is stored |
|
205 ** in mem[memId]. Generate code to write this value back into the |
|
206 ** the sqlite_sequence table. |
|
207 */ |
|
208 static void autoIncEnd( |
|
209 Parse *pParse, /* The parsing context */ |
|
210 int iDb, /* Index of the database holding pTab */ |
|
211 Table *pTab, /* Table we are inserting into */ |
|
212 int memId /* Memory cell holding the maximum rowid */ |
|
213 ){ |
|
214 if( pTab->autoInc ){ |
|
215 int iCur = pParse->nTab; |
|
216 Vdbe *v = pParse->pVdbe; |
|
217 Db *pDb = &pParse->db->aDb[iDb]; |
|
218 int addr; |
|
219 assert( v ); |
|
220 addr = sqlite3VdbeCurrentAddr(v); |
|
221 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); |
|
222 sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0); |
|
223 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7); |
|
224 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); |
|
225 sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0); |
|
226 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0); |
|
227 sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0); |
|
228 sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0); |
|
229 sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND); |
|
230 sqlite3VdbeAddOp(v, OP_Close, iCur, 0); |
|
231 } |
|
232 } |
|
233 #else |
|
234 /* |
|
235 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines |
|
236 ** above are all no-ops |
|
237 */ |
|
238 # define autoIncBegin(A,B,C) (0) |
|
239 # define autoIncStep(A,B) |
|
240 # define autoIncEnd(A,B,C,D) |
|
241 #endif /* SQLITE_OMIT_AUTOINCREMENT */ |
|
242 |
|
243 |
|
244 /* Forward declaration */ |
|
245 static int xferOptimization( |
|
246 Parse *pParse, /* Parser context */ |
|
247 Table *pDest, /* The table we are inserting into */ |
|
248 Select *pSelect, /* A SELECT statement to use as the data source */ |
|
249 int onError, /* How to handle constraint errors */ |
|
250 int iDbDest /* The database of pDest */ |
|
251 ); |
|
252 |
|
253 /* |
|
254 ** This routine is call to handle SQL of the following forms: |
|
255 ** |
|
256 ** insert into TABLE (IDLIST) values(EXPRLIST) |
|
257 ** insert into TABLE (IDLIST) select |
|
258 ** |
|
259 ** The IDLIST following the table name is always optional. If omitted, |
|
260 ** then a list of all columns for the table is substituted. The IDLIST |
|
261 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted. |
|
262 ** |
|
263 ** The pList parameter holds EXPRLIST in the first form of the INSERT |
|
264 ** statement above, and pSelect is NULL. For the second form, pList is |
|
265 ** NULL and pSelect is a pointer to the select statement used to generate |
|
266 ** data for the insert. |
|
267 ** |
|
268 ** The code generated follows one of four templates. For a simple |
|
269 ** select with data coming from a VALUES clause, the code executes |
|
270 ** once straight down through. The template looks like this: |
|
271 ** |
|
272 ** open write cursor to <table> and its indices |
|
273 ** puts VALUES clause expressions onto the stack |
|
274 ** write the resulting record into <table> |
|
275 ** cleanup |
|
276 ** |
|
277 ** The three remaining templates assume the statement is of the form |
|
278 ** |
|
279 ** INSERT INTO <table> SELECT ... |
|
280 ** |
|
281 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - |
|
282 ** in other words if the SELECT pulls all columns from a single table |
|
283 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and |
|
284 ** if <table2> and <table1> are distinct tables but have identical |
|
285 ** schemas, including all the same indices, then a special optimization |
|
286 ** is invoked that copies raw records from <table2> over to <table1>. |
|
287 ** See the xferOptimization() function for the implementation of this |
|
288 ** template. This is the second template. |
|
289 ** |
|
290 ** open a write cursor to <table> |
|
291 ** open read cursor on <table2> |
|
292 ** transfer all records in <table2> over to <table> |
|
293 ** close cursors |
|
294 ** foreach index on <table> |
|
295 ** open a write cursor on the <table> index |
|
296 ** open a read cursor on the corresponding <table2> index |
|
297 ** transfer all records from the read to the write cursors |
|
298 ** close cursors |
|
299 ** end foreach |
|
300 ** |
|
301 ** The third template is for when the second template does not apply |
|
302 ** and the SELECT clause does not read from <table> at any time. |
|
303 ** The generated code follows this template: |
|
304 ** |
|
305 ** goto B |
|
306 ** A: setup for the SELECT |
|
307 ** loop over the rows in the SELECT |
|
308 ** gosub C |
|
309 ** end loop |
|
310 ** cleanup after the SELECT |
|
311 ** goto D |
|
312 ** B: open write cursor to <table> and its indices |
|
313 ** goto A |
|
314 ** C: insert the select result into <table> |
|
315 ** return |
|
316 ** D: cleanup |
|
317 ** |
|
318 ** The fourth template is used if the insert statement takes its |
|
319 ** values from a SELECT but the data is being inserted into a table |
|
320 ** that is also read as part of the SELECT. In the third form, |
|
321 ** we have to use a intermediate table to store the results of |
|
322 ** the select. The template is like this: |
|
323 ** |
|
324 ** goto B |
|
325 ** A: setup for the SELECT |
|
326 ** loop over the tables in the SELECT |
|
327 ** gosub C |
|
328 ** end loop |
|
329 ** cleanup after the SELECT |
|
330 ** goto D |
|
331 ** C: insert the select result into the intermediate table |
|
332 ** return |
|
333 ** B: open a cursor to an intermediate table |
|
334 ** goto A |
|
335 ** D: open write cursor to <table> and its indices |
|
336 ** loop over the intermediate table |
|
337 ** transfer values form intermediate table into <table> |
|
338 ** end the loop |
|
339 ** cleanup |
|
340 */ |
|
341 void sqlite3Insert( |
|
342 Parse *pParse, /* Parser context */ |
|
343 SrcList *pTabList, /* Name of table into which we are inserting */ |
|
344 ExprList *pList, /* List of values to be inserted */ |
|
345 Select *pSelect, /* A SELECT statement to use as the data source */ |
|
346 IdList *pColumn, /* Column names corresponding to IDLIST. */ |
|
347 int onError /* How to handle constraint errors */ |
|
348 ){ |
|
349 Table *pTab; /* The table to insert into */ |
|
350 char *zTab; /* Name of the table into which we are inserting */ |
|
351 const char *zDb; /* Name of the database holding this table */ |
|
352 int i, j, idx; /* Loop counters */ |
|
353 Vdbe *v; /* Generate code into this virtual machine */ |
|
354 Index *pIdx; /* For looping over indices of the table */ |
|
355 int nColumn; /* Number of columns in the data */ |
|
356 int base = 0; /* VDBE Cursor number for pTab */ |
|
357 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */ |
|
358 sqlite3 *db; /* The main database structure */ |
|
359 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ |
|
360 int endOfLoop; /* Label for the end of the insertion loop */ |
|
361 int useTempTable = 0; /* Store SELECT results in intermediate table */ |
|
362 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ |
|
363 int iSelectLoop = 0; /* Address of code that implements the SELECT */ |
|
364 int iCleanup = 0; /* Address of the cleanup code */ |
|
365 int iInsertBlock = 0; /* Address of the subroutine used to insert data */ |
|
366 int iCntMem = 0; /* Memory cell used for the row counter */ |
|
367 int newIdx = -1; /* Cursor for the NEW table */ |
|
368 Db *pDb; /* The database containing table being inserted into */ |
|
369 int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */ |
|
370 int appendFlag = 0; /* True if the insert is likely to be an append */ |
|
371 int iDb; |
|
372 |
|
373 int nHidden = 0; |
|
374 |
|
375 #ifndef SQLITE_OMIT_TRIGGER |
|
376 int isView; /* True if attempting to insert into a view */ |
|
377 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */ |
|
378 #endif |
|
379 |
|
380 db = pParse->db; |
|
381 if( pParse->nErr || db->mallocFailed ){ |
|
382 goto insert_cleanup; |
|
383 } |
|
384 |
|
385 /* Locate the table into which we will be inserting new information. |
|
386 */ |
|
387 assert( pTabList->nSrc==1 ); |
|
388 zTab = pTabList->a[0].zName; |
|
389 if( zTab==0 ) goto insert_cleanup; |
|
390 pTab = sqlite3SrcListLookup(pParse, pTabList); |
|
391 if( pTab==0 ){ |
|
392 goto insert_cleanup; |
|
393 } |
|
394 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); |
|
395 assert( iDb<db->nDb ); |
|
396 pDb = &db->aDb[iDb]; |
|
397 zDb = pDb->zName; |
|
398 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ |
|
399 goto insert_cleanup; |
|
400 } |
|
401 |
|
402 /* Figure out if we have any triggers and if the table being |
|
403 ** inserted into is a view |
|
404 */ |
|
405 #ifndef SQLITE_OMIT_TRIGGER |
|
406 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0); |
|
407 isView = pTab->pSelect!=0; |
|
408 #else |
|
409 # define triggers_exist 0 |
|
410 # define isView 0 |
|
411 #endif |
|
412 #ifdef SQLITE_OMIT_VIEW |
|
413 # undef isView |
|
414 # define isView 0 |
|
415 #endif |
|
416 |
|
417 /* Ensure that: |
|
418 * (a) the table is not read-only, |
|
419 * (b) that if it is a view then ON INSERT triggers exist |
|
420 */ |
|
421 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){ |
|
422 goto insert_cleanup; |
|
423 } |
|
424 assert( pTab!=0 ); |
|
425 |
|
426 /* If pTab is really a view, make sure it has been initialized. |
|
427 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual |
|
428 ** module table). |
|
429 */ |
|
430 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ |
|
431 goto insert_cleanup; |
|
432 } |
|
433 |
|
434 /* Allocate a VDBE |
|
435 */ |
|
436 v = sqlite3GetVdbe(pParse); |
|
437 if( v==0 ) goto insert_cleanup; |
|
438 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); |
|
439 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb); |
|
440 |
|
441 /* if there are row triggers, allocate a temp table for new.* references. */ |
|
442 if( triggers_exist ){ |
|
443 newIdx = pParse->nTab++; |
|
444 } |
|
445 |
|
446 #ifndef SQLITE_OMIT_XFER_OPT |
|
447 /* If the statement is of the form |
|
448 ** |
|
449 ** INSERT INTO <table1> SELECT * FROM <table2>; |
|
450 ** |
|
451 ** Then special optimizations can be applied that make the transfer |
|
452 ** very fast and which reduce fragmentation of indices. |
|
453 */ |
|
454 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ |
|
455 assert( !triggers_exist ); |
|
456 assert( pList==0 ); |
|
457 goto insert_cleanup; |
|
458 } |
|
459 #endif /* SQLITE_OMIT_XFER_OPT */ |
|
460 |
|
461 /* If this is an AUTOINCREMENT table, look up the sequence number in the |
|
462 ** sqlite_sequence table and store it in memory cell counterMem. Also |
|
463 ** remember the rowid of the sqlite_sequence table entry in memory cell |
|
464 ** counterRowid. |
|
465 */ |
|
466 counterMem = autoIncBegin(pParse, iDb, pTab); |
|
467 |
|
468 /* Figure out how many columns of data are supplied. If the data |
|
469 ** is coming from a SELECT statement, then this step also generates |
|
470 ** all the code to implement the SELECT statement and invoke a subroutine |
|
471 ** to process each row of the result. (Template 2.) If the SELECT |
|
472 ** statement uses the the table that is being inserted into, then the |
|
473 ** subroutine is also coded here. That subroutine stores the SELECT |
|
474 ** results in a temporary table. (Template 3.) |
|
475 */ |
|
476 if( pSelect ){ |
|
477 /* Data is coming from a SELECT. Generate code to implement that SELECT |
|
478 */ |
|
479 int rc, iInitCode; |
|
480 iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); |
|
481 iSelectLoop = sqlite3VdbeCurrentAddr(v); |
|
482 iInsertBlock = sqlite3VdbeMakeLabel(v); |
|
483 |
|
484 /* Resolve the expressions in the SELECT statement and execute it. */ |
|
485 rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0); |
|
486 if( rc || pParse->nErr || db->mallocFailed ){ |
|
487 goto insert_cleanup; |
|
488 } |
|
489 |
|
490 iCleanup = sqlite3VdbeMakeLabel(v); |
|
491 sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup); |
|
492 assert( pSelect->pEList ); |
|
493 nColumn = pSelect->pEList->nExpr; |
|
494 |
|
495 /* Set useTempTable to TRUE if the result of the SELECT statement |
|
496 ** should be written into a temporary table. Set to FALSE if each |
|
497 ** row of the SELECT can be written directly into the result table. |
|
498 ** |
|
499 ** A temp table must be used if the table being updated is also one |
|
500 ** of the tables being read by the SELECT statement. Also use a |
|
501 ** temp table in the case of row triggers. |
|
502 */ |
|
503 if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){ |
|
504 useTempTable = 1; |
|
505 } |
|
506 |
|
507 if( useTempTable ){ |
|
508 /* Generate the subroutine that SELECT calls to process each row of |
|
509 ** the result. Store the result in a temporary table |
|
510 */ |
|
511 srcTab = pParse->nTab++; |
|
512 sqlite3VdbeResolveLabel(v, iInsertBlock); |
|
513 sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0); |
|
514 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); |
|
515 sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0); |
|
516 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); |
|
517 sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND); |
|
518 sqlite3VdbeAddOp(v, OP_Return, 0, 0); |
|
519 |
|
520 /* The following code runs first because the GOTO at the very top |
|
521 ** of the program jumps to it. Create the temporary table, then jump |
|
522 ** back up and execute the SELECT code above. |
|
523 */ |
|
524 sqlite3VdbeJumpHere(v, iInitCode); |
|
525 sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0); |
|
526 sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn); |
|
527 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop); |
|
528 sqlite3VdbeResolveLabel(v, iCleanup); |
|
529 }else{ |
|
530 sqlite3VdbeJumpHere(v, iInitCode); |
|
531 } |
|
532 }else{ |
|
533 /* This is the case if the data for the INSERT is coming from a VALUES |
|
534 ** clause |
|
535 */ |
|
536 NameContext sNC; |
|
537 memset(&sNC, 0, sizeof(sNC)); |
|
538 sNC.pParse = pParse; |
|
539 srcTab = -1; |
|
540 assert( useTempTable==0 ); |
|
541 nColumn = pList ? pList->nExpr : 0; |
|
542 for(i=0; i<nColumn; i++){ |
|
543 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){ |
|
544 goto insert_cleanup; |
|
545 } |
|
546 } |
|
547 } |
|
548 |
|
549 /* Make sure the number of columns in the source data matches the number |
|
550 ** of columns to be inserted into the table. |
|
551 */ |
|
552 if( IsVirtual(pTab) ){ |
|
553 for(i=0; i<pTab->nCol; i++){ |
|
554 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); |
|
555 } |
|
556 } |
|
557 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ |
|
558 sqlite3ErrorMsg(pParse, |
|
559 "table %S has %d columns but %d values were supplied", |
|
560 pTabList, 0, pTab->nCol, nColumn); |
|
561 goto insert_cleanup; |
|
562 } |
|
563 if( pColumn!=0 && nColumn!=pColumn->nId ){ |
|
564 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); |
|
565 goto insert_cleanup; |
|
566 } |
|
567 |
|
568 /* If the INSERT statement included an IDLIST term, then make sure |
|
569 ** all elements of the IDLIST really are columns of the table and |
|
570 ** remember the column indices. |
|
571 ** |
|
572 ** If the table has an INTEGER PRIMARY KEY column and that column |
|
573 ** is named in the IDLIST, then record in the keyColumn variable |
|
574 ** the index into IDLIST of the primary key column. keyColumn is |
|
575 ** the index of the primary key as it appears in IDLIST, not as |
|
576 ** is appears in the original table. (The index of the primary |
|
577 ** key in the original table is pTab->iPKey.) |
|
578 */ |
|
579 if( pColumn ){ |
|
580 for(i=0; i<pColumn->nId; i++){ |
|
581 pColumn->a[i].idx = -1; |
|
582 } |
|
583 for(i=0; i<pColumn->nId; i++){ |
|
584 for(j=0; j<pTab->nCol; j++){ |
|
585 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ |
|
586 pColumn->a[i].idx = j; |
|
587 if( j==pTab->iPKey ){ |
|
588 keyColumn = i; |
|
589 } |
|
590 break; |
|
591 } |
|
592 } |
|
593 if( j>=pTab->nCol ){ |
|
594 if( sqlite3IsRowid(pColumn->a[i].zName) ){ |
|
595 keyColumn = i; |
|
596 }else{ |
|
597 sqlite3ErrorMsg(pParse, "table %S has no column named %s", |
|
598 pTabList, 0, pColumn->a[i].zName); |
|
599 pParse->nErr++; |
|
600 goto insert_cleanup; |
|
601 } |
|
602 } |
|
603 } |
|
604 } |
|
605 |
|
606 /* If there is no IDLIST term but the table has an integer primary |
|
607 ** key, the set the keyColumn variable to the primary key column index |
|
608 ** in the original table definition. |
|
609 */ |
|
610 if( pColumn==0 && nColumn>0 ){ |
|
611 keyColumn = pTab->iPKey; |
|
612 } |
|
613 |
|
614 /* Open the temp table for FOR EACH ROW triggers |
|
615 */ |
|
616 if( triggers_exist ){ |
|
617 sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0); |
|
618 sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol); |
|
619 } |
|
620 |
|
621 /* Initialize the count of rows to be inserted |
|
622 */ |
|
623 if( db->flags & SQLITE_CountRows ){ |
|
624 iCntMem = pParse->nMem++; |
|
625 sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem); |
|
626 } |
|
627 |
|
628 /* Open tables and indices if there are no row triggers */ |
|
629 if( !triggers_exist ){ |
|
630 base = pParse->nTab; |
|
631 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite); |
|
632 } |
|
633 |
|
634 /* If the data source is a temporary table, then we have to create |
|
635 ** a loop because there might be multiple rows of data. If the data |
|
636 ** source is a subroutine call from the SELECT statement, then we need |
|
637 ** to launch the SELECT statement processing. |
|
638 */ |
|
639 if( useTempTable ){ |
|
640 iBreak = sqlite3VdbeMakeLabel(v); |
|
641 sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak); |
|
642 iCont = sqlite3VdbeCurrentAddr(v); |
|
643 }else if( pSelect ){ |
|
644 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop); |
|
645 sqlite3VdbeResolveLabel(v, iInsertBlock); |
|
646 sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0); |
|
647 } |
|
648 |
|
649 /* Run the BEFORE and INSTEAD OF triggers, if there are any |
|
650 */ |
|
651 endOfLoop = sqlite3VdbeMakeLabel(v); |
|
652 if( triggers_exist & TRIGGER_BEFORE ){ |
|
653 |
|
654 /* build the NEW.* reference row. Note that if there is an INTEGER |
|
655 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be |
|
656 ** translated into a unique ID for the row. But on a BEFORE trigger, |
|
657 ** we do not know what the unique ID will be (because the insert has |
|
658 ** not happened yet) so we substitute a rowid of -1 |
|
659 */ |
|
660 if( keyColumn<0 ){ |
|
661 sqlite3VdbeAddOp(v, OP_Integer, -1, 0); |
|
662 }else if( useTempTable ){ |
|
663 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn); |
|
664 }else{ |
|
665 assert( pSelect==0 ); /* Otherwise useTempTable is true */ |
|
666 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr); |
|
667 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); |
|
668 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); |
|
669 sqlite3VdbeAddOp(v, OP_Integer, -1, 0); |
|
670 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); |
|
671 } |
|
672 |
|
673 /* Cannot have triggers on a virtual table. If it were possible, |
|
674 ** this block would have to account for hidden column. |
|
675 */ |
|
676 assert(!IsVirtual(pTab)); |
|
677 |
|
678 /* Create the new column data |
|
679 */ |
|
680 for(i=0; i<pTab->nCol; i++){ |
|
681 if( pColumn==0 ){ |
|
682 j = i; |
|
683 }else{ |
|
684 for(j=0; j<pColumn->nId; j++){ |
|
685 if( pColumn->a[j].idx==i ) break; |
|
686 } |
|
687 } |
|
688 if( pColumn && j>=pColumn->nId ){ |
|
689 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt); |
|
690 }else if( useTempTable ){ |
|
691 sqlite3VdbeAddOp(v, OP_Column, srcTab, j); |
|
692 }else{ |
|
693 assert( pSelect==0 ); /* Otherwise useTempTable is true */ |
|
694 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr); |
|
695 } |
|
696 } |
|
697 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0); |
|
698 |
|
699 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, |
|
700 ** do not attempt any conversions before assembling the record. |
|
701 ** If this is a real table, attempt conversions as required by the |
|
702 ** table column affinities. |
|
703 */ |
|
704 if( !isView ){ |
|
705 sqlite3TableAffinityStr(v, pTab); |
|
706 } |
|
707 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0); |
|
708 |
|
709 /* Fire BEFORE or INSTEAD OF triggers */ |
|
710 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, |
|
711 newIdx, -1, onError, endOfLoop) ){ |
|
712 goto insert_cleanup; |
|
713 } |
|
714 } |
|
715 |
|
716 /* If any triggers exists, the opening of tables and indices is deferred |
|
717 ** until now. |
|
718 */ |
|
719 if( triggers_exist && !isView ){ |
|
720 base = pParse->nTab; |
|
721 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite); |
|
722 } |
|
723 |
|
724 /* Push the record number for the new entry onto the stack. The |
|
725 ** record number is a randomly generate integer created by NewRowid |
|
726 ** except when the table has an INTEGER PRIMARY KEY column, in which |
|
727 ** case the record number is the same as that column. |
|
728 */ |
|
729 if( !isView ){ |
|
730 if( IsVirtual(pTab) ){ |
|
731 /* The row that the VUpdate opcode will delete: none */ |
|
732 sqlite3VdbeAddOp(v, OP_Null, 0, 0); |
|
733 } |
|
734 if( keyColumn>=0 ){ |
|
735 if( useTempTable ){ |
|
736 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn); |
|
737 }else if( pSelect ){ |
|
738 sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1); |
|
739 }else{ |
|
740 VdbeOp *pOp; |
|
741 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr); |
|
742 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1); |
|
743 if( pOp && pOp->opcode==OP_Null ){ |
|
744 appendFlag = 1; |
|
745 pOp->opcode = OP_NewRowid; |
|
746 pOp->p1 = base; |
|
747 pOp->p2 = counterMem; |
|
748 } |
|
749 } |
|
750 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid |
|
751 ** to generate a unique primary key value. |
|
752 */ |
|
753 if( !appendFlag ){ |
|
754 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); |
|
755 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); |
|
756 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem); |
|
757 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); |
|
758 } |
|
759 }else if( IsVirtual(pTab) ){ |
|
760 sqlite3VdbeAddOp(v, OP_Null, 0, 0); |
|
761 }else{ |
|
762 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem); |
|
763 appendFlag = 1; |
|
764 } |
|
765 autoIncStep(pParse, counterMem); |
|
766 |
|
767 /* Push onto the stack, data for all columns of the new entry, beginning |
|
768 ** with the first column. |
|
769 */ |
|
770 nHidden = 0; |
|
771 for(i=0; i<pTab->nCol; i++){ |
|
772 if( i==pTab->iPKey ){ |
|
773 /* The value of the INTEGER PRIMARY KEY column is always a NULL. |
|
774 ** Whenever this column is read, the record number will be substituted |
|
775 ** in its place. So will fill this column with a NULL to avoid |
|
776 ** taking up data space with information that will never be used. */ |
|
777 sqlite3VdbeAddOp(v, OP_Null, 0, 0); |
|
778 continue; |
|
779 } |
|
780 if( pColumn==0 ){ |
|
781 if( IsHiddenColumn(&pTab->aCol[i]) ){ |
|
782 assert( IsVirtual(pTab) ); |
|
783 j = -1; |
|
784 nHidden++; |
|
785 }else{ |
|
786 j = i - nHidden; |
|
787 } |
|
788 }else{ |
|
789 for(j=0; j<pColumn->nId; j++){ |
|
790 if( pColumn->a[j].idx==i ) break; |
|
791 } |
|
792 } |
|
793 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ |
|
794 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt); |
|
795 }else if( useTempTable ){ |
|
796 sqlite3VdbeAddOp(v, OP_Column, srcTab, j); |
|
797 }else if( pSelect ){ |
|
798 sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1); |
|
799 }else{ |
|
800 sqlite3ExprCode(pParse, pList->a[j].pExpr); |
|
801 } |
|
802 } |
|
803 |
|
804 /* Generate code to check constraints and generate index keys and |
|
805 ** do the insertion. |
|
806 */ |
|
807 #ifndef SQLITE_OMIT_VIRTUALTABLE |
|
808 if( IsVirtual(pTab) ){ |
|
809 pParse->pVirtualLock = pTab; |
|
810 sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2, |
|
811 (const char*)pTab->pVtab, P3_VTAB); |
|
812 }else |
|
813 #endif |
|
814 { |
|
815 sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0, |
|
816 0, onError, endOfLoop); |
|
817 sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0, |
|
818 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1, |
|
819 appendFlag); |
|
820 } |
|
821 } |
|
822 |
|
823 /* Update the count of rows that are inserted |
|
824 */ |
|
825 if( (db->flags & SQLITE_CountRows)!=0 ){ |
|
826 sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem); |
|
827 } |
|
828 |
|
829 if( triggers_exist ){ |
|
830 /* Close all tables opened */ |
|
831 if( !isView ){ |
|
832 sqlite3VdbeAddOp(v, OP_Close, base, 0); |
|
833 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ |
|
834 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0); |
|
835 } |
|
836 } |
|
837 |
|
838 /* Code AFTER triggers */ |
|
839 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab, |
|
840 newIdx, -1, onError, endOfLoop) ){ |
|
841 goto insert_cleanup; |
|
842 } |
|
843 } |
|
844 |
|
845 /* The bottom of the loop, if the data source is a SELECT statement |
|
846 */ |
|
847 sqlite3VdbeResolveLabel(v, endOfLoop); |
|
848 if( useTempTable ){ |
|
849 sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont); |
|
850 sqlite3VdbeResolveLabel(v, iBreak); |
|
851 sqlite3VdbeAddOp(v, OP_Close, srcTab, 0); |
|
852 }else if( pSelect ){ |
|
853 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); |
|
854 sqlite3VdbeAddOp(v, OP_Return, 0, 0); |
|
855 sqlite3VdbeResolveLabel(v, iCleanup); |
|
856 } |
|
857 |
|
858 if( !triggers_exist && !IsVirtual(pTab) ){ |
|
859 /* Close all tables opened */ |
|
860 sqlite3VdbeAddOp(v, OP_Close, base, 0); |
|
861 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ |
|
862 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0); |
|
863 } |
|
864 } |
|
865 |
|
866 /* Update the sqlite_sequence table by storing the content of the |
|
867 ** counter value in memory counterMem back into the sqlite_sequence |
|
868 ** table. |
|
869 */ |
|
870 autoIncEnd(pParse, iDb, pTab, counterMem); |
|
871 |
|
872 /* |
|
873 ** Return the number of rows inserted. If this routine is |
|
874 ** generating code because of a call to sqlite3NestedParse(), do not |
|
875 ** invoke the callback function. |
|
876 */ |
|
877 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){ |
|
878 sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0); |
|
879 sqlite3VdbeAddOp(v, OP_Callback, 1, 0); |
|
880 sqlite3VdbeSetNumCols(v, 1); |
|
881 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC); |
|
882 } |
|
883 |
|
884 insert_cleanup: |
|
885 sqlite3SrcListDelete(pTabList); |
|
886 sqlite3ExprListDelete(pList); |
|
887 sqlite3SelectDelete(pSelect); |
|
888 sqlite3IdListDelete(pColumn); |
|
889 } |
|
890 |
|
891 /* |
|
892 ** Generate code to do a constraint check prior to an INSERT or an UPDATE. |
|
893 ** |
|
894 ** When this routine is called, the stack contains (from bottom to top) |
|
895 ** the following values: |
|
896 ** |
|
897 ** 1. The rowid of the row to be updated before the update. This |
|
898 ** value is omitted unless we are doing an UPDATE that involves a |
|
899 ** change to the record number. |
|
900 ** |
|
901 ** 2. The rowid of the row after the update. |
|
902 ** |
|
903 ** 3. The data in the first column of the entry after the update. |
|
904 ** |
|
905 ** i. Data from middle columns... |
|
906 ** |
|
907 ** N. The data in the last column of the entry after the update. |
|
908 ** |
|
909 ** The old rowid shown as entry (1) above is omitted unless both isUpdate |
|
910 ** and rowidChng are 1. isUpdate is true for UPDATEs and false for |
|
911 ** INSERTs and rowidChng is true if the record number is being changed. |
|
912 ** |
|
913 ** The code generated by this routine pushes additional entries onto |
|
914 ** the stack which are the keys for new index entries for the new record. |
|
915 ** The order of index keys is the same as the order of the indices on |
|
916 ** the pTable->pIndex list. A key is only created for index i if |
|
917 ** aIdxUsed!=0 and aIdxUsed[i]!=0. |
|
918 ** |
|
919 ** This routine also generates code to check constraints. NOT NULL, |
|
920 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, |
|
921 ** then the appropriate action is performed. There are five possible |
|
922 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. |
|
923 ** |
|
924 ** Constraint type Action What Happens |
|
925 ** --------------- ---------- ---------------------------------------- |
|
926 ** any ROLLBACK The current transaction is rolled back and |
|
927 ** sqlite3_exec() returns immediately with a |
|
928 ** return code of SQLITE_CONSTRAINT. |
|
929 ** |
|
930 ** any ABORT Back out changes from the current command |
|
931 ** only (do not do a complete rollback) then |
|
932 ** cause sqlite3_exec() to return immediately |
|
933 ** with SQLITE_CONSTRAINT. |
|
934 ** |
|
935 ** any FAIL Sqlite_exec() returns immediately with a |
|
936 ** return code of SQLITE_CONSTRAINT. The |
|
937 ** transaction is not rolled back and any |
|
938 ** prior changes are retained. |
|
939 ** |
|
940 ** any IGNORE The record number and data is popped from |
|
941 ** the stack and there is an immediate jump |
|
942 ** to label ignoreDest. |
|
943 ** |
|
944 ** NOT NULL REPLACE The NULL value is replace by the default |
|
945 ** value for that column. If the default value |
|
946 ** is NULL, the action is the same as ABORT. |
|
947 ** |
|
948 ** UNIQUE REPLACE The other row that conflicts with the row |
|
949 ** being inserted is removed. |
|
950 ** |
|
951 ** CHECK REPLACE Illegal. The results in an exception. |
|
952 ** |
|
953 ** Which action to take is determined by the overrideError parameter. |
|
954 ** Or if overrideError==OE_Default, then the pParse->onError parameter |
|
955 ** is used. Or if pParse->onError==OE_Default then the onError value |
|
956 ** for the constraint is used. |
|
957 ** |
|
958 ** The calling routine must open a read/write cursor for pTab with |
|
959 ** cursor number "base". All indices of pTab must also have open |
|
960 ** read/write cursors with cursor number base+i for the i-th cursor. |
|
961 ** Except, if there is no possibility of a REPLACE action then |
|
962 ** cursors do not need to be open for indices where aIdxUsed[i]==0. |
|
963 ** |
|
964 ** If the isUpdate flag is true, it means that the "base" cursor is |
|
965 ** initially pointing to an entry that is being updated. The isUpdate |
|
966 ** flag causes extra code to be generated so that the "base" cursor |
|
967 ** is still pointing at the same entry after the routine returns. |
|
968 ** Without the isUpdate flag, the "base" cursor might be moved. |
|
969 */ |
|
970 void sqlite3GenerateConstraintChecks( |
|
971 Parse *pParse, /* The parser context */ |
|
972 Table *pTab, /* the table into which we are inserting */ |
|
973 int base, /* Index of a read/write cursor pointing at pTab */ |
|
974 char *aIdxUsed, /* Which indices are used. NULL means all are used */ |
|
975 int rowidChng, /* True if the record number will change */ |
|
976 int isUpdate, /* True for UPDATE, False for INSERT */ |
|
977 int overrideError, /* Override onError to this if not OE_Default */ |
|
978 int ignoreDest /* Jump to this label on an OE_Ignore resolution */ |
|
979 ){ |
|
980 int i; |
|
981 Vdbe *v; |
|
982 int nCol; |
|
983 int onError; |
|
984 int addr; |
|
985 int extra; |
|
986 int iCur; |
|
987 Index *pIdx; |
|
988 int seenReplace = 0; |
|
989 int jumpInst1=0, jumpInst2; |
|
990 int hasTwoRowids = (isUpdate && rowidChng); |
|
991 |
|
992 v = sqlite3GetVdbe(pParse); |
|
993 assert( v!=0 ); |
|
994 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ |
|
995 nCol = pTab->nCol; |
|
996 |
|
997 /* Test all NOT NULL constraints. |
|
998 */ |
|
999 for(i=0; i<nCol; i++){ |
|
1000 if( i==pTab->iPKey ){ |
|
1001 continue; |
|
1002 } |
|
1003 onError = pTab->aCol[i].notNull; |
|
1004 if( onError==OE_None ) continue; |
|
1005 if( overrideError!=OE_Default ){ |
|
1006 onError = overrideError; |
|
1007 }else if( onError==OE_Default ){ |
|
1008 onError = OE_Abort; |
|
1009 } |
|
1010 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ |
|
1011 onError = OE_Abort; |
|
1012 } |
|
1013 sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1); |
|
1014 addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0); |
|
1015 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail |
|
1016 || onError==OE_Ignore || onError==OE_Replace ); |
|
1017 switch( onError ){ |
|
1018 case OE_Rollback: |
|
1019 case OE_Abort: |
|
1020 case OE_Fail: { |
|
1021 char *zMsg = 0; |
|
1022 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError); |
|
1023 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName, |
|
1024 " may not be NULL", (char*)0); |
|
1025 sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC); |
|
1026 break; |
|
1027 } |
|
1028 case OE_Ignore: { |
|
1029 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0); |
|
1030 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); |
|
1031 break; |
|
1032 } |
|
1033 case OE_Replace: { |
|
1034 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt); |
|
1035 sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0); |
|
1036 break; |
|
1037 } |
|
1038 } |
|
1039 sqlite3VdbeJumpHere(v, addr); |
|
1040 } |
|
1041 |
|
1042 /* Test all CHECK constraints |
|
1043 */ |
|
1044 #ifndef SQLITE_OMIT_CHECK |
|
1045 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){ |
|
1046 int allOk = sqlite3VdbeMakeLabel(v); |
|
1047 assert( pParse->ckOffset==0 ); |
|
1048 pParse->ckOffset = nCol; |
|
1049 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1); |
|
1050 assert( pParse->ckOffset==nCol ); |
|
1051 pParse->ckOffset = 0; |
|
1052 onError = overrideError!=OE_Default ? overrideError : OE_Abort; |
|
1053 if( onError==OE_Ignore ){ |
|
1054 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0); |
|
1055 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); |
|
1056 }else{ |
|
1057 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError); |
|
1058 } |
|
1059 sqlite3VdbeResolveLabel(v, allOk); |
|
1060 } |
|
1061 #endif /* !defined(SQLITE_OMIT_CHECK) */ |
|
1062 |
|
1063 /* If we have an INTEGER PRIMARY KEY, make sure the primary key |
|
1064 ** of the new record does not previously exist. Except, if this |
|
1065 ** is an UPDATE and the primary key is not changing, that is OK. |
|
1066 */ |
|
1067 if( rowidChng ){ |
|
1068 onError = pTab->keyConf; |
|
1069 if( overrideError!=OE_Default ){ |
|
1070 onError = overrideError; |
|
1071 }else if( onError==OE_Default ){ |
|
1072 onError = OE_Abort; |
|
1073 } |
|
1074 |
|
1075 if( isUpdate ){ |
|
1076 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1); |
|
1077 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1); |
|
1078 jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0); |
|
1079 } |
|
1080 sqlite3VdbeAddOp(v, OP_Dup, nCol, 1); |
|
1081 jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0); |
|
1082 switch( onError ){ |
|
1083 default: { |
|
1084 onError = OE_Abort; |
|
1085 /* Fall thru into the next case */ |
|
1086 } |
|
1087 case OE_Rollback: |
|
1088 case OE_Abort: |
|
1089 case OE_Fail: { |
|
1090 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, |
|
1091 "PRIMARY KEY must be unique", P3_STATIC); |
|
1092 break; |
|
1093 } |
|
1094 case OE_Replace: { |
|
1095 sqlite3GenerateRowIndexDelete(v, pTab, base, 0); |
|
1096 if( isUpdate ){ |
|
1097 sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1); |
|
1098 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); |
|
1099 } |
|
1100 seenReplace = 1; |
|
1101 break; |
|
1102 } |
|
1103 case OE_Ignore: { |
|
1104 assert( seenReplace==0 ); |
|
1105 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0); |
|
1106 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); |
|
1107 break; |
|
1108 } |
|
1109 } |
|
1110 sqlite3VdbeJumpHere(v, jumpInst2); |
|
1111 if( isUpdate ){ |
|
1112 sqlite3VdbeJumpHere(v, jumpInst1); |
|
1113 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1); |
|
1114 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); |
|
1115 } |
|
1116 } |
|
1117 |
|
1118 /* Test all UNIQUE constraints by creating entries for each UNIQUE |
|
1119 ** index and making sure that duplicate entries do not already exist. |
|
1120 ** Add the new records to the indices as we go. |
|
1121 */ |
|
1122 extra = -1; |
|
1123 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){ |
|
1124 if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */ |
|
1125 extra++; |
|
1126 |
|
1127 /* Create a key for accessing the index entry */ |
|
1128 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1); |
|
1129 for(i=0; i<pIdx->nColumn; i++){ |
|
1130 int idx = pIdx->aiColumn[i]; |
|
1131 if( idx==pTab->iPKey ){ |
|
1132 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1); |
|
1133 }else{ |
|
1134 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1); |
|
1135 } |
|
1136 } |
|
1137 jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0); |
|
1138 sqlite3IndexAffinityStr(v, pIdx); |
|
1139 |
|
1140 /* Find out what action to take in case there is an indexing conflict */ |
|
1141 onError = pIdx->onError; |
|
1142 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */ |
|
1143 if( overrideError!=OE_Default ){ |
|
1144 onError = overrideError; |
|
1145 }else if( onError==OE_Default ){ |
|
1146 onError = OE_Abort; |
|
1147 } |
|
1148 if( seenReplace ){ |
|
1149 if( onError==OE_Ignore ) onError = OE_Replace; |
|
1150 else if( onError==OE_Fail ) onError = OE_Abort; |
|
1151 } |
|
1152 |
|
1153 |
|
1154 /* Check to see if the new index entry will be unique */ |
|
1155 sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1); |
|
1156 jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0); |
|
1157 |
|
1158 /* Generate code that executes if the new index entry is not unique */ |
|
1159 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail |
|
1160 || onError==OE_Ignore || onError==OE_Replace ); |
|
1161 switch( onError ){ |
|
1162 case OE_Rollback: |
|
1163 case OE_Abort: |
|
1164 case OE_Fail: { |
|
1165 int j, n1, n2; |
|
1166 char zErrMsg[200]; |
|
1167 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg, |
|
1168 pIdx->nColumn>1 ? "columns " : "column "); |
|
1169 n1 = strlen(zErrMsg); |
|
1170 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){ |
|
1171 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; |
|
1172 n2 = strlen(zCol); |
|
1173 if( j>0 ){ |
|
1174 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", "); |
|
1175 n1 += 2; |
|
1176 } |
|
1177 if( n1+n2>sizeof(zErrMsg)-30 ){ |
|
1178 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "..."); |
|
1179 n1 += 3; |
|
1180 break; |
|
1181 }else{ |
|
1182 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol); |
|
1183 n1 += n2; |
|
1184 } |
|
1185 } |
|
1186 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], |
|
1187 pIdx->nColumn>1 ? " are not unique" : " is not unique"); |
|
1188 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0); |
|
1189 break; |
|
1190 } |
|
1191 case OE_Ignore: { |
|
1192 assert( seenReplace==0 ); |
|
1193 sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0); |
|
1194 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); |
|
1195 break; |
|
1196 } |
|
1197 case OE_Replace: { |
|
1198 sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0); |
|
1199 if( isUpdate ){ |
|
1200 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1); |
|
1201 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); |
|
1202 } |
|
1203 seenReplace = 1; |
|
1204 break; |
|
1205 } |
|
1206 } |
|
1207 #if NULL_DISTINCT_FOR_UNIQUE |
|
1208 sqlite3VdbeJumpHere(v, jumpInst1); |
|
1209 #endif |
|
1210 sqlite3VdbeJumpHere(v, jumpInst2); |
|
1211 } |
|
1212 } |
|
1213 |
|
1214 /* |
|
1215 ** This routine generates code to finish the INSERT or UPDATE operation |
|
1216 ** that was started by a prior call to sqlite3GenerateConstraintChecks. |
|
1217 ** The stack must contain keys for all active indices followed by data |
|
1218 ** and the rowid for the new entry. This routine creates the new |
|
1219 ** entries in all indices and in the main table. |
|
1220 ** |
|
1221 ** The arguments to this routine should be the same as the first six |
|
1222 ** arguments to sqlite3GenerateConstraintChecks. |
|
1223 */ |
|
1224 void sqlite3CompleteInsertion( |
|
1225 Parse *pParse, /* The parser context */ |
|
1226 Table *pTab, /* the table into which we are inserting */ |
|
1227 int base, /* Index of a read/write cursor pointing at pTab */ |
|
1228 char *aIdxUsed, /* Which indices are used. NULL means all are used */ |
|
1229 int rowidChng, /* True if the record number will change */ |
|
1230 int isUpdate, /* True for UPDATE, False for INSERT */ |
|
1231 int newIdx, /* Index of NEW table for triggers. -1 if none */ |
|
1232 int appendBias /* True if this is likely to be an append */ |
|
1233 ){ |
|
1234 int i; |
|
1235 Vdbe *v; |
|
1236 int nIdx; |
|
1237 Index *pIdx; |
|
1238 int pik_flags; |
|
1239 |
|
1240 v = sqlite3GetVdbe(pParse); |
|
1241 assert( v!=0 ); |
|
1242 assert( pTab->pSelect==0 ); /* This table is not a VIEW */ |
|
1243 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} |
|
1244 for(i=nIdx-1; i>=0; i--){ |
|
1245 if( aIdxUsed && aIdxUsed[i]==0 ) continue; |
|
1246 sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0); |
|
1247 } |
|
1248 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0); |
|
1249 sqlite3TableAffinityStr(v, pTab); |
|
1250 #ifndef SQLITE_OMIT_TRIGGER |
|
1251 if( newIdx>=0 ){ |
|
1252 sqlite3VdbeAddOp(v, OP_Dup, 1, 0); |
|
1253 sqlite3VdbeAddOp(v, OP_Dup, 1, 0); |
|
1254 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0); |
|
1255 } |
|
1256 #endif |
|
1257 if( pParse->nested ){ |
|
1258 pik_flags = 0; |
|
1259 }else{ |
|
1260 pik_flags = OPFLAG_NCHANGE; |
|
1261 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); |
|
1262 } |
|
1263 if( appendBias ){ |
|
1264 pik_flags |= OPFLAG_APPEND; |
|
1265 } |
|
1266 sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags); |
|
1267 if( !pParse->nested ){ |
|
1268 sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC); |
|
1269 } |
|
1270 |
|
1271 if( isUpdate && rowidChng ){ |
|
1272 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); |
|
1273 } |
|
1274 } |
|
1275 |
|
1276 /* |
|
1277 ** Generate code that will open cursors for a table and for all |
|
1278 ** indices of that table. The "base" parameter is the cursor number used |
|
1279 ** for the table. Indices are opened on subsequent cursors. |
|
1280 */ |
|
1281 void sqlite3OpenTableAndIndices( |
|
1282 Parse *pParse, /* Parsing context */ |
|
1283 Table *pTab, /* Table to be opened */ |
|
1284 int base, /* Cursor number assigned to the table */ |
|
1285 int op /* OP_OpenRead or OP_OpenWrite */ |
|
1286 ){ |
|
1287 int i; |
|
1288 int iDb; |
|
1289 Index *pIdx; |
|
1290 Vdbe *v; |
|
1291 |
|
1292 if( IsVirtual(pTab) ) return; |
|
1293 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); |
|
1294 v = sqlite3GetVdbe(pParse); |
|
1295 assert( v!=0 ); |
|
1296 sqlite3OpenTable(pParse, base, iDb, pTab, op); |
|
1297 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ |
|
1298 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); |
|
1299 assert( pIdx->pSchema==pTab->pSchema ); |
|
1300 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); |
|
1301 VdbeComment((v, "# %s", pIdx->zName)); |
|
1302 sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF); |
|
1303 } |
|
1304 if( pParse->nTab<=base+i ){ |
|
1305 pParse->nTab = base+i; |
|
1306 } |
|
1307 } |
|
1308 |
|
1309 |
|
1310 #ifdef SQLITE_TEST |
|
1311 /* |
|
1312 ** The following global variable is incremented whenever the |
|
1313 ** transfer optimization is used. This is used for testing |
|
1314 ** purposes only - to make sure the transfer optimization really |
|
1315 ** is happening when it is suppose to. |
|
1316 */ |
|
1317 int sqlite3_xferopt_count; |
|
1318 #endif /* SQLITE_TEST */ |
|
1319 |
|
1320 |
|
1321 #ifndef SQLITE_OMIT_XFER_OPT |
|
1322 /* |
|
1323 ** Check to collation names to see if they are compatible. |
|
1324 */ |
|
1325 static int xferCompatibleCollation(const char *z1, const char *z2){ |
|
1326 if( z1==0 ){ |
|
1327 return z2==0; |
|
1328 } |
|
1329 if( z2==0 ){ |
|
1330 return 0; |
|
1331 } |
|
1332 return sqlite3StrICmp(z1, z2)==0; |
|
1333 } |
|
1334 |
|
1335 |
|
1336 /* |
|
1337 ** Check to see if index pSrc is compatible as a source of data |
|
1338 ** for index pDest in an insert transfer optimization. The rules |
|
1339 ** for a compatible index: |
|
1340 ** |
|
1341 ** * The index is over the same set of columns |
|
1342 ** * The same DESC and ASC markings occurs on all columns |
|
1343 ** * The same onError processing (OE_Abort, OE_Ignore, etc) |
|
1344 ** * The same collating sequence on each column |
|
1345 */ |
|
1346 static int xferCompatibleIndex(Index *pDest, Index *pSrc){ |
|
1347 int i; |
|
1348 assert( pDest && pSrc ); |
|
1349 assert( pDest->pTable!=pSrc->pTable ); |
|
1350 if( pDest->nColumn!=pSrc->nColumn ){ |
|
1351 return 0; /* Different number of columns */ |
|
1352 } |
|
1353 if( pDest->onError!=pSrc->onError ){ |
|
1354 return 0; /* Different conflict resolution strategies */ |
|
1355 } |
|
1356 for(i=0; i<pSrc->nColumn; i++){ |
|
1357 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ |
|
1358 return 0; /* Different columns indexed */ |
|
1359 } |
|
1360 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ |
|
1361 return 0; /* Different sort orders */ |
|
1362 } |
|
1363 if( pSrc->azColl[i]!=pDest->azColl[i] ){ |
|
1364 return 0; /* Different sort orders */ |
|
1365 } |
|
1366 } |
|
1367 |
|
1368 /* If no test above fails then the indices must be compatible */ |
|
1369 return 1; |
|
1370 } |
|
1371 |
|
1372 /* |
|
1373 ** Attempt the transfer optimization on INSERTs of the form |
|
1374 ** |
|
1375 ** INSERT INTO tab1 SELECT * FROM tab2; |
|
1376 ** |
|
1377 ** This optimization is only attempted if |
|
1378 ** |
|
1379 ** (1) tab1 and tab2 have identical schemas including all the |
|
1380 ** same indices and constraints |
|
1381 ** |
|
1382 ** (2) tab1 and tab2 are different tables |
|
1383 ** |
|
1384 ** (3) There must be no triggers on tab1 |
|
1385 ** |
|
1386 ** (4) The result set of the SELECT statement is "*" |
|
1387 ** |
|
1388 ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY, |
|
1389 ** or LIMIT clause. |
|
1390 ** |
|
1391 ** (6) The SELECT statement is a simple (not a compound) select that |
|
1392 ** contains only tab2 in its FROM clause |
|
1393 ** |
|
1394 ** This method for implementing the INSERT transfers raw records from |
|
1395 ** tab2 over to tab1. The columns are not decoded. Raw records from |
|
1396 ** the indices of tab2 are transfered to tab1 as well. In so doing, |
|
1397 ** the resulting tab1 has much less fragmentation. |
|
1398 ** |
|
1399 ** This routine returns TRUE if the optimization is attempted. If any |
|
1400 ** of the conditions above fail so that the optimization should not |
|
1401 ** be attempted, then this routine returns FALSE. |
|
1402 */ |
|
1403 static int xferOptimization( |
|
1404 Parse *pParse, /* Parser context */ |
|
1405 Table *pDest, /* The table we are inserting into */ |
|
1406 Select *pSelect, /* A SELECT statement to use as the data source */ |
|
1407 int onError, /* How to handle constraint errors */ |
|
1408 int iDbDest /* The database of pDest */ |
|
1409 ){ |
|
1410 ExprList *pEList; /* The result set of the SELECT */ |
|
1411 Table *pSrc; /* The table in the FROM clause of SELECT */ |
|
1412 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ |
|
1413 SrcList::SrcList_item *pItem; /* An element of pSelect->pSrc */ |
|
1414 int i; /* Loop counter */ |
|
1415 int iDbSrc; /* The database of pSrc */ |
|
1416 int iSrc, iDest; /* Cursors from source and destination */ |
|
1417 int addr1, addr2; /* Loop addresses */ |
|
1418 int emptyDestTest; /* Address of test for empty pDest */ |
|
1419 int emptySrcTest; /* Address of test for empty pSrc */ |
|
1420 Vdbe *v; /* The VDBE we are building */ |
|
1421 KeyInfo *pKey; /* Key information for an index */ |
|
1422 int counterMem; /* Memory register used by AUTOINC */ |
|
1423 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ |
|
1424 |
|
1425 if( pSelect==0 ){ |
|
1426 return 0; /* Must be of the form INSERT INTO ... SELECT ... */ |
|
1427 } |
|
1428 if( pDest->pTrigger ){ |
|
1429 return 0; /* tab1 must not have triggers */ |
|
1430 } |
|
1431 #ifndef SQLITE_OMIT_VIRTUALTABLE |
|
1432 if( pDest->isVirtual ){ |
|
1433 return 0; /* tab1 must not be a virtual table */ |
|
1434 } |
|
1435 #endif |
|
1436 if( onError==OE_Default ){ |
|
1437 onError = OE_Abort; |
|
1438 } |
|
1439 if( onError!=OE_Abort && onError!=OE_Rollback ){ |
|
1440 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */ |
|
1441 } |
|
1442 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ |
|
1443 if( pSelect->pSrc->nSrc!=1 ){ |
|
1444 return 0; /* FROM clause must have exactly one term */ |
|
1445 } |
|
1446 if( pSelect->pSrc->a[0].pSelect ){ |
|
1447 return 0; /* FROM clause cannot contain a subquery */ |
|
1448 } |
|
1449 if( pSelect->pWhere ){ |
|
1450 return 0; /* SELECT may not have a WHERE clause */ |
|
1451 } |
|
1452 if( pSelect->pOrderBy ){ |
|
1453 return 0; /* SELECT may not have an ORDER BY clause */ |
|
1454 } |
|
1455 /* Do not need to test for a HAVING clause. If HAVING is present but |
|
1456 ** there is no ORDER BY, we will get an error. */ |
|
1457 if( pSelect->pGroupBy ){ |
|
1458 return 0; /* SELECT may not have a GROUP BY clause */ |
|
1459 } |
|
1460 if( pSelect->pLimit ){ |
|
1461 return 0; /* SELECT may not have a LIMIT clause */ |
|
1462 } |
|
1463 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ |
|
1464 if( pSelect->pPrior ){ |
|
1465 return 0; /* SELECT may not be a compound query */ |
|
1466 } |
|
1467 if( pSelect->isDistinct ){ |
|
1468 return 0; /* SELECT may not be DISTINCT */ |
|
1469 } |
|
1470 pEList = pSelect->pEList; |
|
1471 assert( pEList!=0 ); |
|
1472 if( pEList->nExpr!=1 ){ |
|
1473 return 0; /* The result set must have exactly one column */ |
|
1474 } |
|
1475 assert( pEList->a[0].pExpr ); |
|
1476 if( pEList->a[0].pExpr->op!=TK_ALL ){ |
|
1477 return 0; /* The result set must be the special operator "*" */ |
|
1478 } |
|
1479 |
|
1480 /* At this point we have established that the statement is of the |
|
1481 ** correct syntactic form to participate in this optimization. Now |
|
1482 ** we have to check the semantics. |
|
1483 */ |
|
1484 pItem = pSelect->pSrc->a; |
|
1485 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase); |
|
1486 if( pSrc==0 ){ |
|
1487 return 0; /* FROM clause does not contain a real table */ |
|
1488 } |
|
1489 if( pSrc==pDest ){ |
|
1490 return 0; /* tab1 and tab2 may not be the same table */ |
|
1491 } |
|
1492 #ifndef SQLITE_OMIT_VIRTUALTABLE |
|
1493 if( pSrc->isVirtual ){ |
|
1494 return 0; /* tab2 must not be a virtual table */ |
|
1495 } |
|
1496 #endif |
|
1497 if( pSrc->pSelect ){ |
|
1498 return 0; /* tab2 may not be a view */ |
|
1499 } |
|
1500 if( pDest->nCol!=pSrc->nCol ){ |
|
1501 return 0; /* Number of columns must be the same in tab1 and tab2 */ |
|
1502 } |
|
1503 if( pDest->iPKey!=pSrc->iPKey ){ |
|
1504 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ |
|
1505 } |
|
1506 for(i=0; i<pDest->nCol; i++){ |
|
1507 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){ |
|
1508 return 0; /* Affinity must be the same on all columns */ |
|
1509 } |
|
1510 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){ |
|
1511 return 0; /* Collating sequence must be the same on all columns */ |
|
1512 } |
|
1513 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){ |
|
1514 return 0; /* tab2 must be NOT NULL if tab1 is */ |
|
1515 } |
|
1516 } |
|
1517 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ |
|
1518 if( pDestIdx->onError!=OE_None ){ |
|
1519 destHasUniqueIdx = 1; |
|
1520 } |
|
1521 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ |
|
1522 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; |
|
1523 } |
|
1524 if( pSrcIdx==0 ){ |
|
1525 return 0; /* pDestIdx has no corresponding index in pSrc */ |
|
1526 } |
|
1527 } |
|
1528 #ifndef SQLITE_OMIT_CHECK |
|
1529 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){ |
|
1530 return 0; /* Tables have different CHECK constraints. Ticket #2252 */ |
|
1531 } |
|
1532 #endif |
|
1533 |
|
1534 /* If we get this far, it means either: |
|
1535 ** |
|
1536 ** * We can always do the transfer if the table contains an |
|
1537 ** an integer primary key |
|
1538 ** |
|
1539 ** * We can conditionally do the transfer if the destination |
|
1540 ** table is empty. |
|
1541 */ |
|
1542 #ifdef SQLITE_TEST |
|
1543 sqlite3_xferopt_count++; |
|
1544 #endif |
|
1545 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema); |
|
1546 v = sqlite3GetVdbe(pParse); |
|
1547 sqlite3CodeVerifySchema(pParse, iDbSrc); |
|
1548 iSrc = pParse->nTab++; |
|
1549 iDest = pParse->nTab++; |
|
1550 counterMem = autoIncBegin(pParse, iDbDest, pDest); |
|
1551 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); |
|
1552 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){ |
|
1553 /* If tables do not have an INTEGER PRIMARY KEY and there |
|
1554 ** are indices to be copied and the destination is not empty, |
|
1555 ** we have to disallow the transfer optimization because the |
|
1556 ** the rowids might change which will mess up indexing. |
|
1557 ** |
|
1558 ** Or if the destination has a UNIQUE index and is not empty, |
|
1559 ** we also disallow the transfer optimization because we cannot |
|
1560 ** insure that all entries in the union of DEST and SRC will be |
|
1561 ** unique. |
|
1562 */ |
|
1563 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0); |
|
1564 emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); |
|
1565 sqlite3VdbeJumpHere(v, addr1); |
|
1566 }else{ |
|
1567 emptyDestTest = 0; |
|
1568 } |
|
1569 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); |
|
1570 emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0); |
|
1571 if( pDest->iPKey>=0 ){ |
|
1572 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0); |
|
1573 sqlite3VdbeAddOp(v, OP_Dup, 0, 0); |
|
1574 addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0); |
|
1575 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, |
|
1576 "PRIMARY KEY must be unique", P3_STATIC); |
|
1577 sqlite3VdbeJumpHere(v, addr2); |
|
1578 autoIncStep(pParse, counterMem); |
|
1579 }else if( pDest->pIndex==0 ){ |
|
1580 addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0); |
|
1581 }else{ |
|
1582 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0); |
|
1583 assert( pDest->autoInc==0 ); |
|
1584 } |
|
1585 sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0); |
|
1586 sqlite3VdbeOp3(v, OP_Insert, iDest, |
|
1587 OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND, |
|
1588 pDest->zName, 0); |
|
1589 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1); |
|
1590 autoIncEnd(pParse, iDbDest, pDest, counterMem); |
|
1591 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ |
|
1592 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ |
|
1593 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; |
|
1594 } |
|
1595 assert( pSrcIdx ); |
|
1596 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0); |
|
1597 sqlite3VdbeAddOp(v, OP_Close, iDest, 0); |
|
1598 sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0); |
|
1599 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx); |
|
1600 VdbeComment((v, "# %s", pSrcIdx->zName)); |
|
1601 sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, |
|
1602 (char*)pKey, P3_KEYINFO_HANDOFF); |
|
1603 sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0); |
|
1604 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx); |
|
1605 VdbeComment((v, "# %s", pDestIdx->zName)); |
|
1606 sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, |
|
1607 (char*)pKey, P3_KEYINFO_HANDOFF); |
|
1608 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0); |
|
1609 sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0); |
|
1610 sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1); |
|
1611 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1); |
|
1612 sqlite3VdbeJumpHere(v, addr1); |
|
1613 } |
|
1614 sqlite3VdbeJumpHere(v, emptySrcTest); |
|
1615 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0); |
|
1616 sqlite3VdbeAddOp(v, OP_Close, iDest, 0); |
|
1617 if( emptyDestTest ){ |
|
1618 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0); |
|
1619 sqlite3VdbeJumpHere(v, emptyDestTest); |
|
1620 sqlite3VdbeAddOp(v, OP_Close, iDest, 0); |
|
1621 return 0; |
|
1622 }else{ |
|
1623 return 1; |
|
1624 } |
|
1625 } |
|
1626 #endif /* SQLITE_OMIT_XFER_OPT */ |
|