-
Notifications
You must be signed in to change notification settings - Fork 236
Expand file tree
/
Copy pathcomdb2build.c
More file actions
8104 lines (6791 loc) · 229 KB
/
comdb2build.c
File metadata and controls
8104 lines (6791 loc) · 229 KB
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
#include "sqliteInt.h"
#include <vdbeInt.h>
#include "comdb2build.h"
#include "comdb2vdbe.h"
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <schemachange.h>
#include <sc_lua.h>
#include <sc_util.h>
#include <comdb2.h>
#include <bdb_api.h>
#include <osqlsqlthr.h>
#include <sqloffload.h>
#include <analyze.h>
#include <bdb_access.h>
#include <bpfunc.h>
#include <bpfunc.pb-c.h>
#include <osqlcomm.h>
#include <net_types.h>
#include <views.h>
#include <logmsg.h>
#include <str0.h>
#include <zlib.h>
#include <shard_range.h>
#include <logical_cron.h>
#include <str_util.h>
#include <import_util.h>
#include "cdb2_constants.h"
#include "db_access.h" /* gbl_check_access_controls */
#include "comdb2_atomic.h"
#include "alias.h"
#define COMDB2_INVALID_AUTOINCREMENT "invalid datatype for autoincrement"
extern pthread_key_t query_info_key;
extern int gbl_commit_sleep;
extern int gbl_convert_sleep;
extern int gbl_allow_user_schema;
extern int gbl_ddl_cascade_drop;
extern int gbl_legacy_schema;
extern int gbl_permit_small_sequences;
extern int gbl_lightweight_rename;
extern int gbl_transactional_drop_plus_rename;
extern int gbl_gen_shard_verbose;
extern int gbl_sc_protobuf;
extern int gbl_retro_tpt_start;
int gbl_view_feature = 1;
int gbl_disable_sql_table_replacement = 0;
extern int sqlite3GetToken(const unsigned char *z, int *tokenType);
extern int sqlite3ParserFallback(int iToken);
extern int comdb2_save_ddl_context(char *name, void *ctx, comdb2ma mem);
extern void *comdb2_get_ddl_context(char *name);
/******************* Utility ****************************/
static inline int setError(Parse *pParse, int rc, const char *msg)
{
sqlite3ErrorMsg(pParse, "%s", msg);
pParse->rc = rc;
return rc;
}
// return 0 on failure to parse
int readIntFromToken(Token* t, int *rst)
{
char nptr[t->n + 1];
memcpy(nptr, t->z, t->n);
nptr[t->n] = '\0';
char *endptr;
errno = 0;
long int l = strtol(nptr, &endptr, 10);
int i = l; // to detect int overflow
if (errno || *endptr != '\0' || i != l)
return 0;
*rst = i;
return 1;
}
/*
Check whether a remote schema name is specified.
If the schema name is specified and is either "main" or local
schema, we copy it to the first argument and return 0.
*/
static inline int isRemote(Parse *pParse, Token **t1, Token **t2)
{
/* Check if the second token is empty. */
if ((*t2)->n == 0) {
/* No schema name. */
return 0;
} else {
/* We must have both the tokens set. */
assert((*t1)->n > 0 && (*t2)->n > 0);
/* t1 must be a local schema name. */
if ((strncasecmp((*t1)->z, thedb->envname, (*t1)->n) == 0) ||
(strncasecmp((*t1)->z, "main", (*t1)->n) == 0)) {
/*
Its a local schema. Let's move the table/index name in
t2 to t1. Doing so will ease the callers by allowing
them to simply refer to t1 for table/index name.
*/
(*t1)->n = (*t2)->n;
(*t1)->z = (*t2)->z;
(*t2)->n = 0;
(*t2)->z = 0;
return 0;
}
}
return setError(pParse, SQLITE_MISUSE,
"DDL commands operate on local schema only.");
}
enum table_chk_flags {
ERROR_ON_TBL_FOUND = 0,
ERROR_ON_TBL_NOT_FOUND = 1,
ERROR_IGNORE = 2,
};
static int authenticateSC(const char *table, Parse *pParse);
/* chkAndCopyTable expects the dst (OUT) buffer to be of MAXTABLELEN size. */
static inline int chkAndCopyTable(Parse *pParse, char *dst, const char *name,
size_t name_len, enum table_chk_flags error_flag,
int check_shard, int *table_exists,
char **partition_first_shard, int check_for_illegal_chars,
int preserve_name)
{
int rc = 0;
char *table_name;
struct sqlclntstate *clnt = get_sql_clnt();
table_name = strndup(name, name_len);
if (table_name == NULL) {
return setError(pParse, SQLITE_NOMEM, "System out of memory");
}
/* Remove quotes (if any). */
sqlite3Dequote(table_name);
/* Check whether table name is valid. */
const char *error = NULL;
if (validate_table_name(table_name, strlen(table_name),
check_for_illegal_chars, &error) != 0) {
rc = setError(pParse, SQLITE_MISUSE, error);
goto cleanup;
}
if (gbl_allow_user_schema && clnt->current_user.have_name &&
strcasecmp(clnt->current_user.name, DEFAULT_USER) != 0) {
/* Check whether table_name contains user name. */
char* username = strchr(table_name, '@');
if (username) {
/* Do nothing. */
strncpy0(dst, table_name, MAXTABLELEN);
} else { /* Add user nmame. */
/* Make it part of user schema. */
char userschema[MAXTABLELEN];
int bdberr;
int bytes_written;
bdb_state_type *bdb_state = thedb->bdb_env;
tran_type *tran = curtran_gettran();
int rc = bdb_tbl_access_userschema_get(bdb_state, tran, clnt->current_user.name, userschema, &bdberr);
curtran_puttran(tran);
if (rc == 0) {
if (userschema[0] == '\0') {
snprintf(dst, MAXTABLELEN, "%s", table_name);
} else {
bytes_written = snprintf(dst, MAXTABLELEN, "%s@%s", table_name,
userschema);
if (bytes_written >= MAXTABLELEN) {
rc = setError(pParse, SQLITE_MISUSE, "User-schema name is "
"too long");
goto cleanup;
}
}
} else {
bytes_written = snprintf(dst, MAXTABLELEN, "%s@%s", table_name,
clnt->current_user.name);
if (bytes_written >= MAXTABLELEN) {
rc = setError(pParse, SQLITE_MISUSE, "User-schema name is "
"too long");
goto cleanup;
}
}
}
} else {
strncpy0(dst, table_name, MAXTABLELEN);
}
// Check whether the user is allowed perform this schema change.
if (authenticateSC(dst, pParse))
goto cleanup;
char *firstshard = timepart_shard_name(dst, 0, 0, NULL);
if(!firstshard) {
struct dbtable *db = get_dbtable_by_name(dst);
if (table_exists) {
*table_exists = (db) ? 1 : 0;
}
if (db == NULL && (error_flag == ERROR_ON_TBL_NOT_FOUND)) {
rc = setError(pParse, SQLITE_ERROR, "Table not found");
goto cleanup;
}
struct dbview *view = get_view_by_name(dst);
if ((db != NULL || view != NULL) &&
(error_flag == ERROR_ON_TBL_FOUND)) {
rc = setError(pParse, SQLITE_ERROR, "Table already exists");
goto cleanup;
}
if (check_shard && db && db->timepartition_name)
{
setError(pParse, SQLITE_ERROR, "Shards cannot be schema changed independently");
rc = SQLITE_ERROR;
goto cleanup;
}
if (db && ! preserve_name) {
/* use original tablename */
strncpy0(dst, db->tablename, MAXTABLELEN);
}
if (partition_first_shard)
*partition_first_shard = 0;
}
else
{
if (partition_first_shard)
*partition_first_shard = firstshard;
else
free(firstshard);
}
rc = SQLITE_OK;
cleanup:
free(table_name);
return rc;
}
static inline
int create_string_from_token(Vdbe* v, Parse* pParse, char** dst, Token* t)
{
*dst = (char*) malloc (t->n + 1);
if (*dst == NULL)
{
setError(pParse, SQLITE_NOMEM, "System out of memory");
return SQLITE_NOMEM;
}
if (t->z[0] == '\'') {
strncpy(*dst, t->z+1, t->n-2);
(*dst)[t->n - 2] = '\0';
} else {
strncpy(*dst, t->z, t->n);
(*dst)[t->n] = '\0';
}
return SQLITE_OK;
}
static inline int copyNoSqlToken(
Vdbe* v,
Parse *pParse,
char** buf,
Token *t
){
size_t nByte = sizeof(char) * (t->n + 1);
assert( *buf==NULL );
*buf = (char *)malloc(nByte);
if( *buf==NULL ){
setError(pParse, SQLITE_NOMEM, "System out of memory");
return SQLITE_NOMEM;
}
memset(*buf, 0, nByte);
if( t->n>=3 ){
const char *z = t->z;
size_t n = (size_t)t->n;
if( z[0]=='{' && z[n-1]=='}' ){ z++; n -= 2; }
strncpy(*buf, z, n);
}
return SQLITE_OK;
}
static inline int chkAndCopyTableTokens(Parse *pParse, char *dst, Token *t1,
Token *t2, enum table_chk_flags error_flag,
int check_shard, int *table_exists,
char **partition_first_shard, int check_for_illegal_chars)
{
int rc;
if (t1 == NULL)
return SQLITE_OK;
if (t2 && (rc = isRemote(pParse, &t1, &t2)))
return rc;
if ((rc = chkAndCopyTable(pParse, dst, t1->z, t1->n, error_flag, check_shard,
table_exists, partition_first_shard, check_for_illegal_chars, 0))) {
return rc;
}
return SQLITE_OK;
}
static inline int chkAndCopyTableTokensAnalyze(Parse *pParse, char *dst, Token *t1, Token *t2)
{
int rc;
if (t1 == NULL)
return SQLITE_OK;
if (t2 && (rc = isRemote(pParse, &t1, &t2)))
return rc;
if ((rc = chkAndCopyTable(pParse, dst, t1->z, t1->n, ERROR_ON_TBL_NOT_FOUND, 0, NULL, NULL, 0, 1))) {
return rc;
}
return SQLITE_OK;
}
static inline int chkAndCopyPartitionTokens(Parse *pParse, char *dst, Token *t1,
Token *t2)
{
char *table_name;
int rc = SQLITE_OK;
if (t1 == NULL)
return SQLITE_OK;
if (t2 && t2->n>0)
return setError(pParse, SQLITE_MISUSE, "Local counters only");
table_name = strndup(t1->z, t1->n);
if (table_name == NULL) {
return setError(pParse, SQLITE_NOMEM, "System out of memory");
}
sqlite3Dequote(table_name);
if (strlen(table_name) >= MAXTABLELEN) {
rc = setError(pParse, SQLITE_MISUSE, "Table name is too long");
goto cleanup;
}
strncpy0(dst, table_name, MAXTABLELEN);
cleanup:
free(table_name);
return rc;
}
static void fillTableOption(struct schema_change_type* sc, int opt)
{
if (OPT_ON(opt, ODH_OFF))
sc->headers = 0;
else if (OPT_ON(opt, ODH_ON))
sc->headers = 1;
if (OPT_ON(opt, IPU_OFF))
sc->ip_updates = 0;
else if (OPT_ON(opt, IPU_ON))
sc->ip_updates = 1;
if (OPT_ON(opt, ISC_OFF))
sc->instant_sc = 0;
else if (OPT_ON(opt, ISC_ON))
sc->instant_sc = 1;
if (OPT_ON(opt, BLOB_NONE))
sc->compress_blobs = BDB_COMPRESS_NONE;
else if (OPT_ON(opt, BLOB_RLE))
sc->compress_blobs = BDB_COMPRESS_RLE8;
else if (OPT_ON(opt, BLOB_ZLIB))
sc->compress_blobs = BDB_COMPRESS_ZLIB;
else if (OPT_ON(opt, BLOB_LZ4))
sc->compress_blobs = BDB_COMPRESS_LZ4;
if (OPT_ON(opt, REC_NONE))
sc->compress = BDB_COMPRESS_NONE;
else if (OPT_ON(opt, REC_RLE))
sc->compress = BDB_COMPRESS_RLE8;
else if (OPT_ON(opt, REC_CRLE))
sc->compress = BDB_COMPRESS_CRLE;
else if (OPT_ON(opt, REC_ZLIB))
sc->compress = BDB_COMPRESS_ZLIB;
else if (OPT_ON(opt, REC_LZ4))
sc->compress = BDB_COMPRESS_LZ4;
sc->commit_sleep = gbl_commit_sleep;
sc->convert_sleep = gbl_convert_sleep;
}
int comdb2PrepareSC(Vdbe *v, Parse *pParse, int int_arg,
struct schema_change_type *arg, vdbeFunc func,
vdbeFuncArgFree freeFunc)
{
comdb2WriteTransaction(pParse);
Table *t = sqlite3LocateTable(pParse, LOCATE_NOERR, arg->tablename, NULL);
if (t) {
sqlite3VdbeAddTable(v, t);
}
return comdb2prepareNoRows(v, pParse, int_arg, arg, func, freeFunc);
}
extern int gbl_allow_anon_id_for_spmux;
int reject_anon_id(struct sqlclntstate *);
int (*externalComdb2AuthenticateUserDDL)(void*, const char *tablename) = NULL;
int (*externalComdb2CheckOpAccess)(void *) = 0;
static int comdb2AuthenticateUserDDL(const char *tablename)
{
struct sqlclntstate *clnt = get_sql_clnt();
if (clnt->admin)
return SQLITE_OK;
if (gbl_uses_externalauth && externalComdb2AuthenticateUserDDL) {
clnt->authdata = get_authdata(clnt);
if (!clnt->authdata && clnt->secure && !gbl_allow_anon_id_for_spmux) {
return reject_anon_id(clnt);
}
if (gbl_externalauth_warn && !clnt->authdata) {
logmsg(LOGMSG_INFO, "Client %s pid:%d mach:%d is missing authentication data\n",
clnt->argv0 ? clnt->argv0 : "???", clnt->conninfo.pid, clnt->conninfo.node);
} else if (externalComdb2AuthenticateUserDDL(clnt->authdata, tablename)) {
ATOMIC_ADD64(gbl_num_auth_denied, 1);
return SQLITE_AUTH;
}
ATOMIC_ADD64(gbl_num_auth_allowed, 1);
return SQLITE_OK;
}
bdb_state_type *bdb_state = thedb->bdb_env;
tran_type *tran = curtran_gettran();
int bdberr;
int authOn = bdb_authentication_get(bdb_state, tran, &bdberr);
if (authOn != 0) {
curtran_puttran(tran);
return SQLITE_OK;
}
if (clnt && tablename)
{
int rc = bdb_tbl_op_access_get(bdb_state, tran, 0, tablename, clnt->current_user.name, &bdberr);
curtran_puttran(tran);
if (rc) {
ATOMIC_ADD64(gbl_num_auth_denied, 1);
return SQLITE_AUTH;
} else {
ATOMIC_ADD64(gbl_num_auth_allowed, 1);
return SQLITE_OK;
}
}
curtran_puttran(tran);
ATOMIC_ADD64(gbl_num_auth_denied, 1);
return SQLITE_AUTH;
}
static int comdb2CheckOpAccess(void) {
struct sqlclntstate *clnt = get_sql_clnt();
if (clnt->admin)
return SQLITE_OK;
if (gbl_uses_externalauth && externalComdb2CheckOpAccess) {
clnt->authdata = get_authdata(clnt);
if (!clnt->authdata && clnt->secure && !gbl_allow_anon_id_for_spmux) {
return reject_anon_id(clnt);
}
if (gbl_externalauth_warn && !clnt->authdata) {
logmsg(LOGMSG_INFO, "Client %s pid:%d mach:%d is missing authentication data\n",
clnt->argv0 ? clnt->argv0 : "???", clnt->conninfo.pid, clnt->conninfo.node);
} else if (externalComdb2CheckOpAccess(clnt->authdata)) {
ATOMIC_ADD64(gbl_num_auth_denied, 1);
return SQLITE_AUTH;
}
ATOMIC_ADD64(gbl_num_auth_allowed, 1);
return SQLITE_OK;
}
if (comdb2AuthenticateUserDDL(""))
return SQLITE_AUTH;
return SQLITE_OK;
}
int comdb2IsPrepareOnly(Parse* pParse)
{
return pParse==NULL || (pParse->prepFlags & SQLITE_PREPARE_ONLY);
}
int comdb2IsDryrun(Parse* pParse)
{
if(!pParse || !pParse->isDryrun)
return 0;
return 1;
}
int comdb2SCIsDryRunnable(struct schema_change_type *s){
switch(s->kind){
case SC_ADDTABLE:
case SC_DROPTABLE:
case SC_TRUNCATETABLE:
case SC_ALTERTABLE:
case SC_ALTERTABLE_PENDING:
case SC_REBUILDTABLE:
case SC_ALTERTABLE_INDEX:
case SC_REBUILDTABLE_INDEX:
return 1;
default:
return 0;
}
}
int comdb2AuthenticateUserOp(Parse* pParse)
{
int rc;
rc = comdb2CheckOpAccess();
if (rc != SQLITE_OK) {
setError(pParse, rc, "User does not have OP credentials");
}
return rc;
}
/* Only an op user can turn authentication on. */
static int comdb2AuthenticateOpPassword(Parse* pParse)
{
struct sqlclntstate *clnt = get_sql_clnt();
tran_type *tran = curtran_gettran();
bdb_state_type *bdb_state = thedb->bdb_env;
int bdberr;
if (clnt)
{
/* Authenticate the password first, as we haven't been doing it so far. */
if (bdb_user_password_check(tran, clnt->current_user.name,
clnt->current_user.password, NULL))
{
curtran_puttran(tran);
return SQLITE_AUTH;
}
/* Check if the user is OP user. */
int rc = bdb_tbl_op_access_get(bdb_state, tran, 0, "",
clnt->current_user.name, &bdberr);
curtran_puttran(tran);
if (rc)
return SQLITE_AUTH;
else
return SQLITE_OK;
}
curtran_puttran(tran);
return SQLITE_AUTH;
}
int comdb2SqlDryrunSchemaChange(OpFunc *f)
{
struct sqlclntstate *clnt = get_sql_clnt();
struct schema_change_type *s = (struct schema_change_type*)f->arg;
struct ireq iq;
init_fake_ireq(thedb, &iq);
iq.errstrused = 1;
s->iq = &iq;
iq.sc = s;
FILE *fl = tmpfile();
if (!fl) {
fprintf(stderr, "%s:%d SYSTEM RAN OUT OF FILE DESCRIPTORS!!! EXITING\n",
__FILE__, __LINE__);
exit(1);
}
COMDB2BUF *sb = cdb2buf_open( fileno(fl), CDB2BUF_NO_CLOSE_FD); /* sbuf pointed at f */
s->sb = sb;
int sv_onstack = s->onstack;
s->onstack = 1;
f->rc = do_dryrun(s);
s->onstack = sv_onstack;
cdb2buf_close(sb);
rewind(fl);
char buf[1024] = {0};
while (f->rc == 0 && fgets(buf, sizeof(buf), fl)) {
#ifdef DEBUG
printf("%s\n", buf);
#endif
char *sptr = strchr(buf, '\n');
if (sptr) *sptr = 0;
if(buf[0] != '>' && buf[0] != '?') continue; //filter out extra lines
sptr = &buf[1];
printf("%s\n", sptr);
opFuncPrintf(f, "%s", sptr);
}
fclose(fl);
osqlstate_t *osql = &clnt->osql;
osql->xerr.errval = errstat_get_rc(&iq.errstat);
memcpy(osql->xerr.errstr, errstat_get_str(&iq.errstat), strlen(errstat_get_str(&iq.errstat)));
//f->errorMsg = (char *)errstat_get_str(&iq.errstat);
f->errorMsg = osql->xerr.errstr;
s->iq = NULL;
return f->rc;
}
static char** genShardGetShardNames(char *tablename, uint32_t nshards) {
int rc = 0;
if (!tablename) {
return NULL;
}
size_t shardSize = 3 + strlen(tablename) + 1;
char **result = (char **)malloc(sizeof(char *) * nshards);
for(int i=0;i<nshards;i++) {
result[i] = malloc(sizeof(char) * shardSize);
rc = snprintf(result[i] , shardSize, "$%d_%s", i+1, tablename);
if (rc < 0) {
logmsg(LOGMSG_ERROR, "%s:%d oom\n", __func__, __LINE__);
goto oom;
}
}
return result;
oom:
if (result) {
for(int i=0; i<nshards; i++) {
if (result[i]) {
free(result[i]);
}
}
free(result);
}
return NULL;
}
static int comdb2SqlSchemaChange_int(OpFunc *f, int usedb)
{
struct schema_change_type *s = (struct schema_change_type*)f->arg;
char **dbnames = NULL, **shardnames = NULL, **columns = NULL;
uint32_t nshards = 0, numcols = 0;
/* if this is a generic sharding scheme, pass this to upper layer */
if (s->partition.type == PARTITION_ADD_GENSHARD_COORD) {
/* running on coordinator replicant */
dbnames = s->partition.u.genshard.dbnames;
nshards = s->partition.u.genshard.numdbs;
columns = s->partition.u.genshard.columns;
numcols = s->partition.u.genshard.numcols;
s->partition.u.genshard.shardnames = shardnames = genShardGetShardNames(s->tablename, nshards);
if (!shardnames) {
f->errorMsg = "Transaction DDL Error: OOM\n";
f->rc = SQLITE_ABORT;
return f->rc;
}
f->rc = osql_test_create_genshard(s, &f->errorMsg, nshards, dbnames, numcols, columns, shardnames);
return f->rc;
} else if (s->partition.type == PARTITION_REM_GENSHARD_COORD) {
/* dbnames are NULL here, not passed though syntax */
struct dbtable *db = get_dbtable_by_name(s->tablename);
if (!db) {
logmsg(LOGMSG_ERROR, "Couldn't find table %s\n", s->tablename);
f->errorMsg = "DDL Error: Table not found\n";
f->rc = SQLITE_ABORT;
return f->rc;
}
f->rc = osql_test_remove_genshard(s, &f->errorMsg);
return f->rc;
}
f->rc = osql_schemachange_logic(s, usedb);
if (f->rc == SQLITE_DDL_MISUSE)
f->errorMsg = "Transactional DDL Error: Overlapping Tables";
else if (f->rc)
f->errorMsg = "Transactional DDL Error: Internal Errors";
return f->rc;
}
static int comdb2SqlSchemaChange_usedb(OpFunc *f)
{
return comdb2SqlSchemaChange_int(f, 1);
}
int comdb2SqlSchemaChange(OpFunc *f)
{
return comdb2SqlSchemaChange_int(f, 0);
}
int comdb2SqlSchemaChange_tran(OpFunc *f)
{
struct sqlclntstate *clnt = get_sql_clnt();
osqlstate_t *osql = &clnt->osql;
int rc = 0;
int sentops = 0;
int bdberr = 0;
osql_sock_start(clnt, OSQL_SOCK_REQ, 0, 0);
comdb2SqlSchemaChange(f);
if (clnt->dbtran.mode != TRANLEVEL_SOSQL) {
rc = osql_shadtbl_process(clnt, &sentops, &bdberr, 0);
if (rc) {
logmsg(LOGMSG_ERROR,
"%s:%d failed to process shadow table, rc %d, bdberr %d\n",
__func__, __LINE__, rc, bdberr);
osql_sock_abort(clnt, OSQL_SOCK_REQ);
f->rc = osql->xerr.errval = ERR_INTERNAL;
f->errorMsg = "Failed to process shadow table";
return ERR_INTERNAL;
}
}
rc = osql_sock_commit(clnt, OSQL_SOCK_REQ, TRANS_CLNTCOMM_NORMAL);
if (osql->xerr.errval == COMDB2_SCHEMACHANGE_OK) {
osql->xerr.errval = 0;
}
f->rc = osql->xerr.errval;
f->errorMsg = osql->xerr.errstr;
return f->rc;
}
static int comdb2ProcSchemaChange(OpFunc *f)
{
int rc = comdb2SqlSchemaChange_tran(f);
if (rc == 0) {
opFuncPrintf(f, "%s", f->errorMsg);
}
return rc;
}
void free_rstMsg(struct rstMsg* rec)
{
if (rec)
{
if (!rec->staticMsg && rec->msg)
free(rec->msg);
free(rec);
}
}
/*
* Send a BPFUNC to the master
* Returns SQLITE_OK if successful.
*
*/
int comdb2SendBpfunc(OpFunc *f)
{
struct sql_thread *thd = pthread_getspecific(query_info_key);
int rc = 0;
BpfuncArg *arg = (BpfuncArg*)f->arg;
rc = osql_bpfunc_logic(thd, arg);
if (rc) {
f->rc = rc;
f->errorMsg = "FAIL"; // TODO This must be translated to a description
} else {
f->rc = SQLITE_OK;
f->errorMsg = "";
}
return f->rc;
}
/* ######################### Parser Reductions ############################ */
/**************************** Function prototypes ***************************/
static void comdb2Rebuild(Parse *p, Token* nm, Token* lnm, int opt, int oplog_cnt);
/************************** Function definitions ****************************/
static int authenticateSC(const char * table, Parse *pParse)
{
char *username = strstr(table, "@");
struct sqlclntstate *clnt = get_sql_clnt();
if (username && strcmp(username+1, clnt->current_user.name) == 0) {
return 0;
} else if (comdb2AuthenticateUserDDL(table) == 0) {
return 0;
} else if (comdb2AuthenticateUserOp(pParse) == 0) {
return 0;
}
return -1;
}
void comdb2CreateTableCSC2(
Parse *pParse, /* Parser context */
Token *pName1, /* First part of the name of the table or view */
Token *pName2, /* Second part of the name of the table or view */
int opt, /* Various options for create (compress, etc) */
Token *csc2,
int temp,
int noErr
)
{
if (comdb2IsPrepareOnly(pParse))
return;
#ifndef SQLITE_OMIT_AUTHORIZATION
{
if( sqlite3AuthCheck(pParse, SQLITE_CREATE_TABLE, 0, 0, 0) ){
setError(pParse, SQLITE_AUTH, COMDB2_NOT_AUTHORIZED_ERRMSG);
return;
}
}
#endif
Vdbe *v = sqlite3GetVdbe(pParse);
int table_exists = 0;
if (temp) {
setError(pParse, SQLITE_MISUSE, "Can't create temporary csc2 table");
return;
}
struct schema_change_type *sc = new_schemachange_type();
if (sc == NULL) {
setError(pParse, SQLITE_NOMEM, "System out of memory");
return;
}
if (chkAndCopyTableTokens(pParse, sc->tablename, pName1, pName2,
(noErr) ? ERROR_IGNORE : ERROR_ON_TBL_FOUND, 1,
&table_exists, NULL, /* check_for_illegal_chars */ 1))
goto out;
if (noErr && table_exists) {
logmsg(LOGMSG_DEBUG, "Table '%s' already exists.", sc->tablename);
goto out;
}
sc->kind = SC_ADDTABLE;
sc->nothrevent = 1;
sc->live = 1;
if(comdb2IsDryrun(pParse)){
if(comdb2SCIsDryRunnable(sc)){
sc->dryrun = 1;
} else {
setError(pParse, SQLITE_MISUSE, "DRYRUN not supported for this operation");
goto out;
}
}
fillTableOption(sc, opt);
copyNoSqlToken(v, pParse, &sc->newcsc2, csc2);
if(sc->dryrun)
comdb2prepareSString(v, pParse, 0, sc, &comdb2SqlDryrunSchemaChange,
(vdbeFuncArgFree) &free_schema_change_type);
else
comdb2PrepareSC(v, pParse, 0, sc, &comdb2SqlSchemaChange,
(vdbeFuncArgFree)&free_schema_change_type);
return;
out:
free_schema_change_type(sc);
return;
}
void comdb2AlterTableCSC2(
Parse *pParse, /* Parser context */
Token *pName1, /* First part of the name of the table or view */
Token *pName2, /* Second part of the name of the table or view */
int opt, /* Various options for alter (compress, etc) */
Token *csc2
)
{
if (comdb2IsPrepareOnly(pParse))
return;
#ifndef SQLITE_OMIT_AUTHORIZATION
{
if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, 0, 0, 0) ){
setError(pParse, SQLITE_AUTH, COMDB2_NOT_AUTHORIZED_ERRMSG);
return;
}
}
#endif
Vdbe *v = sqlite3GetVdbe(pParse);
struct schema_change_type *sc = new_schemachange_type();
if (sc == NULL) {
setError(pParse, SQLITE_NOMEM, "System out of memory");
return;
}
if (chkAndCopyTableTokens(pParse, sc->tablename, pName1, pName2,
ERROR_ON_TBL_NOT_FOUND, 1, 0, NULL, /* check_for_illegal_chars */ 0))
goto out;
sc->kind = SC_ALTERTABLE;
sc->nothrevent = 1;
sc->live = 1;
sc->use_plan = 1;
sc->scanmode = SCAN_PARALLEL;
if(comdb2IsDryrun(pParse)){
if(comdb2SCIsDryRunnable(sc)){
sc->dryrun = 1;
} else {
setError(pParse, SQLITE_MISUSE, "DRYRUN not supported for this operation");
goto out;
}
}
fillTableOption(sc, opt);
if(OPT_ON(opt, FORCE_SC)){
sc->force = 1;
}
copyNoSqlToken(v, pParse, &sc->newcsc2, csc2);
if(sc->dryrun)
comdb2prepareSString(v, pParse, 0, sc, &comdb2SqlDryrunSchemaChange,
(vdbeFuncArgFree) &free_schema_change_type);
else
comdb2PrepareSC(v, pParse, 0, sc, &comdb2SqlSchemaChange_usedb,
(vdbeFuncArgFree)&free_schema_change_type);
return;
out:
free_schema_change_type(sc);
}
void comdb2DropTable(Parse *pParse, SrcList *pName)
{
char *partition_first_shard = NULL;
if (comdb2IsPrepareOnly(pParse))
return;
#ifndef SQLITE_OMIT_AUTHORIZATION
{
if( sqlite3AuthCheck(pParse, SQLITE_DROP_TABLE, 0, 0, 0) ){
setError(pParse, SQLITE_AUTH, COMDB2_NOT_AUTHORIZED_ERRMSG);
return;
}
}
#endif
Vdbe *v = sqlite3GetVdbe(pParse);
struct schema_change_type *sc = new_schemachange_type();
if (sc == NULL) {
setError(pParse, SQLITE_NOMEM, "System out of memory");
return;
}
Token table = {pName->a[0].zName, strlen(pName->a[0].zName)};
if (chkAndCopyTableTokens(pParse, sc->tablename, &table, 0,
ERROR_ON_TBL_NOT_FOUND, 1, 0,
&partition_first_shard, /* check_for_illegal_chars */ 0))
goto out;
sc->same_schema = 1;
sc->kind = SC_DROPTABLE;
sc->nothrevent = 1;
if(comdb2IsDryrun(pParse)){
if(comdb2SCIsDryRunnable(sc)){
sc->dryrun = 1;
} else {
setError(pParse, SQLITE_MISUSE, "DRYRUN not supported for this operation");
goto out;
}
}
if (partition_first_shard)
sc->partition.type = PARTITION_REMOVE;
else {
/* Check if this is a distributed drop */
struct dbtable *tbl = get_dbtable_by_name(sc->tablename);
if (tbl && tbl->sqlaliasname && tbl->dbnames[0]) {
/* dropping a generic partition */
/* NOTE: there are two was to get here:
* - initial drop table that is actually a partition (coordinator)
* - subsequent individual shard (participant)
* The only way to check which case is by looking a clnt structure;
* a participant receives a SET PARTITION NAME from coordinator
*/
struct sql_thread *thd = pthread_getspecific(query_info_key);
assert(thd && thd->clnt);
sc->partition.type = thd->clnt->remsql_set.is_remsql == IS_REMCREATE ?
PARTITION_REM_GENSHARD : PARTITION_REM_GENSHARD_COORD ;
snprintf(sc->partition.u.genshard.tablename,
sizeof(sc->partition.u.genshard.tablename), "%s", tbl->sqlaliasname);
}
}
tran_type *tran = curtran_gettran();
int rc = get_csc2_file_tran(partition_first_shard ? partition_first_shard :
sc->tablename, -1 , &sc->newcsc2, NULL, tran);
curtran_puttran(tran);
if (rc) {
logmsg(LOGMSG_ERROR, "%s: %s schema not found: %s\n", __func__,
partition_first_shard ? "shard" : "table",