-
Notifications
You must be signed in to change notification settings - Fork 376
/
insert.c
1954 lines (1857 loc) · 64.1 KB
/
insert.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010-2017, Tarantool AUTHORS, please see AUTHORS file.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* This file contains C code routines that are called by the parser
* to handle INSERT statements in SQLite.
*/
#include "sqliteInt.h"
#include "box/session.h"
/*
* Generate code that will open pTab as cursor iCur.
*/
void
sqlite3OpenTable(Parse * pParse, /* Generate code into this VDBE */
int iCur, /* The cursor number of the table */
Table * pTab, /* The table to be opened */
int opcode) /* OP_OpenRead or OP_OpenWrite */
{
Vdbe *v;
v = sqlite3GetVdbe(pParse);
assert(opcode == OP_OpenWrite || opcode == OP_OpenRead);
Index *pPk = sqlite3PrimaryKeyIndex(pTab);
assert(pPk != 0);
assert(pPk->tnum == pTab->tnum);
sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, 0);
sqlite3VdbeSetP4KeyInfo(pParse, pPk);
VdbeComment((v, "%s", pTab->zName));
}
/*
* Return a pointer to the column affinity string associated with index
* pIdx. A column affinity string has one character for each column in
* the table, according to the affinity of the column:
*
* Character Column affinity
* ------------------------------
* 'A' BLOB
* 'B' TEXT
* 'C' NUMERIC
* 'D' INTEGER
* 'F' REAL
*
* Memory for the buffer containing the column index affinity string
* is managed along with the rest of the Index structure. It will be
* released when sqlite3DeleteIndex() is called.
*/
const char *
sqlite3IndexAffinityStr(sqlite3 * db, Index * pIdx)
{
if (!pIdx->zColAff) {
/* The first time a column affinity string for a particular index is
* required, it is allocated and populated here. It is then stored as
* a member of the Index structure for subsequent use.
*
* The column affinity string will eventually be deleted by
* sqliteDeleteIndex() when the Index structure itself is cleaned
* up.
*/
int n;
Table *pTab = pIdx->pTable;
pIdx->zColAff =
(char *)sqlite3DbMallocRaw(0, pIdx->nColumn + 1);
if (!pIdx->zColAff) {
sqlite3OomFault(db);
return 0;
}
for (n = 0; n < pIdx->nColumn; n++) {
i16 x = pIdx->aiColumn[n];
if (x >= 0) {
pIdx->zColAff[n] = pTab->aCol[x].affinity;
} else {
char aff;
assert(x == XN_EXPR);
assert(pIdx->aColExpr != 0);
aff =
sqlite3ExprAffinity(pIdx->aColExpr->a[n].
pExpr);
if (aff == 0)
aff = SQLITE_AFF_BLOB;
pIdx->zColAff[n] = aff;
}
}
pIdx->zColAff[n] = 0;
}
return pIdx->zColAff;
}
/*
* Compute the affinity string for table pTab, if it has not already been
* computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
*
* If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
* if iReg>0 then code an OP_Affinity opcode that will set the affinities
* for register iReg and following. Or if affinities exists and iReg==0,
* then just set the P4 operand of the previous opcode (which should be
* an OP_MakeRecord) to the affinity string.
*
* A column affinity string has one character per column:
*
* Character Column affinity
* ------------------------------
* 'A' BLOB
* 'B' TEXT
* 'C' NUMERIC
* 'D' INTEGER
* 'E' REAL
*/
void
sqlite3TableAffinity(Vdbe * v, Table * pTab, int iReg)
{
int i;
char *zColAff = pTab->zColAff;
if (zColAff == 0) {
sqlite3 *db = sqlite3VdbeDb(v);
zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol + 1);
if (!zColAff) {
sqlite3OomFault(db);
return;
}
for (i = 0; i < pTab->nCol; i++) {
zColAff[i] = pTab->aCol[i].affinity;
}
do {
zColAff[i--] = 0;
} while (i >= 0 && zColAff[i] == SQLITE_AFF_BLOB);
pTab->zColAff = zColAff;
}
i = sqlite3Strlen30(zColAff);
if (i) {
if (iReg) {
sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff,
i);
} else {
sqlite3VdbeChangeP4(v, -1, zColAff, i);
}
}
}
/*
* Return non-zero if the table pTab in database or any of its indices
* have been opened at any point in the VDBE program. This is used to see if
* a statement of the form "INSERT INTO <pTab> SELECT ..." can
* run for the results of the SELECT.
*/
static int
readsTable(Parse * p, Table * pTab)
{
Vdbe *v = sqlite3GetVdbe(p);
int i;
int iEnd = sqlite3VdbeCurrentAddr(v);
for (i = 1; i < iEnd; i++) {
VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
assert(pOp != 0);
if (pOp->opcode == OP_OpenRead && pOp->p3 == 0) {
Index *pIndex;
int tnum = pOp->p2;
if (tnum == pTab->tnum) {
return 1;
}
for (pIndex = pTab->pIndex; pIndex;
pIndex = pIndex->pNext) {
if (tnum == pIndex->tnum) {
return 1;
}
}
}
}
return 0;
}
/* Forward declaration */
static int
xferOptimization(Parse * pParse, /* Parser context */
Table * pDest, /* The table we are inserting into */
Select * pSelect, /* A SELECT statement to use as the data source */
int onError); /* How to handle constraint errors */
/*
* This routine is called to handle SQL of the following forms:
*
* insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
* insert into TABLE (IDLIST) select
* insert into TABLE (IDLIST) default values
*
* The IDLIST following the table name is always optional. If omitted,
* then a list of all columns for the table is substituted.
* The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
* is omitted.
*
* For the pSelect parameter holds the values to be inserted for the
* first two forms shown above. A VALUES clause is really just short-hand
* for a SELECT statement that omits the FROM clause and everything else
* that follows. If the pSelect parameter is NULL, that means that the
* DEFAULT VALUES form of the INSERT statement is intended.
*
* The code generated follows one of four templates. For a simple
* insert with data coming from a single-row VALUES clause, the code executes
* once straight down through. Pseudo-code follows (we call this
* the "1st template"):
*
* open write cursor to <table> and its indices
* put VALUES clause expressions into registers
* write the resulting record into <table>
* cleanup
*
* The three remaining templates assume the statement is of the form
*
* INSERT INTO <table> SELECT ...
*
* If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
* in other words if the SELECT pulls all columns from a single table
* and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
* if <table2> and <table1> are distinct tables but have identical
* schemas, including all the same indices, then a special optimization
* is invoked that copies raw records from <table2> over to <table1>.
* See the xferOptimization() function for the implementation of this
* template. This is the 2nd template.
*
* open a write cursor to <table>
* open read cursor on <table2>
* transfer all records in <table2> over to <table>
* close cursors
* foreach index on <table>
* open a write cursor on the <table> index
* open a read cursor on the corresponding <table2> index
* transfer all records from the read to the write cursors
* close cursors
* end foreach
*
* The 3rd template is for when the second template does not apply
* and the SELECT clause does not read from <table> at any time.
* The generated code follows this template:
*
* X <- A
* goto B
* A: setup for the SELECT
* loop over the rows in the SELECT
* load values into registers R..R+n
* yield X
* end loop
* cleanup after the SELECT
* end-coroutine X
* B: open write cursor to <table> and its indices
* C: yield X, at EOF goto D
* insert the select result into <table> from R..R+n
* goto C
* D: cleanup
*
* The 4th template is used if the insert statement takes its
* values from a SELECT but the data is being inserted into a table
* that is also read as part of the SELECT. In the third form,
* we have to use an intermediate table to store the results of
* the select. The template is like this:
*
* X <- A
* goto B
* A: setup for the SELECT
* loop over the tables in the SELECT
* load value into register R..R+n
* yield X
* end loop
* cleanup after the SELECT
* end co-routine R
* B: open temp table
* L: yield X, at EOF goto M
* insert row from R..R+n into temp table
* goto L
* M: open write cursor to <table> and its indices
* rewind temp table
* C: loop over rows of intermediate table
* transfer values form intermediate table into <table>
* end loop
* D: cleanup
*/
void
sqlite3Insert(Parse * pParse, /* Parser context */
SrcList * pTabList, /* Name of table into which we are inserting */
Select * pSelect, /* A SELECT statement to use as the data source */
IdList * pColumn, /* Column names corresponding to IDLIST. */
int onError) /* How to handle constraint errors */
{
sqlite3 *db; /* The main database structure */
Table *pTab; /* The table to insert into. aka TABLE */
char *zTab; /* Name of the table into which we are inserting */
int i, j; /* Loop counters */
Vdbe *v; /* Generate code into this virtual machine */
Index *pIdx; /* For looping over indices of the table */
int nColumn; /* Number of columns in the data */
int iDataCur = 0; /* VDBE cursor that is the main data repository */
int iIdxCur = 0; /* First index cursor */
int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
int endOfLoop; /* Label for the end of the insertion loop */
int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
int addrInsTop = 0; /* Jump to label "D" */
int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
SelectDest dest; /* Destination for SELECT on rhs of INSERT */
u8 useTempTable = 0; /* Store SELECT results in intermediate table */
u8 bIdListInOrder; /* True if IDLIST is in table order */
ExprList *pList = 0; /* List of VALUES() to be inserted */
struct session *user_session = current_session();
/* Register allocations */
int regFromSelect = 0; /* Base register for data coming from SELECT */
int regRowCount = 0; /* Memory cell used for the row counter */
int regIns; /* Block of regs holding data being inserted */
int regTupleid; /* registers holding insert tupleid */
int regData; /* register holding first column to insert */
int *aRegIdx = 0; /* One register allocated to each index */
#ifndef SQLITE_OMIT_TRIGGER
int isView; /* True if attempting to insert into a view */
Trigger *pTrigger; /* List of triggers on pTab, if required */
int tmask; /* Mask of trigger times */
#endif
db = pParse->db;
memset(&dest, 0, sizeof(dest));
if (pParse->nErr || db->mallocFailed) {
goto insert_cleanup;
}
/* If the Select object is really just a simple VALUES() list with a
* single row (the common case) then keep that one row of values
* and discard the other (unused) parts of the pSelect object
*/
if (pSelect && (pSelect->selFlags & SF_Values) != 0
&& pSelect->pPrior == 0) {
pList = pSelect->pEList;
pSelect->pEList = 0;
sqlite3SelectDelete(db, pSelect);
pSelect = 0;
}
/* Locate the table into which we will be inserting new information.
*/
assert(pTabList->nSrc == 1);
zTab = pTabList->a[0].zName;
if (NEVER(zTab == 0))
goto insert_cleanup;
pTab = sqlite3SrcListLookup(pParse, pTabList);
if (pTab == 0) {
goto insert_cleanup;
}
if (sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, "")) {
goto insert_cleanup;
}
/* Figure out if we have any triggers and if the table being
* inserted into is a view
*/
#ifndef SQLITE_OMIT_TRIGGER
pTrigger = sqlite3TriggersExist(pTab, TK_INSERT, 0, &tmask);
isView = pTab->pSelect != 0;
#else
#define pTrigger 0
#define tmask 0
#define isView 0
#endif
#ifdef SQLITE_OMIT_VIEW
#undef isView
#define isView 0
#endif
assert((pTrigger && tmask) || (pTrigger == 0 && tmask == 0));
/* If pTab is really a view, make sure it has been initialized.
* ViewGetColumnNames() is a no-op if pTab is not a view.
*/
if (sqlite3ViewGetColumnNames(pParse, pTab)) {
goto insert_cleanup;
}
/* Cannot insert into a read-only table.
*/
if (sqlite3IsReadOnly(pParse, pTab, tmask)) {
goto insert_cleanup;
}
/* Allocate a VDBE
*/
v = sqlite3GetVdbe(pParse);
if (v == 0)
goto insert_cleanup;
if (pParse->nested == 0)
sqlite3VdbeCountChanges(v);
sqlite3BeginWriteOperation(pParse, pSelect || pTrigger);
#ifndef SQLITE_OMIT_XFER_OPT
/* If the statement is of the form
*
* INSERT INTO <table1> SELECT * FROM <table2>;
*
* Then special optimizations can be applied that make the transfer
* very fast and which reduce fragmentation of indices.
*
* This is the 2nd template.
*/
if (pColumn == 0 && xferOptimization(pParse, pTab, pSelect, onError)) {
assert(!pTrigger);
assert(pList == 0);
goto insert_end;
}
#endif /* SQLITE_OMIT_XFER_OPT */
/* Allocate registers for holding the tupleid of the new row,
* the content of the new row, and the assembled row record.
*/
regTupleid = regIns = pParse->nMem + 1;
pParse->nMem += pTab->nCol + 1;
regData = regTupleid + 1;
/* If the INSERT statement included an IDLIST term, then make sure
* all elements of the IDLIST really are columns of the table and
* remember the column indices.
*
* If the table has an INTEGER PRIMARY KEY column and that column
* is named in the IDLIST, then record in the ipkColumn variable
* the index into IDLIST of the primary key column. ipkColumn is
* the index of the primary key as it appears in IDLIST, not as
* is appears in the original table. (The index of the INTEGER
* PRIMARY KEY in the original table is pTab->iPKey.)
*/
bIdListInOrder = 1;
if (pColumn) {
for (i = 0; i < pColumn->nId; i++) {
pColumn->a[i].idx = -1;
}
for (i = 0; i < pColumn->nId; i++) {
for (j = 0; j < pTab->nCol; j++) {
if (strcmp
(pColumn->a[i].zName,
pTab->aCol[j].zName) == 0) {
pColumn->a[i].idx = j;
if (i != j)
bIdListInOrder = 0;
if (j == pTab->iPKey) {
ipkColumn = i;
assert(isView);
}
break;
}
}
if (j >= pTab->nCol) {
sqlite3ErrorMsg(pParse,
"table %S has no column named %s",
pTabList, 0, pColumn->a[i].zName);
pParse->checkSchema = 1;
goto insert_cleanup;
}
}
}
/* Figure out how many columns of data are supplied. If the data
* is coming from a SELECT statement, then generate a co-routine that
* produces a single row of the SELECT on each invocation. The
* co-routine is the common header to the 3rd and 4th templates.
*/
if (pSelect) {
/* Data is coming from a SELECT or from a multi-row VALUES clause.
* Generate a co-routine to run the SELECT.
*/
int regYield; /* Register holding co-routine entry-point */
int addrTop; /* Top of the co-routine */
int rc; /* Result code */
regYield = ++pParse->nMem;
addrTop = sqlite3VdbeCurrentAddr(v) + 1;
sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
dest.iSdst = bIdListInOrder ? regData : 0;
dest.nSdst = pTab->nCol;
rc = sqlite3Select(pParse, pSelect, &dest);
regFromSelect = dest.iSdst;
if (rc || db->mallocFailed || pParse->nErr)
goto insert_cleanup;
sqlite3VdbeEndCoroutine(v, regYield);
sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
assert(pSelect->pEList);
nColumn = pSelect->pEList->nExpr;
/* Set useTempTable to TRUE if the result of the SELECT statement
* should be written into a temporary table (template 4). Set to
* FALSE if each output row of the SELECT can be written directly into
* the destination table (template 3).
*
* A temp table must be used if the table being updated is also one
* of the tables being read by the SELECT statement. Also use a
* temp table in the case of row triggers.
*/
if (pTrigger || readsTable(pParse, pTab)) {
useTempTable = 1;
}
if (useTempTable) {
/* Invoke the coroutine to extract information from the SELECT
* and add it to a transient table srcTab. The code generated
* here is from the 4th template:
*
* B: open temp table
* L: yield X, goto M at EOF
* insert row from R..R+n into temp table
* goto L
* M: ...
*/
int regRec; /* Register to hold packed record */
int regTempId; /* Register to hold temp table ID */
int regCopy; /* Register to keep copy of registers from select */
int addrL; /* Label "L" */
srcTab = pParse->nTab++;
regRec = sqlite3GetTempReg(pParse);
regCopy = sqlite3GetTempRange(pParse, nColumn);
regTempId = sqlite3GetTempReg(pParse);
KeyInfo *pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, 1+nColumn, 0);
sqlite3VdbeAddOp4(v, OP_OpenTEphemeral, srcTab, nColumn+1,
0, (char*)pKeyInfo, P4_KEYINFO);
addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_NextIdEphemeral, srcTab, 2, regTempId);
sqlite3VdbeAddOp3(v, OP_Copy, regFromSelect, regCopy, nColumn-1);
sqlite3VdbeAddOp3(v, OP_MakeRecord, regCopy,
nColumn + 1, regRec);
/* Set flag to save memory allocating one by malloc. */
sqlite3VdbeChangeP5(v, 1);
sqlite3VdbeAddOp2(v, OP_IdxInsert, srcTab, regRec);
sqlite3VdbeGoto(v, addrL);
sqlite3VdbeJumpHere(v, addrL);
sqlite3ReleaseTempReg(pParse, regRec);
sqlite3ReleaseTempReg(pParse, regTempId);
sqlite3ReleaseTempRange(pParse, regCopy, nColumn);
}
} else {
/* This is the case if the data for the INSERT is coming from a
* single-row VALUES clause
*/
NameContext sNC;
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = pParse;
srcTab = -1;
assert(useTempTable == 0);
if (pList) {
nColumn = pList->nExpr;
if (sqlite3ResolveExprListNames(&sNC, pList)) {
goto insert_cleanup;
}
} else {
nColumn = 0;
}
}
/* If there is no IDLIST term but the table has an integer primary
* key, the set the ipkColumn variable to the integer primary key
* column index in the original table definition.
*/
if (pColumn == 0 && nColumn > 0) {
ipkColumn = pTab->iPKey;
}
if (pColumn == 0 && nColumn && nColumn != (pTab->nCol)) {
sqlite3ErrorMsg(pParse,
"table %S has %d columns but %d values were supplied",
pTabList, 0, pTab->nCol, nColumn);
goto insert_cleanup;
}
if (pColumn != 0 && nColumn != pColumn->nId) {
sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn,
pColumn->nId);
goto insert_cleanup;
}
/* Initialize the count of rows to be inserted
*/
if (user_session->sql_flags & SQLITE_CountRows) {
regRowCount = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
}
/* If this is not a view, open the table and and all indices */
if (!isView) {
int nIdx;
nIdx =
sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0,
-1, 0, &iDataCur, &iIdxCur,
onError, 0);
aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int) * (nIdx + 1));
if (aRegIdx == 0) {
goto insert_cleanup;
}
for (i = 0, pIdx = pTab->pIndex; i < nIdx;
pIdx = pIdx->pNext, i++) {
assert(pIdx);
aRegIdx[i] = ++pParse->nMem;
pParse->nMem += pIdx->nColumn;
}
}
/* This is the top of the main insertion loop */
if (useTempTable) {
/* This block codes the top of loop only. The complete loop is the
* following pseudocode (template 4):
*
* rewind temp table, if empty goto D
* C: loop over rows of intermediate table
* transfer values form intermediate table into <table>
* end loop
* D: ...
*/
addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
VdbeCoverage(v);
addrCont = sqlite3VdbeCurrentAddr(v);
} else if (pSelect) {
/* This block codes the top of loop only. The complete loop is the
* following pseudocode (template 3):
*
* C: yield X, at EOF goto D
* insert the select result into <table> from R..R+n
* goto C
* D: ...
*/
addrInsTop = addrCont =
sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
VdbeCoverage(v);
}
/* Run the BEFORE and INSTEAD OF triggers, if there are any
*/
endOfLoop = sqlite3VdbeMakeLabel(v);
if (tmask & TRIGGER_BEFORE) {
int regCols = sqlite3GetTempRange(pParse, pTab->nCol + 1);
/* Create the new column data
*/
for (i = j = 0; i < pTab->nCol; i++) {
if (pColumn) {
for (j = 0; j < pColumn->nId; j++) {
if (pColumn->a[j].idx == i)
break;
}
}
if ((!useTempTable && !pList)
|| (pColumn && j >= pColumn->nId)) {
if (i == pTab->iAutoIncPKey)
sqlite3VdbeAddOp2(v, OP_Integer, -1,
regCols + i + 1);
else
sqlite3ExprCode(pParse,
pTab->aCol[i].pDflt,
regCols + i + 1);
} else if (useTempTable) {
sqlite3VdbeAddOp3(v, OP_Column, srcTab, j,
regCols + i + 1);
} else {
assert(pSelect == 0); /* Otherwise useTempTable is true */
sqlite3ExprCodeAndCache(pParse,
pList->a[j].pExpr,
regCols + i + 1);
}
if (pColumn == 0)
j++;
}
/* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
* do not attempt any conversions before assembling the record.
* If this is a real table, attempt conversions as required by the
* table column affinities.
*/
if (!isView) {
sqlite3TableAffinity(v, pTab, regCols + 1);
}
/* Fire BEFORE or INSTEAD OF triggers */
sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0,
TRIGGER_BEFORE, pTab,
regCols - pTab->nCol - 1, onError,
endOfLoop);
sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol + 1);
}
/* Compute the content of the next row to insert into a range of
* registers beginning at regIns.
*/
if (!isView) {
if (ipkColumn >= 0) {
if (useTempTable) {
sqlite3VdbeAddOp3(v, OP_Column, srcTab,
ipkColumn, regTupleid);
} else if (pSelect) {
sqlite3VdbeAddOp2(v, OP_Copy,
regFromSelect + ipkColumn,
regTupleid);
}
} else {
sqlite3VdbeAddOp2(v, OP_Null, 0, regTupleid);
}
/* Compute data for all columns of the new entry, beginning
* with the first column.
*/
for (i = 0; i < pTab->nCol; i++) {
int iRegStore = regTupleid + 1 + i;
if (pColumn == 0) {
j = i;
} else {
for (j = 0; j < pColumn->nId; j++) {
if (pColumn->a[j].idx == i)
break;
}
}
if (j < 0 || nColumn == 0
|| (pColumn && j >= pColumn->nId)) {
if (i == pTab->iAutoIncPKey) {
sqlite3VdbeAddOp2(v,
OP_NextAutoincValue,
pTab->tnum,
iRegStore);
continue;
}
sqlite3ExprCodeFactorable(pParse,
pTab->aCol[i].pDflt,
iRegStore);
} else if (useTempTable) {
if ((pTab->tabFlags & TF_Autoincrement)
&& (i == pTab->iAutoIncPKey)) {
int regTmp = ++pParse->nMem;
/* Emit code which doesn't override
* autoinc-ed value with select result
* in case if result is NULL value.
*/
sqlite3VdbeAddOp3(v, OP_Column, srcTab,
j, regTmp);
sqlite3VdbeAddOp2(v, OP_FCopy, regTmp,
iRegStore);
sqlite3VdbeChangeP3(v, -1,
OPFLAG_SAME_FRAME |
OPFLAG_NOOP_IF_NULL);
} else {
sqlite3VdbeAddOp3(v, OP_Column, srcTab,
j, iRegStore);
}
} else if (pSelect) {
if (regFromSelect != regData) {
if ((pTab->tabFlags & TF_Autoincrement)
&& (i == pTab->iAutoIncPKey)) {
/* Emit code which doesn't override
* autoinc-ed value with select result
* in case that result is NULL
*/
sqlite3VdbeAddOp2(v, OP_FCopy,
regFromSelect
+ j,
iRegStore);
sqlite3VdbeChangeP3(v, -1,
OPFLAG_SAME_FRAME
|
OPFLAG_NOOP_IF_NULL);
} else {
sqlite3VdbeAddOp2(v, OP_SCopy,
regFromSelect
+ j,
iRegStore);
}
}
} else {
if (i == pTab->iAutoIncPKey) {
if (pList->a[j].pExpr->op == TK_NULL) {
sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
continue;
}
if (pList->a[j].pExpr->op ==
TK_REGISTER) {
/* Emit code which doesn't override
* autoinc-ed value with select result
* in case that result is NULL
*/
sqlite3VdbeAddOp2(v, OP_FCopy,
pList->a[j].
pExpr->iTable,
iRegStore);
sqlite3VdbeChangeP3(v, -1,
OPFLAG_SAME_FRAME
|
OPFLAG_NOOP_IF_NULL);
continue;
}
}
sqlite3ExprCode(pParse, pList->a[j].pExpr,
iRegStore);
}
}
/* Generate code to check constraints and generate index keys
and do the insertion.
*/
int isReplace; /* Set to true if constraints may cause a replace */
int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur,
iIdxCur, regIns, 0,
ipkColumn >= 0, onError,
endOfLoop, &isReplace, 0);
sqlite3FkCheck(pParse, pTab, 0, regIns, 0);
/* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
* constraints or (b) there are no triggers and this table is not a
* parent table in a foreign key constraint. It is safe to set the
* flag in the second case as if any REPLACE constraint is hit, an
* OP_Delete or OP_IdxDelete instruction will be executed on each
* cursor that is disturbed. And these instructions both clear the
* VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
* functionality.
*/
bUseSeek = isReplace == 0 || (pTrigger == 0 &&
((user_session->sql_flags &
SQLITE_ForeignKeys) == 0 ||
sqlite3FkReferences(pTab) == 0));
sqlite3CompleteInsertion(pParse, pTab, iIdxCur, aRegIdx,
bUseSeek, onError);
}
/* Update the count of rows that are inserted
*/
if ((user_session->sql_flags & SQLITE_CountRows) != 0) {
sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
}
if (pTrigger) {
/* Code AFTER triggers */
sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0,
TRIGGER_AFTER, pTab,
regData - 2 - pTab->nCol, onError,
endOfLoop);
}
/* The bottom of the main insertion loop, if the data source
* is a SELECT statement.
*/
sqlite3VdbeResolveLabel(v, endOfLoop);
if (useTempTable) {
sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
VdbeCoverage(v);
sqlite3VdbeJumpHere(v, addrInsTop);
sqlite3VdbeAddOp1(v, OP_Close, srcTab);
} else if (pSelect) {
sqlite3VdbeGoto(v, addrCont);
sqlite3VdbeJumpHere(v, addrInsTop);
}
insert_end:
/*
* Return the number of rows inserted. If this routine is
* generating code because of a call to sqlite3NestedParse(), do not
* invoke the callback function.
*/
if ((user_session->sql_flags & SQLITE_CountRows) && !pParse->nested
&& !pParse->pTriggerTab) {
sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
sqlite3VdbeSetNumCols(v, 1);
sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted",
SQLITE_STATIC);
}
insert_cleanup:
sqlite3SrcListDelete(db, pTabList);
sqlite3ExprListDelete(db, pList);
sqlite3SelectDelete(db, pSelect);
sqlite3IdListDelete(db, pColumn);
sqlite3DbFree(db, aRegIdx);
}
/* Make sure "isView" and other macros defined above are undefined. Otherwise
* they may interfere with compilation of other functions in this file
* (or in another file, if this file becomes part of the amalgamation).
*/
#ifdef isView
#undef isView
#endif
#ifdef pTrigger
#undef pTrigger
#endif
#ifdef tmask
#undef tmask
#endif
/*
* Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
*/
#define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
/* This is the Walker callback from checkConstraintUnchanged(). Set
* bit 0x01 of pWalker->eCode if
* pWalker->eCode to 0 if this expression node references any of the
* columns that are being modifed by an UPDATE statement.
*/
static int
checkConstraintExprNode(Walker * pWalker, Expr * pExpr)
{
if (pExpr->op == TK_COLUMN) {
assert(pExpr->iColumn >= 0 || pExpr->iColumn == -1);
if (pExpr->iColumn >= 0) {
if (pWalker->u.aiCol[pExpr->iColumn] >= 0) {
pWalker->eCode |= CKCNSTRNT_COLUMN;
}
}
}
return WRC_Continue;
}
/*
* pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
* only columns that are modified by the UPDATE are those for which
* aiChng[i]>=0.
*
* Return true if CHECK constraint pExpr does not use any of the
* changing columns. In other words, return true if this CHECK constraint
* can be skipped when validating the new row in the UPDATE statement.
*/
static int
checkConstraintUnchanged(Expr * pExpr, int *aiChng)
{
Walker w;
memset(&w, 0, sizeof(w));
w.eCode = 0;
w.xExprCallback = checkConstraintExprNode;
w.u.aiCol = aiChng;
sqlite3WalkExpr(&w, pExpr);
testcase(w.eCode == 0);
testcase(w.eCode == CKCNSTRNT_COLUMN);
return !w.eCode;
}
/*
* Generate code to do constraint checks prior to an INSERT or an UPDATE
* on table pTab.
*
* The regNewData parameter is the first register in a range that contains
* the data to be inserted or the data after the update. There will be
* pTab->nCol+1 registers in this range. The first register (the one
* that regNewData points to) will contain NULL. The second register
* in the range will contain the content of the first table column.
* The third register will contain the content of the second table column.
* And so forth.
*
* The regOldData parameter is similar to regNewData except that it contains
* the data prior to an UPDATE rather than afterwards. regOldData is zero
* for an INSERT. This routine can distinguish between UPDATE and INSERT by
* checking regOldData for zero.
*
* For an UPDATE, the pkChng boolean is true if the primary key
* might be modified by the UPDATE. If pkChng is false, then the key of
* the iDataCur content table is guaranteed to be unchanged by the UPDATE.
*
* On an INSERT, pkChng will only be true if the INSERT statement provides
* an integer value for INTEGER PRIMARY KEY alias.
*
* The code generated by this routine will store new index entries into
* registers identified by aRegIdx[]. No index entry is created for
* indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
* the same as the order of indices on the linked list of indices
* at pTab->pIndex.
*
* The caller must have already opened writeable cursors on the main
* table and all applicable indices (that is to say, all indices for which