-
Notifications
You must be signed in to change notification settings - Fork 225
/
Copy pathsqlinterfaces.c
7332 lines (6420 loc) · 231 KB
/
sqlinterfaces.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 2015, 2021, Bloomberg Finance L.P.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* code needed to support various comdb2 interfaces to the sql engine */
#include <poll.h>
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#include <errno.h>
#include <string.h>
#include <stddef.h>
#include <pthread.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <inttypes.h>
#include <fcntl.h>
#include <limits.h>
#include <time.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <epochlib.h>
#include <plhash.h>
#include <segstr.h>
#include <list.h>
#include <sbuf2.h>
#include <bdb_api.h>
#include <bdb_int.h>
#include "comdb2.h"
#include "types.h"
#include "tag.h"
#include "thdpool.h"
#include "ssl_bend.h"
#include <cdb2api.h>
#include <sys/time.h>
#include <strbuf.h>
#include <math.h>
#include <sqlite3.h>
#include <sqliteInt.h>
#include <vdbeInt.h>
#include "sql.h"
#include "sqlinterfaces.h"
#include "locks.h"
#include "sqloffload.h"
#include "osqlcomm.h"
#include "osqlcheckboard.h"
#include "osqlsqlthr.h"
#include "osqlshadtbl.h"
#include <sqlresponse.pb-c.h>
#include <sqlite3expert.h>
#include <carray.h>
#include <alloca.h>
#include <fsnapf.h>
#include "flibc.h"
#include "sp.h"
#include <ctrace.h>
#include <bb_oscompat.h>
#include <netdb.h>
#include "fdb_bend_sql.h"
#include "fdb_access.h"
#include "sqllog.h"
#include <quantize.h>
#include <str0.h>
#include "debug_switches.h"
#include "intern_strings.h"
#include "views.h"
#include "mem.h"
#include "comdb2_atomic.h"
#include "logmsg.h"
#include "reqlog.h"
#include "eventlog.h"
#include "perf.h"
#include "tohex.h"
#include "dohsql.h"
#include "comdb2_query_preparer.h"
#include "string_ref.h"
#include "osqlsqlsocket.h"
#include <net_appsock.h>
#include <typessql.h>
#include <sqlwriter.h>
/*
** WARNING: These enumeration values are not arbitrary. They represent
** indexes into the array of meta-command names contained in
** the is_transaction_meta_sql() function. New values should
** generally be added at the end and all of these values must
** be kept in sync with the azMeta string array contained in
** the is_transaction_meta_sql() function.
*/
enum tsql_meta_command {
TSMC_NONE = 0,
TSMC_BEGIN = 1,
TSMC_COMMIT = 2,
TSMC_ROLLBACK = 3
};
typedef enum tsql_meta_command tsql_meta_command_t;
/* delete this after comdb2_api.h changes makes it through */
#define SQLHERR_MASTER_QUEUE_FULL -108
#define SQLHERR_MASTER_TIMEOUT -109
extern unsigned long long gbl_sql_deadlock_failures;
extern int gbl_allow_pragma;
extern int g_osql_max_trans;
extern int gbl_fdb_track;
extern int gbl_stable_rootpages_test;
extern int gbl_verbose_normalized_queries;
extern int gbl_group_concat_mem_limit;
extern int gbl_expressions_indexes;
extern int gbl_old_column_names;
extern hash_t *gbl_fingerprint_hash;
extern pthread_mutex_t gbl_fingerprint_hash_mu;
extern int gbl_alternate_normalize;
extern int gbl_typessql;
extern int gbl_modsnap_asof;
extern int gbl_use_modsnap_for_snapshot;
/* Once and for all:
struct sqlthdstate:
This is created per thread executing SQL. Has per-thread resources
like an SQLite handle, logger, etc.
struct sqlclntstate:
Per connection. If a connection is handed off to another handle on the
client side (via sockpool), client request a reset of this structure.
struct sql_thread:
Linked from sqlthdstate. Has per query stats like accumulated cost, etc
as well as the connection lock (which is really a per-session resource
that should be in sqlclntstate). Also has to Btree* which probably
also belongs in sqlthdstate, or sqlclntstate, or lord only knows where
else.
struct Btree:
This is per instance of sqlite, which may be shared when idle among
multiple
connections.
*/
/* An alternate interface. */
extern int gbl_dump_sql_dispatched; /* dump all sql strings dispatched */
extern int gbl_time_osql; /* dump timestamps for osql steps */
extern int gbl_time_fdb; /* dump timestamps for remote sql */
extern int gbl_print_syntax_err;
extern int gbl_max_sqlcache;
extern int gbl_track_sqlengine_states;
extern int gbl_disable_sql_dlmalloc;
extern struct ruleset *gbl_ruleset;
extern int gbl_sql_release_locks_on_slow_reader;
extern int gbl_sql_no_timeouts_on_release_locks;
extern int get_snapshot(struct sqlclntstate *clnt, int *f, int *o);
extern void clnt_try_enable_logdel(struct sqlclntstate *clnt);
/* gets incremented each time a user's password is changed. */
int gbl_bpfunc_auth_gen = 1;
uint64_t gbl_clnt_seq_no = 0;
int gbl_dump_history_on_too_many_verify_errors = 0;
int gbl_thdpool_queue_only = 0;
int gbl_random_sql_work_delayed = 0;
int gbl_random_sql_work_rejected = 0;
comdb2_query_preparer_t *query_preparer_plugin;
int gbl_sql_recover_time = 10;
int gbl_debug_recover_deadlock_evbuffer = 0;
void rcache_init(size_t, size_t);
void rcache_destroy(void);
void sql_reset_sqlthread(struct sql_thread *thd);
int blockproc2sql_error(int rc, const char *func, int line);
static int test_no_btcursors(struct sqlthdstate *thd);
static void sql_thread_describe(void *obj, FILE *out);
static char *get_query_cost_as_string(struct sql_thread *, struct sqlclntstate *);
void handle_sql_intrans_unrecoverable_error(struct sqlclntstate *clnt);
void comdb2_set_sqlite_vdbe_dtprec(Vdbe *p);
static int execute_sql_query_offload(struct sqlthdstate *, struct sqlclntstate *);
static int record_query_cost(struct sql_thread *, struct sqlclntstate *);
static int sql_debug_logf_int(struct sqlclntstate *clnt, const char *func,
int line, const char *fmt, va_list args)
{
char *s;
int cn_len;
snap_uid_t snap = {{0}};
char *cnonce;
int len;
int nchars;
va_list args_c;
if (clnt && get_cnonce(clnt, &snap) == 0) {
cn_len = snap.keylen;
cnonce = alloca(cn_len + 1);
memcpy(cnonce, snap.key, cn_len);
cnonce[cn_len] = '\0';
} else {
cnonce = "(no-cnonce)";
}
len = 256;
s = malloc(len);
if (!s) {
logmsg(LOGMSG_ERROR, "%s:malloc(%d) failed\n", __func__, len);
return -1;
}
va_copy(args_c, args);
nchars = vsnprintf(s, len, fmt, args);
if (nchars >= len) {
len = nchars + 1;
char *news = realloc(s, len);
if (!news) {
logmsg(LOGMSG_ERROR, "%s:realloc(%d) failed\n", __func__, len);
va_end(args_c);
free(s);
return -1;
}
s = news;
len = vsnprintf(s, len, fmt, args_c);
} else {
len = strlen(s);
}
va_end(args_c);
logmsg(LOGMSG_USER, "cnonce=%s %s line %d: %s", cnonce, func, line, s);
free(s);
return 0;
}
int sql_debug_logf(struct sqlclntstate *clnt, const char *func, int line,
const char *fmt, ...)
{
if (!gbl_extended_sql_debug_trace)
return 0;
else {
va_list args;
int rc;
va_start(args, fmt);
rc = sql_debug_logf_int(clnt, func, line, fmt, args);
va_end(args);
return rc;
}
}
static inline void comdb2_set_sqlite_vdbe_tzname_int(Vdbe *p,
struct sqlclntstate *clnt)
{
memcpy(p->tzname, clnt->tzname, TZNAME_MAX);
}
static inline void comdb2_set_sqlite_vdbe_dtprec_int(Vdbe *p,
struct sqlclntstate *clnt)
{
p->dtprec = clnt->dtprec;
}
int disable_server_sql_timeouts(void)
{
return gbl_sql_release_locks_on_slow_reader && gbl_sql_no_timeouts_on_release_locks;
}
#define XRESPONSE(x) #x,
const char *WriteRespString[] = { RESPONSE_TYPES };
#undef XRESPONSE
int gbl_client_heartbeat_ms = 100;
int gbl_fail_client_write_lock = 0;
struct sqlclntstate *get_sql_clnt(void){
struct sql_thread *thd = pthread_getspecific(query_info_key);
if (thd == NULL) return NULL;
return thd->clnt;
}
static inline int lock_client_write_lock_int(struct sqlclntstate *clnt, int try)
{
struct sql_thread *thd = pthread_getspecific(query_info_key);
int rc = 0;
if (thd && clnt)
clnt->emitting_flag = 1;
again:
if (try) {
if ((rc = pthread_mutex_trylock(&clnt->write_lock))) {
if (thd && clnt)
clnt->emitting_flag = 0;
return rc;
}
} else {
Pthread_mutex_lock(&clnt->write_lock);
}
if (clnt->heartbeat_lock && thd) {
if (clnt->need_recover_deadlock) {
/* Call only if there isn't a previous failure */
if (!clnt->recover_deadlock_rcode) {
uint32_t flags = 0;
if (gbl_fail_client_write_lock && !(rand() % gbl_fail_client_write_lock)) {
flags = RECOVER_DEADLOCK_FORCE_FAIL;
}
recover_deadlock_flags(thedb->bdb_env, clnt, NULL, 0, __func__, __LINE__, flags);
}
clnt->need_recover_deadlock = 0;
if (clnt->recover_deadlock_rcode) {
assert(bdb_lockref() == 0);
logmsg(LOGMSG_WARN, "%s recover_deadlock returned %d\n",
__func__, clnt->recover_deadlock_rcode);
}
}
Pthread_cond_signal(&clnt->write_cond);
Pthread_mutex_unlock(&clnt->write_lock);
goto again;
}
return 0;
}
int lock_client_write_trylock(struct sqlclntstate *clnt)
{
return lock_client_write_lock_int(clnt, 1);
}
int lock_client_write_lock(struct sqlclntstate *clnt)
{
return lock_client_write_lock_int(clnt, 0);
}
void unlock_client_write_lock(struct sqlclntstate *clnt)
{
struct sql_thread *thd = pthread_getspecific(query_info_key);
if (thd && clnt)
clnt->emitting_flag = 0;
Pthread_mutex_unlock(&clnt->write_lock);
}
int write_response(struct sqlclntstate *clnt, int R, void *D, int I)
{
#ifdef DEBUG
logmsg(LOGMSG_DEBUG, "write_response(%s,%p,%d)\n", WriteRespString[R], D, I);
#endif
if (gbl_sql_recover_time && R == RESPONSE_ROW) {
/* TODO: Also do this for OP_SorterInsert */
struct timeval now, diff;
gettimeofday(&now, NULL);
timersub(&now, &clnt->last_sql_recover_time, &diff);
int64_t ms = diff.tv_sec * 1000 - diff.tv_usec / 1000;
if (ms >= gbl_sql_recover_time) {
clnt->last_sql_recover_time = now;
if (recover_deadlock_evbuffer(clnt) != 0) {
logmsg(LOGMSG_ERROR, "%s recover_deadlock failed sql:%32s\n", __func__, clnt->sql);
return -1;
}
}
}
return clnt->plugin.write_response(clnt, R, D, I); /* newsql_write_response */
}
int read_response(struct sqlclntstate *clnt, int R, void *D, int I)
{
return clnt->plugin.read_response(clnt, R, D, I);
}
int get_fileno(struct sqlclntstate *clnt)
{
return clnt->plugin.get_fileno(clnt);
}
int column_count(struct sqlclntstate *clnt, sqlite3_stmt *stmt)
{
struct sql_thread *thd = NULL;
if (!clnt) {
thd = pthread_getspecific(query_info_key);
if (thd)
clnt = thd->clnt;
}
if (clnt && clnt->plugin.column_count)
return clnt->plugin.column_count(clnt, stmt);
return sqlite3_column_count(stmt);
}
int column_type(struct sqlclntstate *clnt, sqlite3_stmt *stmt, int iCol)
{
if (clnt && clnt->plugin.column_type) return clnt->plugin.column_type(clnt, stmt, iCol);
return sqlite3_column_type(stmt, iCol);
}
sqlite_int64 column_int64(struct sqlclntstate *clnt, sqlite3_stmt *stmt, int iCol)
{
if (clnt && clnt->plugin.column_int64) return clnt->plugin.column_int64(clnt, stmt, iCol);
return sqlite3_column_int64(stmt, iCol);
}
double column_double(struct sqlclntstate *clnt, sqlite3_stmt *stmt, int iCol)
{
if (clnt && clnt->plugin.column_double) return clnt->plugin.column_double(clnt, stmt, iCol);
return sqlite3_column_double(stmt, iCol);
}
const unsigned char *column_text(struct sqlclntstate *clnt, sqlite3_stmt *stmt, int iCol)
{
if (clnt && clnt->plugin.column_text) return clnt->plugin.column_text(clnt, stmt, iCol);
return sqlite3_column_text(stmt, iCol);
}
int column_bytes(struct sqlclntstate *clnt, sqlite3_stmt *stmt, int iCol)
{
if (clnt && clnt->plugin.column_bytes) return clnt->plugin.column_bytes(clnt, stmt, iCol);
return sqlite3_column_bytes(stmt, iCol);
}
const void *column_blob(struct sqlclntstate *clnt, sqlite3_stmt *stmt, int iCol)
{
if (clnt && clnt->plugin.column_blob) return clnt->plugin.column_blob(clnt, stmt, iCol);
return sqlite3_column_blob(stmt, iCol);
}
const dttz_t *column_datetime(struct sqlclntstate *clnt, sqlite3_stmt *stmt, int iCol)
{
if (clnt && clnt->plugin.column_datetime) return clnt->plugin.column_datetime(clnt, stmt, iCol);
return sqlite3_column_datetime(stmt, iCol);
}
const intv_t *column_interval(struct sqlclntstate *clnt, sqlite3_stmt *stmt, int iCol, int type)
{
if (clnt && clnt->plugin.column_interval) return clnt->plugin.column_interval(clnt, stmt, iCol, type);
return sqlite3_column_interval(stmt, iCol, type);
}
sqlite3_value *column_value(struct sqlclntstate *clnt, sqlite3_stmt *stmt, int iCol)
{
if (clnt && clnt->plugin.column_value) return clnt->plugin.column_value(clnt, stmt, iCol);
return sqlite3_column_value(stmt, iCol);
}
int sqlite_stmt_error(sqlite3_stmt *stmt, const char **errstr)
{
sqlite3 *db = sqlite3_db_handle(stmt);
int errcode;
*errstr = NULL;
errcode = sqlite3_errcode(db);
if (errcode && errcode != SQLITE_ROW) {
*errstr = sqlite3_errmsg(db);
}
return errcode;
}
int sqlite_error(struct sqlclntstate *clnt, sqlite3_stmt *stmt,
const char **errstr)
{
if (clnt && clnt->plugin.sqlite_error)
return clnt->plugin.sqlite_error(clnt, stmt, errstr);
return sqlite_stmt_error(stmt, errstr);
}
int next_row(struct sqlclntstate *clnt, sqlite3_stmt *stmt)
{
if (clnt && clnt->plugin.next_row)
return clnt->plugin.next_row(clnt, stmt);
return sqlite3_maybe_step(clnt, stmt);
}
int has_cnonce(struct sqlclntstate *clnt)
{
return clnt->plugin.has_cnonce(clnt);
}
int set_cnonce(struct sqlclntstate *clnt)
{
return clnt->plugin.set_cnonce(clnt);
}
int clr_cnonce(struct sqlclntstate *clnt)
{
return clnt->plugin.clr_cnonce(clnt);
}
int get_cnonce(struct sqlclntstate *clnt, snap_uid_t *snap)
{
return clnt->plugin.get_cnonce(clnt, snap);
}
static int clr_snapshot(struct sqlclntstate *clnt)
{
return clnt->plugin.clr_snapshot(clnt);
}
static int upd_snapshot(struct sqlclntstate *clnt)
{
return clnt->plugin.upd_snapshot(clnt);
}
int has_high_availability(struct sqlclntstate *clnt)
{
return clnt->plugin.has_high_availability(clnt);
}
int set_high_availability(struct sqlclntstate *clnt)
{
return clnt->plugin.set_high_availability(clnt);
}
int clr_high_availability(struct sqlclntstate *clnt)
{
return clnt->plugin.clr_high_availability(clnt);
}
static int get_high_availability(struct sqlclntstate *clnt)
{
return clnt->plugin.get_high_availability(clnt);
}
int has_parallel_sql(struct sqlclntstate *clnt)
{
if (!clnt) {
struct sql_thread *thd = pthread_getspecific(query_info_key);
if (thd) clnt = thd->clnt;
}
/* disable anything involving shared shadows;
recom requires a read-only share;
snapisol and serializable requires a read-write share
*/
if (!clnt || clnt->dbtran.mode != TRANLEVEL_SOSQL || clnt->dohsql_disable)
return 0;
return clnt && clnt->plugin.has_parallel_sql && clnt->plugin.has_parallel_sql(clnt);
}
static void setup_client_info(struct sqlclntstate *clnt, struct sqlthdstate *thd, char *replay)
{
clnt->plugin.setup_client_info(clnt, thd, replay);
}
uint64_t get_client_starttime(struct sqlclntstate *clnt)
{
return clnt->plugin.get_client_starttime(clnt);
}
int get_client_retries(struct sqlclntstate *clnt)
{
return clnt->plugin.get_client_retries(clnt);
}
void *get_authdata(struct sqlclntstate *clnt)
{
return clnt->plugin.get_authdata(clnt);
}
static int skip_row(struct sqlclntstate *clnt, uint64_t rowid)
{
return clnt->plugin.skip_row(clnt, rowid);
}
static int log_context(struct sqlclntstate *clnt, struct reqlogger *logger)
{
return clnt->plugin.log_context(clnt, logger);
}
static int send_intrans_response(struct sqlclntstate *clnt)
{
return clnt->plugin.send_intrans_response(clnt);
}
void handle_failed_dispatch(struct sqlclntstate *clnt, char *errstr)
{
Pthread_mutex_lock(&clnt->wait_mutex);
write_response(clnt, RESPONSE_ERROR_REJECT, errstr, 0);
Pthread_mutex_unlock(&clnt->wait_mutex);
}
char *tranlevel_tostr(int lvl)
{
switch (lvl) {
case TRANLEVEL_SOSQL:
return "TRANLEVEL_SOSQL";
case TRANLEVEL_RECOM:
return "TRANLEVEL_RECOM";
case TRANLEVEL_MODSNAP:
return "TRANLEVEL_MODSNAP";
case TRANLEVEL_SERIAL:
return "TRANLEVEL_SERIAL";
default:
return "???";
};
}
int toggle_case_sensitive_like(sqlite3 *db, int enable)
{
char sql[80];
int rc;
char *err;
snprintf(sql, sizeof(sql), "PRAGMA case_sensitive_like = %d;",
enable ? 0 : 1);
rc = sqlite3_exec(db, sql, NULL, NULL, &err);
if (rc)
logmsg(LOGMSG_ERROR, "Failed to set case_insensitive_like rc %d err \"%s\"\n", rc,
err ? err : "");
if (err)
sqlite3_free(err);
return rc;
}
static int64_t connid = 0;
/* lru_evbuffers may be accessed by multiple sql threads, hence we need to protect it with a mutex. */
static pthread_mutex_t lru_evbuffers_mtx = PTHREAD_MUTEX_INITIALIZER;
static TAILQ_HEAD(lru_evbuffers, sqlclntstate) lru_evbuffers = TAILQ_HEAD_INITIALIZER(lru_evbuffers);
static TAILQ_HEAD(sql_evbuffers, sqlclntstate) sql_evbuffers = TAILQ_HEAD_INITIALIZER(sql_evbuffers);
static __thread comdb2ma sql_mspace = NULL;
static void sql_mem_create()
{
/* We used to start with 1MB - this isn't quite necessary
as comdb2_malloc pre-allocation is much smarter now.
We also name it "SQLITE" (uppercase) to differentiate it
from those implicitly created per-thread allocators
whose names are "sqlite" (lowercase). Those allocators
are used by other types of threads, e.g., appsock threads. */
sql_mspace = comdb2ma_create(0, 0, "SQLITE", COMDB2MA_MT_UNSAFE);
if (sql_mspace == NULL) {
logmsg(LOGMSG_FATAL, "%s: comdb2a_create failed\n", __func__);
exit(1);
}
}
int sql_mem_init(void *arg)
{
if (unlikely(sql_mspace)) {
return 0;
}
sql_mem_create();
return 0;
}
int sql_mem_init_with_save(void *arg, void **poldm)
{
*poldm = sql_mspace;
sql_mem_create();
return 0;
}
void sql_mem_shutdown(void *arg)
{
if (sql_mspace) {
comdb2ma_destroy(sql_mspace);
sql_mspace = NULL;
}
}
void sql_mem_shutdown_and_restore(void *arg, void **poldm)
{
sql_mem_shutdown(arg);
sql_mspace = *poldm; *poldm = NULL;
}
static void *sql_mem_malloc(size_t size)
{
if (unlikely(sql_mspace == NULL))
sql_mem_init(NULL);
return comdb2_malloc(sql_mspace, size);
}
static void sql_mem_free(void *mem)
{
comdb2_free(mem);
}
static void *sql_mem_realloc(void *mem, int size)
{
if (unlikely(sql_mspace == NULL))
sql_mem_init(NULL);
return comdb2_realloc(sql_mspace, mem, size);
}
static int sql_mem_size(void *mem) { return comdb2_malloc_usable_size(mem); }
static int sql_mem_roundup(int i) { return i; }
void sql_dlmalloc_init(void)
{
sqlite3_mem_methods m;
if (gbl_disable_sql_dlmalloc) {
return;
}
m.xMalloc = sql_mem_malloc;
m.xFree = sql_mem_free;
m.xRealloc = sql_mem_realloc;
m.xSize = sql_mem_size;
m.xRoundup = sql_mem_roundup;
m.xInit = sql_mem_init;
m.xShutdown = sql_mem_shutdown;
m.pAppData = NULL;
sqlite3_config(SQLITE_CONFIG_MALLOC, &m);
}
/* Called once from comdb2. Do all static intialization here */
void sqlinit(void)
{
Pthread_mutex_init(&gbl_sql_lock, NULL);
sql_dlmalloc_init();
/* initialize global structures in sqlite */
if (sqlite3_initialize())
abort();
}
static char *vtable_lockname(sqlite3 *db, const char *vtable, int *is_system_table)
{
*is_system_table = 0;
if (vtable == NULL || db == NULL || db->aModule.count == 0)
return NULL;
struct Module *module;
char *lockname = NULL;
sqlite3_mutex_enter(db->mutex);
if ((module = sqlite3HashFind(&db->aModule, vtable)) != NULL) {
*is_system_table = 1;
lockname = module->pModule->systable_lock;
}
sqlite3_mutex_leave(db->mutex);
return lockname;
}
static int vtable_search(char **vtables, int ntables, const char *table)
{
for (int i = 0; i < ntables; i++) {
if (strcmp(vtables[i], table) == 0) {
return 1;
}
}
return 0;
}
static void record_locked_vtable(struct sql_authorizer_state *pAuthState, const char *table)
{
int is_system_table;
const char *vtable_lock = vtable_lockname(pAuthState->db, table, &is_system_table);
if (vtable_lock && !vtable_search(pAuthState->vTableLocks, pAuthState->numVTableLocks, vtable_lock)) {
pAuthState->vTableLocks =
(char **)realloc(pAuthState->vTableLocks, sizeof(char *) * (pAuthState->numVTableLocks + 1));
pAuthState->vTableLocks[pAuthState->numVTableLocks++] = strdup(vtable_lock);
}
if (is_system_table && !pAuthState->hasVTables)
pAuthState->hasVTables = 1;
}
static int comdb2_authorizer_for_sqlite(
void *pArg, /* IN: NOT USED */
int code, /* IN: NOT USED */
const char *zArg1, /* IN: NOT USED */
const char *zArg2, /* IN: NOT USED */
const char *zArg3, /* IN: NOT USED */
const char *zArg4 /* IN: NOT USED */
#ifdef SQLITE_USER_AUTHENTICATION
,const char *zArg5 /* IN: NOT USED */
#endif
){
struct sql_authorizer_state *pAuthState = pArg;
if (pAuthState == NULL) {
return SQLITE_DENY;
}
int denyCreateTrigger = (pAuthState->flags & PREPARE_DENY_CREATE_TRIGGER);
int denyPragma = (pAuthState->flags & PREPARE_DENY_PRAGMA);
int denyDdl = (pAuthState->flags & PREPARE_DENY_DDL);
int allowTempDDL = (pAuthState->flags & PREPARE_ALLOW_TEMP_DDL);
switch (code) {
case SQLITE_CREATE_INDEX:
case SQLITE_CREATE_TABLE:
case SQLITE_CREATE_VIEW:
case SQLITE_DROP_INDEX:
case SQLITE_DROP_TABLE:
case SQLITE_DROP_TRIGGER:
case SQLITE_DROP_VIEW:
case SQLITE_ALTER_TABLE:
case SQLITE_REINDEX:
case SQLITE_ANALYZE:
case SQLITE_CREATE_VTABLE:
case SQLITE_DROP_VTABLE:
case SQLITE_REBUILD_TABLE: /* COMDB2 ONLY */
case SQLITE_REBUILD_INDEX: /* COMDB2 ONLY */
case SQLITE_REBUILD_DATA: /* COMDB2 ONLY */
case SQLITE_REBUILD_DATABLOB: /* COMDB2 ONLY */
case SQLITE_TRUNCATE_TABLE: /* COMDB2 ONLY */
case SQLITE_CREATE_PROC: /* COMDB2 ONLY */
case SQLITE_DROP_PROC: /* COMDB2 ONLY */
case SQLITE_CREATE_PART: /* COMDB2 ONLY */
case SQLITE_DROP_PART: /* COMDB2 ONLY */
case SQLITE_GET_TUNABLE: /* COMDB2 ONLY */
case SQLITE_PUT_TUNABLE: /* COMDB2 ONLY */
case SQLITE_GRANT: /* COMDB2 ONLY */
case SQLITE_REVOKE: /* COMDB2 ONLY */
case SQLITE_CREATE_LUA_FUNCTION: /* COMDB2 ONLY */
case SQLITE_DROP_LUA_FUNCTION: /* COMDB2 ONLY */
case SQLITE_CREATE_LUA_TRIGGER: /* COMDB2 ONLY */
case SQLITE_DROP_LUA_TRIGGER: /* COMDB2 ONLY */
case SQLITE_CREATE_LUA_CONSUMER: /* COMDB2 ONLY */
case SQLITE_DROP_LUA_CONSUMER: /* COMDB2 ONLY */
pAuthState->numDdls++;
return denyDdl ? SQLITE_DENY : SQLITE_OK;
case SQLITE_PRAGMA:
pAuthState->numDdls++;
if (denyDdl || denyPragma) {
return SQLITE_DENY;
} else if (pAuthState->clnt != NULL) {
logmsg(LOGMSG_DEBUG, "%s:%d %s ALLOWING PRAGMA [%s]\n", __FILE__,
__LINE__, __func__, pAuthState->clnt->sql);
return SQLITE_OK;
} else {
return SQLITE_DENY;
}
case SQLITE_CREATE_TRIGGER:
pAuthState->numDdls++;
if (denyDdl || denyCreateTrigger) {
return SQLITE_DENY;
} else {
return SQLITE_OK;
}
case SQLITE_CREATE_TEMP_INDEX:
case SQLITE_CREATE_TEMP_TABLE:
case SQLITE_CREATE_TEMP_TRIGGER:
case SQLITE_CREATE_TEMP_VIEW:
case SQLITE_DROP_TEMP_INDEX:
case SQLITE_DROP_TEMP_TABLE:
case SQLITE_DROP_TEMP_TRIGGER:
case SQLITE_DROP_TEMP_VIEW:
pAuthState->numDdls++;
return allowTempDDL ? SQLITE_OK : SQLITE_DENY;
case SQLITE_READ:
record_locked_vtable(pAuthState, zArg1);
return SQLITE_OK;
default:
return SQLITE_OK;
}
}
static void comdb2_reset_authstate(struct sqlthdstate *thd)
{
bzero(&thd->authState, sizeof(thd->authState));
}
static void comdb2_set_authstate(struct sqlthdstate *thd, struct sqlclntstate *clnt, int flags)
{
thd->authState.clnt = clnt;
thd->authState.flags = flags;
thd->authState.numDdls = 0;
thd->authState.numVTableLocks = 0;
thd->authState.vTableLocks = NULL;
thd->authState.hasVTables = 0;
thd->authState.db = thd->sqldb;
}
static void comdb2_setup_authorizer_for_sqlite(
sqlite3 *db,
struct sql_authorizer_state *pAuthState,
int bEnable
){
if( !db ) return;
if( bEnable ){
sqlite3_set_authorizer(db, comdb2_authorizer_for_sqlite, pAuthState);
}else{
sqlite3_set_authorizer(db, NULL, NULL);
}
}
int sqlite3_is_success(int rc){
return (rc==SQLITE_OK) || (rc==SQLITE_ROW) || (rc==SQLITE_DONE);
}
int sqlite3_is_prepare_only(
struct sqlclntstate *clnt
){
if( clnt!=NULL && clnt->prepare_only ){
return 1;
}
return 0;
}
int sqlite3_maybe_step(
struct sqlclntstate *clnt,
sqlite3_stmt *stmt
){
assert( clnt );
assert( stmt );
int steps = clnt->nsteps++;
if( unlikely(sqlite3_is_prepare_only(clnt)) ){
if( sqlite3_column_count(stmt)>0 ){
return steps==0 ? SQLITE_ROW : SQLITE_DONE;
}else{
return SQLITE_DONE;
}
}
clnt->step_rc = sqlite3_step(stmt);
return clnt->step_rc;
}
int sqlite3_can_get_column_type_and_data(struct sqlclntstate *clnt,
sqlite3_stmt *stmt)
{
if (!sqlite3_is_prepare_only(clnt)) {
/*
** When the client is not in 'prepare only' mode, the result set
** should always be available (i.e. anytime after sqlite3_step()
** is called). The column type / data should be available -IF-
** this is not a write transaction. An assert is used here to
** verify this invariant.
*/
assert(clnt->step_rc != SQLITE_ROW || sqlite3_hasResultSet(stmt));
return 1;
}
if (sqlite3_hasResultSet(stmt)) {
/*
** If the result set is available for the prepared statement, e.g.
** due to sqlite3_step() having been called, it can always be used
** to query the column type and data. It shouldn't be possible to
** reach this point in 'prepare only' mode; therefore, assert this
** invariant here.
*/
assert(!sqlite3_is_prepare_only(clnt));
return 1;
}
return 0;
}
int validate_columns(struct sqlclntstate *clnt, sqlite3_stmt *stmt)
{
int ncols = column_count(clnt, stmt), type;
if (!sqlite3_can_get_column_type_and_data(clnt, stmt))
return 0;
for (int i = 0; i < ncols; ++i) {
type = column_type(clnt, stmt, i);
if (type == (int)SQLITE_NEXTSEQ)
return -1;
}
return 0;
}
int get_sqlite3_column_type(struct sqlclntstate *clnt, sqlite3_stmt *stmt,
int col, int skip_decltype)
{
int type = SQLITE_NULL;
int ncols = column_count(clnt, stmt);
if (sqlite3_can_get_column_type_and_data(clnt, stmt)) {
int colNum = col;
if (clnt->typessql_state && !skip_decltype)
colNum += ncols;
type = column_type(clnt, stmt, colNum);
if (type == SQLITE_NULL && !skip_decltype) {
type = typestr_to_type(sqlite3_column_decltype(stmt, col));
}
if (type == SQLITE_DECIMAL) {
type = SQLITE_TEXT;
}
}
return type;