wasCSharpSQLite – Blame information for rev

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 office 1 using System;
2 using System.Diagnostics;
3 using System.Text;
4  
5 using Pgno = System.UInt32;
6 using u8 = System.Byte;
7 using u32 = System.UInt32;
8  
9 namespace Community.CsharpSqlite
10 {
11 public partial class Sqlite3
12 {
13 /*
14 ** 2001 September 15
15 **
16 ** The author disclaims copyright to this source code. In place of
17 ** a legal notice, here is a blessing:
18 **
19 ** May you do good and not evil.
20 ** May you find forgiveness for yourself and forgive others.
21 ** May you share freely, never taking more than you give.
22 **
23 *************************************************************************
24 ** This file contains C code routines that are called by the parser
25 ** to handle INSERT statements in SQLite.
26 *************************************************************************
27 ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
28 ** C#-SQLite is an independent reimplementation of the SQLite software library
29 **
30 ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
31 **
32 *************************************************************************
33 */
34 //#include "sqliteInt.h"
35  
36 /*
37 ** Generate code that will open a table for reading.
38 */
39 static void sqlite3OpenTable(
40 Parse p, /* Generate code into this VDBE */
41 int iCur, /* The cursor number of the table */
42 int iDb, /* The database index in sqlite3.aDb[] */
43 Table pTab, /* The table to be opened */
44 int opcode /* OP_OpenRead or OP_OpenWrite */
45 )
46 {
47 Vdbe v;
48 if ( IsVirtual( pTab ) )
49 return;
50 v = sqlite3GetVdbe( p );
51 Debug.Assert( opcode == OP_OpenWrite || opcode == OP_OpenRead );
52 sqlite3TableLock( p, iDb, pTab.tnum, ( opcode == OP_OpenWrite ) ? (byte)1 : (byte)0, pTab.zName );
53 sqlite3VdbeAddOp3( v, opcode, iCur, pTab.tnum, iDb );
54 sqlite3VdbeChangeP4( v, -1, ( pTab.nCol ), P4_INT32 );//SQLITE_INT_TO_PTR( pTab.nCol ), P4_INT32 );
55 VdbeComment( v, "%s", pTab.zName );
56 }
57  
58 /*
59 ** Return a pointer to the column affinity string associated with index
60 ** pIdx. A column affinity string has one character for each column in
61 ** the table, according to the affinity of the column:
62 **
63 ** Character Column affinity
64 ** ------------------------------
65 ** 'a' TEXT
66 ** 'b' NONE
67 ** 'c' NUMERIC
68 ** 'd' INTEGER
69 ** 'e' REAL
70 **
71 ** An extra 'b' is appended to the end of the string to cover the
72 ** rowid that appears as the last column in every index.
73 **
74 ** Memory for the buffer containing the column index affinity string
75 ** is managed along with the rest of the Index structure. It will be
76 ** released when sqlite3DeleteIndex() is called.
77 */
78 static string sqlite3IndexAffinityStr( Vdbe v, Index pIdx )
79 {
80 if ( pIdx.zColAff == null || pIdx.zColAff[0] == '\0' )
81 {
82 /* The first time a column affinity string for a particular index is
83 ** required, it is allocated and populated here. It is then stored as
84 ** a member of the Index structure for subsequent use.
85 **
86 ** The column affinity string will eventually be deleted by
87 ** sqliteDeleteIndex() when the Index structure itself is cleaned
88 ** up.
89 */
90 int n;
91 Table pTab = pIdx.pTable;
92 ////sqlite3 db = sqlite3VdbeDb( v );
93 StringBuilder pIdx_zColAff = new StringBuilder( pIdx.nColumn + 2 );// (char )sqlite3DbMallocRaw(0, pIdx->nColumn+2);
94 // if ( pIdx_zColAff == null )
95 // {
96 // db.mallocFailed = 1;
97 // return null;
98 // }
99 for ( n = 0; n < pIdx.nColumn; n++ )
100 {
101 pIdx_zColAff.Append( pTab.aCol[pIdx.aiColumn[n]].affinity );
102 }
103 pIdx_zColAff.Append( SQLITE_AFF_NONE );
104 pIdx_zColAff.Append( '\0' );
105 pIdx.zColAff = pIdx_zColAff.ToString();
106 }
107 return pIdx.zColAff;
108 }
109  
110 /*
111 ** Set P4 of the most recently inserted opcode to a column affinity
112 ** string for table pTab. A column affinity string has one character
113 ** for each column indexed by the index, according to the affinity of the
114 ** column:
115 **
116 ** Character Column affinity
117 ** ------------------------------
118 ** 'a' TEXT
119 ** 'b' NONE
120 ** 'c' NUMERIC
121 ** 'd' INTEGER
122 ** 'e' REAL
123 */
124 static void sqlite3TableAffinityStr( Vdbe v, Table pTab )
125 {
126 /* The first time a column affinity string for a particular table
127 ** is required, it is allocated and populated here. It is then
128 ** stored as a member of the Table structure for subsequent use.
129 **
130 ** The column affinity string will eventually be deleted by
131 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
132 */
133 if ( pTab.zColAff == null )
134 {
135 StringBuilder zColAff;
136 int i;
137 ////sqlite3 db = sqlite3VdbeDb( v );
138  
139 zColAff = new StringBuilder( pTab.nCol + 1 );// (char)sqlite3DbMallocRaw(0, pTab->nCol+1);
140 if ( zColAff == null )
141 {
142 //// db.mallocFailed = 1;
143 return;
144 }
145  
146 for ( i = 0; i < pTab.nCol; i++ )
147 {
148 zColAff.Append( pTab.aCol[i].affinity );
149 }
150 //zColAff.Append( '\0' );
151  
152 pTab.zColAff = zColAff.ToString();
153 }
154  
155 sqlite3VdbeChangeP4( v, -1, pTab.zColAff, P4_TRANSIENT );
156 }
157  
158 /*
159 ** Return non-zero if the table pTab in database iDb or any of its indices
160 ** have been opened at any point in the VDBE program beginning at location
161 ** iStartAddr throught the end of the program. This is used to see if
162 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
163 ** run without using temporary table for the results of the SELECT.
164 */
165 static bool readsTable( Parse p, int iStartAddr, int iDb, Table pTab )
166 {
167 Vdbe v = sqlite3GetVdbe( p );
168 int i;
169 int iEnd = sqlite3VdbeCurrentAddr( v );
170 #if !SQLITE_OMIT_VIRTUALTABLE
171 VTable pVTab = IsVirtual( pTab ) ? sqlite3GetVTable( p.db, pTab ) : null;
172 #endif
173  
174 for ( i = iStartAddr; i < iEnd; i++ )
175 {
176 VdbeOp pOp = sqlite3VdbeGetOp( v, i );
177 Debug.Assert( pOp != null );
178 if ( pOp.opcode == OP_OpenRead && pOp.p3 == iDb )
179 {
180 Index pIndex;
181 int tnum = pOp.p2;
182 if ( tnum == pTab.tnum )
183 {
184 return true;
185 }
186 for ( pIndex = pTab.pIndex; pIndex != null; pIndex = pIndex.pNext )
187 {
188 if ( tnum == pIndex.tnum )
189 {
190 return true;
191 }
192 }
193 }
194 #if !SQLITE_OMIT_VIRTUALTABLE
195 if ( pOp.opcode == OP_VOpen && pOp.p4.pVtab == pVTab )
196 {
197 Debug.Assert( pOp.p4.pVtab != null );
198 Debug.Assert( pOp.p4type == P4_VTAB );
199 return true;
200 }
201 #endif
202 }
203 return false;
204 }
205  
206 #if !SQLITE_OMIT_AUTOINCREMENT
207 /*
208 ** Locate or create an AutoincInfo structure associated with table pTab
209 ** which is in database iDb. Return the register number for the register
210 ** that holds the maximum rowid.
211 **
212 ** There is at most one AutoincInfo structure per table even if the
213 ** same table is autoincremented multiple times due to inserts within
214 ** triggers. A new AutoincInfo structure is created if this is the
215 ** first use of table pTab. On 2nd and subsequent uses, the original
216 ** AutoincInfo structure is used.
217 **
218 ** Three memory locations are allocated:
219 **
220 ** (1) Register to hold the name of the pTab table.
221 ** (2) Register to hold the maximum ROWID of pTab.
222 ** (3) Register to hold the rowid in sqlite_sequence of pTab
223 **
224 ** The 2nd register is the one that is returned. That is all the
225 ** insert routine needs to know about.
226 */
227 static int autoIncBegin(
228 Parse pParse, /* Parsing context */
229 int iDb, /* Index of the database holding pTab */
230 Table pTab /* The table we are writing to */
231 )
232 {
233 int memId = 0; /* Register holding maximum rowid */
234 if ( ( pTab.tabFlags & TF_Autoincrement ) != 0 )
235 {
236 Parse pToplevel = sqlite3ParseToplevel( pParse );
237 AutoincInfo pInfo;
238  
239 pInfo = pToplevel.pAinc;
240 while ( pInfo != null && pInfo.pTab != pTab )
241 {
242 pInfo = pInfo.pNext;
243 }
244 if ( pInfo == null )
245 {
246 pInfo = new AutoincInfo();//sqlite3DbMallocRaw(pParse.db, sizeof(*pInfo));
247 //if( pInfo==0 ) return 0;
248 pInfo.pNext = pToplevel.pAinc;
249 pToplevel.pAinc = pInfo;
250 pInfo.pTab = pTab;
251 pInfo.iDb = iDb;
252 pToplevel.nMem++; /* Register to hold name of table */
253 pInfo.regCtr = ++pToplevel.nMem; /* Max rowid register */
254 pToplevel.nMem++; /* Rowid in sqlite_sequence */
255 }
256 memId = pInfo.regCtr;
257 }
258 return memId;
259 }
260  
261 /*
262 ** This routine generates code that will initialize all of the
263 ** register used by the autoincrement tracker.
264 */
265 static void sqlite3AutoincrementBegin( Parse pParse )
266 {
267 AutoincInfo p; /* Information about an AUTOINCREMENT */
268 sqlite3 db = pParse.db; /* The database connection */
269 Db pDb; /* Database only autoinc table */
270 int memId; /* Register holding max rowid */
271 int addr; /* A VDBE address */
272 Vdbe v = pParse.pVdbe; /* VDBE under construction */
273  
274 /* This routine is never called during trigger-generation. It is
275 ** only called from the top-level */
276 Debug.Assert( pParse.pTriggerTab == null );
277 Debug.Assert( pParse == sqlite3ParseToplevel( pParse ) );
278  
279 Debug.Assert( v != null ); /* We failed long ago if this is not so */
280 for ( p = pParse.pAinc; p != null; p = p.pNext )
281 {
282 pDb = db.aDb[p.iDb];
283 memId = p.regCtr;
284 Debug.Assert( sqlite3SchemaMutexHeld( db, 0, pDb.pSchema ) );
285 sqlite3OpenTable( pParse, 0, p.iDb, pDb.pSchema.pSeqTab, OP_OpenRead );
286 addr = sqlite3VdbeCurrentAddr( v );
287 sqlite3VdbeAddOp4( v, OP_String8, 0, memId - 1, 0, p.pTab.zName, 0 );
288 sqlite3VdbeAddOp2( v, OP_Rewind, 0, addr + 9 );
289 sqlite3VdbeAddOp3( v, OP_Column, 0, 0, memId );
290 sqlite3VdbeAddOp3( v, OP_Ne, memId - 1, addr + 7, memId );
291 sqlite3VdbeChangeP5( v, SQLITE_JUMPIFNULL );
292 sqlite3VdbeAddOp2( v, OP_Rowid, 0, memId + 1 );
293 sqlite3VdbeAddOp3( v, OP_Column, 0, 1, memId );
294 sqlite3VdbeAddOp2( v, OP_Goto, 0, addr + 9 );
295 sqlite3VdbeAddOp2( v, OP_Next, 0, addr + 2 );
296 sqlite3VdbeAddOp2( v, OP_Integer, 0, memId );
297 sqlite3VdbeAddOp0( v, OP_Close );
298 }
299 }
300  
301 /*
302 ** Update the maximum rowid for an autoincrement calculation.
303 **
304 ** This routine should be called when the top of the stack holds a
305 ** new rowid that is about to be inserted. If that new rowid is
306 ** larger than the maximum rowid in the memId memory cell, then the
307 ** memory cell is updated. The stack is unchanged.
308 */
309 static void autoIncStep( Parse pParse, int memId, int regRowid )
310 {
311 if ( memId > 0 )
312 {
313 sqlite3VdbeAddOp2( pParse.pVdbe, OP_MemMax, memId, regRowid );
314 }
315 }
316  
317 /*
318 ** This routine generates the code needed to write autoincrement
319 ** maximum rowid values back into the sqlite_sequence register.
320 ** Every statement that might do an INSERT into an autoincrement
321 ** table (either directly or through triggers) needs to call this
322 ** routine just before the "exit" code.
323 */
324 static void sqlite3AutoincrementEnd( Parse pParse )
325 {
326 AutoincInfo p;
327 Vdbe v = pParse.pVdbe;
328 sqlite3 db = pParse.db;
329  
330 Debug.Assert( v != null );
331 for ( p = pParse.pAinc; p != null; p = p.pNext )
332 {
333 Db pDb = db.aDb[p.iDb];
334 int j1, j2, j3, j4, j5;
335 int iRec;
336 int memId = p.regCtr;
337  
338 iRec = sqlite3GetTempReg( pParse );
339 Debug.Assert( sqlite3SchemaMutexHeld( db, 0, pDb.pSchema ) );
340 sqlite3OpenTable( pParse, 0, p.iDb, pDb.pSchema.pSeqTab, OP_OpenWrite );
341 j1 = sqlite3VdbeAddOp1( v, OP_NotNull, memId + 1 );
342 j2 = sqlite3VdbeAddOp0( v, OP_Rewind );
343 j3 = sqlite3VdbeAddOp3( v, OP_Column, 0, 0, iRec );
344 j4 = sqlite3VdbeAddOp3( v, OP_Eq, memId - 1, 0, iRec );
345 sqlite3VdbeAddOp2( v, OP_Next, 0, j3 );
346 sqlite3VdbeJumpHere( v, j2 );
347 sqlite3VdbeAddOp2( v, OP_NewRowid, 0, memId + 1 );
348 j5 = sqlite3VdbeAddOp0( v, OP_Goto );
349 sqlite3VdbeJumpHere( v, j4 );
350 sqlite3VdbeAddOp2( v, OP_Rowid, 0, memId + 1 );
351 sqlite3VdbeJumpHere( v, j1 );
352 sqlite3VdbeJumpHere( v, j5 );
353 sqlite3VdbeAddOp3( v, OP_MakeRecord, memId - 1, 2, iRec );
354 sqlite3VdbeAddOp3( v, OP_Insert, 0, iRec, memId + 1 );
355 sqlite3VdbeChangeP5( v, OPFLAG_APPEND );
356 sqlite3VdbeAddOp0( v, OP_Close );
357 sqlite3ReleaseTempReg( pParse, iRec );
358 }
359 }
360 #else
361 /*
362 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
363 ** above are all no-ops
364 */
365 //# define autoIncBegin(A,B,C) (0)
366 //# define autoIncStep(A,B,C)
367 #endif // * SQLITE_OMIT_AUTOINCREMENT */
368  
369  
370 /* Forward declaration */
371 //static int xferOptimization(
372 // Parse pParse, /* Parser context */
373 // Table pDest, /* The table we are inserting into */
374 // Select pSelect, /* A SELECT statement to use as the data source */
375 // int onError, /* How to handle constraint errors */
376 // int iDbDest /* The database of pDest */
377 //);
378  
379 /*
380 ** This routine is call to handle SQL of the following forms:
381 **
382 ** insert into TABLE (IDLIST) values(EXPRLIST)
383 ** insert into TABLE (IDLIST) select
384 **
385 ** The IDLIST following the table name is always optional. If omitted,
386 ** then a list of all columns for the table is substituted. The IDLIST
387 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
388 **
389 ** The pList parameter holds EXPRLIST in the first form of the INSERT
390 ** statement above, and pSelect is NULL. For the second form, pList is
391 ** NULL and pSelect is a pointer to the select statement used to generate
392 ** data for the insert.
393 **
394 ** The code generated follows one of four templates. For a simple
395 ** select with data coming from a VALUES clause, the code executes
396 ** once straight down through. Pseudo-code follows (we call this
397 ** the "1st template"):
398 **
399 ** open write cursor to <table> and its indices
400 ** puts VALUES clause expressions onto the stack
401 ** write the resulting record into <table>
402 ** cleanup
403 **
404 ** The three remaining templates assume the statement is of the form
405 **
406 ** INSERT INTO <table> SELECT ...
407 **
408 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
409 ** in other words if the SELECT pulls all columns from a single table
410 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
411 ** if <table2> and <table1> are distinct tables but have identical
412 ** schemas, including all the same indices, then a special optimization
413 ** is invoked that copies raw records from <table2> over to <table1>.
414 ** See the xferOptimization() function for the implementation of this
415 ** template. This is the 2nd template.
416 **
417 ** open a write cursor to <table>
418 ** open read cursor on <table2>
419 ** transfer all records in <table2> over to <table>
420 ** close cursors
421 ** foreach index on <table>
422 ** open a write cursor on the <table> index
423 ** open a read cursor on the corresponding <table2> index
424 ** transfer all records from the read to the write cursors
425 ** close cursors
426 ** end foreach
427 **
428 ** The 3rd template is for when the second template does not apply
429 ** and the SELECT clause does not read from <table> at any time.
430 ** The generated code follows this template:
431 **
432 ** EOF <- 0
433 ** X <- A
434 ** goto B
435 ** A: setup for the SELECT
436 ** loop over the rows in the SELECT
437 ** load values into registers R..R+n
438 ** yield X
439 ** end loop
440 ** cleanup after the SELECT
441 ** EOF <- 1
442 ** yield X
443 ** goto A
444 ** B: open write cursor to <table> and its indices
445 ** C: yield X
446 ** if EOF goto D
447 ** insert the select result into <table> from R..R+n
448 ** goto C
449 ** D: cleanup
450 **
451 ** The 4th template is used if the insert statement takes its
452 ** values from a SELECT but the data is being inserted into a table
453 ** that is also read as part of the SELECT. In the third form,
454 ** we have to use a intermediate table to store the results of
455 ** the select. The template is like this:
456 **
457 ** EOF <- 0
458 ** X <- A
459 ** goto B
460 ** A: setup for the SELECT
461 ** loop over the tables in the SELECT
462 ** load value into register R..R+n
463 ** yield X
464 ** end loop
465 ** cleanup after the SELECT
466 ** EOF <- 1
467 ** yield X
468 ** halt-error
469 ** B: open temp table
470 ** L: yield X
471 ** if EOF goto M
472 ** insert row from R..R+n into temp table
473 ** goto L
474 ** M: open write cursor to <table> and its indices
475 ** rewind temp table
476 ** C: loop over rows of intermediate table
477 ** transfer values form intermediate table into <table>
478 ** end loop
479 ** D: cleanup
480 */
481 // OVERLOADS, so I don't need to rewrite parse.c
482 static void sqlite3Insert( Parse pParse, SrcList pTabList, int null_3, int null_4, IdList pColumn, int onError )
483 {
484 sqlite3Insert( pParse, pTabList, null, null, pColumn, onError );
485 }
486 static void sqlite3Insert( Parse pParse, SrcList pTabList, int null_3, Select pSelect, IdList pColumn, int onError )
487 {
488 sqlite3Insert( pParse, pTabList, null, pSelect, pColumn, onError );
489 }
490 static void sqlite3Insert( Parse pParse, SrcList pTabList, ExprList pList, int null_4, IdList pColumn, int onError )
491 {
492 sqlite3Insert( pParse, pTabList, pList, null, pColumn, onError );
493 }
494 static void sqlite3Insert(
495 Parse pParse, /* Parser context */
496 SrcList pTabList, /* Name of table into which we are inserting */
497 ExprList pList, /* List of values to be inserted */
498 Select pSelect, /* A SELECT statement to use as the data source */
499 IdList pColumn, /* Column names corresponding to IDLIST. */
500 int onError /* How to handle constraint errors */
501 )
502 {
503 sqlite3 db; /* The main database structure */
504 Table pTab; /* The table to insert into. aka TABLE */
505 string zTab; /* Name of the table into which we are inserting */
506 int i = 0;
507 int j = 0;
508 int idx = 0; /* Loop counters */
509 Vdbe v; /* Generate code into this virtual machine */
510 Index pIdx; /* For looping over indices of the table */
511 int nColumn; /* Number of columns in the data */
512 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
513 int baseCur = 0; /* VDBE VdbeCursor number for pTab */
514 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
515 int endOfLoop = 0; /* Label for the end of the insertion loop */
516 bool useTempTable = false; /* Store SELECT results in intermediate table */
517 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
518 int addrInsTop = 0; /* Jump to label "D" */
519 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
520 int addrSelect = 0; /* Address of coroutine that implements the SELECT */
521 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
522 int iDb; /* Index of database holding TABLE */
523 bool appendFlag = false; /* True if the insert is likely to be an append */
524  
525 /* Register allocations */
526 int regFromSelect = 0; /* Base register for data coming from SELECT */
527 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
528 int regRowCount = 0; /* Memory cell used for the row counter */
529 int regIns; /* Block of regs holding rowid+data being inserted */
530 int regRowid; /* registers holding insert rowid */
531 int regData; /* register holding first column to insert */
532 int regEof = 0; /* Register recording end of SELECT data */
533 int[] aRegIdx = null; /* One register allocated to each index */
534  
535  
536 #if !SQLITE_OMIT_TRIGGER
537 bool isView = false; /* True if attempting to insert into a view */
538 Trigger pTrigger; /* List of triggers on pTab, if required */
539 int tmask = 0; /* Mask of trigger times */
540 #endif
541  
542 db = pParse.db;
543 dest = new SelectDest();// memset( &dest, 0, sizeof( dest ) );
544  
545 if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ )
546 {
547 goto insert_cleanup;
548 }
549  
550 /* Locate the table into which we will be inserting new information.
551 */
552 Debug.Assert( pTabList.nSrc == 1 );
553 zTab = pTabList.a[0].zName;
554 if ( NEVER( zTab == null ) )
555 goto insert_cleanup;
556 pTab = sqlite3SrcListLookup( pParse, pTabList );
557 if ( pTab == null )
558 {
559 goto insert_cleanup;
560 }
561 iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
562 Debug.Assert( iDb < db.nDb );
563 #if !SQLITE_OMIT_AUTHORIZATION
564 Db pDb; /* The database containing table being inserted into */
565 pDb = db.aDb[iDb];
566 string zDb; /* Name of the database holding this table */
567 zDb = pDb.zName;
568 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab.zName, 0, zDb) ){
569 goto insert_cleanup;
570 }
571 #endif
572 /* Figure out if we have any triggers and if the table being
573 ** inserted into is a view
574 */
575 #if !SQLITE_OMIT_TRIGGER
576 pTrigger = sqlite3TriggersExist( pParse, pTab, TK_INSERT, null, out tmask );
577 isView = pTab.pSelect != null;
578 #else
579 Trigger pTrigger = null; //# define pTrigger 0
580 int tmask = 0; //# define tmask 0
581 bool isView = false;
582 #endif
583 #if SQLITE_OMIT_VIEW
584 //# undef isView
585 isView = false;
586 #endif
587 #if !SQLITE_OMIT_TRIGGER
588 Debug.Assert( ( pTrigger != null && tmask != 0 ) || ( pTrigger == null && tmask == 0 ) );
589 #endif
590  
591 #if !SQLITE_OMIT_VIEW
592 /* If pTab is really a view, make sure it has been initialized.
593 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
594 ** module table).
595 */
596 if ( sqlite3ViewGetColumnNames( pParse, pTab ) != -0 )
597 {
598 goto insert_cleanup;
599 }
600 #endif
601  
602 /* Ensure that:
603 * (a) the table is not read-only,
604 * (b) that if it is a view then ON INSERT triggers exist
605 */
606 if ( sqlite3IsReadOnly( pParse, pTab, tmask ) )
607 {
608 goto insert_cleanup;
609 }
610  
611 /* Allocate a VDBE
612 */
613 v = sqlite3GetVdbe( pParse );
614 if ( v == null )
615 goto insert_cleanup;
616 if ( pParse.nested == 0 )
617 sqlite3VdbeCountChanges( v );
618 sqlite3BeginWriteOperation( pParse, ( pSelect != null || pTrigger != null ) ? 1 : 0, iDb );
619  
620 #if !SQLITE_OMIT_XFER_OPT
621 /* If the statement is of the form
622 **
623 ** INSERT INTO <table1> SELECT * FROM <table2>;
624 **
625 ** Then special optimizations can be applied that make the transfer
626 ** very fast and which reduce fragmentation of indices.
627 **
628 ** This is the 2nd template.
629 */
630 if ( pColumn == null && xferOptimization( pParse, pTab, pSelect, onError, iDb ) != 0 )
631 {
632 Debug.Assert( null == pTrigger );
633 Debug.Assert( pList == null );
634 goto insert_end;
635 }
636 #endif // * SQLITE_OMIT_XFER_OPT */
637  
638 /* If this is an AUTOINCREMENT table, look up the sequence number in the
639 ** sqlite_sequence table and store it in memory cell regAutoinc.
640 */
641 regAutoinc = autoIncBegin( pParse, iDb, pTab );
642  
643 /* Figure out how many columns of data are supplied. If the data
644 ** is coming from a SELECT statement, then generate a co-routine that
645 ** produces a single row of the SELECT on each invocation. The
646 ** co-routine is the common header to the 3rd and 4th templates.
647 */
648 if ( pSelect != null )
649 {
650 /* Data is coming from a SELECT. Generate code to implement that SELECT
651 ** as a co-routine. The code is common to both the 3rd and 4th
652 ** templates:
653 **
654 ** EOF <- 0
655 ** X <- A
656 ** goto B
657 ** A: setup for the SELECT
658 ** loop over the tables in the SELECT
659 ** load value into register R..R+n
660 ** yield X
661 ** end loop
662 ** cleanup after the SELECT
663 ** EOF <- 1
664 ** yield X
665 ** halt-error
666 **
667 ** On each invocation of the co-routine, it puts a single row of the
668 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
669 ** (These output registers are allocated by sqlite3Select().) When
670 ** the SELECT completes, it sets the EOF flag stored in regEof.
671 */
672 int rc = 0, j1;
673  
674 regEof = ++pParse.nMem;
675 sqlite3VdbeAddOp2( v, OP_Integer, 0, regEof ); /* EOF <- 0 */
676 #if SQLITE_DEBUG
677 VdbeComment( v, "SELECT eof flag" );
678 #endif
679 sqlite3SelectDestInit( dest, SRT_Coroutine, ++pParse.nMem );
680 addrSelect = sqlite3VdbeCurrentAddr( v ) + 2;
681 sqlite3VdbeAddOp2( v, OP_Integer, addrSelect - 1, dest.iParm );
682 j1 = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 );
683 #if SQLITE_DEBUG
684 VdbeComment( v, "Jump over SELECT coroutine" );
685 #endif
686 /* Resolve the expressions in the SELECT statement and execute it. */
687 rc = sqlite3Select( pParse, pSelect, ref dest );
688 Debug.Assert( pParse.nErr == 0 || rc != 0 );
689 if ( rc != 0 || NEVER( pParse.nErr != 0 ) /*|| db.mallocFailed != 0 */ )
690 {
691 goto insert_cleanup;
692 }
693 sqlite3VdbeAddOp2( v, OP_Integer, 1, regEof ); /* EOF <- 1 */
694 sqlite3VdbeAddOp1( v, OP_Yield, dest.iParm ); /* yield X */
695 sqlite3VdbeAddOp2( v, OP_Halt, SQLITE_INTERNAL, OE_Abort );
696 #if SQLITE_DEBUG
697 VdbeComment( v, "End of SELECT coroutine" );
698 #endif
699 sqlite3VdbeJumpHere( v, j1 ); /* label B: */
700  
701 regFromSelect = dest.iMem;
702 Debug.Assert( pSelect.pEList != null );
703 nColumn = pSelect.pEList.nExpr;
704 Debug.Assert( dest.nMem == nColumn );
705  
706 /* Set useTempTable to TRUE if the result of the SELECT statement
707 ** should be written into a temporary table (template 4). Set to
708 ** FALSE if each* row of the SELECT can be written directly into
709 ** the destination table (template 3).
710 **
711 ** A temp table must be used if the table being updated is also one
712 ** of the tables being read by the SELECT statement. Also use a
713 ** temp table in the case of row triggers.
714 */
715 if ( pTrigger != null || readsTable( pParse, addrSelect, iDb, pTab ) )
716 {
717 useTempTable = true;
718 }
719  
720 if ( useTempTable )
721 {
722 /* Invoke the coroutine to extract information from the SELECT
723 ** and add it to a transient table srcTab. The code generated
724 ** here is from the 4th template:
725 **
726 ** B: open temp table
727 ** L: yield X
728 ** if EOF goto M
729 ** insert row from R..R+n into temp table
730 ** goto L
731 ** M: ...
732 */
733 int regRec; /* Register to hold packed record */
734 int regTempRowid; /* Register to hold temp table ROWID */
735 int addrTop; /* Label "L" */
736 int addrIf; /* Address of jump to M */
737  
738 srcTab = pParse.nTab++;
739 regRec = sqlite3GetTempReg( pParse );
740 regTempRowid = sqlite3GetTempReg( pParse );
741 sqlite3VdbeAddOp2( v, OP_OpenEphemeral, srcTab, nColumn );
742 addrTop = sqlite3VdbeAddOp1( v, OP_Yield, dest.iParm );
743 addrIf = sqlite3VdbeAddOp1( v, OP_If, regEof );
744 sqlite3VdbeAddOp3( v, OP_MakeRecord, regFromSelect, nColumn, regRec );
745 sqlite3VdbeAddOp2( v, OP_NewRowid, srcTab, regTempRowid );
746 sqlite3VdbeAddOp3( v, OP_Insert, srcTab, regRec, regTempRowid );
747 sqlite3VdbeAddOp2( v, OP_Goto, 0, addrTop );
748 sqlite3VdbeJumpHere( v, addrIf );
749 sqlite3ReleaseTempReg( pParse, regRec );
750 sqlite3ReleaseTempReg( pParse, regTempRowid );
751 }
752 }
753 else
754 {
755 /* This is the case if the data for the INSERT is coming from a VALUES
756 ** clause
757 */
758 NameContext sNC;
759 sNC = new NameContext();// memset( &sNC, 0, sNC ).Length;
760 sNC.pParse = pParse;
761 srcTab = -1;
762 Debug.Assert( !useTempTable );
763 nColumn = pList != null ? pList.nExpr : 0;
764 for ( i = 0; i < nColumn; i++ )
765 {
766 if ( sqlite3ResolveExprNames( sNC, ref pList.a[i].pExpr ) != 0 )
767 {
768 goto insert_cleanup;
769 }
770 }
771 }
772  
773 /* Make sure the number of columns in the source data matches the number
774 ** of columns to be inserted into the table.
775 */
776 if ( IsVirtual( pTab ) )
777 {
778 for ( i = 0; i < pTab.nCol; i++ )
779 {
780 nHidden += ( IsHiddenColumn( pTab.aCol[i] ) ? 1 : 0 );
781 }
782 }
783 if ( pColumn == null && nColumn != 0 && nColumn != ( pTab.nCol - nHidden ) )
784 {
785 sqlite3ErrorMsg( pParse,
786 "table %S has %d columns but %d values were supplied",
787 pTabList, 0, pTab.nCol - nHidden, nColumn );
788 goto insert_cleanup;
789 }
790 if ( pColumn != null && nColumn != pColumn.nId )
791 {
792 sqlite3ErrorMsg( pParse, "%d values for %d columns", nColumn, pColumn.nId );
793 goto insert_cleanup;
794 }
795  
796 /* If the INSERT statement included an IDLIST term, then make sure
797 ** all elements of the IDLIST really are columns of the table and
798 ** remember the column indices.
799 **
800 ** If the table has an INTEGER PRIMARY KEY column and that column
801 ** is named in the IDLIST, then record in the keyColumn variable
802 ** the index into IDLIST of the primary key column. keyColumn is
803 ** the index of the primary key as it appears in IDLIST, not as
804 ** is appears in the original table. (The index of the primary
805 ** key in the original table is pTab.iPKey.)
806 */
807 if ( pColumn != null )
808 {
809 for ( i = 0; i < pColumn.nId; i++ )
810 {
811 pColumn.a[i].idx = -1;
812 }
813 for ( i = 0; i < pColumn.nId; i++ )
814 {
815 for ( j = 0; j < pTab.nCol; j++ )
816 {
817 if ( pColumn.a[i].zName.Equals( pTab.aCol[j].zName ,StringComparison.OrdinalIgnoreCase ) )
818 {
819 pColumn.a[i].idx = j;
820 if ( j == pTab.iPKey )
821 {
822 keyColumn = i;
823 }
824 break;
825 }
826 }
827 if ( j >= pTab.nCol )
828 {
829 if ( sqlite3IsRowid( pColumn.a[i].zName ) )
830 {
831 keyColumn = i;
832 }
833 else
834 {
835 sqlite3ErrorMsg( pParse, "table %S has no column named %s",
836 pTabList, 0, pColumn.a[i].zName );
837 pParse.checkSchema = 1;
838 goto insert_cleanup;
839 }
840 }
841 }
842 }
843  
844 /* If there is no IDLIST term but the table has an integer primary
845 ** key, the set the keyColumn variable to the primary key column index
846 ** in the original table definition.
847 */
848 if ( pColumn == null && nColumn > 0 )
849 {
850 keyColumn = pTab.iPKey;
851 }
852  
853 /* Initialize the count of rows to be inserted
854 */
855 if ( ( db.flags & SQLITE_CountRows ) != 0 )
856 {
857 regRowCount = ++pParse.nMem;
858 sqlite3VdbeAddOp2( v, OP_Integer, 0, regRowCount );
859 }
860  
861 /* If this is not a view, open the table and and all indices */
862 if ( !isView )
863 {
864 int nIdx;
865  
866 baseCur = pParse.nTab;
867 nIdx = sqlite3OpenTableAndIndices( pParse, pTab, baseCur, OP_OpenWrite );
868 aRegIdx = new int[nIdx + 1];// sqlite3DbMallocRaw( db, sizeof( int ) * ( nIdx + 1 ) );
869 if ( aRegIdx == null )
870 {
871 goto insert_cleanup;
872 }
873 for ( i = 0; i < nIdx; i++ )
874 {
875 aRegIdx[i] = ++pParse.nMem;
876 }
877 }
878  
879 /* This is the top of the main insertion loop */
880 if ( useTempTable )
881 {
882 /* This block codes the top of loop only. The complete loop is the
883 ** following pseudocode (template 4):
884 **
885 ** rewind temp table
886 ** C: loop over rows of intermediate table
887 ** transfer values form intermediate table into <table>
888 ** end loop
889 ** D: ...
890 */
891 addrInsTop = sqlite3VdbeAddOp1( v, OP_Rewind, srcTab );
892 addrCont = sqlite3VdbeCurrentAddr( v );
893 }
894 else if ( pSelect != null )
895 {
896 /* This block codes the top of loop only. The complete loop is the
897 ** following pseudocode (template 3):
898 **
899 ** C: yield X
900 ** if EOF goto D
901 ** insert the select result into <table> from R..R+n
902 ** goto C
903 ** D: ...
904 */
905 addrCont = sqlite3VdbeAddOp1( v, OP_Yield, dest.iParm );
906 addrInsTop = sqlite3VdbeAddOp1( v, OP_If, regEof );
907 }
908  
909 /* Allocate registers for holding the rowid of the new row,
910 ** the content of the new row, and the assemblied row record.
911 */
912 regRowid = regIns = pParse.nMem + 1;
913 pParse.nMem += pTab.nCol + 1;
914 if ( IsVirtual( pTab ) )
915 {
916 regRowid++;
917 pParse.nMem++;
918 }
919 regData = regRowid + 1;
920  
921 /* Run the BEFORE and INSTEAD OF triggers, if there are any
922 */
923 endOfLoop = sqlite3VdbeMakeLabel( v );
924 #if !SQLITE_OMIT_TRIGGER
925 if ( ( tmask & TRIGGER_BEFORE ) != 0 )
926 {
927 int regCols = sqlite3GetTempRange( pParse, pTab.nCol + 1 );
928  
929 /* build the NEW.* reference row. Note that if there is an INTEGER
930 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
931 ** translated into a unique ID for the row. But on a BEFORE trigger,
932 ** we do not know what the unique ID will be (because the insert has
933 ** not happened yet) so we substitute a rowid of -1
934 */
935 if ( keyColumn < 0 )
936 {
937 sqlite3VdbeAddOp2( v, OP_Integer, -1, regCols );
938 }
939 else
940 {
941 int j1;
942 if ( useTempTable )
943 {
944 sqlite3VdbeAddOp3( v, OP_Column, srcTab, keyColumn, regCols );
945 }
946 else
947 {
948 Debug.Assert( pSelect == null ); /* Otherwise useTempTable is true */
949 sqlite3ExprCode( pParse, pList.a[keyColumn].pExpr, regCols );
950 }
951 j1 = sqlite3VdbeAddOp1( v, OP_NotNull, regCols );
952 sqlite3VdbeAddOp2( v, OP_Integer, -1, regCols );
953 sqlite3VdbeJumpHere( v, j1 );
954 sqlite3VdbeAddOp1( v, OP_MustBeInt, regCols );
955 }
956 /* Cannot have triggers on a virtual table. If it were possible,
957 ** this block would have to account for hidden column.
958 */
959 Debug.Assert( !IsVirtual( pTab ) );
960 /* Create the new column data
961 */
962 for ( i = 0; i < pTab.nCol; i++ )
963 {
964 if ( pColumn == null )
965 {
966 j = i;
967 }
968 else
969 {
970 for ( j = 0; j < pColumn.nId; j++ )
971 {
972 if ( pColumn.a[j].idx == i )
973 break;
974 }
975 }
976 if ( ( !useTempTable && null == pList ) || ( pColumn != null && j >= pColumn.nId ) )
977 {
978 sqlite3ExprCode( pParse, pTab.aCol[i].pDflt, regCols + i + 1 );
979 }
980 else if ( useTempTable )
981 {
982 sqlite3VdbeAddOp3( v, OP_Column, srcTab, j, regCols + i + 1 );
983 }
984 else
985 {
986 Debug.Assert( pSelect == null ); /* Otherwise useTempTable is true */
987 sqlite3ExprCodeAndCache( pParse, pList.a[j].pExpr, regCols + i + 1 );
988 }
989 }
990  
991 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
992 ** do not attempt any conversions before assembling the record.
993 ** If this is a real table, attempt conversions as required by the
994 ** table column affinities.
995 */
996 if ( !isView )
997 {
998 sqlite3VdbeAddOp2( v, OP_Affinity, regCols + 1, pTab.nCol );
999 sqlite3TableAffinityStr( v, pTab );
1000 }
1001  
1002 /* Fire BEFORE or INSTEAD OF triggers */
1003 sqlite3CodeRowTrigger( pParse, pTrigger, TK_INSERT, null, TRIGGER_BEFORE,
1004 pTab, regCols - pTab.nCol - 1, onError, endOfLoop );
1005  
1006 sqlite3ReleaseTempRange( pParse, regCols, pTab.nCol + 1 );
1007 }
1008 #endif
1009  
1010 /* Push the record number for the new entry onto the stack. The
1011 ** record number is a randomly generate integer created by NewRowid
1012 ** except when the table has an INTEGER PRIMARY KEY column, in which
1013 ** case the record number is the same as that column.
1014 */
1015 if ( !isView )
1016 {
1017 if ( IsVirtual( pTab ) )
1018 {
1019 /* The row that the VUpdate opcode will delete: none */
1020 sqlite3VdbeAddOp2( v, OP_Null, 0, regIns );
1021 }
1022 if ( keyColumn >= 0 )
1023 {
1024 if ( useTempTable )
1025 {
1026 sqlite3VdbeAddOp3( v, OP_Column, srcTab, keyColumn, regRowid );
1027 }
1028 else if ( pSelect != null )
1029 {
1030 sqlite3VdbeAddOp2( v, OP_SCopy, regFromSelect + keyColumn, regRowid );
1031 }
1032 else
1033 {
1034 VdbeOp pOp;
1035 sqlite3ExprCode( pParse, pList.a[keyColumn].pExpr, regRowid );
1036 pOp = sqlite3VdbeGetOp( v, -1 );
1037 if ( ALWAYS( pOp != null ) && pOp.opcode == OP_Null && !IsVirtual( pTab ) )
1038 {
1039 appendFlag = true;
1040 pOp.opcode = OP_NewRowid;
1041 pOp.p1 = baseCur;
1042 pOp.p2 = regRowid;
1043 pOp.p3 = regAutoinc;
1044 }
1045 }
1046 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
1047 ** to generate a unique primary key value.
1048 */
1049 if ( !appendFlag )
1050 {
1051 int j1;
1052 if ( !IsVirtual( pTab ) )
1053 {
1054 j1 = sqlite3VdbeAddOp1( v, OP_NotNull, regRowid );
1055 sqlite3VdbeAddOp3( v, OP_NewRowid, baseCur, regRowid, regAutoinc );
1056 sqlite3VdbeJumpHere( v, j1 );
1057 }
1058 else
1059 {
1060 j1 = sqlite3VdbeCurrentAddr( v );
1061 sqlite3VdbeAddOp2( v, OP_IsNull, regRowid, j1 + 2 );
1062 }
1063 sqlite3VdbeAddOp1( v, OP_MustBeInt, regRowid );
1064 }
1065 }
1066 else if ( IsVirtual( pTab ) )
1067 {
1068 sqlite3VdbeAddOp2( v, OP_Null, 0, regRowid );
1069 }
1070 else
1071 {
1072 sqlite3VdbeAddOp3( v, OP_NewRowid, baseCur, regRowid, regAutoinc );
1073 appendFlag = true;
1074 }
1075 autoIncStep( pParse, regAutoinc, regRowid );
1076  
1077 /* Push onto the stack, data for all columns of the new entry, beginning
1078 ** with the first column.
1079 */
1080 nHidden = 0;
1081 for ( i = 0; i < pTab.nCol; i++ )
1082 {
1083 int iRegStore = regRowid + 1 + i;
1084 if ( i == pTab.iPKey )
1085 {
1086 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
1087 ** Whenever this column is read, the record number will be substituted
1088 ** in its place. So will fill this column with a NULL to avoid
1089 ** taking up data space with information that will never be used. */
1090 sqlite3VdbeAddOp2( v, OP_Null, 0, iRegStore );
1091 continue;
1092 }
1093 if ( pColumn == null )
1094 {
1095 if ( IsHiddenColumn( pTab.aCol[i] ) )
1096 {
1097 Debug.Assert( IsVirtual( pTab ) );
1098 j = -1;
1099 nHidden++;
1100 }
1101 else
1102 {
1103 j = i - nHidden;
1104 }
1105 }
1106 else
1107 {
1108 for ( j = 0; j < pColumn.nId; j++ )
1109 {
1110 if ( pColumn.a[j].idx == i )
1111 break;
1112 }
1113 }
1114 if ( j < 0 || nColumn == 0 || ( pColumn != null && j >= pColumn.nId ) )
1115 {
1116 sqlite3ExprCode( pParse, pTab.aCol[i].pDflt, iRegStore );
1117 }
1118 else if ( useTempTable )
1119 {
1120 sqlite3VdbeAddOp3( v, OP_Column, srcTab, j, iRegStore );
1121 }
1122 else if ( pSelect != null )
1123 {
1124 sqlite3VdbeAddOp2( v, OP_SCopy, regFromSelect + j, iRegStore );
1125 }
1126 else
1127 {
1128 sqlite3ExprCode( pParse, pList.a[j].pExpr, iRegStore );
1129 }
1130 }
1131  
1132 /* Generate code to check constraints and generate index keys and
1133 ** do the insertion.
1134 */
1135 #if !SQLITE_OMIT_VIRTUALTABLE
1136 if ( IsVirtual( pTab ) )
1137 {
1138 VTable pVTab = sqlite3GetVTable( db, pTab );
1139 sqlite3VtabMakeWritable( pParse, pTab );
1140 sqlite3VdbeAddOp4( v, OP_VUpdate, 1, pTab.nCol + 2, regIns, pVTab, P4_VTAB );
1141 sqlite3VdbeChangeP5( v, (byte)( onError == OE_Default ? OE_Abort : onError ) );
1142 sqlite3MayAbort( pParse );
1143 }
1144 else
1145 #endif
1146 {
1147 int isReplace = 0; /* Set to true if constraints may cause a replace */
1148 sqlite3GenerateConstraintChecks( pParse, pTab, baseCur, regIns, aRegIdx,
1149 keyColumn >= 0 ? 1 : 0, false, onError, endOfLoop, out isReplace
1150 );
1151 sqlite3FkCheck( pParse, pTab, 0, regIns );
1152 sqlite3CompleteInsertion(
1153 pParse, pTab, baseCur, regIns, aRegIdx, false, appendFlag, isReplace == 0
1154 );
1155 }
1156 }
1157  
1158 /* Update the count of rows that are inserted
1159 */
1160 if ( ( db.flags & SQLITE_CountRows ) != 0 )
1161 {
1162 sqlite3VdbeAddOp2( v, OP_AddImm, regRowCount, 1 );
1163 }
1164  
1165 #if !SQLITE_OMIT_TRIGGER
1166 if ( pTrigger != null )
1167 {
1168 /* Code AFTER triggers */
1169 sqlite3CodeRowTrigger( pParse, pTrigger, TK_INSERT, null, TRIGGER_AFTER,
1170 pTab, regData - 2 - pTab.nCol, onError, endOfLoop );
1171 }
1172 #endif
1173  
1174 /* The bottom of the main insertion loop, if the data source
1175 ** is a SELECT statement.
1176 */
1177 sqlite3VdbeResolveLabel( v, endOfLoop );
1178 if ( useTempTable )
1179 {
1180 sqlite3VdbeAddOp2( v, OP_Next, srcTab, addrCont );
1181 sqlite3VdbeJumpHere( v, addrInsTop );
1182 sqlite3VdbeAddOp1( v, OP_Close, srcTab );
1183 }
1184 else if ( pSelect != null )
1185 {
1186 sqlite3VdbeAddOp2( v, OP_Goto, 0, addrCont );
1187 sqlite3VdbeJumpHere( v, addrInsTop );
1188 }
1189  
1190 if ( !IsVirtual( pTab ) && !isView )
1191 {
1192 /* Close all tables opened */
1193 sqlite3VdbeAddOp1( v, OP_Close, baseCur );
1194 for ( idx = 1, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, idx++ )
1195 {
1196 sqlite3VdbeAddOp1( v, OP_Close, idx + baseCur );
1197 }
1198 }
1199  
1200 insert_end:
1201 /* Update the sqlite_sequence table by storing the content of the
1202 ** maximum rowid counter values recorded while inserting into
1203 ** autoincrement tables.
1204 */
1205 if ( pParse.nested == 0 && pParse.pTriggerTab == null )
1206 {
1207 sqlite3AutoincrementEnd( pParse );
1208 }
1209  
1210 /*
1211 ** Return the number of rows inserted. If this routine is
1212 ** generating code because of a call to sqlite3NestedParse(), do not
1213 ** invoke the callback function.
1214 */
1215 if ( ( db.flags & SQLITE_CountRows ) != 0 && 0 == pParse.nested && null == pParse.pTriggerTab )
1216 {
1217 sqlite3VdbeAddOp2( v, OP_ResultRow, regRowCount, 1 );
1218 sqlite3VdbeSetNumCols( v, 1 );
1219 sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC );
1220 }
1221  
1222 insert_cleanup:
1223 sqlite3SrcListDelete( db, ref pTabList );
1224 sqlite3ExprListDelete( db, ref pList );
1225 sqlite3SelectDelete( db, ref pSelect );
1226 sqlite3IdListDelete( db, ref pColumn );
1227 sqlite3DbFree( db, ref aRegIdx );
1228 }
1229  
1230 /* Make sure "isView" and other macros defined above are undefined. Otherwise
1231 ** thely may interfere with compilation of other functions in this file
1232 ** (or in another file, if this file becomes part of the amalgamation). */
1233 //#if isView
1234 // #undef isView
1235 //#endif
1236 //#if pTrigger
1237 // #undef pTrigger
1238 //#endif
1239 //#if tmask
1240 // #undef tmask
1241 //#endif
1242  
1243 /*
1244 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
1245 **
1246 ** The input is a range of consecutive registers as follows:
1247 **
1248 ** 1. The rowid of the row after the update.
1249 **
1250 ** 2. The data in the first column of the entry after the update.
1251 **
1252 ** i. Data from middle columns...
1253 **
1254 ** N. The data in the last column of the entry after the update.
1255 **
1256 ** The regRowid parameter is the index of the register containing (1).
1257 **
1258 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
1259 ** the address of a register containing the rowid before the update takes
1260 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
1261 ** is false, indicating an INSERT statement, then a non-zero rowidChng
1262 ** indicates that the rowid was explicitly specified as part of the
1263 ** INSERT statement. If rowidChng is false, it means that the rowid is
1264 ** computed automatically in an insert or that the rowid value is not
1265 ** modified by an update.
1266 **
1267 ** The code generated by this routine store new index entries into
1268 ** registers identified by aRegIdx[]. No index entry is created for
1269 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
1270 ** the same as the order of indices on the linked list of indices
1271 ** attached to the table.
1272 **
1273 ** This routine also generates code to check constraints. NOT NULL,
1274 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
1275 ** then the appropriate action is performed. There are five possible
1276 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
1277 **
1278 ** Constraint type Action What Happens
1279 ** --------------- ---------- ----------------------------------------
1280 ** any ROLLBACK The current transaction is rolled back and
1281 ** sqlite3_exec() returns immediately with a
1282 ** return code of SQLITE_CONSTRAINT.
1283 **
1284 ** any ABORT Back out changes from the current command
1285 ** only (do not do a complete rollback) then
1286 ** cause sqlite3_exec() to return immediately
1287 ** with SQLITE_CONSTRAINT.
1288 **
1289 ** any FAIL Sqlite_exec() returns immediately with a
1290 ** return code of SQLITE_CONSTRAINT. The
1291 ** transaction is not rolled back and any
1292 ** prior changes are retained.
1293 **
1294 ** any IGNORE The record number and data is popped from
1295 ** the stack and there is an immediate jump
1296 ** to label ignoreDest.
1297 **
1298 ** NOT NULL REPLACE The NULL value is replace by the default
1299 ** value for that column. If the default value
1300 ** is NULL, the action is the same as ABORT.
1301 **
1302 ** UNIQUE REPLACE The other row that conflicts with the row
1303 ** being inserted is removed.
1304 **
1305 ** CHECK REPLACE Illegal. The results in an exception.
1306 **
1307 ** Which action to take is determined by the overrideError parameter.
1308 ** Or if overrideError==OE_Default, then the pParse.onError parameter
1309 ** is used. Or if pParse.onError==OE_Default then the onError value
1310 ** for the constraint is used.
1311 **
1312 ** The calling routine must open a read/write cursor for pTab with
1313 ** cursor number "baseCur". All indices of pTab must also have open
1314 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
1315 ** Except, if there is no possibility of a REPLACE action then
1316 ** cursors do not need to be open for indices where aRegIdx[i]==0.
1317 */
1318 static void sqlite3GenerateConstraintChecks(
1319 Parse pParse, /* The parser context */
1320 Table pTab, /* the table into which we are inserting */
1321 int baseCur, /* Index of a read/write cursor pointing at pTab */
1322 int regRowid, /* Index of the range of input registers */
1323 int[] aRegIdx, /* Register used by each index. 0 for unused indices */
1324 int rowidChng, /* True if the rowid might collide with existing entry */
1325 bool isUpdate, /* True for UPDATE, False for INSERT */
1326 int overrideError, /* Override onError to this if not OE_Default */
1327 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
1328 out int pbMayReplace /* OUT: Set to true if constraint may cause a replace */
1329 )
1330 {
1331  
1332 int i; /* loop counter */
1333 Vdbe v; /* VDBE under constrution */
1334 int nCol; /* Number of columns */
1335 int onError; /* Conflict resolution strategy */
1336 int j1; /* Addresss of jump instruction */
1337 int j2 = 0, j3; /* Addresses of jump instructions */
1338 int regData; /* Register containing first data column */
1339 int iCur; /* Table cursor number */
1340 Index pIdx; /* Pointer to one of the indices */
1341 bool seenReplace = false; /* True if REPLACE is used to resolve INT PK conflict */
1342 int regOldRowid = ( rowidChng != 0 && isUpdate ) ? rowidChng : regRowid;
1343  
1344 v = sqlite3GetVdbe( pParse );
1345 Debug.Assert( v != null );
1346 Debug.Assert( pTab.pSelect == null ); /* This table is not a VIEW */
1347 nCol = pTab.nCol;
1348 regData = regRowid + 1;
1349  
1350  
1351 /* Test all NOT NULL constraints.
1352 */
1353 for ( i = 0; i < nCol; i++ )
1354 {
1355 if ( i == pTab.iPKey )
1356 {
1357 continue;
1358 }
1359 onError = pTab.aCol[i].notNull;
1360 if ( onError == OE_None )
1361 continue;
1362 if ( overrideError != OE_Default )
1363 {
1364 onError = overrideError;
1365 }
1366 else if ( onError == OE_Default )
1367 {
1368 onError = OE_Abort;
1369 }
1370 if ( onError == OE_Replace && pTab.aCol[i].pDflt == null )
1371 {
1372 onError = OE_Abort;
1373 }
1374 Debug.Assert( onError == OE_Rollback || onError == OE_Abort || onError == OE_Fail
1375 || onError == OE_Ignore || onError == OE_Replace );
1376 switch ( onError )
1377 {
1378 case OE_Abort:
1379 {
1380 sqlite3MayAbort( pParse );
1381 goto case OE_Fail;
1382 }
1383 case OE_Rollback:
1384 case OE_Fail:
1385 {
1386 string zMsg;
1387 sqlite3VdbeAddOp3( v, OP_HaltIfNull,
1388 SQLITE_CONSTRAINT, onError, regData + i );
1389 zMsg = sqlite3MPrintf( pParse.db, "%s.%s may not be NULL",
1390 pTab.zName, pTab.aCol[i].zName );
1391 sqlite3VdbeChangeP4( v, -1, zMsg, P4_DYNAMIC );
1392 break;
1393 }
1394 case OE_Ignore:
1395 {
1396 sqlite3VdbeAddOp2( v, OP_IsNull, regData + i, ignoreDest );
1397 break;
1398 }
1399 default:
1400 {
1401 Debug.Assert( onError == OE_Replace );
1402 j1 = sqlite3VdbeAddOp1( v, OP_NotNull, regData + i );
1403 sqlite3ExprCode( pParse, pTab.aCol[i].pDflt, regData + i );
1404 sqlite3VdbeJumpHere( v, j1 );
1405 break;
1406 }
1407 }
1408 }
1409  
1410 /* Test all CHECK constraints
1411 */
1412 #if !SQLITE_OMIT_CHECK
1413 if ( pTab.pCheck != null && ( pParse.db.flags & SQLITE_IgnoreChecks ) == 0 )
1414 {
1415 int allOk = sqlite3VdbeMakeLabel( v );
1416 pParse.ckBase = regData;
1417 sqlite3ExprIfTrue( pParse, pTab.pCheck, allOk, SQLITE_JUMPIFNULL );
1418 onError = overrideError != OE_Default ? overrideError : OE_Abort;
1419 if ( onError == OE_Ignore )
1420 {
1421 sqlite3VdbeAddOp2( v, OP_Goto, 0, ignoreDest );
1422 }
1423 else
1424 {
1425 if ( onError == OE_Replace )
1426 onError = OE_Abort; /* IMP: R-15569-63625 */
1427 sqlite3HaltConstraint( pParse, onError, (string)null, 0 );
1428 }
1429 sqlite3VdbeResolveLabel( v, allOk );
1430 }
1431 #endif // * !SQLITE_OMIT_CHECK) */
1432  
1433 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
1434 ** of the new record does not previously exist. Except, if this
1435 ** is an UPDATE and the primary key is not changing, that is OK.
1436 */
1437 if ( rowidChng != 0 )
1438 {
1439 onError = pTab.keyConf;
1440 if ( overrideError != OE_Default )
1441 {
1442 onError = overrideError;
1443 }
1444 else if ( onError == OE_Default )
1445 {
1446 onError = OE_Abort;
1447 }
1448  
1449 if ( isUpdate )
1450 {
1451 j2 = sqlite3VdbeAddOp3( v, OP_Eq, regRowid, 0, rowidChng );
1452 }
1453 j3 = sqlite3VdbeAddOp3( v, OP_NotExists, baseCur, 0, regRowid );
1454 switch ( onError )
1455 {
1456 default:
1457 {
1458 onError = OE_Abort;
1459 /* Fall thru into the next case */
1460 }
1461 goto case OE_Rollback;
1462 case OE_Rollback:
1463 case OE_Abort:
1464 case OE_Fail:
1465 {
1466 sqlite3HaltConstraint(
1467 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC );
1468 break;
1469 }
1470 case OE_Replace:
1471 {
1472 /* If there are DELETE triggers on this table and the
1473 ** recursive-triggers flag is set, call GenerateRowDelete() to
1474 ** remove the conflicting row from the the table. This will fire
1475 ** the triggers and remove both the table and index b-tree entries.
1476 **
1477 ** Otherwise, if there are no triggers or the recursive-triggers
1478 ** flag is not set, but the table has one or more indexes, call
1479 ** GenerateRowIndexDelete(). This removes the index b-tree entries
1480 ** only. The table b-tree entry will be replaced by the new entry
1481 ** when it is inserted.
1482 **
1483 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
1484 ** also invoke MultiWrite() to indicate that this VDBE may require
1485 ** statement rollback (if the statement is aborted after the delete
1486 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
1487 ** but being more selective here allows statements like:
1488 **
1489 ** REPLACE INTO t(rowid) VALUES($newrowid)
1490 **
1491 ** to run without a statement journal if there are no indexes on the
1492 ** table.
1493 */
1494 Trigger pTrigger = null;
1495 if ( ( pParse.db.flags & SQLITE_RecTriggers ) != 0 )
1496 {
1497 int iDummy;
1498 pTrigger = sqlite3TriggersExist( pParse, pTab, TK_DELETE, null, out iDummy );
1499 }
1500 if ( pTrigger != null || sqlite3FkRequired( pParse, pTab, null, 0 ) != 0 )
1501 {
1502 sqlite3MultiWrite( pParse );
1503 sqlite3GenerateRowDelete(
1504 pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
1505 );
1506 }
1507 else
1508 if ( pTab.pIndex != null )
1509 {
1510 sqlite3MultiWrite( pParse );
1511 sqlite3GenerateRowIndexDelete( pParse, pTab, baseCur, 0 );
1512 }
1513 seenReplace = true;
1514 break;
1515 }
1516 case OE_Ignore:
1517 {
1518 Debug.Assert( !seenReplace );
1519 sqlite3VdbeAddOp2( v, OP_Goto, 0, ignoreDest );
1520 break;
1521 }
1522 }
1523 sqlite3VdbeJumpHere( v, j3 );
1524 if ( isUpdate )
1525 {
1526 sqlite3VdbeJumpHere( v, j2 );
1527 }
1528 }
1529  
1530 /* Test all UNIQUE constraints by creating entries for each UNIQUE
1531 ** index and making sure that duplicate entries do not already exist.
1532 ** Add the new records to the indices as we go.
1533 */
1534 for ( iCur = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, iCur++ )
1535 {
1536 int regIdx;
1537 int regR;
1538  
1539 if ( aRegIdx[iCur] == 0 )
1540 continue; /* Skip unused indices */
1541  
1542 /* Create a key for accessing the index entry */
1543 regIdx = sqlite3GetTempRange( pParse, pIdx.nColumn + 1 );
1544 for ( i = 0; i < pIdx.nColumn; i++ )
1545 {
1546 int idx = pIdx.aiColumn[i];
1547 if ( idx == pTab.iPKey )
1548 {
1549 sqlite3VdbeAddOp2( v, OP_SCopy, regRowid, regIdx + i );
1550 }
1551 else
1552 {
1553 sqlite3VdbeAddOp2( v, OP_SCopy, regData + idx, regIdx + i );
1554 }
1555 }
1556 sqlite3VdbeAddOp2( v, OP_SCopy, regRowid, regIdx + i );
1557 sqlite3VdbeAddOp3( v, OP_MakeRecord, regIdx, pIdx.nColumn + 1, aRegIdx[iCur] );
1558 sqlite3VdbeChangeP4( v, -1, sqlite3IndexAffinityStr( v, pIdx ), P4_TRANSIENT );
1559 sqlite3ExprCacheAffinityChange( pParse, regIdx, pIdx.nColumn + 1 );
1560  
1561 /* Find out what action to take in case there is an indexing conflict */
1562 onError = pIdx.onError;
1563 if ( onError == OE_None )
1564 {
1565 sqlite3ReleaseTempRange( pParse, regIdx, pIdx.nColumn + 1 );
1566 continue; /* pIdx is not a UNIQUE index */
1567 }
1568  
1569 if ( overrideError != OE_Default )
1570 {
1571 onError = overrideError;
1572 }
1573 else if ( onError == OE_Default )
1574 {
1575 onError = OE_Abort;
1576 }
1577 if ( seenReplace )
1578 {
1579 if ( onError == OE_Ignore )
1580 onError = OE_Replace;
1581 else if ( onError == OE_Fail )
1582 onError = OE_Abort;
1583 }
1584  
1585  
1586 /* Check to see if the new index entry will be unique */
1587 regR = sqlite3GetTempReg( pParse );
1588 sqlite3VdbeAddOp2( v, OP_SCopy, regOldRowid, regR );
1589 j3 = sqlite3VdbeAddOp4( v, OP_IsUnique, baseCur + iCur + 1, 0,
1590 regR, regIdx,//regR, SQLITE_INT_TO_PTR(regIdx),
1591 P4_INT32 );
1592 sqlite3ReleaseTempRange( pParse, regIdx, pIdx.nColumn + 1 );
1593  
1594 /* Generate code that executes if the new index entry is not unique */
1595 Debug.Assert( onError == OE_Rollback || onError == OE_Abort || onError == OE_Fail
1596 || onError == OE_Ignore || onError == OE_Replace );
1597 switch ( onError )
1598 {
1599 case OE_Rollback:
1600 case OE_Abort:
1601 case OE_Fail:
1602 {
1603 int j;
1604 StrAccum errMsg = new StrAccum( 200 );
1605 string zSep;
1606 string zErr;
1607  
1608 sqlite3StrAccumInit( errMsg, null, 0, 200 );
1609 errMsg.db = pParse.db;
1610 zSep = pIdx.nColumn > 1 ? "columns " : "column ";
1611 for ( j = 0; j < pIdx.nColumn; j++ )
1612 {
1613 string zCol = pTab.aCol[pIdx.aiColumn[j]].zName;
1614 sqlite3StrAccumAppend( errMsg, zSep, -1 );
1615 zSep = ", ";
1616 sqlite3StrAccumAppend( errMsg, zCol, -1 );
1617 }
1618 sqlite3StrAccumAppend( errMsg,
1619 pIdx.nColumn > 1 ? " are not unique" : " is not unique", -1 );
1620 zErr = sqlite3StrAccumFinish( errMsg );
1621 sqlite3HaltConstraint( pParse, onError, zErr, 0 );
1622 sqlite3DbFree( errMsg.db, ref zErr );
1623 break;
1624 }
1625 case OE_Ignore:
1626 {
1627 Debug.Assert( !seenReplace );
1628 sqlite3VdbeAddOp2( v, OP_Goto, 0, ignoreDest );
1629 break;
1630 }
1631 default:
1632 {
1633 Trigger pTrigger = null;
1634 Debug.Assert( onError == OE_Replace );
1635 sqlite3MultiWrite( pParse );
1636 if ( ( pParse.db.flags & SQLITE_RecTriggers ) != 0 )
1637 {
1638 int iDummy;
1639 pTrigger = sqlite3TriggersExist( pParse, pTab, TK_DELETE, null, out iDummy );
1640 }
1641 sqlite3GenerateRowDelete(
1642 pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
1643 );
1644 seenReplace = true;
1645 break;
1646 }
1647 }
1648 sqlite3VdbeJumpHere( v, j3 );
1649 sqlite3ReleaseTempReg( pParse, regR );
1650 }
1651 //if ( pbMayReplace )
1652 {
1653 pbMayReplace = seenReplace ? 1 : 0;
1654 }
1655 }
1656  
1657 /*
1658 ** This routine generates code to finish the INSERT or UPDATE operation
1659 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
1660 ** A consecutive range of registers starting at regRowid contains the
1661 ** rowid and the content to be inserted.
1662 **
1663 ** The arguments to this routine should be the same as the first six
1664 ** arguments to sqlite3GenerateConstraintChecks.
1665 */
1666 static void sqlite3CompleteInsertion(
1667 Parse pParse, /* The parser context */
1668 Table pTab, /* the table into which we are inserting */
1669 int baseCur, /* Index of a read/write cursor pointing at pTab */
1670 int regRowid, /* Range of content */
1671 int[] aRegIdx, /* Register used by each index. 0 for unused indices */
1672 bool isUpdate, /* True for UPDATE, False for INSERT */
1673 bool appendBias, /* True if this is likely to be an append */
1674 bool useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
1675 )
1676 {
1677 int i;
1678 Vdbe v;
1679 int nIdx;
1680 Index pIdx;
1681 u8 pik_flags;
1682 int regData;
1683 int regRec;
1684  
1685 v = sqlite3GetVdbe( pParse );
1686 Debug.Assert( v != null );
1687 Debug.Assert( pTab.pSelect == null ); /* This table is not a VIEW */
1688 for ( nIdx = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, nIdx++ )
1689 {
1690 }
1691 for ( i = nIdx - 1; i >= 0; i-- )
1692 {
1693 if ( aRegIdx[i] == 0 )
1694 continue;
1695 sqlite3VdbeAddOp2( v, OP_IdxInsert, baseCur + i + 1, aRegIdx[i] );
1696 if ( useSeekResult )
1697 {
1698 sqlite3VdbeChangeP5( v, OPFLAG_USESEEKRESULT );
1699 }
1700 }
1701 regData = regRowid + 1;
1702 regRec = sqlite3GetTempReg( pParse );
1703 sqlite3VdbeAddOp3( v, OP_MakeRecord, regData, pTab.nCol, regRec );
1704 sqlite3TableAffinityStr( v, pTab );
1705 sqlite3ExprCacheAffinityChange( pParse, regData, pTab.nCol );
1706 if ( pParse.nested != 0 )
1707 {
1708 pik_flags = 0;
1709 }
1710 else
1711 {
1712 pik_flags = OPFLAG_NCHANGE;
1713 pik_flags |= ( isUpdate ? OPFLAG_ISUPDATE : OPFLAG_LASTROWID );
1714 }
1715 if ( appendBias )
1716 {
1717 pik_flags |= OPFLAG_APPEND;
1718 }
1719 if ( useSeekResult )
1720 {
1721 pik_flags |= OPFLAG_USESEEKRESULT;
1722 }
1723 sqlite3VdbeAddOp3( v, OP_Insert, baseCur, regRec, regRowid );
1724 if ( pParse.nested == 0 )
1725 {
1726 sqlite3VdbeChangeP4( v, -1, pTab.zName, P4_TRANSIENT );
1727 }
1728 sqlite3VdbeChangeP5( v, pik_flags );
1729 }
1730  
1731 /*
1732 ** Generate code that will open cursors for a table and for all
1733 ** indices of that table. The "baseCur" parameter is the cursor number used
1734 ** for the table. Indices are opened on subsequent cursors.
1735 **
1736 ** Return the number of indices on the table.
1737 */
1738 static int sqlite3OpenTableAndIndices(
1739 Parse pParse, /* Parsing context */
1740 Table pTab, /* Table to be opened */
1741 int baseCur, /* VdbeCursor number assigned to the table */
1742 int op /* OP_OpenRead or OP_OpenWrite */
1743 )
1744 {
1745 int i;
1746 int iDb;
1747 Index pIdx;
1748 Vdbe v;
1749  
1750 if ( IsVirtual( pTab ) )
1751 return 0;
1752 iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
1753 v = sqlite3GetVdbe( pParse );
1754 Debug.Assert( v != null );
1755 sqlite3OpenTable( pParse, baseCur, iDb, pTab, op );
1756 for ( i = 1, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++ )
1757 {
1758 KeyInfo pKey = sqlite3IndexKeyinfo( pParse, pIdx );
1759 Debug.Assert( pIdx.pSchema == pTab.pSchema );
1760 sqlite3VdbeAddOp4( v, op, i + baseCur, pIdx.tnum, iDb,
1761 pKey, P4_KEYINFO_HANDOFF );
1762 #if SQLITE_DEBUG
1763 VdbeComment( v, "%s", pIdx.zName );
1764 #endif
1765 }
1766 if ( pParse.nTab < baseCur + i )
1767 {
1768 pParse.nTab = baseCur + i;
1769 }
1770 return i - 1;
1771 }
1772  
1773  
1774 #if SQLITE_TEST
1775 /*
1776 ** The following global variable is incremented whenever the
1777 ** transfer optimization is used. This is used for testing
1778 ** purposes only - to make sure the transfer optimization really
1779 ** is happening when it is suppose to.
1780 */
1781 #if !TCLSH
1782 static int sqlite3_xferopt_count = 0;
1783 #else
1784 static tcl.lang.Var.SQLITE3_GETSET sqlite3_xferopt_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_xferopt_count" );
1785 #endif
1786 #endif // * SQLITE_TEST */
1787  
1788  
1789 #if !SQLITE_OMIT_XFER_OPT
1790 /*
1791 ** Check to collation names to see if they are compatible.
1792 */
1793 static bool xferCompatibleCollation( string z1, string z2 )
1794 {
1795 if ( z1 == null )
1796 {
1797 return z2 == null;
1798 }
1799 if ( z2 == null )
1800 {
1801 return false;
1802 }
1803 return z1.Equals( z2 ,StringComparison.OrdinalIgnoreCase ) ;
1804 }
1805  
1806  
1807 /*
1808 ** Check to see if index pSrc is compatible as a source of data
1809 ** for index pDest in an insert transfer optimization. The rules
1810 ** for a compatible index:
1811 **
1812 ** * The index is over the same set of columns
1813 ** * The same DESC and ASC markings occurs on all columns
1814 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
1815 ** * The same collating sequence on each column
1816 */
1817 static bool xferCompatibleIndex( Index pDest, Index pSrc )
1818 {
1819 int i;
1820 Debug.Assert( pDest != null && pSrc != null );
1821 Debug.Assert( pDest.pTable != pSrc.pTable );
1822 if ( pDest.nColumn != pSrc.nColumn )
1823 {
1824 return false; /* Different number of columns */
1825 }
1826 if ( pDest.onError != pSrc.onError )
1827 {
1828 return false; /* Different conflict resolution strategies */
1829 }
1830 for ( i = 0; i < pSrc.nColumn; i++ )
1831 {
1832 if ( pSrc.aiColumn[i] != pDest.aiColumn[i] )
1833 {
1834 return false; /* Different columns indexed */
1835 }
1836 if ( pSrc.aSortOrder[i] != pDest.aSortOrder[i] )
1837 {
1838 return false; /* Different sort orders */
1839 }
1840 if ( !xferCompatibleCollation( pSrc.azColl[i], pDest.azColl[i] ) )
1841 {
1842 return false; /* Different collating sequences */
1843 }
1844 }
1845  
1846 /* If no test above fails then the indices must be compatible */
1847 return true;
1848 }
1849  
1850 /*
1851 ** Attempt the transfer optimization on INSERTs of the form
1852 **
1853 ** INSERT INTO tab1 SELECT * FROM tab2;
1854 **
1855 ** This optimization is only attempted if
1856 **
1857 ** (1) tab1 and tab2 have identical schemas including all the
1858 ** same indices and constraints
1859 **
1860 ** (2) tab1 and tab2 are different tables
1861 **
1862 ** (3) There must be no triggers on tab1
1863 **
1864 ** (4) The result set of the SELECT statement is "*"
1865 **
1866 ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
1867 ** or LIMIT clause.
1868 **
1869 ** (6) The SELECT statement is a simple (not a compound) select that
1870 ** contains only tab2 in its FROM clause
1871 **
1872 ** This method for implementing the INSERT transfers raw records from
1873 ** tab2 over to tab1. The columns are not decoded. Raw records from
1874 ** the indices of tab2 are transfered to tab1 as well. In so doing,
1875 ** the resulting tab1 has much less fragmentation.
1876 **
1877 ** This routine returns TRUE if the optimization is attempted. If any
1878 ** of the conditions above fail so that the optimization should not
1879 ** be attempted, then this routine returns FALSE.
1880 */
1881 static int xferOptimization(
1882 Parse pParse, /* Parser context */
1883 Table pDest, /* The table we are inserting into */
1884 Select pSelect, /* A SELECT statement to use as the data source */
1885 int onError, /* How to handle constraint errors */
1886 int iDbDest /* The database of pDest */
1887 )
1888 {
1889 ExprList pEList; /* The result set of the SELECT */
1890 Table pSrc; /* The table in the FROM clause of SELECT */
1891 Index pSrcIdx, pDestIdx; /* Source and destination indices */
1892 SrcList_item pItem; /* An element of pSelect.pSrc */
1893 int i; /* Loop counter */
1894 int iDbSrc; /* The database of pSrc */
1895 int iSrc, iDest; /* Cursors from source and destination */
1896 int addr1, addr2; /* Loop addresses */
1897 int emptyDestTest; /* Address of test for empty pDest */
1898 int emptySrcTest; /* Address of test for empty pSrc */
1899 Vdbe v; /* The VDBE we are building */
1900 KeyInfo pKey; /* Key information for an index */
1901 int regAutoinc; /* Memory register used by AUTOINC */
1902 bool destHasUniqueIdx = false; /* True if pDest has a UNIQUE index */
1903 int regData, regRowid; /* Registers holding data and rowid */
1904  
1905 if ( pSelect == null )
1906 {
1907 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
1908 }
1909 #if !SQLITE_OMIT_TRIGGER
1910 if ( sqlite3TriggerList( pParse, pDest ) != null )
1911 {
1912 return 0; /* tab1 must not have triggers */
1913 }
1914 #endif
1915  
1916 if ( ( pDest.tabFlags & TF_Virtual ) != 0 )
1917 {
1918 return 0; /* tab1 must not be a virtual table */
1919 }
1920 if ( onError == OE_Default )
1921 {
1922 onError = OE_Abort;
1923 }
1924 if ( onError != OE_Abort && onError != OE_Rollback )
1925 {
1926 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
1927 }
1928 Debug.Assert( pSelect.pSrc != null ); /* allocated even if there is no FROM clause */
1929 if ( pSelect.pSrc.nSrc != 1 )
1930 {
1931 return 0; /* FROM clause must have exactly one term */
1932 }
1933 if ( pSelect.pSrc.a[0].pSelect != null )
1934 {
1935 return 0; /* FROM clause cannot contain a subquery */
1936 }
1937 if ( pSelect.pWhere != null )
1938 {
1939 return 0; /* SELECT may not have a WHERE clause */
1940 }
1941 if ( pSelect.pOrderBy != null )
1942 {
1943 return 0; /* SELECT may not have an ORDER BY clause */
1944 }
1945 /* Do not need to test for a HAVING clause. If HAVING is present but
1946 ** there is no ORDER BY, we will get an error. */
1947 if ( pSelect.pGroupBy != null )
1948 {
1949 return 0; /* SELECT may not have a GROUP BY clause */
1950 }
1951 if ( pSelect.pLimit != null )
1952 {
1953 return 0; /* SELECT may not have a LIMIT clause */
1954 }
1955 Debug.Assert( pSelect.pOffset == null ); /* Must be so if pLimit==0 */
1956 if ( pSelect.pPrior != null )
1957 {
1958 return 0; /* SELECT may not be a compound query */
1959 }
1960 if ( ( pSelect.selFlags & SF_Distinct ) != 0 )
1961 {
1962 return 0; /* SELECT may not be DISTINCT */
1963 }
1964 pEList = pSelect.pEList;
1965 Debug.Assert( pEList != null );
1966 if ( pEList.nExpr != 1 )
1967 {
1968 return 0; /* The result set must have exactly one column */
1969 }
1970 Debug.Assert( pEList.a[0].pExpr != null );
1971 if ( pEList.a[0].pExpr.op != TK_ALL )
1972 {
1973 return 0; /* The result set must be the special operator "*" */
1974 }
1975  
1976 /* At this point we have established that the statement is of the
1977 ** correct syntactic form to participate in this optimization. Now
1978 ** we have to check the semantics.
1979 */
1980 pItem = pSelect.pSrc.a[0];
1981 pSrc = sqlite3LocateTable( pParse, 0, pItem.zName, pItem.zDatabase );
1982 if ( pSrc == null )
1983 {
1984 return 0; /* FROM clause does not contain a real table */
1985 }
1986 if ( pSrc == pDest )
1987 {
1988 return 0; /* tab1 and tab2 may not be the same table */
1989 }
1990 if ( ( pSrc.tabFlags & TF_Virtual ) != 0 )
1991 {
1992 return 0; /* tab2 must not be a virtual table */
1993 }
1994 if ( pSrc.pSelect != null )
1995 {
1996 return 0; /* tab2 may not be a view */
1997 }
1998 if ( pDest.nCol != pSrc.nCol )
1999 {
2000 return 0; /* Number of columns must be the same in tab1 and tab2 */
2001 }
2002 if ( pDest.iPKey != pSrc.iPKey )
2003 {
2004 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
2005 }
2006 for ( i = 0; i < pDest.nCol; i++ )
2007 {
2008 if ( pDest.aCol[i].affinity != pSrc.aCol[i].affinity )
2009 {
2010 return 0; /* Affinity must be the same on all columns */
2011 }
2012 if ( !xferCompatibleCollation( pDest.aCol[i].zColl, pSrc.aCol[i].zColl ) )
2013 {
2014 return 0; /* Collating sequence must be the same on all columns */
2015 }
2016 if ( pDest.aCol[i].notNull != 0 && pSrc.aCol[i].notNull == 0 )
2017 {
2018 return 0; /* tab2 must be NOT NULL if tab1 is */
2019 }
2020 }
2021 for ( pDestIdx = pDest.pIndex; pDestIdx != null; pDestIdx = pDestIdx.pNext )
2022 {
2023 if ( pDestIdx.onError != OE_None )
2024 {
2025 destHasUniqueIdx = true;
2026 }
2027 for ( pSrcIdx = pSrc.pIndex; pSrcIdx != null; pSrcIdx = pSrcIdx.pNext )
2028 {
2029 if ( xferCompatibleIndex( pDestIdx, pSrcIdx ) )
2030 break;
2031 }
2032 if ( pSrcIdx == null )
2033 {
2034 return 0; /* pDestIdx has no corresponding index in pSrc */
2035 }
2036 }
2037 #if !SQLITE_OMIT_CHECK
2038 if ( pDest.pCheck != null && 0 != sqlite3ExprCompare( pSrc.pCheck, pDest.pCheck ) )
2039 {
2040 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
2041 }
2042 #endif
2043 #if !SQLITE_OMIT_FOREIGN_KEY
2044 /* Disallow the transfer optimization if the destination table constains
2045 ** any foreign key constraints. This is more restrictive than necessary.
2046 ** But the main beneficiary of the transfer optimization is the VACUUM
2047 ** command, and the VACUUM command disables foreign key constraints. So
2048 ** the extra complication to make this rule less restrictive is probably
2049 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
2050 */
2051 if ( ( pParse.db.flags & SQLITE_ForeignKeys ) != 0 && pDest.pFKey != null )
2052 {
2053 return 0;
2054 }
2055 #endif
2056  
2057 /* If we get this far, it means either:
2058 **
2059 ** * We can always do the transfer if the table contains an
2060 ** an integer primary key
2061 **
2062 ** * We can conditionally do the transfer if the destination
2063 ** table is empty.
2064 */
2065 #if SQLITE_TEST
2066 #if !TCLSH
2067 sqlite3_xferopt_count++;
2068 #else
2069 sqlite3_xferopt_count.iValue++;
2070 #endif
2071 #endif
2072 iDbSrc = sqlite3SchemaToIndex( pParse.db, pSrc.pSchema );
2073 v = sqlite3GetVdbe( pParse );
2074 sqlite3CodeVerifySchema( pParse, iDbSrc );
2075 iSrc = pParse.nTab++;
2076 iDest = pParse.nTab++;
2077 regAutoinc = autoIncBegin( pParse, iDbDest, pDest );
2078 sqlite3OpenTable( pParse, iDest, iDbDest, pDest, OP_OpenWrite );
2079 if ( ( pDest.iPKey < 0 && pDest.pIndex != null ) || destHasUniqueIdx )
2080 {
2081 /* If tables do not have an INTEGER PRIMARY KEY and there
2082 ** are indices to be copied and the destination is not empty,
2083 ** we have to disallow the transfer optimization because the
2084 ** the rowids might change which will mess up indexing.
2085 **
2086 ** Or if the destination has a UNIQUE index and is not empty,
2087 ** we also disallow the transfer optimization because we cannot
2088 ** insure that all entries in the union of DEST and SRC will be
2089 ** unique.
2090 */
2091 addr1 = sqlite3VdbeAddOp2( v, OP_Rewind, iDest, 0 );
2092 emptyDestTest = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 );
2093 sqlite3VdbeJumpHere( v, addr1 );
2094 }
2095 else
2096 {
2097 emptyDestTest = 0;
2098 }
2099 sqlite3OpenTable( pParse, iSrc, iDbSrc, pSrc, OP_OpenRead );
2100 emptySrcTest = sqlite3VdbeAddOp2( v, OP_Rewind, iSrc, 0 );
2101 regData = sqlite3GetTempReg( pParse );
2102 regRowid = sqlite3GetTempReg( pParse );
2103 if ( pDest.iPKey >= 0 )
2104 {
2105 addr1 = sqlite3VdbeAddOp2( v, OP_Rowid, iSrc, regRowid );
2106 addr2 = sqlite3VdbeAddOp3( v, OP_NotExists, iDest, 0, regRowid );
2107 sqlite3HaltConstraint(
2108 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC );
2109 sqlite3VdbeJumpHere( v, addr2 );
2110 autoIncStep( pParse, regAutoinc, regRowid );
2111 }
2112 else if ( pDest.pIndex == null )
2113 {
2114 addr1 = sqlite3VdbeAddOp2( v, OP_NewRowid, iDest, regRowid );
2115 }
2116 else
2117 {
2118 addr1 = sqlite3VdbeAddOp2( v, OP_Rowid, iSrc, regRowid );
2119 Debug.Assert( ( pDest.tabFlags & TF_Autoincrement ) == 0 );
2120 }
2121 sqlite3VdbeAddOp2( v, OP_RowData, iSrc, regData );
2122 sqlite3VdbeAddOp3( v, OP_Insert, iDest, regData, regRowid );
2123 sqlite3VdbeChangeP5( v, OPFLAG_NCHANGE | OPFLAG_LASTROWID | OPFLAG_APPEND );
2124 sqlite3VdbeChangeP4( v, -1, pDest.zName, 0 );
2125 sqlite3VdbeAddOp2( v, OP_Next, iSrc, addr1 );
2126 for ( pDestIdx = pDest.pIndex; pDestIdx != null; pDestIdx = pDestIdx.pNext )
2127 {
2128 for ( pSrcIdx = pSrc.pIndex; pSrcIdx != null; pSrcIdx = pSrcIdx.pNext )
2129 {
2130 if ( xferCompatibleIndex( pDestIdx, pSrcIdx ) )
2131 break;
2132 }
2133 Debug.Assert( pSrcIdx != null );
2134 sqlite3VdbeAddOp2( v, OP_Close, iSrc, 0 );
2135 sqlite3VdbeAddOp2( v, OP_Close, iDest, 0 );
2136 pKey = sqlite3IndexKeyinfo( pParse, pSrcIdx );
2137 sqlite3VdbeAddOp4( v, OP_OpenRead, iSrc, pSrcIdx.tnum, iDbSrc,
2138 pKey, P4_KEYINFO_HANDOFF );
2139 #if SQLITE_DEBUG
2140 VdbeComment( v, "%s", pSrcIdx.zName );
2141 #endif
2142 pKey = sqlite3IndexKeyinfo( pParse, pDestIdx );
2143 sqlite3VdbeAddOp4( v, OP_OpenWrite, iDest, pDestIdx.tnum, iDbDest,
2144 pKey, P4_KEYINFO_HANDOFF );
2145 #if SQLITE_DEBUG
2146 VdbeComment( v, "%s", pDestIdx.zName );
2147 #endif
2148 addr1 = sqlite3VdbeAddOp2( v, OP_Rewind, iSrc, 0 );
2149 sqlite3VdbeAddOp2( v, OP_RowKey, iSrc, regData );
2150 sqlite3VdbeAddOp3( v, OP_IdxInsert, iDest, regData, 1 );
2151 sqlite3VdbeAddOp2( v, OP_Next, iSrc, addr1 + 1 );
2152 sqlite3VdbeJumpHere( v, addr1 );
2153 }
2154 sqlite3VdbeJumpHere( v, emptySrcTest );
2155 sqlite3ReleaseTempReg( pParse, regRowid );
2156 sqlite3ReleaseTempReg( pParse, regData );
2157 sqlite3VdbeAddOp2( v, OP_Close, iSrc, 0 );
2158 sqlite3VdbeAddOp2( v, OP_Close, iDest, 0 );
2159 if ( emptyDestTest != 0 )
2160 {
2161 sqlite3VdbeAddOp2( v, OP_Halt, SQLITE_OK, 0 );
2162 sqlite3VdbeJumpHere( v, emptyDestTest );
2163 sqlite3VdbeAddOp2( v, OP_Close, iDest, 0 );
2164 return 0;
2165 }
2166 else
2167 {
2168 return 1;
2169 }
2170 }
2171 #endif // * SQLITE_OMIT_XFER_OPT */
2172 }
2173 }