/
sql.c
1864 lines (1692 loc) · 53.9 KB
/
sql.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-2015, 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.
*/
#include <assert.h>
#include "field_def.h"
#include "sql.h"
/*
* Both Tarantool and SQLite codebases declare Index, hence the
* workaround below.
*/
#define Index SqliteIndex
#include "sql/sqliteInt.h"
#include "sql/tarantoolInt.h"
#include "sql/vdbeInt.h"
#undef Index
#include "index.h"
#include "info.h"
#include "schema.h"
#include "box.h"
#include "txn.h"
#include "space.h"
#include "space_def.h"
#include "index_def.h"
#include "tuple.h"
#include "fiber.h"
#include "small/region.h"
#include "session.h"
#include "xrow.h"
#include "iproto_constants.h"
static sqlite3 *db = NULL;
static const char nil_key[] = { 0x90 }; /* Empty MsgPack array. */
static const uint32_t default_sql_flags = SQLITE_ShortColNames
| SQLITE_EnableTrigger
| SQLITE_AutoIndex
| SQLITE_RecTriggers
| SQLITE_ForeignKeys;
void
sql_init()
{
default_flags |= default_sql_flags;
current_session()->sql_flags |= default_sql_flags;
if (sql_init_db(&db) != SQLITE_OK)
panic("failed to initialize SQL subsystem");
assert(db != NULL);
/* Initialize pSchema to use SQL parser. */
db->pSchema = sqlite3SchemaCreate(db);
if (db->pSchema == NULL) {
sqlite3_close(db);
panic("failed to initialize SQL Schema subsystem");
}
}
void
sql_load_schema()
{
assert(db->pSchema != NULL);
int rc;
struct session *user_session = current_session();
int commit_internal = !(user_session->sql_flags
& SQLITE_InternChanges);
assert(db->init.busy == 0);
db->init.busy = 1;
rc = sqlite3InitDatabase(db);
if (rc != SQLITE_OK) {
sqlite3SchemaClear(db);
panic("failed to initialize SQL subsystem");
}
db->init.busy = 0;
if (rc == SQLITE_OK && commit_internal)
sqlite3CommitInternalChanges();
}
void
sql_free()
{
sqlite3_close(db); db = NULL;
}
sqlite3 *
sql_get()
{
return db;
}
/*********************************************************************
* SQLite cursor implementation on top of Tarantool storage API-s.
*
* NB: SQLite btree cursor emulation is less than perfect. The problem
* is that btree cursors are more low-level compared to Tarantool
* iterators. The 2 most drastic differences being:
*
* i. Positioning - sqlite3BtreeMovetoUnpacked(key) moves to a leaf
* entry that is "reasonably close" to the requested
* key. The result from the last comparator invocation
* is returned to caller, so she can Prev/Next to
* adjust the position if needed. Ex:
*
* SQL: "... WHERE v>42",
* Data: [40,45]
* The engine does M2U(42), ending up with the cursor
* @40. The caller learns that the current item under
* cursor is less than 42, and advances the cursor
* ending up @45.
*
* Another complication is due to equal keys (sometimes
* a lookup is done with a key prefix which may equal
* multiple keys even in a unique index). Depending on
* the configuration stored in UnpackedRecord either
* the first or the last key in a run of equal keys is
* selected.
*
* ii. Direction - SQLite cursors are bidirectional while Tarantool
* iterators are not.
*
* Fortunately, cursor semantics defined by VDBE matches Tarantool's one
* well. Ex: a cursor positioned with Seek_GE can only move forward.
*
* We extended UnpackedRecord (UR) to include current running opcode
* number. In M2U we request the matching Tarantool iterator type and
* ignore detailed config in UR which we can't implement anyway. We are
* lacking last comparator result so we make up one. The value is
* innacurate: for instance for Seek_GE we return 0 (equal item) if
* iterator will produce any items. If the first item is greater than
* the key, +1 would be more apropriate. However, the value is only used
* in VDBE interpretor to invoke Next when the current item is less than
* the search key (-1), which is unnecessary since Tarantool iterators
* are accurately positioned, hence both 0 and 1 are fine.
*/
int
key_alloc(BtCursor *c, size_t key_size);
static int
cursor_seek(BtCursor *pCur, int *pRes);
static int
cursor_advance(BtCursor *pCur, int *pRes);
const char *tarantoolErrorMessage()
{
if (diag_is_empty(&fiber()->diag))
return NULL;
return box_error_message(box_error_last());
}
int
is_tarantool_error(int rc)
{
return (rc == SQL_TARANTOOL_ERROR ||
rc == SQL_TARANTOOL_ITERATOR_FAIL ||
rc == SQL_TARANTOOL_DELETE_FAIL ||
rc == SQL_TARANTOOL_INSERT_FAIL);
}
const void *tarantoolSqlite3PayloadFetch(BtCursor *pCur, u32 *pAmt)
{
assert(pCur->curFlags & BTCF_TaCursor ||
pCur->curFlags & BTCF_TEphemCursor);
assert(pCur->last_tuple != NULL);
*pAmt = box_tuple_bsize(pCur->last_tuple);
return tuple_data(pCur->last_tuple);
}
const void *
tarantoolSqlite3TupleColumnFast(BtCursor *pCur, u32 fieldno, u32 *field_size)
{
assert(pCur->curFlags & BTCF_TaCursor ||
pCur->curFlags & BTCF_TEphemCursor);
assert(pCur->last_tuple != NULL);
struct tuple_format *format = tuple_format(pCur->last_tuple);
assert(format->exact_field_count == 0
|| fieldno < format->exact_field_count);
if (format->fields[fieldno].offset_slot == TUPLE_OFFSET_SLOT_NIL)
return NULL;
const char *field = tuple_field(pCur->last_tuple, fieldno);
const char *end = field;
mp_next(&end);
*field_size = end - field;
return field;
}
/*
* Set cursor to the first tuple in given space.
* It is a simple wrapper around cursor_seek().
*/
int tarantoolSqlite3First(BtCursor *pCur, int *pRes)
{
if (key_alloc(pCur, sizeof(nil_key)) != 0)
return SQL_TARANTOOL_ERROR;
memcpy(pCur->key, nil_key, sizeof(nil_key));
pCur->iter_type = ITER_GE;
return cursor_seek(pCur, pRes);
}
/* Set cursor to the last tuple in given space. */
int tarantoolSqlite3Last(BtCursor *pCur, int *pRes)
{
if (key_alloc(pCur, sizeof(nil_key)) != 0)
return SQL_TARANTOOL_ERROR;
memcpy(pCur->key, nil_key, sizeof(nil_key));
pCur->iter_type = ITER_LE;
return cursor_seek(pCur, pRes);
}
/*
* Set cursor to the next entry in given space.
* If state of cursor is invalid (e.g. it is still under construction,
* or already destroyed), it immediately returns.
* Second argument is output parameter: success movement of cursor
* results in 0 value of pRes, otherwise it is set to 1.
*/
int tarantoolSqlite3Next(BtCursor *pCur, int *pRes)
{
if (pCur->eState == CURSOR_INVALID) {
*pRes = 1;
return SQLITE_OK;
}
assert(iterator_direction(pCur->iter_type) > 0);
return cursor_advance(pCur, pRes);
}
/*
* Set cursor to the previous entry in ephemeral space.
* If state of cursor is invalid (e.g. it is still under construction,
* or already destroyed), it immediately returns.
*/
int tarantoolSqlite3Previous(BtCursor *pCur, int *pRes)
{
if (pCur->eState == CURSOR_INVALID) {
*pRes = 1;
return SQLITE_OK;
}
assert(iterator_direction(pCur->iter_type) < 0);
return cursor_advance(pCur, pRes);
}
int tarantoolSqlite3MovetoUnpacked(BtCursor *pCur, UnpackedRecord *pIdxKey,
int *pRes)
{
int rc, res_success;
size_t ks;
ks = sqlite3VdbeMsgpackRecordLen(pIdxKey->aMem, pIdxKey->nField);
if (key_alloc(pCur, ks) != 0)
return SQL_TARANTOOL_ERROR;
sqlite3VdbeMsgpackRecordPut((u8 *)pCur->key, pIdxKey->aMem,
pIdxKey->nField);
switch (pIdxKey->opcode) {
default:
/* "Unexpected opcode" */
assert(0);
case 255:
/* Restore saved state. Just re-seek cursor.
TODO: replace w/ named constant. */
res_success = 0;
break;
case OP_SeekLT:
pCur->iter_type = ITER_LT;
res_success = -1; /* item<key */
break;
case OP_SeekLE:
pCur->iter_type = (pCur->hints & BTREE_SEEK_EQ) ?
ITER_REQ : ITER_LE;
res_success = 0; /* item==key */
break;
case OP_SeekGE:
pCur->iter_type = (pCur->hints & BTREE_SEEK_EQ) ?
ITER_EQ : ITER_GE;
res_success = 0; /* item==key */
break;
case OP_SeekGT:
pCur->iter_type = ITER_GT;
res_success = 1; /* item>key */
break;
case OP_NoConflict:
case OP_NotFound:
case OP_Found:
case OP_IdxDelete:
pCur->iter_type = ITER_EQ;
res_success = 0;
break;
}
rc = cursor_seek(pCur, pRes);
if (*pRes == 0) {
*pRes = res_success;
/*
* To select the first item in a row of equal items
* (last item), SQLite comparator is configured to
* return +1 (-1) if an item equals the key making it
* impossible to distinguish from an item>key (item<key)
* from comparator output alone.
* To make it possible to learn if the current item
* equals the key, the comparator sets eqSeen.
*/
pIdxKey->eqSeen = 1;
} else {
*pRes = -1; /* -1 also means EOF */
}
return rc;
}
/*
* Count number of tuples in ephemeral space and write it to pnEntry.
*
* @param pCur Cursor which will point to ephemeral space.
* @param[out] pnEntry Number of tuples in ephemeral space.
*
* @retval SQLITE_OK
*/
int tarantoolSqlite3EphemeralCount(struct BtCursor *pCur, i64 *pnEntry)
{
assert(pCur->curFlags & BTCF_TEphemCursor);
struct index *primary_index = space_index(pCur->space, 0 /* PK */);
*pnEntry = index_size(primary_index);
return SQLITE_OK;
}
int tarantoolSqlite3Count(BtCursor *pCur, i64 *pnEntry)
{
assert(pCur->curFlags & BTCF_TaCursor);
*pnEntry = index_size(pCur->index);
return SQLITE_OK;
}
/**
* Create ephemeral space and set cursor to the first entry. Features of
* ephemeral spaces: id == 0, name == "ephemeral", memtx engine (in future it
* can be changed, but now only memtx engine is supported), primary index
* which covers all fields and no secondary indexes, given field number and
* collation sequence. All fields are scalar and nullable.
*
* @param pCur Cursor which will point to the new ephemeral space.
* @param field_count Number of fields in ephemeral space.
* @param def Keys description for new ephemeral space.
*
* @retval SQLITE_OK on success, SQLITE_TARANTOOL_ERROR otherwise.
*/
int
tarantoolSqlite3EphemeralCreate(BtCursor *pCur, uint32_t field_count,
struct key_def *def)
{
assert(pCur);
assert(pCur->curFlags & BTCF_TEphemCursor);
struct key_def *ephemer_key_def = key_def_new(field_count);
if (ephemer_key_def == NULL)
return SQL_TARANTOOL_ERROR;
for (uint32_t part = 0; part < field_count; ++part) {
struct coll *coll;
uint32_t id;
if (def != NULL && part < def->part_count) {
coll = def->parts[part].coll;
id = def->parts[part].coll_id;
} else {
coll = NULL;
id = COLL_NONE;
}
key_def_set_part(ephemer_key_def, part, part, FIELD_TYPE_SCALAR,
ON_CONFLICT_ACTION_NONE, coll, id,
SORT_ORDER_ASC);
}
struct index_def *ephemer_index_def =
index_def_new(0, 0, "ephemer_idx", strlen("ephemer_idx"), TREE,
&index_opts_default, ephemer_key_def, NULL);
key_def_delete(ephemer_key_def);
if (ephemer_index_def == NULL)
return SQL_TARANTOOL_ERROR;
struct rlist key_list;
rlist_create(&key_list);
rlist_add_entry(&key_list, ephemer_index_def, link);
struct space_def *ephemer_space_def =
space_def_new(0 /* space id */, 0 /* user id */, field_count,
"ephemeral", strlen("ephemeral"),
"memtx", strlen("memtx"),
&space_opts_default, &field_def_default,
0 /* length of field_def */);
if (ephemer_space_def == NULL) {
index_def_delete(ephemer_index_def);
return SQL_TARANTOOL_ERROR;
}
struct space *ephemer_new_space = space_new_ephemeral(ephemer_space_def,
&key_list);
index_def_delete(ephemer_index_def);
space_def_delete(ephemer_space_def);
if (ephemer_new_space == NULL)
return SQL_TARANTOOL_ERROR;
if (key_alloc(pCur, field_count) != 0) {
space_delete(ephemer_new_space);
return SQL_TARANTOOL_ERROR;
}
pCur->space = ephemer_new_space;
pCur->index = *ephemer_new_space->index;
int unused;
return tarantoolSqlite3First(pCur, &unused);
}
int tarantoolSqlite3EphemeralInsert(struct space *space, const char *tuple,
const char *tuple_end)
{
assert(space != NULL);
mp_tuple_assert(tuple, tuple_end);
if (space_ephemeral_replace(space, tuple, tuple_end) != 0)
return SQL_TARANTOOL_INSERT_FAIL;
return SQLITE_OK;
}
/* Simply delete ephemeral space by calling space_delete(). */
int tarantoolSqlite3EphemeralDrop(BtCursor *pCur)
{
assert(pCur);
assert(pCur->curFlags & BTCF_TEphemCursor);
space_delete(pCur->space);
pCur->space = NULL;
return SQLITE_OK;
}
static inline int
insertOrReplace(struct space *space, const char *tuple, const char *tuple_end,
enum iproto_type type)
{
assert(space != NULL);
struct request request;
memset(&request, 0, sizeof(request));
request.tuple = tuple;
request.tuple_end = tuple_end;
request.space_id = space->def->id;
request.type = type;
mp_tuple_assert(request.tuple, request.tuple_end);
int rc = box_process_rw(&request, space, NULL);
return rc == 0 ? SQLITE_OK : SQL_TARANTOOL_INSERT_FAIL;
}
int tarantoolSqlite3Insert(struct space *space, const char *tuple,
const char *tuple_end)
{
return insertOrReplace(space, tuple, tuple_end, IPROTO_INSERT);
}
int tarantoolSqlite3Replace(struct space *space, const char *tuple,
const char *tuple_end)
{
return insertOrReplace(space, tuple, tuple_end, IPROTO_REPLACE);
}
/*
* Delete tuple from ephemeral space. It is contained in cursor
* as a result of previous call to cursor_advance().
*
* @param pCur Cursor pointing to ephemeral space.
*
* @retval SQLITE_OK on success, SQLITE_TARANTOOL_ERROR otherwise.
*/
int tarantoolSqlite3EphemeralDelete(BtCursor *pCur)
{
assert(pCur->curFlags & BTCF_TEphemCursor);
assert(pCur->iter != NULL);
assert(pCur->last_tuple != NULL);
char *key;
uint32_t key_size;
key = tuple_extract_key(pCur->last_tuple,
pCur->iter->index->def->key_def,
&key_size);
if (key == NULL)
return SQL_TARANTOOL_DELETE_FAIL;
int rc = space_ephemeral_delete(pCur->space, key);
if (rc != 0) {
diag_log();
return SQL_TARANTOOL_DELETE_FAIL;
}
return SQLITE_OK;
}
int tarantoolSqlite3Delete(BtCursor *pCur, u8 flags)
{
(void)flags;
assert(pCur->curFlags & BTCF_TaCursor);
assert(pCur->iter != NULL);
assert(pCur->last_tuple != NULL);
char *key;
uint32_t key_size;
int rc;
key = tuple_extract_key(pCur->last_tuple,
pCur->iter->index->def->key_def,
&key_size);
if (key == NULL)
return SQL_TARANTOOL_DELETE_FAIL;
rc = sql_delete_by_key(pCur->space, key, key_size);
return rc == 0 ? SQLITE_OK : SQL_TARANTOOL_DELETE_FAIL;
}
/**
* Delete entry from space by its key.
*
* @param space Space which contains record to be deleted.
* @param key Key of record to be deleted.
* @param key_size Size of key.
*
* @retval SQLITE_OK on success, SQL_TARANTOOL_DELETE_FAIL otherwise.
*/
int
sql_delete_by_key(struct space *space, char *key, uint32_t key_size)
{
struct request request;
struct tuple *unused;
memset(&request, 0, sizeof(request));
request.type = IPROTO_DELETE;
request.key = key;
request.key_end = key + key_size;
request.space_id = space->def->id;
int rc = box_process_rw(&request, space, &unused);
return rc == 0 ? SQLITE_OK : SQL_TARANTOOL_DELETE_FAIL;
}
/*
* Delete all tuples from space. It is worth noting, that truncate can't
* be applied to ephemeral space, so this routine manually deletes
* tuples one by one.
*
* @param pCur Cursor pointing to ephemeral space.
*
* @retval SQLITE_OK on success, SQLITE_TARANTOOL_ERROR otherwise.
*/
int tarantoolSqlite3EphemeralClearTable(BtCursor *pCur)
{
assert(pCur);
assert(pCur->curFlags & BTCF_TEphemCursor);
struct iterator *it = index_create_iterator(*pCur->space->index,
ITER_ALL, nil_key,
0 /* part_count */);
if (it == NULL) {
pCur->eState = CURSOR_INVALID;
return SQL_TARANTOOL_ITERATOR_FAIL;
}
struct tuple *tuple;
char *key;
uint32_t key_size;
while (iterator_next(it, &tuple) == 0 && tuple != NULL) {
key = tuple_extract_key(tuple, it->index->def->key_def,
&key_size);
if (space_ephemeral_delete(pCur->space, key) != 0) {
iterator_delete(it);
return SQL_TARANTOOL_DELETE_FAIL;
}
}
iterator_delete(it);
return SQLITE_OK;
}
/*
* Removes all instances from table.
* Iterate through the space and delete one by one all tuples.
*/
int tarantoolSqlite3ClearTable(struct space *space)
{
uint32_t key_size;
box_tuple_t *tuple;
int rc;
struct tuple *unused;
struct request request;
memset(&request, 0, sizeof(request));
request.type = IPROTO_DELETE;
request.space_id = space->def->id;
struct index *pk = space_index(space, 0 /* PK */);
struct iterator *iter = index_create_iterator(pk, ITER_ALL, nil_key, 0);
if (iter == NULL)
return SQL_TARANTOOL_ITERATOR_FAIL;
while (iterator_next(iter, &tuple) == 0 && tuple != NULL) {
request.key = tuple_extract_key(tuple, pk->def->key_def,
&key_size);
request.key_end = request.key + key_size;
rc = box_process_rw(&request, space, &unused);
if (rc != 0) {
iterator_delete(iter);
return SQL_TARANTOOL_DELETE_FAIL;
}
}
iterator_delete(iter);
return SQLITE_OK;
}
/*
* Change the statement of trigger in _trigger space.
* This function is called after tarantoolSqlite3RenameTable,
* in order to update name of table in create trigger statement.
*/
int tarantoolSqlite3RenameTrigger(const char *trig_name,
const char *old_table_name,
const char *new_table_name)
{
assert(trig_name);
assert(old_table_name);
assert(new_table_name);
box_tuple_t *tuple;
uint32_t trig_name_len = strlen(trig_name);
uint32_t old_table_name_len = strlen(old_table_name);
uint32_t new_table_name_len = strlen(new_table_name);
uint32_t key_len = mp_sizeof_str(trig_name_len) + mp_sizeof_array(1);
char *key_begin = (char*) region_alloc(&fiber()->gc, key_len);
if (key_begin == NULL) {
diag_set(OutOfMemory, key_len, "region_alloc", "key_begin");
return SQL_TARANTOOL_ERROR;
}
char *key = mp_encode_array(key_begin, 1);
key = mp_encode_str(key, trig_name, trig_name_len);
if (box_index_get(BOX_TRIGGER_ID, 0, key_begin, key, &tuple) != 0)
return SQL_TARANTOOL_ERROR;
assert(tuple != NULL);
assert(tuple_field_count(tuple) == 2);
const char *field = box_tuple_field(tuple, 1);
assert(mp_typeof(*field) == MP_MAP);
mp_decode_map(&field);
const char *sql_str = mp_decode_str(&field, &key_len);
if (sqlite3StrNICmp(sql_str, "sql", 3) != 0)
goto rename_fail;
uint32_t trigger_stmt_len;
const char *trigger_stmt_old = mp_decode_str(&field, &trigger_stmt_len);
char *trigger_stmt = (char*)region_alloc(&fiber()->gc,
trigger_stmt_len + 1);
if (trigger_stmt == NULL) {
diag_set(OutOfMemory, trigger_stmt_len + 1, "region_alloc",
"trigger_stmt");
return SQL_TARANTOOL_ERROR;
}
memcpy(trigger_stmt, trigger_stmt_old, trigger_stmt_len);
trigger_stmt[trigger_stmt_len] = '\0';
bool is_quoted = false;
trigger_stmt = rename_trigger(db, trigger_stmt, new_table_name, &is_quoted);
uint32_t trigger_stmt_new_len = trigger_stmt_len + new_table_name_len -
old_table_name_len + 2 * (!is_quoted);
assert(trigger_stmt_new_len > 0);
key_len = mp_sizeof_array(2) + mp_sizeof_str(trig_name_len) +
mp_sizeof_map(1) + mp_sizeof_str(3) +
mp_sizeof_str(trigger_stmt_new_len);
char *new_tuple = (char*)region_alloc(&fiber()->gc, key_len);
if (new_tuple == NULL) {
diag_set(OutOfMemory, key_len, "region_alloc", "new_tuple");
return SQL_TARANTOOL_ERROR;
}
char *new_tuple_end = mp_encode_array(new_tuple, 2);
new_tuple_end = mp_encode_str(new_tuple_end, trig_name, trig_name_len);
new_tuple_end = mp_encode_map(new_tuple_end, 1);
new_tuple_end = mp_encode_str(new_tuple_end, "sql", 3);
new_tuple_end = mp_encode_str(new_tuple_end, trigger_stmt,
trigger_stmt_new_len);
if (box_replace(BOX_TRIGGER_ID, new_tuple, new_tuple_end, NULL) != 0)
return SQL_TARANTOOL_ERROR;
else
return SQLITE_OK;
rename_fail:
diag_set(ClientError, ER_SQL_EXECUTE, "can't modify name of space "
"created not via SQL facilities");
return SQL_TARANTOOL_ERROR;
}
/*
* Rename the table in _space. Update tuple with corresponding id with
* new name and statement fields and insert back. If sql_stmt is NULL,
* then return from function after getting length of new statement:
* it is the way how to dynamically allocate memory for new statement in VDBE.
* So basically this function should be called twice: firstly to get length of
* CREATE TABLE statement, and secondly to make routine of replacing tuple and
* filling out param sql_stmt with new CREATE TABLE statement.
*
* @param iTab pageno of table to be renamed
* @param new_name new name of table
* @param[out] sql_stmt CREATE TABLE statement for new name table, can be NULL.
*
* @retval SQLITE_OK on success, SQLITE_TARANTOOL_ERROR otherwise.
*/
int tarantoolSqlite3RenameTable(int iTab, const char *new_name, char **sql_stmt)
{
assert(iTab > 0);
assert(new_name);
assert(sql_stmt);
int space_id = SQLITE_PAGENO_TO_SPACEID(iTab);
box_tuple_t *tuple;
uint32_t key_len = mp_sizeof_uint(space_id) + mp_sizeof_array(1);
char *key_begin = (char*) region_alloc(&fiber()->gc, key_len);
if (key_begin == NULL) {
diag_set(OutOfMemory, key_len, "region_alloc", "key_begin");
return SQL_TARANTOOL_ERROR;
}
char *key = mp_encode_array(key_begin, 1);
key = mp_encode_uint(key, space_id);
if (box_index_get(BOX_SPACE_ID, 0, key_begin, key, &tuple) != 0)
return SQL_TARANTOOL_ERROR;
assert(tuple != NULL);
/* Code below relies on format of _space. If number of fields or their
* order will ever change, this code should be changed too.
*/
assert(tuple_field_count(tuple) == 7);
const char *sql_stmt_map = box_tuple_field(tuple, 5);
if (sql_stmt_map == NULL || mp_typeof(*sql_stmt_map) != MP_MAP)
goto rename_fail;
uint32_t map_size = mp_decode_map(&sql_stmt_map);
if (map_size != 1)
goto rename_fail;
const char *sql_str = mp_decode_str(&sql_stmt_map, &key_len);
/* If this table hasn't been created via SQL facilities,
* we can't do anything yet.
*/
if (sqlite3StrNICmp(sql_str, "sql", 3) != 0)
goto rename_fail;
uint32_t sql_stmt_decoded_len;
const char *sql_stmt_old = mp_decode_str(&sql_stmt_map,
&sql_stmt_decoded_len);
uint32_t old_name_len;
const char *old_name = box_tuple_field(tuple, 2);
old_name = mp_decode_str(&old_name, &old_name_len);
uint32_t new_name_len = strlen(new_name);
*sql_stmt = (char*)region_alloc(&fiber()->gc, sql_stmt_decoded_len + 1);
if (*sql_stmt == NULL) {
diag_set(OutOfMemory, sql_stmt_decoded_len + 1, "region_alloc",
"sql_stmt");
return SQL_TARANTOOL_ERROR;
}
memcpy(*sql_stmt, sql_stmt_old, sql_stmt_decoded_len);
*(*sql_stmt + sql_stmt_decoded_len) = '\0';
bool is_quoted = false;
*sql_stmt = rename_table(db, *sql_stmt, new_name, &is_quoted);
if (*sql_stmt == NULL)
goto rename_fail;
/* If old table name isn't quoted, then need to reserve space for quotes. */
uint32_t sql_stmt_len = sql_stmt_decoded_len +
new_name_len - old_name_len +
2 * (!is_quoted);
assert(sql_stmt_len > 0);
/* Construct new msgpack to insert to _space.
* Since we have changed only name of table and create statement,
* there is no need to decode/encode other fields of tuple,
* just memcpy constant parts.
*/
char *new_tuple = (char*)region_alloc(&fiber()->gc, tuple->bsize +
mp_sizeof_str(sql_stmt_len));
if (new_tuple == NULL) {
free(*sql_stmt);
*sql_stmt = NULL;
diag_set(OutOfMemory,
tuple->bsize + mp_sizeof_str(sql_stmt_len),
"region_alloc", "new_tuple");
return SQL_TARANTOOL_ERROR;
}
char *new_tuple_end = new_tuple;
const char *data_begin = tuple_data(tuple);
const char *data_end = tuple_field(tuple, 2);
uint32_t data_size = data_end - data_begin;
memcpy(new_tuple, data_begin, data_size);
new_tuple_end += data_size;
new_tuple_end = mp_encode_str(new_tuple_end, new_name, new_name_len);
data_begin = tuple_field(tuple, 3);
data_end = tuple_field(tuple, 5);
data_size = data_end - data_begin;
memcpy(new_tuple_end, data_begin, data_size);
new_tuple_end += data_size;
new_tuple_end = mp_encode_map(new_tuple_end, 1);
new_tuple_end = mp_encode_str(new_tuple_end, "sql", 3);
new_tuple_end = mp_encode_str(new_tuple_end, *sql_stmt, sql_stmt_len);
data_begin = tuple_field(tuple, 6);
data_end = (char*) tuple + tuple_size(tuple);
data_size = data_end - data_begin;
memcpy(new_tuple_end, data_begin, data_size);
new_tuple_end += data_size;
if (box_replace(BOX_SPACE_ID, new_tuple, new_tuple_end, NULL) != 0)
return SQL_TARANTOOL_ERROR;
else
return SQLITE_OK;
rename_fail:
diag_set(ClientError, ER_SQL_EXECUTE, "can't modify name of space "
"created not via SQL facilities");
return SQL_TARANTOOL_ERROR;
}
/*
* Acts almost as tarantoolSqlite3RenameTable, but doesn't change
* name of table, only statement.
*/
int tarantoolSqlite3RenameParentTable(int iTab, const char *old_parent_name,
const char *new_parent_name)
{
assert(iTab > 0);
assert(old_parent_name);
assert(new_parent_name);
int space_id = SQLITE_PAGENO_TO_SPACEID(iTab);
box_tuple_t *tuple;
uint32_t key_len = mp_sizeof_uint(space_id) + mp_sizeof_array(1);
char *key_begin = (char*) region_alloc(&fiber()->gc, key_len);
if (key_begin == NULL) {
diag_set(OutOfMemory, key_len, "region_alloc", "key_begin");
return SQL_TARANTOOL_ERROR;
}
char *key = mp_encode_array(key_begin, 1);
key = mp_encode_uint(key, space_id);
if (box_index_get(BOX_SPACE_ID, 0, key_begin, key, &tuple) != 0)
return SQL_TARANTOOL_ERROR;
assert(tuple != NULL);
assert(tuple_field_count(tuple) == 7);
const char *sql_stmt_map = box_tuple_field(tuple, 5);
if (sql_stmt_map == NULL || mp_typeof(*sql_stmt_map) != MP_MAP)
goto rename_fail;
uint32_t map_size = mp_decode_map(&sql_stmt_map);
if (map_size != 1)
goto rename_fail;
const char *sql_str = mp_decode_str(&sql_stmt_map, &key_len);
if (sqlite3StrNICmp(sql_str, "sql", 3) != 0)
goto rename_fail;
uint32_t create_stmt_decoded_len;
const char *create_stmt_old = mp_decode_str(&sql_stmt_map,
&create_stmt_decoded_len);
uint32_t old_name_len = strlen(old_parent_name);
uint32_t new_name_len = strlen(new_parent_name);
char *create_stmt_new = (char*) region_alloc(&fiber()->gc,
create_stmt_decoded_len + 1);
if (create_stmt_new == NULL) {
diag_set(OutOfMemory, create_stmt_decoded_len + 1,
"region_alloc", "create_stmt_new");
return SQL_TARANTOOL_ERROR;
}
memcpy(create_stmt_new, create_stmt_old, create_stmt_decoded_len);
create_stmt_new[create_stmt_decoded_len] = '\0';
uint32_t numb_of_quotes = 0;
uint32_t numb_of_occurrences = 0;
create_stmt_new = rename_parent_table(db, create_stmt_new, old_parent_name,
new_parent_name, &numb_of_occurrences,
&numb_of_quotes);
uint32_t create_stmt_new_len = create_stmt_decoded_len -
numb_of_occurrences *
(old_name_len - new_name_len) +
2 * numb_of_quotes;
assert(create_stmt_new_len > 0);
key_len = tuple->bsize + mp_sizeof_str(create_stmt_new_len);
char *new_tuple = (char*)region_alloc(&fiber()->gc, key_len);
if (new_tuple == NULL) {
sqlite3DbFree(db, create_stmt_new);
diag_set(OutOfMemory, key_len, "region_alloc", "new_tuple");
return SQL_TARANTOOL_ERROR;
}
char *new_tuple_end = new_tuple;
const char *data_begin = tuple_data(tuple);
const char *data_end = tuple_field(tuple, 5);
uint32_t data_size = data_end - data_begin;
memcpy(new_tuple, data_begin, data_size);
new_tuple_end += data_size;
new_tuple_end = mp_encode_map(new_tuple_end, 1);
new_tuple_end = mp_encode_str(new_tuple_end, "sql", 3);
new_tuple_end = mp_encode_str(new_tuple_end, create_stmt_new,
create_stmt_new_len);
sqlite3DbFree(db, create_stmt_new);
data_begin = tuple_field(tuple, 6);
data_end = (char*) tuple + tuple_size(tuple);
data_size = data_end - data_begin;
memcpy(new_tuple_end, data_begin, data_size);
new_tuple_end += data_size;
if (box_replace(BOX_SPACE_ID, new_tuple, new_tuple_end, NULL) != 0)
return SQL_TARANTOOL_ERROR;
else
return SQLITE_OK;
rename_fail:
diag_set(ClientError, ER_SQL_EXECUTE, "can't modify name of space "
"created not via SQL facilities");
return SQL_TARANTOOL_ERROR;
}
int
tarantoolSqlite3IdxKeyCompare(struct BtCursor *cursor,
struct UnpackedRecord *unpacked)
{
assert(cursor->curFlags & BTCF_TaCursor);
assert(cursor->iter != NULL);
assert(cursor->last_tuple != NULL);
const box_key_def_t *key_def;
const struct tuple *tuple;
const char *base;
const struct tuple_format *format;
const uint32_t *field_map;
uint32_t field_count, next_fieldno = 0;
const char *p, *field0;
u32 i, n;
int rc;
#ifndef NDEBUG
size_t original_size;
const char *key;
uint32_t key_size;
#endif
key_def = cursor->iter->index->def->key_def;
n = MIN(unpacked->nField, key_def->part_count);
tuple = cursor->last_tuple;
base = tuple_data(tuple);
format = tuple_format(tuple);
field_map = tuple_field_map(tuple);
field_count = format->field_count;
field0 = base; mp_decode_array(&field0); p = field0;
for (i = 0; i < n; i++) {
/*
* Tuple contains offset map to make it possible to
* extract indexed fields without decoding all prior
* fields. There's a caveat though:
* (1) The very first field's offset is never stored;
* (2) if an index samples consequetive fields,
* ex: 3-4-5, only the very first field in a run
* has its offset stored;
* (3) field maps are rebuilt lazily when a new index
* is added, i.e. it is possible to encounter a
* tuple with an incomplete offset map.
*/
uint32_t fieldno = key_def->parts[i].fieldno;
if (fieldno != next_fieldno) {
if (fieldno >= field_count ||
format->fields[fieldno].offset_slot ==
TUPLE_OFFSET_SLOT_NIL) {
/* Outdated field_map. */
uint32_t j = 0;
p = field0;
while (j++ != fieldno)
mp_next(&p);
} else {