comparison sqlite/insert.c @ 1434:b6b61becdf4e trunk

[svn] - add sqlite/ directory
author nenolod
date Thu, 27 Jul 2006 22:41:31 -0700
parents
children
comparison
equal deleted inserted replaced
1433:3cbe3d14ea68 1434:b6b61becdf4e
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains C code routines that are called by the parser
13 ** to handle INSERT statements in SQLite.
14 **
15 ** $Id: insert.c,v 1.164 2006/03/15 16:26:10 drh Exp $
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 pIdx->zColAff = (char *)sqliteMalloc(pIdx->nColumn+1);
45 if( !pIdx->zColAff ){
46 return;
47 }
48 for(n=0; n<pIdx->nColumn; n++){
49 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
50 }
51 pIdx->zColAff[pIdx->nColumn] = '\0';
52 }
53
54 sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
55 }
56
57 /*
58 ** Set P3 of the most recently inserted opcode to a column affinity
59 ** string for table pTab. A column affinity string has one character
60 ** for each column indexed by the index, according to the affinity of the
61 ** column:
62 **
63 ** Character Column affinity
64 ** ------------------------------
65 ** 'a' TEXT
66 ** 'b' NONE
67 ** 'c' NUMERIC
68 ** 'd' INTEGER
69 ** 'e' REAL
70 */
71 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
72 /* The first time a column affinity string for a particular table
73 ** is required, it is allocated and populated here. It is then
74 ** stored as a member of the Table structure for subsequent use.
75 **
76 ** The column affinity string will eventually be deleted by
77 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
78 */
79 if( !pTab->zColAff ){
80 char *zColAff;
81 int i;
82
83 zColAff = (char *)sqliteMalloc(pTab->nCol+1);
84 if( !zColAff ){
85 return;
86 }
87
88 for(i=0; i<pTab->nCol; i++){
89 zColAff[i] = pTab->aCol[i].affinity;
90 }
91 zColAff[pTab->nCol] = '\0';
92
93 pTab->zColAff = zColAff;
94 }
95
96 sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
97 }
98
99 /*
100 ** Return non-zero if SELECT statement p opens the table with rootpage
101 ** iTab in database iDb. This is used to see if a statement of the form
102 ** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
103 ** table for the results of the SELECT.
104 **
105 ** No checking is done for sub-selects that are part of expressions.
106 */
107 static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
108 int i;
109 struct SrcList_item *pItem;
110 if( p->pSrc==0 ) return 0;
111 for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
112 if( pItem->pSelect ){
113 if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
114 }else{
115 if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
116 }
117 }
118 return 0;
119 }
120
121 /*
122 ** This routine is call to handle SQL of the following forms:
123 **
124 ** insert into TABLE (IDLIST) values(EXPRLIST)
125 ** insert into TABLE (IDLIST) select
126 **
127 ** The IDLIST following the table name is always optional. If omitted,
128 ** then a list of all columns for the table is substituted. The IDLIST
129 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
130 **
131 ** The pList parameter holds EXPRLIST in the first form of the INSERT
132 ** statement above, and pSelect is NULL. For the second form, pList is
133 ** NULL and pSelect is a pointer to the select statement used to generate
134 ** data for the insert.
135 **
136 ** The code generated follows one of three templates. For a simple
137 ** select with data coming from a VALUES clause, the code executes
138 ** once straight down through. The template looks like this:
139 **
140 ** open write cursor to <table> and its indices
141 ** puts VALUES clause expressions onto the stack
142 ** write the resulting record into <table>
143 ** cleanup
144 **
145 ** If the statement is of the form
146 **
147 ** INSERT INTO <table> SELECT ...
148 **
149 ** And the SELECT clause does not read from <table> at any time, then
150 ** the generated code follows this template:
151 **
152 ** goto B
153 ** A: setup for the SELECT
154 ** loop over the tables in the SELECT
155 ** gosub C
156 ** end loop
157 ** cleanup after the SELECT
158 ** goto D
159 ** B: open write cursor to <table> and its indices
160 ** goto A
161 ** C: insert the select result into <table>
162 ** return
163 ** D: cleanup
164 **
165 ** The third template is used if the insert statement takes its
166 ** values from a SELECT but the data is being inserted into a table
167 ** that is also read as part of the SELECT. In the third form,
168 ** we have to use a intermediate table to store the results of
169 ** the select. The template is like this:
170 **
171 ** goto B
172 ** A: setup for the SELECT
173 ** loop over the tables in the SELECT
174 ** gosub C
175 ** end loop
176 ** cleanup after the SELECT
177 ** goto D
178 ** C: insert the select result into the intermediate table
179 ** return
180 ** B: open a cursor to an intermediate table
181 ** goto A
182 ** D: open write cursor to <table> and its indices
183 ** loop over the intermediate table
184 ** transfer values form intermediate table into <table>
185 ** end the loop
186 ** cleanup
187 */
188 void sqlite3Insert(
189 Parse *pParse, /* Parser context */
190 SrcList *pTabList, /* Name of table into which we are inserting */
191 ExprList *pList, /* List of values to be inserted */
192 Select *pSelect, /* A SELECT statement to use as the data source */
193 IdList *pColumn, /* Column names corresponding to IDLIST. */
194 int onError /* How to handle constraint errors */
195 ){
196 Table *pTab; /* The table to insert into */
197 char *zTab; /* Name of the table into which we are inserting */
198 const char *zDb; /* Name of the database holding this table */
199 int i, j, idx; /* Loop counters */
200 Vdbe *v; /* Generate code into this virtual machine */
201 Index *pIdx; /* For looping over indices of the table */
202 int nColumn; /* Number of columns in the data */
203 int base = 0; /* VDBE Cursor number for pTab */
204 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
205 sqlite3 *db; /* The main database structure */
206 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
207 int endOfLoop; /* Label for the end of the insertion loop */
208 int useTempTable = 0; /* Store SELECT results in intermediate table */
209 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
210 int iSelectLoop = 0; /* Address of code that implements the SELECT */
211 int iCleanup = 0; /* Address of the cleanup code */
212 int iInsertBlock = 0; /* Address of the subroutine used to insert data */
213 int iCntMem = 0; /* Memory cell used for the row counter */
214 int newIdx = -1; /* Cursor for the NEW table */
215 Db *pDb; /* The database containing table being inserted into */
216 int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */
217 int iDb;
218
219 #ifndef SQLITE_OMIT_TRIGGER
220 int isView; /* True if attempting to insert into a view */
221 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
222 #endif
223
224 #ifndef SQLITE_OMIT_AUTOINCREMENT
225 int counterRowid = 0; /* Memory cell holding rowid of autoinc counter */
226 #endif
227
228 if( pParse->nErr || sqlite3MallocFailed() ){
229 goto insert_cleanup;
230 }
231 db = pParse->db;
232
233 /* Locate the table into which we will be inserting new information.
234 */
235 assert( pTabList->nSrc==1 );
236 zTab = pTabList->a[0].zName;
237 if( zTab==0 ) goto insert_cleanup;
238 pTab = sqlite3SrcListLookup(pParse, pTabList);
239 if( pTab==0 ){
240 goto insert_cleanup;
241 }
242 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
243 assert( iDb<db->nDb );
244 pDb = &db->aDb[iDb];
245 zDb = pDb->zName;
246 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
247 goto insert_cleanup;
248 }
249
250 /* Figure out if we have any triggers and if the table being
251 ** inserted into is a view
252 */
253 #ifndef SQLITE_OMIT_TRIGGER
254 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
255 isView = pTab->pSelect!=0;
256 #else
257 # define triggers_exist 0
258 # define isView 0
259 #endif
260 #ifdef SQLITE_OMIT_VIEW
261 # undef isView
262 # define isView 0
263 #endif
264
265 /* Ensure that:
266 * (a) the table is not read-only,
267 * (b) that if it is a view then ON INSERT triggers exist
268 */
269 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
270 goto insert_cleanup;
271 }
272 assert( pTab!=0 );
273
274 /* If pTab is really a view, make sure it has been initialized.
275 */
276 if( isView && sqlite3ViewGetColumnNames(pParse, pTab) ){
277 goto insert_cleanup;
278 }
279
280 /* Allocate a VDBE
281 */
282 v = sqlite3GetVdbe(pParse);
283 if( v==0 ) goto insert_cleanup;
284 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
285 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
286
287 /* if there are row triggers, allocate a temp table for new.* references. */
288 if( triggers_exist ){
289 newIdx = pParse->nTab++;
290 }
291
292 #ifndef SQLITE_OMIT_AUTOINCREMENT
293 /* If this is an AUTOINCREMENT table, look up the sequence number in the
294 ** sqlite_sequence table and store it in memory cell counterMem. Also
295 ** remember the rowid of the sqlite_sequence table entry in memory cell
296 ** counterRowid.
297 */
298 if( pTab->autoInc ){
299 int iCur = pParse->nTab;
300 int addr = sqlite3VdbeCurrentAddr(v);
301 counterRowid = pParse->nMem++;
302 counterMem = pParse->nMem++;
303 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
304 sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
305 sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
306 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
307 sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
308 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
309 sqlite3VdbeAddOp(v, OP_MemStore, counterRowid, 1);
310 sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
311 sqlite3VdbeAddOp(v, OP_MemStore, counterMem, 1);
312 sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
313 sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
314 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
315 }
316 #endif /* SQLITE_OMIT_AUTOINCREMENT */
317
318 /* Figure out how many columns of data are supplied. If the data
319 ** is coming from a SELECT statement, then this step also generates
320 ** all the code to implement the SELECT statement and invoke a subroutine
321 ** to process each row of the result. (Template 2.) If the SELECT
322 ** statement uses the the table that is being inserted into, then the
323 ** subroutine is also coded here. That subroutine stores the SELECT
324 ** results in a temporary table. (Template 3.)
325 */
326 if( pSelect ){
327 /* Data is coming from a SELECT. Generate code to implement that SELECT
328 */
329 int rc, iInitCode;
330 iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
331 iSelectLoop = sqlite3VdbeCurrentAddr(v);
332 iInsertBlock = sqlite3VdbeMakeLabel(v);
333
334 /* Resolve the expressions in the SELECT statement and execute it. */
335 rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
336 if( rc || pParse->nErr || sqlite3MallocFailed() ){
337 goto insert_cleanup;
338 }
339
340 iCleanup = sqlite3VdbeMakeLabel(v);
341 sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
342 assert( pSelect->pEList );
343 nColumn = pSelect->pEList->nExpr;
344
345 /* Set useTempTable to TRUE if the result of the SELECT statement
346 ** should be written into a temporary table. Set to FALSE if each
347 ** row of the SELECT can be written directly into the result table.
348 **
349 ** A temp table must be used if the table being updated is also one
350 ** of the tables being read by the SELECT statement. Also use a
351 ** temp table in the case of row triggers.
352 */
353 if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
354 useTempTable = 1;
355 }
356
357 if( useTempTable ){
358 /* Generate the subroutine that SELECT calls to process each row of
359 ** the result. Store the result in a temporary table
360 */
361 srcTab = pParse->nTab++;
362 sqlite3VdbeResolveLabel(v, iInsertBlock);
363 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
364 sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
365 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
366 sqlite3VdbeAddOp(v, OP_Insert, srcTab, 0);
367 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
368
369 /* The following code runs first because the GOTO at the very top
370 ** of the program jumps to it. Create the temporary table, then jump
371 ** back up and execute the SELECT code above.
372 */
373 sqlite3VdbeJumpHere(v, iInitCode);
374 sqlite3VdbeAddOp(v, OP_OpenVirtual, srcTab, 0);
375 sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
376 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
377 sqlite3VdbeResolveLabel(v, iCleanup);
378 }else{
379 sqlite3VdbeJumpHere(v, iInitCode);
380 }
381 }else{
382 /* This is the case if the data for the INSERT is coming from a VALUES
383 ** clause
384 */
385 NameContext sNC;
386 memset(&sNC, 0, sizeof(sNC));
387 sNC.pParse = pParse;
388 assert( pList!=0 );
389 srcTab = -1;
390 useTempTable = 0;
391 assert( pList );
392 nColumn = pList->nExpr;
393 for(i=0; i<nColumn; i++){
394 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
395 goto insert_cleanup;
396 }
397 }
398 }
399
400 /* Make sure the number of columns in the source data matches the number
401 ** of columns to be inserted into the table.
402 */
403 if( pColumn==0 && nColumn!=pTab->nCol ){
404 sqlite3ErrorMsg(pParse,
405 "table %S has %d columns but %d values were supplied",
406 pTabList, 0, pTab->nCol, nColumn);
407 goto insert_cleanup;
408 }
409 if( pColumn!=0 && nColumn!=pColumn->nId ){
410 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
411 goto insert_cleanup;
412 }
413
414 /* If the INSERT statement included an IDLIST term, then make sure
415 ** all elements of the IDLIST really are columns of the table and
416 ** remember the column indices.
417 **
418 ** If the table has an INTEGER PRIMARY KEY column and that column
419 ** is named in the IDLIST, then record in the keyColumn variable
420 ** the index into IDLIST of the primary key column. keyColumn is
421 ** the index of the primary key as it appears in IDLIST, not as
422 ** is appears in the original table. (The index of the primary
423 ** key in the original table is pTab->iPKey.)
424 */
425 if( pColumn ){
426 for(i=0; i<pColumn->nId; i++){
427 pColumn->a[i].idx = -1;
428 }
429 for(i=0; i<pColumn->nId; i++){
430 for(j=0; j<pTab->nCol; j++){
431 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
432 pColumn->a[i].idx = j;
433 if( j==pTab->iPKey ){
434 keyColumn = i;
435 }
436 break;
437 }
438 }
439 if( j>=pTab->nCol ){
440 if( sqlite3IsRowid(pColumn->a[i].zName) ){
441 keyColumn = i;
442 }else{
443 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
444 pTabList, 0, pColumn->a[i].zName);
445 pParse->nErr++;
446 goto insert_cleanup;
447 }
448 }
449 }
450 }
451
452 /* If there is no IDLIST term but the table has an integer primary
453 ** key, the set the keyColumn variable to the primary key column index
454 ** in the original table definition.
455 */
456 if( pColumn==0 ){
457 keyColumn = pTab->iPKey;
458 }
459
460 /* Open the temp table for FOR EACH ROW triggers
461 */
462 if( triggers_exist ){
463 sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
464 sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
465 }
466
467 /* Initialize the count of rows to be inserted
468 */
469 if( db->flags & SQLITE_CountRows ){
470 iCntMem = pParse->nMem++;
471 sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
472 }
473
474 /* Open tables and indices if there are no row triggers */
475 if( !triggers_exist ){
476 base = pParse->nTab;
477 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
478 }
479
480 /* If the data source is a temporary table, then we have to create
481 ** a loop because there might be multiple rows of data. If the data
482 ** source is a subroutine call from the SELECT statement, then we need
483 ** to launch the SELECT statement processing.
484 */
485 if( useTempTable ){
486 iBreak = sqlite3VdbeMakeLabel(v);
487 sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
488 iCont = sqlite3VdbeCurrentAddr(v);
489 }else if( pSelect ){
490 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
491 sqlite3VdbeResolveLabel(v, iInsertBlock);
492 }
493
494 /* Run the BEFORE and INSTEAD OF triggers, if there are any
495 */
496 endOfLoop = sqlite3VdbeMakeLabel(v);
497 if( triggers_exist & TRIGGER_BEFORE ){
498
499 /* build the NEW.* reference row. Note that if there is an INTEGER
500 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
501 ** translated into a unique ID for the row. But on a BEFORE trigger,
502 ** we do not know what the unique ID will be (because the insert has
503 ** not happened yet) so we substitute a rowid of -1
504 */
505 if( keyColumn<0 ){
506 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
507 }else if( useTempTable ){
508 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
509 }else{
510 assert( pSelect==0 ); /* Otherwise useTempTable is true */
511 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
512 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
513 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
514 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
515 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
516 }
517
518 /* Create the new column data
519 */
520 for(i=0; i<pTab->nCol; i++){
521 if( pColumn==0 ){
522 j = i;
523 }else{
524 for(j=0; j<pColumn->nId; j++){
525 if( pColumn->a[j].idx==i ) break;
526 }
527 }
528 if( pColumn && j>=pColumn->nId ){
529 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
530 }else if( useTempTable ){
531 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
532 }else{
533 assert( pSelect==0 ); /* Otherwise useTempTable is true */
534 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
535 }
536 }
537 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
538
539 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
540 ** do not attempt any conversions before assembling the record.
541 ** If this is a real table, attempt conversions as required by the
542 ** table column affinities.
543 */
544 if( !isView ){
545 sqlite3TableAffinityStr(v, pTab);
546 }
547 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
548
549 /* Fire BEFORE or INSTEAD OF triggers */
550 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
551 newIdx, -1, onError, endOfLoop) ){
552 goto insert_cleanup;
553 }
554 }
555
556 /* If any triggers exists, the opening of tables and indices is deferred
557 ** until now.
558 */
559 if( triggers_exist && !isView ){
560 base = pParse->nTab;
561 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
562 }
563
564 /* Push the record number for the new entry onto the stack. The
565 ** record number is a randomly generate integer created by NewRowid
566 ** except when the table has an INTEGER PRIMARY KEY column, in which
567 ** case the record number is the same as that column.
568 */
569 if( !isView ){
570 if( keyColumn>=0 ){
571 if( useTempTable ){
572 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
573 }else if( pSelect ){
574 sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
575 }else{
576 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
577 }
578 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
579 ** to generate a unique primary key value.
580 */
581 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
582 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
583 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
584 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
585 }else{
586 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
587 }
588 #ifndef SQLITE_OMIT_AUTOINCREMENT
589 if( pTab->autoInc ){
590 sqlite3VdbeAddOp(v, OP_MemMax, counterMem, 0);
591 }
592 #endif /* SQLITE_OMIT_AUTOINCREMENT */
593
594 /* Push onto the stack, data for all columns of the new entry, beginning
595 ** with the first column.
596 */
597 for(i=0; i<pTab->nCol; i++){
598 if( i==pTab->iPKey ){
599 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
600 ** Whenever this column is read, the record number will be substituted
601 ** in its place. So will fill this column with a NULL to avoid
602 ** taking up data space with information that will never be used. */
603 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
604 continue;
605 }
606 if( pColumn==0 ){
607 j = i;
608 }else{
609 for(j=0; j<pColumn->nId; j++){
610 if( pColumn->a[j].idx==i ) break;
611 }
612 }
613 if( pColumn && j>=pColumn->nId ){
614 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
615 }else if( useTempTable ){
616 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
617 }else if( pSelect ){
618 sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j, 1);
619 }else{
620 sqlite3ExprCode(pParse, pList->a[j].pExpr);
621 }
622 }
623
624 /* Generate code to check constraints and generate index keys and
625 ** do the insertion.
626 */
627 sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
628 0, onError, endOfLoop);
629 sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
630 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1);
631 }
632
633 /* Update the count of rows that are inserted
634 */
635 if( (db->flags & SQLITE_CountRows)!=0 ){
636 sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
637 }
638
639 if( triggers_exist ){
640 /* Close all tables opened */
641 if( !isView ){
642 sqlite3VdbeAddOp(v, OP_Close, base, 0);
643 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
644 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
645 }
646 }
647
648 /* Code AFTER triggers */
649 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
650 newIdx, -1, onError, endOfLoop) ){
651 goto insert_cleanup;
652 }
653 }
654
655 /* The bottom of the loop, if the data source is a SELECT statement
656 */
657 sqlite3VdbeResolveLabel(v, endOfLoop);
658 if( useTempTable ){
659 sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
660 sqlite3VdbeResolveLabel(v, iBreak);
661 sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
662 }else if( pSelect ){
663 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
664 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
665 sqlite3VdbeResolveLabel(v, iCleanup);
666 }
667
668 if( !triggers_exist ){
669 /* Close all tables opened */
670 sqlite3VdbeAddOp(v, OP_Close, base, 0);
671 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
672 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
673 }
674 }
675
676 #ifndef SQLITE_OMIT_AUTOINCREMENT
677 /* Update the sqlite_sequence table by storing the content of the
678 ** counter value in memory counterMem back into the sqlite_sequence
679 ** table.
680 */
681 if( pTab->autoInc ){
682 int iCur = pParse->nTab;
683 int addr = sqlite3VdbeCurrentAddr(v);
684 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
685 sqlite3VdbeAddOp(v, OP_MemLoad, counterRowid, 0);
686 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
687 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
688 sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
689 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
690 sqlite3VdbeAddOp(v, OP_MemLoad, counterMem, 0);
691 sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
692 sqlite3VdbeAddOp(v, OP_Insert, iCur, 0);
693 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
694 }
695 #endif
696
697 /*
698 ** Return the number of rows inserted. If this routine is
699 ** generating code because of a call to sqlite3NestedParse(), do not
700 ** invoke the callback function.
701 */
702 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
703 sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
704 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
705 sqlite3VdbeSetNumCols(v, 1);
706 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
707 }
708
709 insert_cleanup:
710 sqlite3SrcListDelete(pTabList);
711 sqlite3ExprListDelete(pList);
712 sqlite3SelectDelete(pSelect);
713 sqlite3IdListDelete(pColumn);
714 }
715
716 /*
717 ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
718 **
719 ** When this routine is called, the stack contains (from bottom to top)
720 ** the following values:
721 **
722 ** 1. The rowid of the row to be updated before the update. This
723 ** value is omitted unless we are doing an UPDATE that involves a
724 ** change to the record number.
725 **
726 ** 2. The rowid of the row after the update.
727 **
728 ** 3. The data in the first column of the entry after the update.
729 **
730 ** i. Data from middle columns...
731 **
732 ** N. The data in the last column of the entry after the update.
733 **
734 ** The old rowid shown as entry (1) above is omitted unless both isUpdate
735 ** and rowidChng are 1. isUpdate is true for UPDATEs and false for
736 ** INSERTs and rowidChng is true if the record number is being changed.
737 **
738 ** The code generated by this routine pushes additional entries onto
739 ** the stack which are the keys for new index entries for the new record.
740 ** The order of index keys is the same as the order of the indices on
741 ** the pTable->pIndex list. A key is only created for index i if
742 ** aIdxUsed!=0 and aIdxUsed[i]!=0.
743 **
744 ** This routine also generates code to check constraints. NOT NULL,
745 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
746 ** then the appropriate action is performed. There are five possible
747 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
748 **
749 ** Constraint type Action What Happens
750 ** --------------- ---------- ----------------------------------------
751 ** any ROLLBACK The current transaction is rolled back and
752 ** sqlite3_exec() returns immediately with a
753 ** return code of SQLITE_CONSTRAINT.
754 **
755 ** any ABORT Back out changes from the current command
756 ** only (do not do a complete rollback) then
757 ** cause sqlite3_exec() to return immediately
758 ** with SQLITE_CONSTRAINT.
759 **
760 ** any FAIL Sqlite_exec() returns immediately with a
761 ** return code of SQLITE_CONSTRAINT. The
762 ** transaction is not rolled back and any
763 ** prior changes are retained.
764 **
765 ** any IGNORE The record number and data is popped from
766 ** the stack and there is an immediate jump
767 ** to label ignoreDest.
768 **
769 ** NOT NULL REPLACE The NULL value is replace by the default
770 ** value for that column. If the default value
771 ** is NULL, the action is the same as ABORT.
772 **
773 ** UNIQUE REPLACE The other row that conflicts with the row
774 ** being inserted is removed.
775 **
776 ** CHECK REPLACE Illegal. The results in an exception.
777 **
778 ** Which action to take is determined by the overrideError parameter.
779 ** Or if overrideError==OE_Default, then the pParse->onError parameter
780 ** is used. Or if pParse->onError==OE_Default then the onError value
781 ** for the constraint is used.
782 **
783 ** The calling routine must open a read/write cursor for pTab with
784 ** cursor number "base". All indices of pTab must also have open
785 ** read/write cursors with cursor number base+i for the i-th cursor.
786 ** Except, if there is no possibility of a REPLACE action then
787 ** cursors do not need to be open for indices where aIdxUsed[i]==0.
788 **
789 ** If the isUpdate flag is true, it means that the "base" cursor is
790 ** initially pointing to an entry that is being updated. The isUpdate
791 ** flag causes extra code to be generated so that the "base" cursor
792 ** is still pointing at the same entry after the routine returns.
793 ** Without the isUpdate flag, the "base" cursor might be moved.
794 */
795 void sqlite3GenerateConstraintChecks(
796 Parse *pParse, /* The parser context */
797 Table *pTab, /* the table into which we are inserting */
798 int base, /* Index of a read/write cursor pointing at pTab */
799 char *aIdxUsed, /* Which indices are used. NULL means all are used */
800 int rowidChng, /* True if the record number will change */
801 int isUpdate, /* True for UPDATE, False for INSERT */
802 int overrideError, /* Override onError to this if not OE_Default */
803 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
804 ){
805 int i;
806 Vdbe *v;
807 int nCol;
808 int onError;
809 int addr;
810 int extra;
811 int iCur;
812 Index *pIdx;
813 int seenReplace = 0;
814 int jumpInst1=0, jumpInst2;
815 int hasTwoRowids = (isUpdate && rowidChng);
816
817 v = sqlite3GetVdbe(pParse);
818 assert( v!=0 );
819 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
820 nCol = pTab->nCol;
821
822 /* Test all NOT NULL constraints.
823 */
824 for(i=0; i<nCol; i++){
825 if( i==pTab->iPKey ){
826 continue;
827 }
828 onError = pTab->aCol[i].notNull;
829 if( onError==OE_None ) continue;
830 if( overrideError!=OE_Default ){
831 onError = overrideError;
832 }else if( onError==OE_Default ){
833 onError = OE_Abort;
834 }
835 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
836 onError = OE_Abort;
837 }
838 sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
839 addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
840 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
841 || onError==OE_Ignore || onError==OE_Replace );
842 switch( onError ){
843 case OE_Rollback:
844 case OE_Abort:
845 case OE_Fail: {
846 char *zMsg = 0;
847 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
848 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
849 " may not be NULL", (char*)0);
850 sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
851 break;
852 }
853 case OE_Ignore: {
854 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
855 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
856 break;
857 }
858 case OE_Replace: {
859 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
860 sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
861 break;
862 }
863 }
864 sqlite3VdbeJumpHere(v, addr);
865 }
866
867 /* Test all CHECK constraints
868 */
869 #ifndef SQLITE_OMIT_CHECK
870 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
871 int allOk = sqlite3VdbeMakeLabel(v);
872 assert( pParse->ckOffset==0 );
873 pParse->ckOffset = nCol;
874 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
875 assert( pParse->ckOffset==nCol );
876 pParse->ckOffset = 0;
877 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
878 if( onError==OE_Ignore || onError==OE_Replace ){
879 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
880 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
881 }else{
882 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
883 }
884 sqlite3VdbeResolveLabel(v, allOk);
885 }
886 #endif /* !defined(SQLITE_OMIT_CHECK) */
887
888 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
889 ** of the new record does not previously exist. Except, if this
890 ** is an UPDATE and the primary key is not changing, that is OK.
891 */
892 if( rowidChng ){
893 onError = pTab->keyConf;
894 if( overrideError!=OE_Default ){
895 onError = overrideError;
896 }else if( onError==OE_Default ){
897 onError = OE_Abort;
898 }
899
900 if( isUpdate ){
901 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
902 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
903 jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
904 }
905 sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
906 jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
907 switch( onError ){
908 default: {
909 onError = OE_Abort;
910 /* Fall thru into the next case */
911 }
912 case OE_Rollback:
913 case OE_Abort:
914 case OE_Fail: {
915 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
916 "PRIMARY KEY must be unique", P3_STATIC);
917 break;
918 }
919 case OE_Replace: {
920 sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
921 if( isUpdate ){
922 sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
923 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
924 }
925 seenReplace = 1;
926 break;
927 }
928 case OE_Ignore: {
929 assert( seenReplace==0 );
930 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
931 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
932 break;
933 }
934 }
935 sqlite3VdbeJumpHere(v, jumpInst2);
936 if( isUpdate ){
937 sqlite3VdbeJumpHere(v, jumpInst1);
938 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
939 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
940 }
941 }
942
943 /* Test all UNIQUE constraints by creating entries for each UNIQUE
944 ** index and making sure that duplicate entries do not already exist.
945 ** Add the new records to the indices as we go.
946 */
947 extra = -1;
948 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
949 if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
950 extra++;
951
952 /* Create a key for accessing the index entry */
953 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
954 for(i=0; i<pIdx->nColumn; i++){
955 int idx = pIdx->aiColumn[i];
956 if( idx==pTab->iPKey ){
957 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
958 }else{
959 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
960 }
961 }
962 jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
963 sqlite3IndexAffinityStr(v, pIdx);
964
965 /* Find out what action to take in case there is an indexing conflict */
966 onError = pIdx->onError;
967 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
968 if( overrideError!=OE_Default ){
969 onError = overrideError;
970 }else if( onError==OE_Default ){
971 onError = OE_Abort;
972 }
973 if( seenReplace ){
974 if( onError==OE_Ignore ) onError = OE_Replace;
975 else if( onError==OE_Fail ) onError = OE_Abort;
976 }
977
978
979 /* Check to see if the new index entry will be unique */
980 sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
981 jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
982
983 /* Generate code that executes if the new index entry is not unique */
984 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
985 || onError==OE_Ignore || onError==OE_Replace );
986 switch( onError ){
987 case OE_Rollback:
988 case OE_Abort:
989 case OE_Fail: {
990 int j, n1, n2;
991 char zErrMsg[200];
992 strcpy(zErrMsg, pIdx->nColumn>1 ? "columns " : "column ");
993 n1 = strlen(zErrMsg);
994 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
995 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
996 n2 = strlen(zCol);
997 if( j>0 ){
998 strcpy(&zErrMsg[n1], ", ");
999 n1 += 2;
1000 }
1001 if( n1+n2>sizeof(zErrMsg)-30 ){
1002 strcpy(&zErrMsg[n1], "...");
1003 n1 += 3;
1004 break;
1005 }else{
1006 strcpy(&zErrMsg[n1], zCol);
1007 n1 += n2;
1008 }
1009 }
1010 strcpy(&zErrMsg[n1],
1011 pIdx->nColumn>1 ? " are not unique" : " is not unique");
1012 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
1013 break;
1014 }
1015 case OE_Ignore: {
1016 assert( seenReplace==0 );
1017 sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
1018 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
1019 break;
1020 }
1021 case OE_Replace: {
1022 sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
1023 if( isUpdate ){
1024 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
1025 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
1026 }
1027 seenReplace = 1;
1028 break;
1029 }
1030 }
1031 #if NULL_DISTINCT_FOR_UNIQUE
1032 sqlite3VdbeJumpHere(v, jumpInst1);
1033 #endif
1034 sqlite3VdbeJumpHere(v, jumpInst2);
1035 }
1036 }
1037
1038 /*
1039 ** This routine generates code to finish the INSERT or UPDATE operation
1040 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
1041 ** The stack must contain keys for all active indices followed by data
1042 ** and the rowid for the new entry. This routine creates the new
1043 ** entries in all indices and in the main table.
1044 **
1045 ** The arguments to this routine should be the same as the first six
1046 ** arguments to sqlite3GenerateConstraintChecks.
1047 */
1048 void sqlite3CompleteInsertion(
1049 Parse *pParse, /* The parser context */
1050 Table *pTab, /* the table into which we are inserting */
1051 int base, /* Index of a read/write cursor pointing at pTab */
1052 char *aIdxUsed, /* Which indices are used. NULL means all are used */
1053 int rowidChng, /* True if the record number will change */
1054 int isUpdate, /* True for UPDATE, False for INSERT */
1055 int newIdx /* Index of NEW table for triggers. -1 if none */
1056 ){
1057 int i;
1058 Vdbe *v;
1059 int nIdx;
1060 Index *pIdx;
1061 int pik_flags;
1062
1063 v = sqlite3GetVdbe(pParse);
1064 assert( v!=0 );
1065 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
1066 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
1067 for(i=nIdx-1; i>=0; i--){
1068 if( aIdxUsed && aIdxUsed[i]==0 ) continue;
1069 sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
1070 }
1071 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
1072 sqlite3TableAffinityStr(v, pTab);
1073 #ifndef SQLITE_OMIT_TRIGGER
1074 if( newIdx>=0 ){
1075 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1076 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
1077 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
1078 }
1079 #endif
1080 if( pParse->nested ){
1081 pik_flags = 0;
1082 }else{
1083 pik_flags = OPFLAG_NCHANGE;
1084 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
1085 }
1086 sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
1087 if( !pParse->nested ){
1088 sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
1089 }
1090
1091 if( isUpdate && rowidChng ){
1092 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1093 }
1094 }
1095
1096 /*
1097 ** Generate code that will open cursors for a table and for all
1098 ** indices of that table. The "base" parameter is the cursor number used
1099 ** for the table. Indices are opened on subsequent cursors.
1100 */
1101 void sqlite3OpenTableAndIndices(
1102 Parse *pParse, /* Parsing context */
1103 Table *pTab, /* Table to be opened */
1104 int base, /* Cursor number assigned to the table */
1105 int op /* OP_OpenRead or OP_OpenWrite */
1106 ){
1107 int i;
1108 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1109 Index *pIdx;
1110 Vdbe *v = sqlite3GetVdbe(pParse);
1111 assert( v!=0 );
1112 sqlite3OpenTable(pParse, base, iDb, pTab, op);
1113 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1114 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1115 assert( pIdx->pSchema==pTab->pSchema );
1116 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
1117 VdbeComment((v, "# %s", pIdx->zName));
1118 sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
1119 }
1120 if( pParse->nTab<=base+i ){
1121 pParse->nTab = base+i;
1122 }
1123 }