/
build.c
3115 lines (2966 loc) · 94.6 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 sql 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 "sqlInt.h"
#include "vdbeInt.h"
#include "tarantoolInt.h"
#include "box/box.h"
#include "box/fk_constraint.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"
/**
* Structure that contains information about record that was
* inserted into system space.
*/
struct saved_record
{
/** A link in a record list. */
struct rlist link;
/** Id of space in which the record was inserted. */
uint32_t space_id;
/** First register of the key of the record. */
int reg_key;
/** Number of registers the key consists of. */
int reg_key_count;
/** The number of the OP_SInsert operation. */
int insertion_opcode;
};
/**
* Save inserted in system space record in list.
*
* @param parser SQL Parser object.
* @param space_id Id of table in which record is inserted.
* @param reg_key Register that contains first field of the key.
* @param reg_key_count Exact number of fields of the key.
* @param insertion_opcode Number of OP_SInsert opcode.
*/
static inline void
save_record(struct Parse *parser, uint32_t space_id, int reg_key,
int reg_key_count, int insertion_opcode)
{
struct saved_record *record =
region_alloc(&parser->region, sizeof(*record));
if (record == NULL) {
diag_set(OutOfMemory, sizeof(*record), "region_alloc",
"record");
parser->is_aborted = true;
return;
}
record->space_id = space_id;
record->reg_key = reg_key;
record->reg_key_count = reg_key_count;
record->insertion_opcode = insertion_opcode;
rlist_add_entry(&parser->record_list, record, link);
}
void
sql_finish_coding(struct Parse *parse_context)
{
assert(parse_context->pToplevel == NULL);
struct sql *db = parse_context->db;
struct Vdbe *v = sqlGetVdbe(parse_context);
sqlVdbeAddOp0(v, OP_Halt);
/*
* In case statement "CREATE TABLE ..." fails it can
* left some records in system spaces that shouldn't be
* there. To clean-up properly this code is added. Last
* record isn't deleted because if statement fails than
* it won't be created. This code works the same way for
* other "CREATE ..." statements but it won't delete
* anything as these statements create no more than one
* record.
*/
if (!rlist_empty(&parse_context->record_list)) {
struct saved_record *record =
rlist_shift_entry(&parse_context->record_list,
struct saved_record, link);
/* Set P2 of SInsert. */
sqlVdbeChangeP2(v, record->insertion_opcode, v->nOp);
MAYBE_UNUSED const char *comment =
"Delete entry from %s if CREATE TABLE fails";
rlist_foreach_entry(record, &parse_context->record_list, link) {
int record_reg = ++parse_context->nMem;
sqlVdbeAddOp3(v, OP_MakeRecord, record->reg_key,
record->reg_key_count, record_reg);
sqlVdbeAddOp2(v, OP_SDelete, record->space_id,
record_reg);
MAYBE_UNUSED struct space *space =
space_by_id(record->space_id);
VdbeComment((v, comment, space_name(space)));
/* Set P2 of SInsert. */
sqlVdbeChangeP2(v, record->insertion_opcode,
v->nOp);
}
sqlVdbeAddOp1(v, OP_Halt, SQL_TARANTOOL_ERROR);
VdbeComment((v,
"Exit with an error if CREATE statement fails"));
}
if (db->mallocFailed)
parse_context->is_aborted = true;
if (parse_context->is_aborted)
return;
/*
* Begin by generating some termination code at the end
* of the vdbe program
*/
int last_instruction = v->nOp;
if (parse_context->initiateTTrans)
sqlVdbeAddOp0(v, OP_TTransaction);
if (parse_context->pConstExpr != NULL) {
assert(sqlVdbeGetOp(v, 0)->opcode == OP_Init);
/*
* Code constant expressions that where
* factored out of inner loops.
*/
struct ExprList *exprs = parse_context->pConstExpr;
parse_context->okConstFactor = 0;
for (int i = 0; i < exprs->nExpr; ++i) {
sqlExprCode(parse_context, exprs->a[i].pExpr,
exprs->a[i].u. iConstExprReg);
}
}
/*
* Finally, jump back to the beginning of
* the executable code. In fact, it is required
* only if some additional opcodes are generated.
* Otherwise, it would be useless jump:
*
* 0: OP_Init 0 vdbe_end ...
* 1: ...
* ...
* vdbe_end: OP_Goto 0 1 ...
*/
if (parse_context->initiateTTrans ||
parse_context->pConstExpr != NULL) {
sqlVdbeChangeP2(v, 0, last_instruction);
sqlVdbeGoto(v, 1);
}
/* Get the VDBE program ready for execution. */
if (!parse_context->is_aborted && !db->mallocFailed) {
assert(parse_context->iCacheLevel == 0);
sqlVdbeMakeReady(v, parse_context);
} else {
parse_context->is_aborted = true;
}
}
/**
* Find index by its name.
*
* @param space Space index belongs to.
* @param name Name of index to be found.
*
* @retval NULL in case index doesn't exist.
*/
static struct index *
sql_space_index_by_name(struct space *space, const char *name)
{
for (uint32_t i = 0; i < space->index_count; ++i) {
struct index *idx = space->index[i];
if (strcmp(name, idx->def->name) == 0)
return idx;
}
return NULL;
}
bool
sql_space_column_is_in_pk(struct space *space, uint32_t column)
{
if (space->def->opts.is_view)
return false;
struct index *primary_idx = space_index(space, 0);
assert(primary_idx != NULL);
struct key_def *key_def = primary_idx->def->key_def;
uint64_t pk_mask = key_def->column_mask;
if (column < 63)
return (pk_mask & (((uint64_t) 1) << column)) != 0;
else if ((pk_mask & (((uint64_t) 1) << 63)) != 0)
return key_def_find_by_fieldno(key_def, column) != NULL;
return false;
}
/*
* 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.
*
* @param pParse Parser context.
* @param zName Identifier to check.
*
* @retval 0 on success.
* @retval -1 on error.
*/
int
sqlCheckIdentifierName(Parse *pParse, char *zName)
{
ssize_t len = strlen(zName);
if (len > BOX_NAME_MAX) {
diag_set(ClientError, ER_IDENTIFIER,
tt_cstr(zName, BOX_INVALID_NAME_MAX));
pParse->is_aborted = true;
return -1;
}
if (identifier_check(zName, len) != 0) {
pParse->is_aborted = true;
return -1;
}
return 0;
}
/**
* Return the PRIMARY KEY index of a table.
*
* Note that during parsing routines this function is not equal
* to space_index(space, 0); call since primary key can be added
* after seconary keys:
*
* CREATE TABLE t (a INT UNIQUE, b PRIMARY KEY);
*
* In this particular case, after secondary index processing
* space still lacks PK, but index[0] != NULL since index array
* is filled in a straightforward way. Hence, function must
* return NULL.
*/
static struct index *
sql_space_primary_key(const struct space *space)
{
if (space->index_count == 0 || space->index[0]->def->iid != 0)
return NULL;
return space->index[0];
}
/*
* 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->create_table_def.
* 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 sqlEndTable() 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.
*/
struct space *
sqlStartTable(Parse *pParse, Token *pName, int noErr)
{
char *zName = 0; /* The name of the new table */
sql *db = pParse->db;
struct space *new_space = NULL;
struct Vdbe *v = sqlGetVdbe(pParse);
if (v == NULL)
goto cleanup;
sqlVdbeCountChanges(v);
zName = sql_name_from_token(db, pName);
if (zName == NULL) {
pParse->is_aborted = true;
goto cleanup;
}
if (sqlCheckIdentifierName(pParse, zName) != 0)
goto cleanup;
struct space *space = space_by_name(zName);
if (space != NULL) {
if (!noErr) {
diag_set(ClientError, ER_SPACE_EXISTS, zName);
pParse->is_aborted = true;
} else {
assert(!db->init.busy || CORRUPT_DB);
}
goto cleanup;
}
new_space = sql_ephemeral_space_new(pParse, zName);
if (new_space == NULL)
goto cleanup;
strcpy(new_space->def->engine_name,
sql_storage_engine_strs[current_session()->sql_default_engine]);
if (!db->init.busy && (v = sqlGetVdbe(pParse)) != 0)
sql_set_multi_write(pParse, true);
cleanup:
sqlDbFree(db, zName);
return new_space;
}
/**
* 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 space_def Space definition.
* @param id column identifier.
* @retval not NULL on success.
* @retval NULL on out of memory.
*/
static struct field_def *
sql_field_retrieve(Parse *parser, struct space_def *space_def, uint32_t id)
{
struct field_def *field;
assert(space_def != NULL);
assert(id < SQL_MAX_COLUMN);
if (id >= space_def->exact_field_count) {
uint32_t columns_new = space_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(space_def->fields[0]));
if (field == NULL) {
diag_set(OutOfMemory, columns_new *
sizeof(space_def->fields[0]),
"region_alloc", "sql_field_retrieve");
parser->is_aborted = true;
return NULL;
}
memcpy(field, space_def->fields,
sizeof(*field) * space_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));
}
space_def->fields = field;
space_def->exact_field_count = columns_new;
}
field = &space_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. sqlStartTable() gets called
* first to get things going. Then this routine is called for each
* column.
*/
void
sqlAddColumn(Parse * pParse, Token * pName, struct type_def *type_def)
{
assert(type_def != NULL);
char *z;
sql *db = pParse->db;
if (pParse->create_table_def.new_space == NULL)
return;
struct space_def *def = pParse->create_table_def.new_space->def;
#if SQL_MAX_COLUMN
if ((int)def->field_count + 1 > db->aLimit[SQL_LIMIT_COLUMN]) {
diag_set(ClientError, ER_SQL_COLUMN_COUNT_MAX, def->name,
def->field_count + 1, db->aLimit[SQL_LIMIT_COLUMN]);
pParse->is_aborted = true;
return;
}
#endif
/*
* As sql_field_retrieve will allocate memory on region
* ensure that def is also temporal and would be dropped.
*/
assert(def->opts.is_temporary);
if (sql_field_retrieve(pParse, def, def->field_count) == NULL)
return;
struct region *region = &pParse->region;
z = sql_normalized_name_region_new(region, pName->z, pName->n);
if (z == NULL) {
pParse->is_aborted = true;
return;
}
for (uint32_t i = 0; i < def->field_count; i++) {
if (strcmp(z, def->fields[i].name) == 0) {
diag_set(ClientError, ER_SPACE_FIELD_IS_DUPLICATE, z);
pParse->is_aborted = true;
return;
}
}
struct field_def *column_def = &def->fields[def->field_count];
memcpy(column_def, &field_def_default, sizeof(field_def_default));
column_def->name = z;
/*
* Marker ON_CONFLICT_ACTION_DEFAULT is used to detect
* attempts to define NULL multiple time or to detect
* invalid primary key definition.
*/
column_def->nullable_action = ON_CONFLICT_ACTION_DEFAULT;
column_def->is_nullable = true;
column_def->type = type_def->type;
def->field_count++;
}
void
sql_column_add_nullable_action(struct Parse *parser,
enum on_conflict_action nullable_action)
{
struct space *space = parser->create_table_def.new_space;
if (space == NULL || NEVER(space->def->field_count < 1))
return;
struct space_def *def = space->def;
struct field_def *field = &def->fields[def->field_count - 1];
if (field->nullable_action != ON_CONFLICT_ACTION_DEFAULT &&
nullable_action != field->nullable_action) {
/* Prevent defining nullable_action many times. */
const char *err = "NULL declaration for column '%s' of table "
"'%s' has been already set to '%s'";
const char *action =
on_conflict_action_strs[field->nullable_action];
err = tt_sprintf(err, field->name, def->name, action);
diag_set(ClientError, ER_SQL, err);
parser->is_aborted = true;
return;
}
field->nullable_action = nullable_action;
field->is_nullable = action_is_nullable(nullable_action);
}
/*
* 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
sqlAddDefaultValue(Parse * pParse, ExprSpan * pSpan)
{
sql *db = pParse->db;
struct space *p = pParse->create_table_def.new_space;
if (p != NULL) {
assert(p->def->opts.is_temporary);
struct space_def *def = p->def;
if (!sqlExprIsConstantOrFunction
(pSpan->pExpr, db->init.busy)) {
const char *column_name =
def->fields[def->field_count - 1].name;
diag_set(ClientError, ER_CREATE_SPACE, def->name,
tt_sprintf("default value of column '%s' is "\
"not constant", column_name));
pParse->is_aborted = true;
} else {
assert(def != NULL);
struct field_def *field =
&def->fields[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->is_aborted = true;
return;
}
strncpy(field->default_value, pSpan->zStart,
default_length);
field->default_value[default_length] = '\0';
}
}
sql_expr_delete(db, pSpan->pExpr, false);
}
static int
field_def_create_for_pk(struct Parse *parser, struct field_def *field,
const char *space_name)
{
if (field->nullable_action != ON_CONFLICT_ACTION_ABORT &&
field->nullable_action != ON_CONFLICT_ACTION_DEFAULT) {
diag_set(ClientError, ER_NULLABLE_PRIMARY, space_name);
parser->is_aborted = true;
return -1;
} else if (field->nullable_action == ON_CONFLICT_ACTION_DEFAULT) {
field->nullable_action = ON_CONFLICT_ACTION_ABORT;
field->is_nullable = false;
}
return 0;
}
/*
* 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.
*
* 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
sqlAddPrimaryKey(struct Parse *pParse)
{
int iCol = -1, i;
int nTerm;
struct ExprList *pList = pParse->create_index_def.cols;
struct space *space = pParse->create_table_def.new_space;
if (space == NULL)
goto primary_key_exit;
if (sql_space_primary_key(space) != NULL) {
diag_set(ClientError, ER_CREATE_SPACE, space->def->name,
"primary key has been already declared");
pParse->is_aborted = true;
goto primary_key_exit;
}
if (pList == NULL) {
iCol = space->def->field_count - 1;
nTerm = 1;
} else {
nTerm = pList->nExpr;
for (i = 0; i < nTerm; i++) {
Expr *pCExpr =
sqlExprSkipCollate(pList->a[i].pExpr);
assert(pCExpr != 0);
if (pCExpr->op != TK_ID) {
diag_set(ClientError, ER_INDEX_DEF_UNSUPPORTED,
"Expressions");
pParse->is_aborted = true;
goto primary_key_exit;
}
const char *name = pCExpr->u.zToken;
struct space_def *def = space->def;
for (uint32_t idx = 0; idx < def->field_count; idx++) {
if (strcmp(name, def->fields[idx].name) == 0) {
iCol = idx;
break;
}
}
}
}
if (nTerm == 1 && iCol != -1 &&
space->def->fields[iCol].type == FIELD_TYPE_INTEGER) {
struct sql *db = pParse->db;
struct ExprList *list;
struct Token token;
sqlTokenInit(&token, space->def->fields[iCol].name);
struct Expr *expr = sql_expr_new(db, TK_ID, &token);
if (expr == NULL) {
pParse->is_aborted = true;
goto primary_key_exit;
}
list = sql_expr_list_append(db, NULL, expr);
if (list == NULL)
goto primary_key_exit;
pParse->create_index_def.cols = list;
sql_create_index(pParse);
if (db->mallocFailed)
goto primary_key_exit;
} else if (pParse->create_table_def.has_autoinc) {
diag_set(ClientError, ER_CREATE_SPACE, space->def->name,
"AUTOINCREMENT is only allowed on an INTEGER PRIMARY "\
"KEY or INT PRIMARY KEY");
pParse->is_aborted = true;
goto primary_key_exit;
} else {
sql_create_index(pParse);
pList = NULL;
if (pParse->is_aborted)
goto primary_key_exit;
}
struct index *pk = sql_space_primary_key(space);
assert(pk != NULL);
struct key_def *pk_key_def = pk->def->key_def;
for (uint32_t i = 0; i < pk_key_def->part_count; i++) {
uint32_t idx = pk_key_def->parts[i].fieldno;
field_def_create_for_pk(pParse, &space->def->fields[idx],
space->def->name);
}
primary_key_exit:
sql_expr_list_delete(pParse->db, pList);
return;
}
void
sql_add_check_constraint(struct Parse *parser)
{
struct create_ck_def *ck_def = &parser->create_ck_def;
struct alter_entity_def *alter_def =
(struct alter_entity_def *) &parser->create_ck_def;
assert(alter_def->entity_type == ENTITY_TYPE_CK);
(void) alter_def;
struct Expr *expr = ck_def->expr->pExpr;
struct space *space = parser->create_table_def.new_space;
if (space != NULL) {
expr->u.zToken =
sqlDbStrNDup(parser->db,
(char *) ck_def->expr->zStart,
(int) (ck_def->expr->zEnd -
ck_def->expr->zStart));
if (expr->u.zToken == NULL)
goto release_expr;
space->def->opts.checks =
sql_expr_list_append(parser->db,
space->def->opts.checks, expr);
if (space->def->opts.checks == NULL) {
sqlDbFree(parser->db, expr->u.zToken);
goto release_expr;
}
struct create_entity_def *entity_def = &ck_def->base.base;
if (entity_def->name.n > 0) {
sqlExprListSetName(parser, space->def->opts.checks,
&entity_def->name, 1);
}
} else {
release_expr:
sql_expr_delete(parser->db, expr, false);
}
}
/*
* Set the collation function of the most recently parsed table column
* to the CollSeq given.
*/
void
sqlAddCollateType(Parse * pParse, Token * pToken)
{
struct space *space = pParse->create_table_def.new_space;
if (space == NULL)
return;
uint32_t i = space->def->field_count - 1;
sql *db = pParse->db;
char *coll_name = sql_name_from_token(db, pToken);
if (coll_name == NULL) {
pParse->is_aborted = true;
return;
}
uint32_t *coll_id = &space->def->fields[i].coll_id;
if (sql_get_coll_seq(pParse, coll_name, coll_id) != NULL) {
/* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
* then an index may have been created on this column before the
* collation type was added. Correct this if it is the case.
*/
for (uint32_t i = 0; i < space->index_count; ++i) {
struct index *idx = space->index[i];
assert(idx->def->key_def->part_count == 1);
if (idx->def->key_def->parts[0].fieldno == i) {
coll_id = &idx->def->key_def->parts[0].coll_id;
(void)sql_column_collation(space->def, i, coll_id);
}
}
}
sqlDbFree(db, coll_name);
}
struct coll *
sql_column_collation(struct space_def *def, uint32_t column, uint32_t *coll_id)
{
assert(def != NULL);
struct space *space = space_by_id(def->id);
/*
* It is not always possible to fetch collation directly
* from struct space due to its absence in space cache.
* To be more precise when space is ephemeral or it is
* under construction.
*
* In cases mentioned above collation is fetched by id.
*/
if (space == NULL) {
assert(def->opts.is_temporary);
assert(column < (uint32_t)def->field_count);
*coll_id = def->fields[column].coll_id;
struct coll_id *collation = coll_by_id(*coll_id);
return collation != NULL ? collation->coll : NULL;
}
struct tuple_field *field = tuple_format_field(space->format, column);
*coll_id = field->coll_id;
return field->coll;
}
int
vdbe_emit_open_cursor(struct Parse *parse_context, int cursor, int index_id,
struct space *space)
{
assert(space != NULL);
return sqlVdbeAddOp4(parse_context->pVdbe, OP_IteratorOpen, cursor,
index_id, 0, (void *) space, P4_SPACEPTR);
}
/*
* Generate code to determine the new space Id.
* Fetch the max space id seen so far from _schema and increment it.
* Return register storing the result.
*/
static int
getNewSpaceId(Parse * pParse)
{
Vdbe *v = sqlGetVdbe(pParse);
int iRes = ++pParse->nMem;
sqlVdbeAddOp1(v, OP_IncMaxid, iRes);
return iRes;
}
/**
* Generate VDBE code to create an Index. This is accomplished by
* adding an entry to the _index table.
*
* @param parse Current parsing context.
* @param def Definition of space which index belongs to.
* @param idx_def Definition of index under construction.
* @param pk_def Definition of primary key index.
* @param space_id_reg Register containing generated space id.
* @param index_id_reg Register containing generated index id.
*/
static void
vdbe_emit_create_index(struct Parse *parse, struct space_def *def,
const struct index_def *idx_def, int space_id_reg,
int index_id_reg)
{
struct Vdbe *v = sqlGetVdbe(parse);
int entry_reg = ++parse->nMem;
/*
* Entry in _index space contains 6 fields.
* The last one contains encoded tuple.
*/
int tuple_reg = (parse->nMem += 6);
/* Format "opts" and "parts" for _index entry. */
struct region *region = &parse->region;
uint32_t index_opts_sz = 0;
char *index_opts = sql_encode_index_opts(region, &idx_def->opts,
&index_opts_sz);
if (index_opts == NULL)
goto error;
uint32_t index_parts_sz = 0;
char *index_parts = sql_encode_index_parts(region, def->fields, idx_def,
&index_parts_sz);
if (index_parts == NULL)
goto error;
char *raw = sqlDbMallocRaw(parse->db,
index_opts_sz +index_parts_sz);
if (raw == NULL)
return;
memcpy(raw, index_opts, index_opts_sz);
index_opts = raw;
raw += index_opts_sz;
memcpy(raw, index_parts, index_parts_sz);
index_parts = raw;
if (parse->create_table_def.new_space != NULL) {
sqlVdbeAddOp2(v, OP_SCopy, space_id_reg, entry_reg);
sqlVdbeAddOp2(v, OP_Integer, idx_def->iid, entry_reg + 1);
} else {
/*
* An existing table is being modified;
* space_id_reg is literal, but index_id_reg is
* register.
*/
sqlVdbeAddOp2(v, OP_Integer, space_id_reg, entry_reg);
sqlVdbeAddOp2(v, OP_SCopy, index_id_reg, entry_reg + 1);
}
sqlVdbeAddOp4(v, OP_String8, 0, entry_reg + 2, 0,
sqlDbStrDup(parse->db, idx_def->name),
P4_DYNAMIC);
sqlVdbeAddOp4(v, OP_String8, 0, entry_reg + 3, 0, "tree",
P4_STATIC);
sqlVdbeAddOp4(v, OP_Blob, index_opts_sz, entry_reg + 4,
SQL_SUBTYPE_MSGPACK, index_opts, P4_DYNAMIC);
/* opts and parts are co-located, hence STATIC. */
sqlVdbeAddOp4(v, OP_Blob, index_parts_sz, entry_reg + 5,
SQL_SUBTYPE_MSGPACK, index_parts, P4_STATIC);
sqlVdbeAddOp3(v, OP_MakeRecord, entry_reg, 6, tuple_reg);
sqlVdbeAddOp3(v, OP_SInsert, BOX_INDEX_ID, 0, tuple_reg);
save_record(parse, BOX_INDEX_ID, entry_reg, 2, v->nOp - 1);
return;
error:
parse->is_aborted = true;
}
/**
* Generate code to create a new space.
*
* @param space_id_reg is a register storing the id of the space.
* @param table Table containing meta-information of space to be
* created.
*/
static void
vdbe_emit_space_create(struct Parse *pParse, int space_id_reg,
struct space *space)
{
Vdbe *v = sqlGetVdbe(pParse);
int iFirstCol = ++pParse->nMem;
int tuple_reg = (pParse->nMem += 7);
struct region *region = &pParse->region;
uint32_t table_opts_stmt_sz = 0;
char *table_opts_stmt = sql_encode_table_opts(region, space->def,
&table_opts_stmt_sz);
if (table_opts_stmt == NULL)
goto error;
uint32_t table_stmt_sz = 0;
char *table_stmt = sql_encode_table(region, space->def, &table_stmt_sz);
if (table_stmt == NULL)
goto error;
char *raw = sqlDbMallocRaw(pParse->db,
table_stmt_sz + table_opts_stmt_sz);
if (raw == NULL)
return;
memcpy(raw, table_opts_stmt, table_opts_stmt_sz);
table_opts_stmt = raw;
raw += table_opts_stmt_sz;
memcpy(raw, table_stmt, table_stmt_sz);
table_stmt = raw;
sqlVdbeAddOp2(v, OP_SCopy, space_id_reg, iFirstCol /* spaceId */ );
sqlVdbeAddOp2(v, OP_Integer, effective_user()->uid,
iFirstCol + 1 /* owner */ );
sqlVdbeAddOp4(v, OP_String8, 0, iFirstCol + 2 /* name */ , 0,
sqlDbStrDup(pParse->db, space->def->name),
P4_DYNAMIC);
sqlVdbeAddOp4(v, OP_String8, 0, iFirstCol + 3 /* engine */ , 0,
sqlDbStrDup(pParse->db, space->def->engine_name),
P4_DYNAMIC);
sqlVdbeAddOp2(v, OP_Integer, space->def->field_count,
iFirstCol + 4 /* field_count */ );
sqlVdbeAddOp4(v, OP_Blob, table_opts_stmt_sz, iFirstCol + 5,
SQL_SUBTYPE_MSGPACK, table_opts_stmt, P4_DYNAMIC);
/* zOpts and zFormat are co-located, hence STATIC */
sqlVdbeAddOp4(v, OP_Blob, table_stmt_sz, iFirstCol + 6,
SQL_SUBTYPE_MSGPACK, table_stmt, P4_STATIC);
sqlVdbeAddOp3(v, OP_MakeRecord, iFirstCol, 7, tuple_reg);
sqlVdbeAddOp3(v, OP_SInsert, BOX_SPACE_ID, 0, tuple_reg);
sqlVdbeChangeP5(v, OPFLAG_NCHANGE);
save_record(pParse, BOX_SPACE_ID, iFirstCol, 1, v->nOp - 1);
return;
error:
pParse->is_aborted = true;
}
int
emitNewSysSequenceRecord(Parse *pParse, int reg_seq_id, const char *seq_name)
{
Vdbe *v = sqlGetVdbe(pParse);
sql *db = pParse->db;
int first_col = pParse->nMem + 1;
pParse->nMem += 10; /* 9 fields + new record pointer */
const long long int min_usigned_long_long = 0;
const long long int max_usigned_long_long = LLONG_MAX;
const bool const_false = false;
/* 1. New sequence id */
sqlVdbeAddOp2(v, OP_SCopy, reg_seq_id, first_col + 1);
/* 2. user is */
sqlVdbeAddOp2(v, OP_Integer, effective_user()->uid, first_col + 2);
/* 3. New sequence name */
sqlVdbeAddOp4(v, OP_String8, 0, first_col + 3, 0,
sqlDbStrDup(pParse->db, seq_name), P4_DYNAMIC);
/* 4. Step */
sqlVdbeAddOp2(v, OP_Integer, 1, first_col + 4);
/* 5. Minimum */
sqlVdbeAddOp4Dup8(v, OP_Int64, 0, first_col + 5, 0,
(unsigned char*)&min_usigned_long_long, P4_INT64);
/* 6. Maximum */
sqlVdbeAddOp4Dup8(v, OP_Int64, 0, first_col + 6, 0,
(unsigned char*)&max_usigned_long_long, P4_INT64);
/* 7. Start */
sqlVdbeAddOp2(v, OP_Integer, 1, first_col + 7);
/* 8. Cache */
sqlVdbeAddOp2(v, OP_Integer, 0, first_col + 8);
/* 9. Cycle */
sqlVdbeAddOp2(v, OP_Bool, 0, first_col + 9);
sqlVdbeChangeP4(v, -1, (char*)&const_false, P4_BOOL);
sqlVdbeAddOp3(v, OP_MakeRecord, first_col + 1, 9, first_col);
if (db->mallocFailed)
return -1;
else
return first_col;
}
int
emitNewSysSpaceSequenceRecord(Parse *pParse, int space_id, const char reg_seq_id)
{
Vdbe *v = sqlGetVdbe(pParse);
const bool const_true = true;
int first_col = pParse->nMem + 1;
pParse->nMem += 4; /* 3 fields + new record pointer */
/* 1. Space id */
sqlVdbeAddOp2(v, OP_SCopy, space_id, first_col + 1);
/* 2. Sequence id */
sqlVdbeAddOp2(v, OP_IntCopy, reg_seq_id, first_col + 2);
/* 3. True, which is 1 in SQL */
sqlVdbeAddOp2(v, OP_Bool, 0, first_col + 3);
sqlVdbeChangeP4(v, -1, (char*)&const_true, P4_BOOL);
sqlVdbeAddOp3(v, OP_MakeRecord, first_col + 1, 3, first_col);
return first_col;
}
/**
* Generate opcodes to serialize foreign key into MsgPack and
* insert produced tuple into _fk_constraint space.
*
* @param parse_context Parsing context.
* @param fk Foreign key to be created.
*/
static void
vdbe_emit_fk_constraint_create(struct Parse *parse_context,
const struct fk_constraint_def *fk)
{
assert(parse_context != NULL);
assert(fk != NULL);
struct Vdbe *vdbe = sqlGetVdbe(parse_context);
assert(vdbe != NULL);
/*
* Occupy registers for 8 fields: each member in
* _constraint space plus one for final msgpack tuple.
*/
int constr_tuple_reg = sqlGetTempRange(parse_context, 10);
char *name_copy = sqlDbStrDup(parse_context->db, fk->name);
if (name_copy == NULL)
return;
sqlVdbeAddOp4(vdbe, OP_String8, 0, constr_tuple_reg, 0, name_copy,
P4_DYNAMIC);
/*
* In case we are adding FK constraints during execution
* of <CREATE TABLE ...> statement, we don't have child
* id, but we know register where it will be stored.
*/
if (parse_context->create_table_def.new_space != NULL) {
sqlVdbeAddOp2(vdbe, OP_SCopy, fk->child_id,
constr_tuple_reg + 1);
} else {