-
Notifications
You must be signed in to change notification settings - Fork 377
/
build.c
4133 lines (3870 loc) · 121 KB
/
build.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 SQLite parser
* when syntax rules are reduced. The routines in this file handle the
* following kinds of SQL syntax:
*
* CREATE TABLE
* DROP TABLE
* CREATE INDEX
* DROP INDEX
* creating ID lists
* BEGIN TRANSACTION
* COMMIT
* ROLLBACK
*/
#include "sqliteInt.h"
#include "vdbeInt.h"
#include "tarantoolInt.h"
#include "box/box.h"
#include "box/sequence.h"
#include "box/session.h"
#include "box/identifier.h"
#include "box/schema.h"
#include "box/tuple_format.h"
#include "box/coll_id_cache.h"
/*
* This routine is called after a single SQL statement has been
* parsed and a VDBE program to execute that statement has been
* prepared. This routine puts the finishing touches on the
* VDBE program and resets the pParse structure for the next
* parse.
*
* Note that if an error occurred, it might be the case that
* no VDBE code was generated.
*/
void
sqlite3FinishCoding(Parse * pParse)
{
sqlite3 *db;
Vdbe *v;
assert(pParse->pToplevel == 0);
db = pParse->db;
if (pParse->nested)
return;
if (db->mallocFailed || pParse->nErr) {
if (pParse->rc == SQLITE_OK)
pParse->rc = SQLITE_ERROR;
return;
}
/* Begin by generating some termination code at the end of the
* vdbe program
*/
v = sqlite3GetVdbe(pParse);
assert(!pParse->isMultiWrite
|| sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
if (v) {
sqlite3VdbeAddOp0(v, OP_Halt);
if (db->mallocFailed == 0 || pParse->pConstExpr) {
int i;
assert(sqlite3VdbeGetOp(v, 0)->opcode == OP_Init);
sqlite3VdbeJumpHere(v, 0);
if (pParse->initiateTTrans)
sqlite3VdbeAddOp0(v, OP_TTransaction);
if (db->init.busy == 0)
sqlite3VdbeChangeP5(v, 1);
/* Code constant expressions that where factored out of inner loops */
if (pParse->pConstExpr) {
ExprList *pEL = pParse->pConstExpr;
pParse->okConstFactor = 0;
for (i = 0; i < pEL->nExpr; i++) {
sqlite3ExprCode(pParse, pEL->a[i].pExpr,
pEL->a[i].u.
iConstExprReg);
}
}
/* Finally, jump back to the beginning of the executable code. */
sqlite3VdbeGoto(v, 1);
}
}
/* Get the VDBE program ready for execution
*/
if (v && pParse->nErr == 0 && !db->mallocFailed) {
assert(pParse->iCacheLevel == 0); /* Disables and re-enables match */
/* A minimum of one cursor is required if autoincrement is used
* See ticket [a696379c1f08866]
*/
sqlite3VdbeMakeReady(v, pParse);
pParse->rc = SQLITE_DONE;
} else {
pParse->rc = SQLITE_ERROR;
}
}
/*
* Run the parser and code generator recursively in order to generate
* code for the SQL statement given onto the end of the pParse context
* currently under construction. When the parser is run recursively
* this way, the final OP_Halt is not appended and other initialization
* and finalization steps are omitted because those are handling by the
* outermost parser.
*
* Not everything is nestable. This facility is designed to perform
* basic DDL operations. Use care if you decide to try to use this routine
* for some other purposes.
*/
void
sqlite3NestedParse(Parse * pParse, const char *zFormat, ...)
{
va_list ap;
char *zSql;
char *zErrMsg = 0;
sqlite3 *db = pParse->db;
char saveBuf[PARSE_TAIL_SZ];
if (pParse->nErr)
return;
assert(pParse->nested < 10); /* Nesting should only be of limited depth */
va_start(ap, zFormat);
zSql = sqlite3VMPrintf(db, zFormat, ap);
va_end(ap);
if (zSql == 0) {
return; /* A malloc must have failed */
}
pParse->nested++;
memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
sqlite3RunParser(pParse, zSql, &zErrMsg);
sqlite3DbFree(db, zErrMsg);
sqlite3DbFree(db, zSql);
memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
pParse->nested--;
}
/**
* This is a function which should be called during execution
* of sqlite3EndTable. It ensures that only PRIMARY KEY
* constraint may have ON CONFLICT REPLACE clause.
*
* @param table Space which should be checked.
* @retval False, if only primary key constraint has
* ON CONFLICT REPLACE clause or if there are no indexes
* with REPLACE as error action. True otherwise.
*/
static bool
check_on_conflict_replace_entries(struct Table *table)
{
/* Check all NOT NULL constraints. */
for (int i = 0; i < (int)table->def->field_count; i++) {
enum on_conflict_action on_error =
table->def->fields[i].nullable_action;
if (on_error == ON_CONFLICT_ACTION_REPLACE &&
table->aCol[i].is_primkey == false) {
return true;
}
}
/* Check all UNIQUE constraints. */
for (struct Index *idx = table->pIndex; idx; idx = idx->pNext) {
if (idx->onError == ON_CONFLICT_ACTION_REPLACE &&
!IsPrimaryKeyIndex(idx)) {
return true;
}
}
/*
* CHECK constraints are not allowed to have REPLACE as
* error action and therefore can be skipped.
*/
return false;
}
/*
* Locate the in-memory structure that describes a particular database
* table given the name of that table. Return NULL if not found.
* Also leave an error message in pParse->zErrMsg.
*/
Table *
sqlite3LocateTable(Parse * pParse, /* context in which to report errors */
u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
const char *zName /* Name of the table we are looking for */
)
{
Table *p;
assert(pParse->db->pSchema != NULL);
p = sqlite3HashFind(&pParse->db->pSchema->tblHash, zName);
if (p == NULL) {
const char *zMsg =
flags & LOCATE_VIEW ? "no such view" : "no such table";
if ((flags & LOCATE_NOERR) == 0) {
sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
pParse->checkSchema = 1;
}
}
return p;
}
Index *
sqlite3LocateIndex(sqlite3 * db, const char *zName, const char *zTable)
{
assert(zName);
assert(zTable);
Table *pTab = sqlite3HashFind(&db->pSchema->tblHash, zTable);
if (pTab == NULL)
return NULL;
return sqlite3HashFind(&pTab->idxHash, zName);
}
/*
* Reclaim the memory used by an index
*/
static void
freeIndex(sqlite3 * db, Index * p)
{
sql_expr_delete(db, p->pPartIdxWhere, false);
sqlite3DbFree(db, p->zColAff);
sqlite3DbFree(db, p);
}
/*
* For the index called zIdxName which is found in the database,
* unlike that index from its Table then remove the index from
* the index hash table and free all memory structures associated
* with the index.
*/
void
sqlite3UnlinkAndDeleteIndex(sqlite3 * db, Index * pIndex)
{
assert(pIndex != 0);
assert(&pIndex->pTable->idxHash);
struct session *user_session = current_session();
pIndex = sqlite3HashInsert(&pIndex->pTable->idxHash, pIndex->zName, 0);
if (ALWAYS(pIndex)) {
if (pIndex->pTable->pIndex == pIndex) {
pIndex->pTable->pIndex = pIndex->pNext;
} else {
Index *p;
/* Justification of ALWAYS(); The index must be on the list of
* indices.
*/
p = pIndex->pTable->pIndex;
while (ALWAYS(p) && p->pNext != pIndex) {
p = p->pNext;
}
if (ALWAYS(p && p->pNext == pIndex)) {
p->pNext = pIndex->pNext;
}
}
freeIndex(db, pIndex);
}
user_session->sql_flags |= SQLITE_InternChanges;
}
/*
* Erase all schema information from all attached databases (including
* "main" and "temp") for a single database connection.
*/
void
sqlite3ResetAllSchemasOfConnection(sqlite3 * db)
{
struct session *user_session = current_session();
if (db->pSchema) {
sqlite3SchemaClear(db);
}
user_session->sql_flags &= ~SQLITE_InternChanges;
}
/*
* This routine is called when a commit occurs.
*/
void
sqlite3CommitInternalChanges()
{
current_session()->sql_flags &= ~SQLITE_InternChanges;
}
/*
* Return true if given column is part of primary key.
* If field number is less than 63, corresponding bit
* in column mask is tested. Otherwise, check whether 64-th bit
* in mask is set or not. If it is set, then iterate through
* key parts of primary index and check field number.
* In case it isn't set, there are no key columns among
* the rest of fields.
*/
bool
table_column_is_in_pk(Table *table, uint32_t column)
{
uint32_t space_id = SQLITE_PAGENO_TO_SPACEID(table->tnum);
struct space *space = space_by_id(space_id);
assert(space != NULL);
struct index *primary_idx = index_find(space, 0 /* PK */);
/* Views don't have any indexes. */
if (primary_idx == NULL)
return false;
struct index_def *idx_def = primary_idx->def;
uint64_t pk_mask = idx_def->key_def->column_mask;
if (column < 63) {
return pk_mask & (((uint64_t) 1) << column);
} else if ((pk_mask & (((uint64_t) 1) << 63)) != 0) {
for (uint32_t i = 0; i < idx_def->key_def->part_count; ++i) {
struct key_part *part = &idx_def->key_def->parts[i];
if (part->fieldno == column)
return true;
}
}
return false;
}
/*
* Remove the memory data structures associated with the given
* Table. No changes are made to disk by this routine.
*
* This routine just deletes the data structure. It does not unlink
* the table data structure from the hash table. But it does destroy
* memory structures of the indices and foreign keys associated with
* the table.
*
* The db parameter is optional. It is needed if the Table object
* contains lookaside memory. (Table objects in the schema do not use
* lookaside memory, but some ephemeral Table objects do.) Or the
* db parameter can be used with db->pnBytesFreed to measure the memory
* used by the Table object.
*/
static void SQLITE_NOINLINE
deleteTable(sqlite3 * db, Table * pTable)
{
Index *pIndex, *pNext;
TESTONLY(int nLookaside;
)
/* Used to verify lookaside not used for schema */
/* Record the number of outstanding lookaside allocations in schema Tables
* prior to doing any free() operations. Since schema Tables do not use
* lookaside, this number should not change.
*/
TESTONLY(nLookaside =
(db
&& (pTable->tabFlags & TF_Ephemeral) ==
0) ? db->lookaside.nOut : 0);
/* Delete all indices associated with this table. */
for (pIndex = pTable->pIndex; pIndex; pIndex = pNext) {
pNext = pIndex->pNext;
assert(pIndex->pSchema == pTable->pSchema);
if ((db == 0 || db->pnBytesFreed == 0)) {
char *zName = pIndex->zName;
TESTONLY(Index *
pOld =) sqlite3HashInsert(&pTable->idxHash,
zName, 0);
assert(pOld == pIndex || pOld == 0);
}
freeIndex(db, pIndex);
}
/* Delete any foreign keys attached to this table. */
sqlite3FkDelete(db, pTable);
/* Delete the Table structure itself.
*/
sqlite3HashClear(&pTable->idxHash);
sqlite3DbFree(db, pTable->aCol);
sqlite3DbFree(db, pTable->zColAff);
sqlite3SelectDelete(db, pTable->pSelect);
assert(pTable->def != NULL);
/* Do not delete pTable->def allocated on region. */
if (!pTable->def->opts.temporary)
space_def_delete(pTable->def);
else
sql_expr_list_delete(db, pTable->def->opts.checks);
sqlite3DbFree(db, pTable);
/* Verify that no lookaside memory was used by schema tables */
assert(nLookaside == 0 || nLookaside == db->lookaside.nOut);
}
void
sqlite3DeleteTable(sqlite3 * db, Table * pTable)
{
/* Do not delete the table until the reference count reaches zero. */
if (!pTable)
return;
if (((!db || db->pnBytesFreed == 0) && (--pTable->nTabRef) > 0))
return;
deleteTable(db, pTable);
}
/*
* Unlink the given table from the hash tables and the delete the
* table structure with all its indices and foreign keys.
*/
void
sqlite3UnlinkAndDeleteTable(sqlite3 * db, const char *zTabName)
{
Table *p;
assert(db != 0);
assert(zTabName);
testcase(zTabName[0] == 0); /* Zero-length table names are allowed */
p = sqlite3HashInsert(&db->pSchema->tblHash, zTabName, 0);
sqlite3DeleteTable(db, p);
}
/*
* Given a token, return a string that consists of the text of that
* token. Space to hold the returned string
* is obtained from sqliteMalloc() and must be freed by the calling
* function.
*
* Any quotation marks (ex: "name", 'name', [name], or `name`) that
* surround the body of the token are removed.
*
* Tokens are often just pointers into the original SQL text and so
* are not \000 terminated and are not persistent. The returned string
* is \000 terminated and is persistent.
*/
char *
sqlite3NameFromToken(sqlite3 * db, Token * pName)
{
char *zName;
if (pName) {
zName = sqlite3DbStrNDup(db, (char *)pName->z, pName->n);
sqlite3NormalizeName(zName);
} else {
zName = 0;
}
return zName;
}
/*
* This routine is used to check if the UTF-8 string zName is a legal
* unqualified name for an identifier.
* Some objects may not be checked, because they are validated in Tarantool.
* (e.g. table, index, column name of a real table)
* All names are legal except those that cantain non-printable
* characters or have length greater than BOX_NAME_MAX.
*/
int
sqlite3CheckIdentifierName(Parse *pParse, char *zName)
{
ssize_t len = strlen(zName);
if (len > BOX_NAME_MAX || identifier_check(zName, len) != 0) {
sqlite3ErrorMsg(pParse,
"identifier name is invalid: %s",
zName);
return SQLITE_ERROR;
}
return SQLITE_OK;
}
/*
* Return the PRIMARY KEY index of a table
*/
Index *
sqlite3PrimaryKeyIndex(Table * pTab)
{
Index *p;
for (p = pTab->pIndex; p && !IsPrimaryKeyIndex(p); p = p->pNext) {
}
return p;
}
/**
* Create and initialize a new SQL Table object.
* All memory except table object itself is allocated on region.
* @param parser SQL Parser object.
* @param name Table to create name.
* @retval NULL on memory allocation error, Parser state is
* changed.
* @retval not NULL on success.
*/
static Table *
sql_table_new(Parse *parser, char *name)
{
sqlite3 *db = parser->db;
struct Table *table = sql_ephemeral_table_new(parser, name);
if (table == NULL)
return NULL;
table->iPKey = -1;
table->iAutoIncPKey = -1;
table->pSchema = db->pSchema;
sqlite3HashInit(&table->idxHash);
table->nTabRef = 1;
return table;
}
/*
* Begin constructing a new table representation in memory. This is
* the first of several action routines that get called in response
* to a CREATE TABLE statement. In particular, this routine is called
* after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
* flag is true if the table should be stored in the auxiliary database
* file instead of in the main database file. This is normally the case
* when the "TEMP" or "TEMPORARY" keyword occurs in between
* CREATE and TABLE.
*
* The new table record is initialized and put in pParse->pNewTable.
* As more of the CREATE TABLE statement is parsed, additional action
* routines will be called to add more information to this record.
* At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
* is called to complete the construction of the new table record.
*
* @param pParse Parser context.
* @param pName1 First part of the name of the table or view.
* @param noErr Do nothing if table already exists.
*/
void
sqlite3StartTable(Parse *pParse, Token *pName, int noErr)
{
Table *pTable;
char *zName = 0; /* The name of the new table */
sqlite3 *db = pParse->db;
Vdbe *v;
/* Do not account nested operations: the count of such
* operations depends on Tarantool data dictionary internals,
* such as data layout in system spaces.
*/
if (!pParse->nested) {
if ((v = sqlite3GetVdbe(pParse)) == NULL)
goto cleanup;
sqlite3VdbeCountChanges(v);
}
zName = sqlite3NameFromToken(db, pName);
pParse->sNameToken = *pName;
if (zName == 0)
return;
if (sqlite3CheckIdentifierName(pParse, zName) != SQLITE_OK)
goto cleanup;
assert(db->pSchema != NULL);
pTable = sqlite3HashFind(&db->pSchema->tblHash, zName);
if (pTable != NULL) {
if (!noErr) {
sqlite3ErrorMsg(pParse,
"table %s already exists",
zName);
} else {
assert(!db->init.busy || CORRUPT_DB);
}
goto cleanup;
}
pTable = sql_table_new(pParse, zName);
if (pTable == NULL)
goto cleanup;
assert(pParse->pNewTable == 0);
pParse->pNewTable = pTable;
/* Begin generating the code that will create a new table.
* Note in particular that we must go ahead and allocate the
* record number for the table entry now. Before any
* PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
* indices to be created and the table record must come before the
* indices. Hence, the record number for the table must be allocated
* now.
*/
if (!db->init.busy && (v = sqlite3GetVdbe(pParse)) != 0)
sql_set_multi_write(pParse, true);
cleanup:
sqlite3DbFree(db, zName);
return;
}
/**
* Get field by id. Allocate memory if needed.
* Useful in cases when initial field_count is unknown.
* Allocated memory should by manually released.
* @param parser SQL Parser object.
* @param table SQL Table object.
* @param id column identifier.
* @retval not NULL on success.
* @retval NULL on out of memory.
*/
static struct field_def *
sql_field_retrieve(Parse *parser, Table *table, uint32_t id)
{
struct field_def *field;
assert(table->def != NULL);
assert(id < SQLITE_MAX_COLUMN);
if (id >= table->def->exact_field_count) {
uint32_t columns_new = table->def->exact_field_count;
columns_new = (columns_new > 0) ? 2 * columns_new : 1;
struct region *region = &parser->region;
field = region_alloc(region, columns_new *
sizeof(table->def->fields[0]));
if (field == NULL) {
diag_set(OutOfMemory, columns_new *
sizeof(table->def->fields[0]),
"region_alloc", "sql_field_retrieve");
parser->rc = SQL_TARANTOOL_ERROR;
parser->nErr++;
return NULL;
}
memcpy(field, table->def->fields,
sizeof(*field) * table->def->exact_field_count);
for (uint32_t i = columns_new / 2; i < columns_new; i++) {
memcpy(&field[i], &field_def_default,
sizeof(struct field_def));
}
table->def->fields = field;
table->def->exact_field_count = columns_new;
}
field = &table->def->fields[id];
return field;
}
/*
* Add a new column to the table currently being constructed.
*
* The parser calls this routine once for each column declaration
* in a CREATE TABLE statement. sqlite3StartTable() gets called
* first to get things going. Then this routine is called for each
* column.
*/
void
sqlite3AddColumn(Parse * pParse, Token * pName, Token * pType)
{
Table *p;
int i;
char *z;
char *zType;
Column *pCol;
sqlite3 *db = pParse->db;
if ((p = pParse->pNewTable) == 0)
return;
#if SQLITE_MAX_COLUMN
if ((int)p->def->field_count + 1 > db->aLimit[SQLITE_LIMIT_COLUMN]) {
sqlite3ErrorMsg(pParse, "too many columns on %s",
p->def->name);
return;
}
#endif
/*
* As sql_field_retrieve will allocate memory on region
* ensure that p->def is also temporal and would be rebuilded or
* dropped.
*/
assert(p->def->opts.temporary);
if (sql_field_retrieve(pParse, p,
(uint32_t) p->def->field_count) == NULL)
return;
struct region *region = &pParse->region;
z = region_alloc(region, pName->n + 1);
if (z == NULL) {
diag_set(OutOfMemory, pName->n + 1,
"region_alloc", "z");
pParse->rc = SQL_TARANTOOL_ERROR;
pParse->nErr++;
return;
}
memcpy(z, pName->z, pName->n);
z[pName->n] = 0;
sqlite3NormalizeName(z);
for (i = 0; i < (int)p->def->field_count; i++) {
if (strcmp(z, p->def->fields[i].name) == 0) {
sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
return;
}
}
if ((p->def->field_count & 0x7) == 0) {
Column *aNew =
sqlite3DbRealloc(db, p->aCol,
(p->def->field_count + 8) *
sizeof(p->aCol[0]));
if (aNew == NULL)
return;
p->aCol = aNew;
}
pCol = &p->aCol[p->def->field_count];
memset(pCol, 0, sizeof(p->aCol[0]));
struct field_def *column_def = &p->def->fields[p->def->field_count];
memcpy(column_def, &field_def_default, sizeof(field_def_default));
column_def->name = z;
column_def->nullable_action = ON_CONFLICT_ACTION_NONE;
column_def->is_nullable = true;
if (pType->n == 0) {
/* If there is no type specified, columns have the default affinity
* 'BLOB' and type SCALAR.
* TODO: since SQL standard prohibits column creation without
* specified type, the code below should emit an error.
*/
column_def->affinity = AFFINITY_BLOB;
column_def->type = FIELD_TYPE_SCALAR;
} else {
/* TODO: convert string of type into runtime
* FIELD_TYPE value for other types.
*/
if ((sqlite3StrNICmp(pType->z, "INTEGER", 7) == 0 &&
pType->n == 7) ||
(sqlite3StrNICmp(pType->z, "INT", 3) == 0 &&
pType->n == 3)) {
column_def->type = FIELD_TYPE_INTEGER;
column_def->affinity = AFFINITY_INTEGER;
} else {
zType = sqlite3_malloc(pType->n + 1);
memcpy(zType, pType->z, pType->n);
zType[pType->n] = 0;
sqlite3Dequote(zType);
column_def->affinity = sqlite3AffinityType(zType, 0);
column_def->type = FIELD_TYPE_SCALAR;
sqlite3_free(zType);
}
}
p->def->field_count++;
pParse->constraintName.n = 0;
}
/*
* This routine is called by the parser while in the middle of
* parsing a CREATE TABLE statement. A "NOT NULL" constraint has
* been seen on a column. This routine sets the notNull flag on
* the column currently under construction.
*/
void
sqlite3AddNotNull(Parse * pParse, int onError)
{
Table *p;
p = pParse->pNewTable;
if (p == 0 || NEVER(p->def->field_count < 1))
return;
p->def->fields[p->def->field_count - 1].nullable_action = (u8)onError;
p->def->fields[p->def->field_count - 1].is_nullable =
action_is_nullable(onError);
}
/*
* Scan the column type name zType (length nType) and return the
* associated affinity type.
*
* This routine does a case-independent search of zType for the
* substrings in the following table. If one of the substrings is
* found, the corresponding affinity is returned. If zType contains
* more than one of the substrings, entries toward the top of
* the table take priority. For example, if zType is 'BLOBINT',
* AFFINITY_INTEGER is returned.
*
* Substring | Affinity
* --------------------------------
* 'INT' | AFFINITY_INTEGER
* 'CHAR' | AFFINITY_TEXT
* 'CLOB' | AFFINITY_TEXT
* 'TEXT' | AFFINITY_TEXT
* 'BLOB' | AFFINITY_BLOB
* 'REAL' | AFFINITY_REAL
* 'FLOA' | AFFINITY_REAL
* 'DOUB' | AFFINITY_REAL
*
* If none of the substrings in the above table are found,
* AFFINITY_NUMERIC is returned.
*/
char
sqlite3AffinityType(const char *zIn, u8 * pszEst)
{
u32 h = 0;
char aff = AFFINITY_NUMERIC;
const char *zChar = 0;
assert(zIn != 0);
while (zIn[0]) {
h = (h << 8) + sqlite3UpperToLower[(*zIn) & 0xff];
zIn++;
if (h == (('c' << 24) + ('h' << 16) + ('a' << 8) + 'r')) { /* CHAR */
aff = AFFINITY_TEXT;
zChar = zIn;
} else if (h == (('c' << 24) + ('l' << 16) + ('o' << 8) + 'b')) { /* CLOB */
aff = AFFINITY_TEXT;
} else if (h == (('t' << 24) + ('e' << 16) + ('x' << 8) + 't')) { /* TEXT */
aff = AFFINITY_TEXT;
} else if (h == (('b' << 24) + ('l' << 16) + ('o' << 8) + 'b') /* BLOB */
&&(aff == AFFINITY_NUMERIC
|| aff == AFFINITY_REAL)) {
aff = AFFINITY_BLOB;
if (zIn[0] == '(')
zChar = zIn;
#ifndef SQLITE_OMIT_FLOATING_POINT
} else if (h == (('r' << 24) + ('e' << 16) + ('a' << 8) + 'l') /* REAL */
&&aff == AFFINITY_NUMERIC) {
aff = AFFINITY_REAL;
} else if (h == (('f' << 24) + ('l' << 16) + ('o' << 8) + 'a') /* FLOA */
&&aff == AFFINITY_NUMERIC) {
aff = AFFINITY_REAL;
} else if (h == (('d' << 24) + ('o' << 16) + ('u' << 8) + 'b') /* DOUB */
&&aff == AFFINITY_NUMERIC) {
aff = AFFINITY_REAL;
#endif
} else if ((h & 0x00FFFFFF) == (('i' << 16) + ('n' << 8) + 't')) { /* INT */
aff = AFFINITY_INTEGER;
break;
}
}
/* If pszEst is not NULL, store an estimate of the field size. The
* estimate is scaled so that the size of an integer is 1.
*/
if (pszEst) {
*pszEst = 1; /* default size is approx 4 bytes
*/
if (aff < AFFINITY_NUMERIC) {
if (zChar) {
while (zChar[0]) {
if (sqlite3Isdigit(zChar[0])) {
int v = 0;
sqlite3GetInt32(zChar, &v);
v = v / 4 + 1;
if (v > 255)
v = 255;
*pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1)
*/
break;
}
zChar++;
}
} else {
*pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)
*/
}
}
}
return aff;
}
/*
* The expression is the default value for the most recently added column
* of the table currently under construction.
*
* Default value expressions must be constant. Raise an exception if this
* is not the case.
*
* This routine is called by the parser while in the middle of
* parsing a CREATE TABLE statement.
*/
void
sqlite3AddDefaultValue(Parse * pParse, ExprSpan * pSpan)
{
Table *p;
sqlite3 *db = pParse->db;
p = pParse->pNewTable;
assert(p->def->opts.temporary);
if (p != 0) {
if (!sqlite3ExprIsConstantOrFunction
(pSpan->pExpr, db->init.busy)) {
sqlite3ErrorMsg(pParse,
"default value of column [%s] is not constant",
p->def->fields[p->def->field_count - 1].name);
} else {
assert(p->def != NULL);
struct field_def *field =
&p->def->fields[p->def->field_count - 1];
struct region *region = &pParse->region;
uint32_t default_length = (int)(pSpan->zEnd - pSpan->zStart);
field->default_value = region_alloc(region,
default_length + 1);
if (field->default_value == NULL) {
diag_set(OutOfMemory, default_length + 1,
"region_alloc",
"field->default_value");
pParse->rc = SQL_TARANTOOL_ERROR;
pParse->nErr++;
return;
}
strncpy(field->default_value, pSpan->zStart,
default_length);
field->default_value[default_length] = '\0';
}
}
sql_expr_delete(db, pSpan->pExpr, false);
}
/*
* Designate the PRIMARY KEY for the table. pList is a list of names
* of columns that form the primary key. If pList is NULL, then the
* most recently added column of the table is the primary key.
*
* A table can have at most one primary key. If the table already has
* a primary key (and this is the second primary key) then create an
* error.
*
* Set the Table.iPKey field of the table under construction to be the
* index of the INTEGER PRIMARY KEY column.
* Table.iPKey is set to -1 if there is no INTEGER PRIMARY KEY.
*
* If the key is not an INTEGER PRIMARY KEY, then create a unique
* index for the key. No index is created for INTEGER PRIMARY KEYs.
*/
void
sqlite3AddPrimaryKey(Parse * pParse, /* Parsing context */
ExprList * pList, /* List of field names to be indexed */
int onError, /* What to do with a uniqueness conflict */
int autoInc, /* True if the AUTOINCREMENT keyword is present */
enum sort_order sortOrder
)
{
Table *pTab = pParse->pNewTable;
Column *pCol = 0;
int iCol = -1, i;
int nTerm;
if (pTab == 0)
goto primary_key_exit;
if (pTab->tabFlags & TF_HasPrimaryKey) {
sqlite3ErrorMsg(pParse,
"table \"%s\" has more than one primary key",
pTab->def->name);
goto primary_key_exit;
}
pTab->tabFlags |= TF_HasPrimaryKey;
if (pList == 0) {
iCol = pTab->def->field_count - 1;
pCol = &pTab->aCol[iCol];
pCol->is_primkey = 1;
nTerm = 1;
} else {
nTerm = pList->nExpr;
for (i = 0; i < nTerm; i++) {
Expr *pCExpr =
sqlite3ExprSkipCollate(pList->a[i].pExpr);
assert(pCExpr != 0);
if (pCExpr->op != TK_ID) {
sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY");
goto primary_key_exit;
}
const char *zCName = pCExpr->u.zToken;
for (iCol = 0;
iCol < (int)pTab->def->field_count; iCol++) {
if (strcmp
(zCName,
pTab->def->fields[iCol].name) == 0) {
pCol = &pTab->aCol[iCol];
pCol->is_primkey = 1;
break;
}
}
}
}
assert(pCol == &pTab->aCol[iCol]);
if (nTerm == 1 && pCol != NULL &&
(pTab->def->fields[iCol].type == FIELD_TYPE_INTEGER) &&
sortOrder != SORT_ORDER_DESC) {
assert(autoInc == 0 || autoInc == 1);
pTab->iPKey = iCol;
pTab->keyConf = (u8) onError;
if (autoInc) {
pTab->iAutoIncPKey = iCol;
pTab->tabFlags |= TF_Autoincrement;