-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsqlmath_base.c
More file actions
1831 lines (1751 loc) · 55.6 KB
/
Copy pathsqlmath_base.c
File metadata and controls
1831 lines (1751 loc) · 55.6 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
// copyright nobody
// LINT_C_FILE
/*
file sqlmath_h - start
*/
#ifndef SQLMATH_H
#define SQLMATH_H
// header
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// header2
#ifdef WIN32
#include <windows.h>
#endif
#include <sqlite3.h>
// define
#define ALLOCC calloc
#define ALLOCF free
#define ALLOCM malloc
inline void *ALLOCR(
void *ptr,
size_t size
) {
// handle null-case
if (ptr == NULL) {
return NULL;
}
void *ptr2 = realloc(ptr, size);
// if nomem, cleanup old ptr
if (ptr2 == NULL) {
free(ptr);
}
return ptr2;
}
#define JS_MAX_SAFE_INTEGER 0x1fffffffffffff
#define JS_MIN_SAFE_INTEGER -0x1fffffffffffff
#define MAX(aa, bb) (((aa) < (bb)) ? (bb) : (aa))
#define MIN(aa, bb) (((aa) > (bb)) ? (bb) : (aa))
#define SIZEOF_MESSAGE_DEFAULT 1024
#define SQLITE_DATATYPE_BLOB 0x04
#define SQLITE_DATATYPE_BLOB_0 0x14
#define SQLITE_DATATYPE_FLOAT 0x02
#define SQLITE_DATATYPE_FLOAT_0 0x12
#define SQLITE_DATATYPE_INTEGER 0x01
#define SQLITE_DATATYPE_INTEGER_0 0x11
#define SQLITE_DATATYPE_INTEGER_1 0x21
#define SQLITE_DATATYPE_NULL 0x05
#define SQLITE_DATATYPE_SHAREDARRAYBUFFER -0x01
#define SQLITE_DATATYPE_TEXT 0x03
#define SQLITE_DATATYPE_TEXT_0 0x13
#define SQLITE_ERROR_DATATYPE_INVALID 0x10003
#define SQLITE_ERROR_NOMEM2 0x10001
#define SQLITE_ERROR_TOOBIG2 0x10002
#define SQLITE_MAX_LENGTH2 1000000000
#define SQLITE_RESPONSETYPE_LAST_MATRIX_DOUBLE 2
#define SQLITE_RESPONSETYPE_LAST_VALUE 1
#define SQLMATH_API
#define SWAP(aa, bb) tmp = (aa); (aa)=(bb); (bb) = tmp
#define UNUSED(x) (void)(x)
// define2
/*
** A macro to hint to the compiler that a function should not be
** inlined.
*/
#if defined(__GNUC__)
# define NOINLINE __attribute__((noinline))
#elif defined(_MSC_VER) && _MSC_VER >= 1310
# define NOINLINE __declspec(noinline)
#else
# define NOINLINE
#endif
/*
file sqlmath_h_struct
*/
#define JSBATON_ARGC 16
typedef struct napi_async_work__ *napi_async_work;
typedef struct napi_deferred__ *napi_deferred;
typedef struct napi_value__ *napi_value;
typedef struct BindElem {
const char *buf;
char *key;
int buflen;
char datatype;
} BindElem;
typedef struct Jsbaton {
// data
int64_t argint64[JSBATON_ARGC];
const char *bufin[JSBATON_ARGC];
char *bufout[JSBATON_ARGC];
char errmsg[SIZEOF_MESSAGE_DEFAULT];
napi_value result;
// async
napi_async_work work;
napi_deferred deferred;
} Jsbaton;
/*
file sqlmath_h_assert
*/
#define ASSERT_SQLITE_CONTEXT_OK(context, errcode) \
if (!IS_SQLITE_OK(errcode)) { \
sqlite3_result_error_code(context, errcode); \
return; \
}
// this function will exec <sql> and if <errcode> is not ok,
// throw <baton->errmsg>
#define ASSERT_SQLITE_EXEC(baton, db, sql, errcode) \
errcode = sqlite3_exec(db, sql, NULL, NULL, NULL); \
ASSERT_SQLITE_OK(baton, db, errcode);
// this function will if <errcode> is not ok, throw <baton->errmsg>
#define ASSERT_SQLITE_OK(baton, db, errcode) \
if (!IS_SQLITE_OK(errcode)) { \
assertSqliteOk(baton, db, errcode, __func__, __FILE__, __LINE__); \
goto catch_error; \
}
// this function will return if <errcode> is ok or not
#define IS_SQLITE_OK(errcode) \
(errcode == 0 || errcode == SQLITE_ROW || errcode == SQLITE_DONE)
static const char *__snprintfTrace(
char *buf,
const char *prefix,
const char *errmsg,
const char *func,
const char *file,
int line
) {
// this function will write <errmsg> to <buf> with additional trace-info
if (snprintf(buf, // NO_LINT
SIZEOF_MESSAGE_DEFAULT, "%s%s\n at %s (%s:%d)", prefix, errmsg,
func, file, line) < 0) {
abort();
}
return (const char *) buf;
}
static NOINLINE int assertSqliteOk(
Jsbaton * baton,
sqlite3 * db,
int errcode,
const char *func,
const char *file,
int line
) {
// this function will if errcode != 0, set baton->errmsg
switch (errcode) {
case SQLITE_DONE:
case SQLITE_OK:
case SQLITE_ROW:
return errcode;
}
if (baton == NULL || baton->errmsg[0] != '\x00') {
return errcode;
}
switch (errcode) {
case SQLITE_ERROR_DATATYPE_INVALID:
__snprintfTrace(baton->errmsg, "sqlite - ", "invalid datatype", func,
file, line);
return errcode;
case SQLITE_ERROR_NOMEM2:
__snprintfTrace(baton->errmsg, "sqlite - ", "out of memory", func,
file, line);
return errcode;
case SQLITE_ERROR_TOOBIG2:
__snprintfTrace(baton->errmsg, "sqlite - ", "string or blob too big",
func, file, line);
return errcode;
default:
__snprintfTrace(baton->errmsg, "sqlite - ",
db == NULL ? sqlite3_errstr(errcode) : sqlite3_errmsg(db), func,
file, line);
return errcode;
}
}
inline static int doubleCompare(
const void *aa,
const void *bb
) {
// this function will compare aa with bb
const double cc = *(double *) aa - *(double *) bb;
return cc == 0 ? 0 : cc > 0 ? 1 : -1;
}
inline static double doubleMax(
double aa,
double bb
) {
// this function will return max of aa, bb
return aa < bb ? bb : aa;
}
inline static double doubleMin(
double aa,
double bb
) {
// this function will return min of aa, bb
return aa > bb ? bb : aa;
}
inline static const int noop(
) {
// this function will do nothing except return 0
return 0;
}
#endif // SQLMATH_H
/*
file sqlmath_h - end
*/
/*
file sqlmath_c - start
*/
#ifdef SQLMATH_C
// header
#include <sqlite3ext.h>
static const sqlite3_api_routines *sqlite3_api;
/*
file sqlmath_c_base
*/
static char *base64Encode(
const unsigned char *blob,
int *nn
) {
// this function will base64-encode <blob> to <text>
#define base64EncodeCleanup ALLOCF
if (blob == NULL || *nn < 0) {
*nn = 0;
}
// declare var
char *text = NULL;
int aa = *nn - 3;
int bb = 0;
int ii = 0;
int triplet = 0;
static const char BASE64_ENCODE_TABLE[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// init bb
bb = 4 * ceil((double) *nn / 3);
// init text
text = ALLOCM(MAX(bb, 4));
// handle nomem
if (text == NULL) {
return NULL;
}
// handle null-case
if (bb < 4) {
text[0] = '\x00';
}
// base64-encode loop
while (ii < aa) {
triplet = blob[0];
triplet = triplet << 8 | blob[1];
triplet = triplet << 8 | blob[2];
blob += 3;
text[0] = BASE64_ENCODE_TABLE[(triplet >> 18) & 0x3f];
text[1] = BASE64_ENCODE_TABLE[(triplet >> 12) & 0x3f];
text[2] = BASE64_ENCODE_TABLE[(triplet >> 6) & 0x3f];
text[3] = BASE64_ENCODE_TABLE[triplet & 0x3f];
text += 4;
ii += 3;
}
// base64-encode '='
if (bb >= 4 && blob != NULL) {
aa += 3;
triplet = blob[0];
triplet = ii + 1 < aa ? triplet << 8 | blob[1] : triplet << 8;
triplet = ii + 2 < aa ? triplet << 8 | blob[2] : triplet << 8;
blob += 3;
text[0] = BASE64_ENCODE_TABLE[(triplet >> 18) & 0x3f];
text[1] = BASE64_ENCODE_TABLE[(triplet >> 12) & 0x3f];
text[2] =
(ii + 1 < aa) ? BASE64_ENCODE_TABLE[(triplet >> 6) & 0x3f] : '=';
text[3] = (ii + 2 < aa) ? BASE64_ENCODE_TABLE[triplet & 0x3f] : '=';
text += 4;
ii += 3;
}
// save bb
*nn = bb;
// return text
return text - bb;
}
/*
file sqlmath_c_str99
*/
// dynamically growable string
#define STR99_APPEND_CHAR(cc) \
errcode = str99AppendChar(str99, cc, errcode); \
if (!IS_SQLITE_OK(errcode)) { goto catch_error; }
#define STR99_APPEND_DOUBLE(ff) \
errcode = str99AppendDouble(str99, ff, errcode); \
if (!IS_SQLITE_OK(errcode)) { goto catch_error; }
#define STR99_APPEND_JSON(zz, nn) \
errcode = str99AppendJson(str99, zz, nn, errcode); \
if (!IS_SQLITE_OK(errcode)) { goto catch_error; }
#define STR99_APPEND_RAW(zz, nn) \
errcode = str99AppendRaw(str99, zz, nn, errcode); \
if (!IS_SQLITE_OK(errcode)) { goto catch_error; }
typedef struct Str99 {
char *zBuf; /* Accumulated string */
int nAlloced; /* Space allocated for zBuf[] */
int nUsed; /* Number of used-bytes in zBuf[] */
} Str99;
static NOINLINE int str99AppendRawAfterGrow(
Str99 * str99,
const char *zz,
int nn,
int errcode
);
static int str99AppendChar(
Str99 * str99,
const char cc,
int errcode
) {
/*
** Append <cc> to <str99->zBuf>.
** Increase the size of the memory allocation for <str99->zBuf> if necessary.
*/
// write <cc> to <str99->zBuf> if space available
if (str99->nUsed < str99->nAlloced) {
str99->zBuf[str99->nUsed] = cc;
str99->nUsed += 1;
return errcode;
}
// else resize and retry
return str99AppendRawAfterGrow(str99, &cc, 1, errcode);
}
static int str99AppendDouble(
Str99 * str99,
double ff,
int errcode
) {
/*
** Append <ff> to <str99->zBuf>.
** Increase the size of the memory allocation for <str99->zBuf> if necessary.
*/
// write <ff> to <str99->zBuf> if space available
if (str99->nUsed < str99->nAlloced) {
((double *) (str99->zBuf + str99->nUsed))[0] = ff;
str99->nUsed += 8;
return errcode;
}
// else resize and retry
return str99AppendRawAfterGrow(str99, (char *) (&ff), 8, errcode);
}
static int str99AppendRaw(
Str99 * str99,
const char *zz,
int nn,
int errcode
) {
/*
** Append <nn> bytes of text from <zz> to <str99->zBuf>.
** Increase the size of the memory allocation for <str99->zBuf> if necessary.
*/
if (nn == 0) {
return errcode;
}
// write <zz> to <str99->zBuf> if space available
if (0 < nn && str99->nUsed + nn <= str99->nAlloced) {
memcpy(str99->zBuf + str99->nUsed, zz, nn);
str99->nUsed += nn;
return errcode;
}
// else resize and retry
return str99AppendRawAfterGrow(str99, zz, nn, errcode);
}
static NOINLINE int str99AppendRawAfterGrow(
Str99 * str99,
const char *zz,
int nn,
int errcode
) {
/*
** Increase the size of the memory allocation for <str99->zBuf>.
*/
// declare var
int nAlloc;
// sanity check
if (!IS_SQLITE_OK(errcode)) {
return errcode;
}
// check SQLITE_MAX_LENGTH2
if (nn < 0 || str99->nUsed + nn > SQLITE_MAX_LENGTH2) {
return SQLITE_ERROR_TOOBIG2;
}
// grow str99 exponentially
nAlloc = str99->nAlloced;
while (nAlloc < str99->nUsed + nn) {
nAlloc *= 2;
}
if (nAlloc > str99->nAlloced) {
str99->zBuf = ALLOCR(str99->zBuf, nAlloc);
if (str99->zBuf == NULL) {
return SQLITE_ERROR_NOMEM2;
}
str99->nAlloced = nAlloc;
}
if (zz == NULL) {
return errcode;
}
// recurse
return str99AppendRaw(str99, zz, nn, errcode);
}
static int str99AppendJson(
Str99 * str99,
const char *zz,
int nn,
int errcode
) {
/*
** Append <nn> bytes of text from <zz> to <str99->zBuf> with json-encoding.
** Increase the size of the memory allocation for <str99->zBuf> if necessary.
*/
// declare var
const char *zz2 = zz + nn;
// double-quote open
STR99_APPEND_RAW("\"", 1);
while (zz < zz2) {
switch (*zz) {
case '\x00':
STR99_APPEND_RAW("\\u0000", 6);
break;
case '\x01':
STR99_APPEND_RAW("\\u0001", 6);
break;
case '\x02':
STR99_APPEND_RAW("\\u0002", 6);
break;
case '\x03':
STR99_APPEND_RAW("\\u0003", 6);
break;
case '\x04':
STR99_APPEND_RAW("\\u0004", 6);
break;
case '\x05':
STR99_APPEND_RAW("\\u0005", 6);
break;
case '\x06':
STR99_APPEND_RAW("\\u0006", 6);
break;
case '\x07':
STR99_APPEND_RAW("\\u0007", 6);
break;
case '\x08':
STR99_APPEND_CHAR('\\');
STR99_APPEND_CHAR('b');
break;
case '\x09':
STR99_APPEND_CHAR('\\');
STR99_APPEND_CHAR('t');
break;
case '\x0a':
STR99_APPEND_CHAR('\\');
STR99_APPEND_CHAR('n');
break;
case '\x0b':
STR99_APPEND_RAW("\\u000b", 6);
break;
case '\x0c':
STR99_APPEND_CHAR('\\');
STR99_APPEND_CHAR('f');
break;
case '\x0d':
STR99_APPEND_CHAR('\\');
STR99_APPEND_CHAR('r');
break;
case '\x0e':
STR99_APPEND_RAW("\\u000e", 6);
break;
case '\x0f':
STR99_APPEND_RAW("\\u000f", 6);
break;
case '\x10':
STR99_APPEND_RAW("\\u0010", 6);
break;
case '\x11':
STR99_APPEND_RAW("\\u0011", 6);
break;
case '\x12':
STR99_APPEND_RAW("\\u0012", 6);
break;
case '\x13':
STR99_APPEND_RAW("\\u0013", 6);
break;
case '\x14':
STR99_APPEND_RAW("\\u0014", 6);
break;
case '\x15':
STR99_APPEND_RAW("\\u0015", 6);
break;
case '\x16':
STR99_APPEND_RAW("\\u0016", 6);
break;
case '\x17':
STR99_APPEND_RAW("\\u0017", 6);
break;
case '\x18':
STR99_APPEND_RAW("\\u0018", 6);
break;
case '\x19':
STR99_APPEND_RAW("\\u0019", 6);
break;
case '\x1a':
STR99_APPEND_RAW("\\u001a", 6);
break;
case '\x1b':
STR99_APPEND_RAW("\\u001b", 6);
break;
case '\x1c':
STR99_APPEND_RAW("\\u001c", 6);
break;
case '\x1d':
STR99_APPEND_RAW("\\u001d", 6);
break;
case '\x22':
STR99_APPEND_CHAR('\\');
STR99_APPEND_CHAR('\"');
break;
case '\x5c':
STR99_APPEND_CHAR('\\');
STR99_APPEND_CHAR('\\');
break;
default:
STR99_APPEND_CHAR(*zz);
}
zz += 1;
}
// double-quote close
STR99_APPEND_RAW("\"", 1);
catch_error:
return errcode;
}
/*
file sqlmath_c_dbXxx
*/
SQLMATH_API int dbExec(
sqlite3 * db, /* The database on which the SQL executes */
Jsbaton * baton
) {
// This function will run <zSql> in <db> and save any result (list of tables
// containing rows from SELECT/pragma/etc) as serialized json-string in <str99>.
#define STR99_APPEND_CHAR2(cc) \
if (!responseType) { \
errcode = str99AppendChar(str99, cc, errcode); \
if (!IS_SQLITE_OK(errcode)) { goto catch_error; } \
}
// declare var
BindElem *bindElem;
BindElem *bindList = NULL;
Str99 *str99 = NULL;
Str99 str0 = { 0 };
const char **pzShared = baton->bufin + 6;
const char *zBind = baton->bufin[3];
const char *zSql = baton->bufin[1];
const char *zTmp = NULL;
double rTmp = 0;
int bindByKey = (int) baton->argint64[4];
int bindIdx = 0;
int bindListLength = (int) baton->argint64[2];
int errcode = 0;
int ii = 0;
int jj = 0;
int nCol = 0;
int nRow = 0;
int responseType = (int) baton->argint64[5];
int64_t *pnShared = baton->argint64 + 6;
int64_t iTmp = 0;
sqlite3_stmt *pStmt = NULL; /* The current SQL statement */
static const char bindPrefix[] = "$:@";
// printf("\n[errcode=%d, sql=%s]\n", errcode, zSql);
// mutext enter
sqlite3_mutex_enter(sqlite3_db_mutex(db));
// init bindList
bindList = ALLOCC(bindListLength, sizeof(BindElem));
if (bindListLength > 0 && bindList == NULL) {
errcode = SQLITE_ERROR_NOMEM2;
ASSERT_SQLITE_OK(baton, db, errcode);
}
bindElem = bindList;
ii = 1;
while (ii <= bindListLength) {
// init key and
if (bindByKey) {
zBind += 1;
bindElem->key = (char *) zBind + 8;
zBind += 8 + *(int *) zBind;
}
// init datatype
bindElem->datatype = zBind[0];
zBind += 1;
switch (bindElem->datatype) {
case SQLITE_DATATYPE_BLOB:
case SQLITE_DATATYPE_TEXT:
bindElem->buflen = *(int *) zBind;
bindElem->buf = zBind + 8;
zBind += 8 + bindElem->buflen;
break;
case SQLITE_DATATYPE_FLOAT:
case SQLITE_DATATYPE_INTEGER:
bindElem->buf = zBind;
zBind += 8;
break;
case SQLITE_DATATYPE_INTEGER_0:
case SQLITE_DATATYPE_INTEGER_1:
case SQLITE_DATATYPE_NULL:
case SQLITE_DATATYPE_TEXT_0:
break;
case SQLITE_DATATYPE_SHAREDARRAYBUFFER:
bindElem->buflen = *(int *) pnShared;
bindElem->buf = *pzShared;
pnShared += 1;
pzShared += 1;
break;
default:
printf("\n[ii=%d, datatype=%d, len=%d]\n", ii, bindElem->datatype,
bindElem->buflen);
errcode = SQLITE_ERROR_DATATYPE_INVALID;
ASSERT_SQLITE_OK(baton, db, errcode);
}
bindElem += 1;
ii += 1;
}
// init str99
str99 = &str0;
// will be cleaned up by jsbatonBufferFinalize()
str99->zBuf = ALLOCM(SIZEOF_MESSAGE_DEFAULT);
if (str99->zBuf == NULL) {
errcode = SQLITE_ERROR_NOMEM2;
ASSERT_SQLITE_OK(baton, db, errcode);
}
str99->nAlloced = SIZEOF_MESSAGE_DEFAULT;
// bracket database [
STR99_APPEND_CHAR2('[');
// loop over each table
while (1) {
// ignore whitespace
while (*zSql == ' ' || *zSql == '\t' || *zSql == '\n'
|| *zSql == '\r') {
zSql += 1;
}
// printf("\n[prepare=%s]\n", zSql);
errcode = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zTmp);
if (errcode != 0 || *zSql == '\x00') {
break;
}
zSql = zTmp;
// bind bindList to pStmt
bindElem = bindList;
ii = 1;
while (ii <= bindListLength) {
bindIdx = ii;
jj = 0;
while (jj < 3) {
// if bindByKey, then get idx for given key
if (bindByKey) {
bindElem->key[0] = bindPrefix[jj];
bindIdx =
sqlite3_bind_parameter_index(pStmt, bindElem->key);
}
// printf("\n[errcode=%d, ii=%d, idx=%d, key=%s, datatype=%d,"
// " len=%d]\n", errcode, ii, bindIdx, bindElem->key,
// bindElem->datatype, bindElem->buflen);
if (bindIdx > 0) {
switch (bindElem->datatype) {
case SQLITE_DATATYPE_BLOB:
errcode =
sqlite3_bind_blob(pStmt, bindIdx, bindElem->buf,
bindElem->buflen, SQLITE_TRANSIENT);
break;
case SQLITE_DATATYPE_FLOAT:
errcode =
sqlite3_bind_double(pStmt, bindIdx,
*(double *) bindElem->buf);
break;
case SQLITE_DATATYPE_INTEGER:
errcode =
sqlite3_bind_int64(pStmt, bindIdx,
*(int64_t *) bindElem->buf);
break;
case SQLITE_DATATYPE_INTEGER_0:
errcode = sqlite3_bind_int(pStmt, bindIdx, 0);
break;
case SQLITE_DATATYPE_INTEGER_1:
errcode = sqlite3_bind_int(pStmt, bindIdx, 1);
break;
case SQLITE_DATATYPE_NULL:
errcode = sqlite3_bind_null(pStmt, bindIdx);
break;
case SQLITE_DATATYPE_SHAREDARRAYBUFFER:
errcode =
sqlite3_bind_blob(pStmt, bindIdx, bindElem->buf,
bindElem->buflen, SQLITE_STATIC);
break;
case SQLITE_DATATYPE_TEXT_0:
errcode =
sqlite3_bind_text(pStmt, bindIdx, "", 0,
SQLITE_STATIC);
break;
case SQLITE_DATATYPE_TEXT:
errcode =
sqlite3_bind_text(pStmt, bindIdx, bindElem->buf,
bindElem->buflen, SQLITE_TRANSIENT);
break;
default:
printf("\n[ii=%d, datatype=%d, len=%d]\n", ii,
bindElem->datatype, bindElem->buflen);
errcode = SQLITE_ERROR_DATATYPE_INVALID;
}
// ignore bind-range-error
if (errcode != SQLITE_RANGE) {
ASSERT_SQLITE_OK(baton, db, errcode);
}
}
if (!bindByKey) {
break;
}
jj += 1;
}
bindElem += 1;
ii += 1;
}
nCol = -1;
// loop over each row
while (1) {
errcode = sqlite3_step(pStmt);
if (errcode != SQLITE_ROW) {
sqlite3_finalize(pStmt);
pStmt = NULL;
if (errcode == SQLITE_DONE || errcode == SQLITE_OK) {
break;
}
// printf("\n[errcode=%d, line=%d]\n", errcode, __LINE__);
goto catch_error;
}
// insert row of column-names
if (nCol == -1) {
nRow = 0;
if (str99->nUsed > 1) {
STR99_APPEND_CHAR2(',');
STR99_APPEND_CHAR2('\n');
STR99_APPEND_CHAR2('\n');
}
// bracket table [
STR99_APPEND_CHAR2('[');
// bracket column [
STR99_APPEND_CHAR2('[');
// loop over each column-name
nCol = sqlite3_column_count(pStmt);
// SQLITE_RESPONSETYPE_LAST_MATRIX_DOUBLE - save nCol
if (responseType == SQLITE_RESPONSETYPE_LAST_MATRIX_DOUBLE) {
str99->nUsed = 8;
STR99_APPEND_DOUBLE((double) nCol);
} else {
ii = 0;
while (ii < nCol) {
if (ii > 0) {
STR99_APPEND_CHAR2(',');
}
zTmp = sqlite3_column_name(pStmt, ii);
STR99_APPEND_JSON(zTmp, strlen(zTmp));
ii += 1;
}
// bracket column ]
STR99_APPEND_CHAR2(']');
}
}
// bracket row [
STR99_APPEND_CHAR2(',');
STR99_APPEND_CHAR2('\n');
STR99_APPEND_CHAR2('[');
ii = 0;
nRow += 1;
// loop over each column-value
while (ii < nCol) {
switch (responseType) {
case SQLITE_RESPONSETYPE_LAST_VALUE:
// export last-value as blob
str99->nUsed = 0;
errcode =
str99AppendRaw(str99, sqlite3_column_blob(pStmt, ii),
sqlite3_column_bytes(pStmt, ii), errcode);
if (!IS_SQLITE_OK(errcode)) {
// printf("\n[errcode=%d, line=%d]\n", errcode,
// __LINE__);
goto catch_error;
}
ii += 1;
continue;
case SQLITE_RESPONSETYPE_LAST_MATRIX_DOUBLE:
// export last-table as matrix of doubles
STR99_APPEND_DOUBLE(sqlite3_column_double(pStmt, ii));
ii += 1;
continue;
}
if (ii > 0) {
STR99_APPEND_CHAR2(',');
}
switch (sqlite3_column_type(pStmt, ii)) {
case SQLITE_INTEGER:
iTmp = sqlite3_column_int64(pStmt, ii);
if (JS_MIN_SAFE_INTEGER <= iTmp
// convert integer to double
&& iTmp <= JS_MAX_SAFE_INTEGER) {
STR99_APPEND_RAW((const char *)
sqlite3_column_text(pStmt, ii),
sqlite3_column_bytes(pStmt, ii));
} else {
// convert integer to string
STR99_APPEND_JSON((const char *)
sqlite3_column_text(pStmt, ii),
sqlite3_column_bytes(pStmt, ii));
}
break;
case SQLITE_FLOAT:
rTmp = sqlite3_column_double(pStmt, ii);
if (isnan(rTmp) || rTmp == -INFINITY || rTmp == INFINITY) {
STR99_APPEND_RAW("null", 4);
} else {
STR99_APPEND_RAW((const char *)
sqlite3_column_text(pStmt, ii),
sqlite3_column_bytes(pStmt, ii));
}
break;
case SQLITE_TEXT:
// append text as json-escaped string
STR99_APPEND_JSON((const char *)
sqlite3_column_text(pStmt, ii),
sqlite3_column_bytes(pStmt, ii));
break;
// case SQLITE_BLOB:
default: /* case SQLITE_NULL: */
STR99_APPEND_RAW("null", 4);
break;
}
ii += 1;
}
// bracket row ]
STR99_APPEND_CHAR2(']');
if (errcode != SQLITE_ROW) {
break;
}
}
if (nCol != -1) {
// bracket table ]
STR99_APPEND_CHAR2(']');
}
}
// bracket database ]
STR99_APPEND_CHAR2(']');
STR99_APPEND_CHAR2('\n');
// SQLITE_RESPONSETYPE_LAST_MATRIX_DOUBLE - save nRow
if (responseType == SQLITE_RESPONSETYPE_LAST_MATRIX_DOUBLE) {
((double *) str99->zBuf)[0] = nRow;
}
// shrink str99
str99->nAlloced = str99->nUsed;
str99->zBuf = (char *) ALLOCR(str99->zBuf, MAX(str99->nAlloced, 1));
if (str99->zBuf == NULL) {
errcode = SQLITE_ERROR_NOMEM2;
ASSERT_SQLITE_OK(baton, db, errcode);
}
catch_error:
// cleanup bindList
ALLOCF(bindList);
// cleanup pStmt
sqlite3_finalize(pStmt);
// handle errcode
if (errcode != 0) {
// cleanup str99
ALLOCF(str99->zBuf);
assertSqliteOk(baton, db, errcode, __func__, __FILE__, __LINE__);
// printf("\n[errcode=%d, errmsg=%s]\n", errcode, baton->errmsg);
// mutext leave
sqlite3_mutex_leave(sqlite3_db_mutex(db));
return errcode;
}
// save str99
baton->argint64[0] = (int64_t) str99->nAlloced;
baton->bufout[0] = str99->zBuf;
// mutext leave
sqlite3_mutex_leave(sqlite3_db_mutex(db));
return 0;
}
SQLMATH_API int dbTableInsert(
sqlite3 * db, /* The database on which the SQL executes */
Jsbaton * baton
) {
// This function will run <zSql> in <db> and save any result (list of tables
// containing rows from SELECT/pragma/etc) as serialized json-string in <str99>.
// declare var
const char *pp = baton->bufin[3];
const char *zTmp = NULL;
char datatype = 0;
int bTxn = 0;
int errcode = 0;
int ii = 0;
int jj = 0;
int nCol = (int) baton->argint64[4];
int nLen = 0;
int nRow = (int) baton->argint64[5];
sqlite3_stmt *pStmt = NULL;
// mutext enter
sqlite3_mutex_enter(sqlite3_db_mutex(db));
// create temp table
ASSERT_SQLITE_EXEC(baton, db, baton->bufin[1], errcode);
// begin transaction
ASSERT_SQLITE_EXEC(baton, db, "BEGIN TRANSACTION;", errcode);
bTxn = 1;
// init pStmt
errcode = sqlite3_prepare_v2(db, baton->bufin[2], -1, &pStmt, &zTmp);
// printf("\n[errcode=%d, nCol=%d, nRow=%d]\n", errcode, nCol, nRow);
while (ii < nRow) {
jj = 1;
// type - js
// 1. bigint
// 2. boolean
// 3. null
// 4. number
// 5. object
// 6. string
// 7. symbol
// 8. undefined
while (jj <= nCol) {
datatype = pp[0];
pp += 1;
switch (datatype) {
case SQLITE_DATATYPE_BLOB:
nLen = *(int *) pp;
errcode = sqlite3_bind_blob(pStmt, jj, pp + 8, nLen,
SQLITE_TRANSIENT);
ASSERT_SQLITE_OK(baton, db, errcode);
pp += 8 + nLen;
break;
case SQLITE_DATATYPE_FLOAT:
errcode = sqlite3_bind_double(pStmt, jj, *(double *) pp);
ASSERT_SQLITE_OK(baton, db, errcode);
pp += 8;
break;
case SQLITE_DATATYPE_INTEGER:
errcode = sqlite3_bind_int64(pStmt, jj, *(int64_t *) pp);
ASSERT_SQLITE_OK(baton, db, errcode);
pp += 8;
break;
case SQLITE_DATATYPE_INTEGER_0:
errcode = sqlite3_bind_int(pStmt, jj, 0);
ASSERT_SQLITE_OK(baton, db, errcode);
break;
case SQLITE_DATATYPE_INTEGER_1:
errcode = sqlite3_bind_int(pStmt, jj, 1);
ASSERT_SQLITE_OK(baton, db, errcode);
break;
case SQLITE_DATATYPE_NULL:
errcode = sqlite3_bind_null(pStmt, jj);
ASSERT_SQLITE_OK(baton, db, errcode);
break;
case SQLITE_DATATYPE_TEXT_0:
errcode = sqlite3_bind_text(pStmt, jj, "", 0, SQLITE_STATIC);
ASSERT_SQLITE_OK(baton, db, errcode);
break;
case SQLITE_DATATYPE_TEXT:
nLen = *(int *) pp;
errcode = sqlite3_bind_text(pStmt, jj, pp + 8, nLen,
SQLITE_TRANSIENT);
ASSERT_SQLITE_OK(baton, db, errcode);
pp += 8 + nLen;
break;