forked from sqlmath/sqlmath
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlmath_base.c
More file actions
5268 lines (4969 loc) · 162 KB
/
sqlmath_base.c
File metadata and controls
5268 lines (4969 loc) · 162 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
// MIT License
//
// Copyright (c) 2021 Kai Zhu
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// LINT_C_FILE
#if !defined(SRC_SQLMATH_H2)
#define SRC_SQLMATH_H2
/*
file sqlmath_h - start
*/
#define NAPI_VERSION 6
#if defined(SRC_SQLITE_BASE_C2)
# undef SRC_SQLITE_BASE_C2
#endif // SRC_SQLITE_BASE_C2
#if defined(_WIN32)
# include <windows.h>
#else
# include <dlfcn.h>
# include <unistd.h>
# include <zlib.h>
#endif // _WIN32
#include <assert.h>
#include <float.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sqlmath_external_sqlite.c"
#include "./sqlmath_base.h"
/*
** A macro to hint to the compiler that a function should not be
** inlined.
*/
#if defined(__GNUC__)
# define SQLITE_NOINLINE __attribute__((noinline))
#elif defined(_MSC_VER) && _MSC_VER >= 1310
# define SQLITE_NOINLINE __declspec(noinline)
#else
# define SQLITE_NOINLINE
#endif // defined(__GNUC__)
#define JSBATON_ARGC 8
#define JSBATON_OFFSET_ALL 256
#define JSBATON_OFFSET_ARGV 128
#define JSBATON_OFFSET_BUFV 192
#define JSBATON_OFFSET_ERRMSG 48
#define JSBATON_OFFSET_FUNCNAME 8
#define JS_MAX_SAFE_INTEGER 0x1fffffffffffffLL
#define JS_MIN_SAFE_INTEGER -0x1fffffffffffffLL
#define SIZEOF_BLOB_MAX 1000000000
#define SIZEOF_ERRMSG 80
#define SIZEOF_FUNCNAME 16
#define SQLITE_DATATYPE_BLOB 0x04
#define SQLITE_DATATYPE_EXTERNALBUFFER 0x71
#define SQLITE_DATATYPE_FLOAT 0x02
#define SQLITE_DATATYPE_INTEGER 0x01
#define SQLITE_DATATYPE_INTEGER_0 0x00
#define SQLITE_DATATYPE_INTEGER_1 0x21
#define SQLITE_DATATYPE_NULL 0x05
#define SQLITE_DATATYPE_TEXT 0x03
#define SQLITE_DATATYPE_TEXT_0 0x13
#define SQLITE_RESPONSETYPE_LASTBLOB 1
#define SQLITE_RESPONSETYPE_LASTVALUE 2
#define LGBM_EVAL_BUF_LEN_MAX 16
#define LGBM_EVAL_OUT_LEN_MAX 8
#define LGBM_MODE_TRAIN 1
#define LGBM_PARAM_BUF_LEN_MAX 1024
#define MATH_MAX(aa, bb) (((aa) < (bb)) ? (bb) : (aa))
#define MATH_MIN(aa, bb) (((aa) > (bb)) ? (bb) : (aa))
#define MATH_PI 3.141592653589793238463
#define MATH_SIGN(aa) (((aa) < 0) ? -1 : ((aa) > 0) ? 1 : 0)
#define SQLITE_COLUMNTYPE_INTEGER_BIG 11
#define SQLITE_COLUMNTYPE_TEXT_BIG 13
#define SQLITE_ERROR_DATATYPE_INVALID 0x10003
#define SQLITE_ERROR_JSON_ARRAY_INVALID 0x71
#define SQLITE_ERROR_ZSQL_NULL 0x10004
#define SQLMATH_API
#define SQLMATH_FUNC
#define UNUSED_PARAMETER(x) ((void)(x))
#if !defined(SQLITE_MAX_FUNCTION_ARG)
# define SQLITE_MAX_FUNCTION_ARG 1000
#endif // SQLITE_MAX_FUNCTION_ARG
#define DOUBLEWIN_AGGREGATE_CONTEXT(nhead) \
Doublewin **dblwinAgg = (Doublewin **) \
sqlite3_aggregate_context(context, sizeof(*dblwinAgg)); \
if (doublewinAggmalloc(dblwinAgg, nhead) != SQLITE_OK) { \
sqlite3_result_error_nomem(context); \
return; \
} \
Doublewin *dblwin = *dblwinAgg; \
double *dblwin_body = doublewinBody(dblwin); \
double *dblwin_head = doublewinHead(dblwin); \
UNUSED_PARAMETER(dblwin_body); \
UNUSED_PARAMETER(dblwin_head);
#define DOUBLEWIN_AGGREGATE_PUSH(xx) \
if (doublewinAggpush(dblwinAgg, xx) != SQLITE_OK) { \
sqlite3_result_error_nomem(context); \
return; \
} \
dblwin = *dblwinAgg; \
dblwin_body = doublewinBody(dblwin); \
dblwin_head = doublewinHead(dblwin);
// This function will exec <sql> and if <errcode> is not ok,
// throw <baton>->errmsg with given sqlite-<errcode>.
#define JSBATON_ASSERT_OK() \
if (jsbatonAssertOk(baton, db, errcode)) { \
goto catch_error; \
}
#define JSBATON_DEBUG(header, baton) \
fprintf(stderr, "\n#### " header " p=%p p=%p s=%s\n", baton, \
(char *) (baton)->bufv[0].buf, \
(char *) (baton)->bufv[0].buf);
#define LGBM_ASSERT_OK() \
if (errcode) { \
sqlite3_result_error(context, LGBM_GetLastError(), -1); \
goto catch_error; \
}
// This function will if <cond> is falsy, terminate process with <msg>.
#define NAPI_ASSERT_FATAL(cond, msg) \
if (!(cond)) { \
napi_fatal_error(__func__, NAPI_AUTO_LENGTH , msg, NAPI_AUTO_LENGTH); \
}
// This function will assert <errcode> == napi_ok in <env>.
#define NAPI_ASSERT_OK() \
if (0 != napiAssertOk(env, __func__, __FILE__, __LINE__, errcode)) { \
return NULL; \
}
#define NAPI_PARSE_ARGV(funcname, argc0) \
Jsbaton *baton = NULL; \
int errcode = 0; \
napi_value argv[argc0] = { 0 }; \
size_t argc = argc0; \
errcode = napi_get_cb_info(env, info, &argc, argv, NULL, NULL); \
NAPI_ASSERT_OK(); \
if (argc != argc0) { \
napi_throw_error(env, NULL, \
"sqlmath._" #funcname " - expected " #argc0 " arguments"); \
return NULL; \
} \
errcode = \
napi_get_arraybuffer_info(env, argv[0], (void **) &baton, &argc); \
NAPI_ASSERT_OK();
#define NAPI_CREATE_FUNCTION(func) \
{"_" #func, NULL, func, NULL, NULL, NULL, napi_default, NULL}
#define PY_ARG_PARSE(bufc, ...) \
Jsbaton *baton = NULL; \
Py_buffer pybuf[bufc] = { 0 }; \
if (!PyArg_ParseTuple(__VA_ARGS__)) { \
return NULL; \
} \
baton = pybuf->buf; \
PyBuffer_Release(pybuf);
#define SQLITE3_AGGREGATE_CONTEXT(type) \
type *agg = (type *) sqlite3_aggregate_context(context, sizeof(*agg)); \
if (agg == NULL) { \
sqlite3_result_error_nomem(context); \
return; \
}
#define SQLITE_OK_OR_RETURN_RC(rc) \
if (rc != SQLITE_OK) { \
return rc; \
}
#define SQL_CREATE_FUNC1(func, argc, flag) \
errcode = sqlite3_create_function(db, #func, argc, \
flag | SQLITE_DIRECTONLY | SQLITE_UTF8, NULL, \
sql1_##func##_func, NULL, NULL); \
if (errcode) { \
return errcode; \
}
#define SQL_CREATE_FUNC2(func, argc, flag) \
errcode = sqlite3_create_function(db, #func, argc, \
flag | SQLITE_DIRECTONLY | SQLITE_UTF8, NULL, \
NULL, sql2_##func##_step, sql2_##func##_final); \
if (errcode) { \
return errcode; \
}
#define SQL_CREATE_FUNC3(func, argc, flag) \
errcode = sqlite3_create_window_function(db, #func, argc, \
flag | SQLITE_DIRECTONLY | SQLITE_UTF8, NULL, \
sql3_##func##_step, sql3_##func##_final, \
sql3_##func##_value, sql3_##func##_inverse, NULL); \
if (errcode) { \
return errcode; \
}
#define STR99_ALLOCA(str99) \
sqlite3_str __##str99 = { 0 }; \
sqlite3_str *str99 = &__##str99; \
str99->mxAlloc = SIZEOF_BLOB_MAX; \
#define STR99_RESULT_ERROR(str99) \
errcode = sqlite3_str_errcode(str99); \
if (errcode == SQLITE_ERROR_JSON_ARRAY_INVALID) { \
sqlite3_str_reset(str99); \
sqlite3_result_error(context, \
"str99ArrayAppendJsonarray - invalid JSON array", -1); \
goto catch_error; \
} \
if (errcode) { \
sqlite3_str_reset(str99); \
sqlite3_result_error_code(context, errcode); \
goto catch_error; \
} \
if (sqlite3_str_length(str99) <= 0) { \
sqlite3_str_reset(str99); \
goto catch_error; \
}
// file sqlmath_h - sqlite3
// *INDENT-OFF*
typedef uint32_t u32;
typedef uint64_t u64;
typedef uint8_t u8;
// file sqlmath_h - db
typedef struct Jsbuffer {
int64_t buf;
int64_t len;
} Jsbuffer;
typedef struct Jsbaton {
int32_t nallc; // offset 000-004
int32_t nused; // offset 004-008
char funcname[SIZEOF_FUNCNAME]; // offset 008-024
int64_t napi_argv; // offset 024-032
int64_t napi_deferred; // offset 032-040
int64_t napi_work; // offset 040-048
char errmsg[SIZEOF_ERRMSG]; // offset 048-128
int64_t argv[JSBATON_ARGC]; // offset 128-192
Jsbuffer bufv[JSBATON_ARGC]; // offset 192-320
} Jsbaton;
SQLMATH_API void dbCall(
Jsbaton * baton
);
SQLMATH_API void dbClose(
Jsbaton * baton
);
SQLMATH_API int dbDlopen(
sqlite3_context * context,
const char *filename,
void **library
);
SQLMATH_API void dbExec(
Jsbaton * baton
);
SQLMATH_API void dbFileLoad(
Jsbaton * baton
);
SQLMATH_API int dbFileLoadOrSave(
sqlite3 * pInMemory,
const char *zFilename,
const int isSave
);
SQLMATH_API void dbNoop(
Jsbaton * baton
);
SQLMATH_API void dbOpen(
Jsbaton * baton
);
// file sqlmath_h - doublewin
typedef struct Doublewin {
double alloc; // allocated size in bytes
double nbody; // number of body elements
double nhead; // number of head elements
//
double ncol; // number of columns
double waa; // window-position-left
double wnn; // window-mode
} Doublewin;
SQLMATH_API void doublewinAggfree(
Doublewin ** dblwinAgg
);
SQLMATH_API int doublewinAggmalloc(
Doublewin ** dblwinAgg,
const int nhead
);
SQLMATH_API int doublewinAggpush(
Doublewin ** dblwinAgg,
const double xx
);
SQLMATH_API double *doublewinBody(
const Doublewin * dblwin
);
SQLMATH_API double *doublewinHead(
const Doublewin * dblwin
);
SQLMATH_API void doublewinResultBlob(
Doublewin * dblwin,
sqlite3_context * context
);
// file sqlmath_h - idate
#define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
#define SQLITE_FUNC_SLOCHNG 0x2000 // "Slow Change". Value constant during a
// single query - might change over time
#define SQLITE_FUNC_IDATE \
(SQLITE_FUNC_SLOCHNG | SQLITE_UTF8 | SQLITE_FUNC_CONSTANT)
#define SQL1_IDATE_FUNC(func, typeFrom, typeTo) \
sql1_##func##_func( \
sqlite3_context * context, \
int argc, \
sqlite3_value ** argv \
) { \
sql1_idatefromto_func0(context, argc, argv, typeFrom, typeTo); \
}
/*
** A structure for holding a single date and time.
*/
typedef struct DateTime {
sqlite3_int64 iJD; /* The julian day number times 86400000 */
int Y, M, D; /* Year, month, and day */
int h, m; /* Hour and minutes */
int tz; /* Timezone offset in minutes */
double s; /* Seconds */
char validJD; /* True (1) if iJD is valid */
char validYMD; /* True (1) if Y,M,D are valid */
char validHMS; /* True (1) if h,m,s are valid */
char nFloor; /* Days to implement "floor" */
unsigned rawS : 1; /* Raw numeric value stored in s */
unsigned isError : 1; /* An overflow has occurred */
unsigned useSubsec : 1; /* Display subsecond precision */
unsigned isUtc : 1; /* Time is known to be UTC */
unsigned isLocal : 1; /* Time is known to be localtime */
} DateTime;
SQLITE_API int sqlite3_isDate2(
sqlite3_context * context,
const int argc,
sqlite3_value ** argv,
DateTime * dt,
const int typeFrom
);
// file sqlmath_h - str99
/*
** An objected used to accumulate the text of a string where we
** do not necessarily know how big the string will be in the end.
*/
struct sqlite3_str {
sqlite3 *db; /* Optional database for lookaside. Can be NULL */
char *zText; /* The string collected so far */
u32 nAlloc; /* Amount of space allocated in zText */
u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
u32 nChar; /* Length of the string so far */
u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */
u8 printfFlags; /* SQLITE_PRINTF flags below */
};
// *INDENT-ON*
SQLITE_API void str99JsonAppendText(
sqlite3_str * str99,
const char *zIn,
u32 nn
);
SQLMATH_API void str99ArrayAppendDouble(
sqlite3_str * str99,
const double xx
);
SQLMATH_API void str99ArrayAppendJsonarray(
sqlite3_str * str99,
const char *json,
int nn
);
SQLMATH_API void str99ResultBlob(
sqlite3_str * str99,
sqlite3_context * context
);
SQLMATH_API void str99ResultText(
sqlite3_str * str99,
sqlite3_context * context
);
// file sqlmath_h - SQLMATH_API
SQLMATH_API double doubleAbs(
const double aa
);
SQLMATH_API double doubleMax(
const double aa,
const double bb
);
SQLMATH_API double doubleMin(
const double aa,
const double bb
);
SQLMATH_API int doubleSign(
const double aa
);
SQLMATH_API int doubleSortCompare(
const void *aa,
const void *bb
);
SQLMATH_API void doublearrayResult(
sqlite3_context * context,
const double *arr,
const int nn,
void (*xDel) (void *) // NOLINT
);
SQLMATH_API int jsbatonAssertOk(
Jsbaton * baton,
sqlite3 * db,
int errcode
);
SQLMATH_API char *jsbatonGetErrmsg(
Jsbaton * baton
);
SQLMATH_API int64_t jsbatonGetInt64(
Jsbaton * baton,
int argi
);
SQLMATH_API char *jsbatonGetString(
Jsbaton * baton,
int argi
);
SQLMATH_API void jsbatonSetErrmsg(
Jsbaton * baton,
const char *format,
...
);
SQLMATH_API void jsonResultDoublearray(
sqlite3_context * context,
const double *arr,
int nn
);
SQLMATH_API int noop(
);
SQLMATH_API double quantile(
double *arr,
const int nn,
const double pp
);
SQLMATH_API void sqlite3_result_double_or_null(
sqlite3_context * context,
const double xx
);
SQLMATH_API void sqlite3_result_error2(
sqlite3_context * context,
const char *template,
... // NOLINT
);
SQLMATH_API double sqlite3_value_double_or_nan(
sqlite3_value * arg
);
SQLMATH_API double sqlite3_value_double_or_prev(
sqlite3_value * arg,
double *previous
);
/*
file sqlmath_h - end
*/
/*
file sqlmath_base - start
*/
#if defined(SRC_SQLMATH_BASE_C2)
// track how many sqlite-db open
static int dbCount = 0;
// file sqlmath_base - SQLMATH_API
// SQLMATH_API db - start
SQLMATH_API void dbCall(
Jsbaton * baton
) {
// This function will call c-function dbXxx() with given <funcname>.
char *funcname = (char *) baton + JSBATON_OFFSET_FUNCNAME;
if (strcmp(funcname, "_dbClose") == 0) {
dbClose(baton);
} else if (strcmp(funcname, "_dbExec") == 0) {
dbExec(baton);
} else if (strcmp(funcname, "_dbFileLoad") == 0) {
dbFileLoad(baton);
} else if (strcmp(funcname, "_dbNoop") == 0) {
dbNoop(baton);
} else if (strcmp(funcname, "_dbOpen") == 0) {
dbOpen(baton);
} else {
jsbatonSetErrmsg(baton, "sqlmath._dbCall - invalid funcname '%s'",
funcname);
}
}
SQLMATH_API void dbClose(
Jsbaton * baton
) {
// int sqlite3_close_v2(sqlite3*);
// declare var
int errcode = 0;
sqlite3 *db = (sqlite3 *) baton->argv[0];
// call c-function
errcode = sqlite3_close_v2(db);
JSBATON_ASSERT_OK();
if (db != NULL) {
dbCount -= 1;
}
catch_error:
(void) 0;
}
SQLMATH_API int dbDlopen(
sqlite3_context * context,
const char *filename,
void **library
) {
// This function will set <library> = dlopen(<filename>).
static const intptr_t isBusy = 1;
for (int ii = 0; *library == (void *) isBusy && ii < 100; ii += 1) {
#if defined(_WIN32)
Sleep(100);
#else
sleep(100);
#endif // _WIN32
}
if (*library == (void *) isBusy) {
*library = (void *) 0;
sqlite3_result_error2(context, "dbDlopen - dlopen(\"%s\") timeout",
filename);
return SQLITE_BUSY;
}
if (*library > (void *) isBusy) {
return 0;
}
*library = (void *) isBusy;
#if defined(_WIN32)
*library = (void *) LoadLibrary(filename);
if (*library == NULL) {
sqlite3_result_error2(context,
"dbDlopen - LoadLibrary(\"%s\") failed with code=%lu", filename,
GetLastError());
return SQLITE_ERROR;
}
#else
*library = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
if (*library == NULL) {
// fprintf(stderr, "%s", dlerror());
sqlite3_result_error2(context, "dbDlopen - dlopen(\"%s\") - %s",
filename, dlerror());
return SQLITE_ERROR;
}
#endif // _WIN32
return 0;
}
// SQLMATH_API dbExec - start
typedef struct DbExecBindElem {
const char *buf;
char *key;
int buflen;
char datatype;
} DbExecBindElem;
static inline void dbExecStr99AppendValue(
sqlite3_str * str99,
sqlite3_stmt * pStmt,
int ii
) {
// This function will append json-value to <str99> from <pStmt> at column <ii>.
double valDouble = 0;
int64_t valInt64 = 0;
switch (sqlite3_column_type(pStmt, ii)) {
case SQLITE_INTEGER:
valInt64 = sqlite3_column_int64(pStmt, ii);
if (JS_MIN_SAFE_INTEGER <= valInt64
// convert integer to double
&& valInt64 <= JS_MAX_SAFE_INTEGER) {
sqlite3_str_append(str99,
(char *) sqlite3_column_text(pStmt, ii),
sqlite3_column_bytes(pStmt, ii));
} else {
// convert integer to string
str99JsonAppendText(str99,
(char *) sqlite3_column_text(pStmt, ii),
sqlite3_column_bytes(pStmt, ii));
}
break;
case SQLITE_FLOAT:
valDouble = sqlite3_column_double(pStmt, ii);
if (!isfinite(valDouble)) {
sqlite3_str_append(str99, "null", 4);
} else {
sqlite3_str_append(str99,
(char *) sqlite3_column_text(pStmt, ii),
sqlite3_column_bytes(pStmt, ii));
}
break;
case SQLITE_TEXT:
// append text as json-escaped string
str99JsonAppendText(str99,
(char *) sqlite3_column_text(pStmt, ii),
sqlite3_column_bytes(pStmt, ii));
break;
// case SQLITE_BLOB:
default: /* case SQLITE_NULL: */
sqlite3_str_append(str99, "null", 4);
break;
}
}
SQLMATH_API void dbExec(
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
DbExecBindElem *bindElem = NULL;
DbExecBindElem *bindList = NULL;
const char *zBind = (char *) baton + JSBATON_OFFSET_ALL;
const char *zSql = jsbatonGetString(baton, 1);
const char *zTmp = NULL;
int bindByKey = (int) baton->argv[3];
int bindIdx = 0;
int bindListLength = (int) baton->argv[2];
int errcode = 0;
int ii = 0;
int jj = 0;
int nCol = 0;
int responseType = (int) baton->argv[4];
sqlite3 *db = (sqlite3 *) baton->argv[0];
sqlite3_stmt *pStmt = NULL; /* The current SQL statement */
static const char bindPrefix[] = "$:@";
// str99 - init
STR99_ALLOCA(str99);
// fprintf(stderr, "\nsqlmath._dbExec(db=%p blen=%d sql=%s)\n",
// db, bindListLength, zSql);
#if !defined(__EMSCRIPTEN__)
// mutex enter
sqlite3_mutex_enter(sqlite3_db_mutex(db));
#endif // __EMSCRIPTEN__
if (zSql == NULL) {
errcode = SQLITE_ERROR_ZSQL_NULL;
JSBATON_ASSERT_OK();
}
// init bindList
bindList =
(DbExecBindElem *) sqlite3_malloc(bindListLength *
sizeof(DbExecBindElem));
memset(bindList, 0, bindListLength * sizeof(DbExecBindElem));
if (bindListLength > 0 && bindList == NULL) {
errcode = SQLITE_NOMEM;
JSBATON_ASSERT_OK()
}
bindElem = bindList;
ii = 1;
while (ii <= bindListLength) {
// init key and
if (bindByKey) {
zBind += 1;
bindElem->key = (char *) zBind + 4;
zBind += 4 + *(int32_t *) zBind;
}
// init datatype
bindElem->datatype = zBind[0];
zBind += 1;
switch (bindElem->datatype) {
case SQLITE_DATATYPE_BLOB:
case SQLITE_DATATYPE_TEXT:
bindElem->buflen = *(int32_t *) zBind;
bindElem->buf = zBind + 4;
zBind += 4 + bindElem->buflen;
break;
case SQLITE_DATATYPE_EXTERNALBUFFER:
bindElem->buflen = (int) baton->bufv[*(int32_t *) zBind].len;
bindElem->buf = (char *) baton->bufv[*(int32_t *) zBind].buf;
zBind += 4;
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;
default:
fprintf(stderr, "\nsqlmath._dbExec(ii=%d datatype=%d len=%d)\n",
ii, bindElem->datatype, bindElem->buflen);
errcode = SQLITE_ERROR_DATATYPE_INVALID;
JSBATON_ASSERT_OK();
}
bindElem += 1;
ii += 1;
}
// bracket database [
switch (responseType) {
case SQLITE_RESPONSETYPE_LASTBLOB:
case SQLITE_RESPONSETYPE_LASTVALUE:
break;
default:
sqlite3_str_appendchar(str99, 1, '[');
}
// loop over each table - start
while (1) {
// ignore whitespace
while (*zSql == ' ' || *zSql == '\t' || *zSql == '\n'
|| *zSql == '\r') {
zSql += 1;
}
errcode = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zTmp);
JSBATON_ASSERT_OK();
if (errcode || *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);
}
if (bindIdx > 0) {
switch (bindElem->datatype) {
case SQLITE_DATATYPE_BLOB:
case SQLITE_DATATYPE_EXTERNALBUFFER:
errcode =
sqlite3_bind_blob(pStmt, bindIdx, bindElem->buf,
bindElem->buflen, SQLITE_STATIC);
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_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_STATIC);
break;
default:
fprintf(stderr,
"\nsqlmath._dbExec(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) {
JSBATON_ASSERT_OK();
}
}
if (!bindByKey) {
break;
}
jj += 1;
}
bindElem += 1;
ii += 1;
}
nCol = -1;
// loop over each row - start
while (1) {
errcode = sqlite3_step(pStmt);
if (errcode == SQLITE_DONE) {
errcode = SQLITE_OK;
}
// if no next row, then break
if (errcode != SQLITE_ROW) {
// cleanup pStmt
sqlite3_finalize(pStmt);
pStmt = NULL;
JSBATON_ASSERT_OK();
break;
}
// switch (responseType) - start
switch (responseType) {
case SQLITE_RESPONSETYPE_LASTBLOB:
// export last-value as blob
if (nCol == -1) {
nCol = sqlite3_column_count(pStmt);
}
sqlite3_str_reset(str99);
sqlite3_str_append(str99,
(char *) sqlite3_column_blob(pStmt, nCol - 1),
sqlite3_column_bytes(pStmt, nCol - 1));
break;
case SQLITE_RESPONSETYPE_LASTVALUE:
// export last-value as json-value
if (nCol == -1) {
nCol = sqlite3_column_count(pStmt);
}
sqlite3_str_reset(str99);
dbExecStr99AppendValue(str99, pStmt, nCol - 1);
break;
default:
// insert row of column-names
if (nCol == -1) {
nCol = sqlite3_column_count(pStmt);
if (sqlite3_str_length(str99) > 1) {
sqlite3_str_appendchar(str99, 1, ',');
sqlite3_str_appendchar(str99, 1, '\n');
sqlite3_str_appendchar(str99, 1, '\n');
}
// bracket table [
sqlite3_str_appendchar(str99, 1, '[');
// bracket column [
sqlite3_str_appendchar(str99, 1, '[');
// loop over each column-name
ii = 0;
while (ii < nCol) {
if (ii > 0) {
sqlite3_str_appendchar(str99, 1, ',');
}
zTmp = sqlite3_column_name(pStmt, ii);
str99JsonAppendText(str99, zTmp,
(uint32_t) strlen(zTmp));
ii += 1;
}
// bracket column ]
sqlite3_str_appendchar(str99, 1, ']');
}
// bracket row [
sqlite3_str_appendchar(str99, 1, ',');
sqlite3_str_appendchar(str99, 1, '\n');
sqlite3_str_appendchar(str99, 1, '[');
// loop over each column-value
ii = 0;
while (ii < nCol) {
if (ii > 0) {
sqlite3_str_appendchar(str99, 1, ',');
}
dbExecStr99AppendValue(str99, pStmt, ii);
ii += 1;
}
// bracket row ]
sqlite3_str_appendchar(str99, 1, ']');
}
// switch (responseType) - end
}
// while (1)
// loop over each row - end
switch (responseType) {
case SQLITE_RESPONSETYPE_LASTBLOB:
case SQLITE_RESPONSETYPE_LASTVALUE:
break;
default:
if (nCol != -1) {
// bracket table ]
sqlite3_str_appendchar(str99, 1, ']');
}
}
}
// while (1)
// loop over each table - end
switch (responseType) {
case SQLITE_RESPONSETYPE_LASTBLOB:
case SQLITE_RESPONSETYPE_LASTVALUE:
break;
default:
// bracket database ]
sqlite3_str_appendchar(str99, 1, ']');
sqlite3_str_appendchar(str99, 1, '\n');
}
errcode = sqlite3_str_errcode(str99);
JSBATON_ASSERT_OK();
// copy str99 to baton
baton->bufv[0].buf = (int64_t) str99->zText;
baton->bufv[0].len = sqlite3_str_length(str99);
catch_error:
// cleanup pStmt
sqlite3_finalize(pStmt);
// cleanup bindList
sqlite3_free(bindList);
// cleanup str99
if (errcode && str99->zText) {
sqlite3_free(str99->zText);
}
#if !defined(__EMSCRIPTEN__)
// mutex leave
sqlite3_mutex_leave(sqlite3_db_mutex(db));
#endif // __EMSCRIPTEN__
}
// SQLMATH_API dbExec - end
SQLMATH_API void dbFileLoad(
Jsbaton * baton
) {
// This function will load/save <zFilename> to/from <db>.
sqlite3 *db = NULL;
int errcode = dbFileLoadOrSave( //
(sqlite3 *) jsbatonGetInt64(baton, 0), // sqlite3 * pInMemory
jsbatonGetString(baton, 1), // char *zFilename
(int) jsbatonGetInt64(baton, 2)); // const int isSave
JSBATON_ASSERT_OK();
catch_error:
(void) 0;
}
SQLMATH_API int dbFileLoadOrSave(
sqlite3 * pInMemory,
const char *zFilename,
const int isSave
) {
// fprintf(stderr, "\nsqlmath._dbFileLoadOrSave(pp=%p ff=%s ss=%d)\n",