-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlbug_java.cpp
More file actions
2772 lines (2537 loc) · 101 KB
/
Copy pathlbug_java.cpp
File metadata and controls
2772 lines (2537 loc) · 101 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 <stdexcept>
#ifdef _WIN32
// Do nothing on Windows
#else
#include <dlfcn.h>
#endif
// This header is generated at build time. See CMakeLists.txt.
#include <vector>
#include "com_ladybugdb_Native.h"
#if __has_include("lbug.h")
#include "lbug.h"
#elif __has_include("c_api/lbug.h")
#include "c_api/lbug.h"
#else
#error "Public lbug header not found"
#endif
#include <sstream>
#include <format>
#include <jni.h>
using Exception = std::exception;
using NotImplementedException = std::runtime_error;
namespace {
constexpr auto JAVA_DECIMAL_PRECISION_LIMIT = 38;
} // namespace
#ifdef __ANDROID__
static jint JNI_VERSION = JNI_VERSION_1_6;
#else
static jint JNI_VERSION = JNI_VERSION_1_8;
#endif
// map
static jclass J_C_Map;
static jmethodID J_C_Map_M_entrySet;
// set
static jclass J_C_Set;
static jmethodID J_C_Set_M_iterator;
// iterator
static jclass J_C_Iterator;
static jmethodID J_C_Iterator_M_hasNext;
static jmethodID J_C_Iterator_M_next;
// Map$Entry
static jclass J_C_Map$Entry;
static jmethodID J_C_Map$Entry_M_getKey;
static jmethodID J_C_Map$Entry_M_getValue;
// Exception
static jclass J_C_Exception;
// QueryResult
static jclass J_C_QueryResult;
static jfieldID J_C_QueryResult_F_qr_ref;
static jfieldID J_C_QueryResult_F_isOwnedByCPP;
// PreparedStatement
static jclass J_C_PreparedStatement;
static jfieldID J_C_PreparedStatement_F_ps_ref;
// DataType
static jclass J_C_DataType;
static jfieldID J_C_DataType_F_dt_ref;
// QuerySummary
static jclass J_C_QuerySummary;
static jmethodID J_C_QuerySummary_M_ctor;
// FlatTuple
static jclass J_C_FlatTuple;
static jfieldID J_C_FlatTuple_F_ft_ref;
static jfieldID J_C_FlatTuple_F_isOwnedByCPP;
// Value
static jclass J_C_Value;
static jfieldID J_C_Value_F_v_ref;
static jfieldID J_C_Value_F_isOwnedByCPP;
// DataTypeID
static jclass J_C_DataTypeID;
static jfieldID J_C_DataTypeID_F_value;
// Boolean
static jclass J_C_Boolean;
static jmethodID J_C_Boolean_M_init;
static jmethodID J_C_Boolean_M_booleanValue;
// Long
static jclass J_C_Long;
static jmethodID J_C_Long_M_init;
static jmethodID J_C_Long_M_longValue;
// Integer
static jclass J_C_Integer;
static jmethodID J_C_Integer_M_init;
static jmethodID J_C_Integer_M_intValue;
// InternalID
static jclass J_C_InternalID;
static jmethodID J_C_InternalID_M_init;
static jfieldID J_C_InternalID_F_tableId;
static jfieldID J_C_InternalID_F_offset;
// Double
static jclass J_C_Double;
static jmethodID J_C_Double_M_init;
static jmethodID J_C_Double_M_doubleValue;
// BigDecimal
static jclass J_C_BigDecimal;
static jmethodID J_C_BigDecimal_M_init;
static jmethodID J_C_BigDecimal_M_toString;
static jmethodID J_C_BigDecimal_M_stripTrailingZeros;
static jmethodID J_C_BigDecimal_M_precision;
static jmethodID J_C_BigDecimal_M_scale;
// LocalDate
static jclass J_C_LocalDate;
static jmethodID J_C_LocalDate_M_ofEpochDay;
static jmethodID J_C_LocalDate_M_toEpochDay;
static jmethodID J_C_LocalDate_M_getEpochSecond;
static jmethodID J_C_LocalDate_M_getNano;
// Instant
static jclass J_C_Instant;
static jmethodID J_C_Instant_M_ofEpochSecond;
// Short
static jclass J_C_Short;
static jmethodID J_C_Short_M_init;
static jmethodID J_C_Short_M_shortValue;
// Byte
static jclass J_C_Byte;
static jmethodID J_C_Byte_M_init;
static jmethodID J_C_Byte_M_byteValue;
// BigInteger
static jclass J_C_BigInteger;
static jmethodID J_C_BigInteger_M_init;
static jmethodID J_C_BigInteger_M_longValue;
static jmethodID J_C_BigInteger_M_shiftRight;
// Float
static jclass J_C_Float;
static jmethodID J_C_Float_M_init;
static jmethodID J_C_Float_M_floatValue;
// Duration
static jclass J_C_Duration;
static jmethodID J_C_Duration_M_ofMillis;
static jmethodID J_C_Duration_M_toMillis;
// UUID
static jclass J_C_UUID;
static jmethodID J_C_UUID_M_init;
static jmethodID J_C_UUID_M_fromString;
static jmethodID J_C_UUID_M_getMostSignificantBits;
static jmethodID J_C_UUID_M_getLeastSignificantBits;
static jmethodID J_C_UUID_M_toString;
// Connection
static jclass J_C_Connection;
static jfieldID J_C_Connection_F_conn_ref;
// Database
static jclass J_C_Database;
static jfieldID J_C_Database_db_ref;
// String
static jclass J_C_String;
static jmethodID J_C_String_M_ctor;
static jmethodID J_C_String_M_getBytes;
static void throwJNIException(JNIEnv* env, const char* message) {
jclass exClass = env->FindClass("java/lang/RuntimeException");
if (exClass == nullptr) {
return;
}
env->ThrowNew(exClass, message);
}
template<typename... Args>
static jobject callObjectMethodChecked(JNIEnv* env, jobject object, jmethodID method,
Args... args) {
auto result = env->CallObjectMethod(object, method, args...);
if (env->ExceptionCheck()) {
throw NotImplementedException("Java exception raised during JNI object call");
}
return result;
}
template<typename... Args>
static jobject callStaticObjectMethodChecked(JNIEnv* env, jclass objectClass, jmethodID method,
Args... args) {
auto result = env->CallStaticObjectMethod(objectClass, method, args...);
if (env->ExceptionCheck()) {
throw NotImplementedException("Java exception raised during JNI static object call");
}
return result;
}
template<typename... Args>
static jboolean callBooleanMethodChecked(JNIEnv* env, jobject object, jmethodID method,
Args... args) {
auto result = env->CallBooleanMethod(object, method, args...);
if (env->ExceptionCheck()) {
throw NotImplementedException("Java exception raised during JNI boolean call");
}
return result;
}
template<typename... Args>
static jbyte callByteMethodChecked(JNIEnv* env, jobject object, jmethodID method, Args... args) {
auto result = env->CallByteMethod(object, method, args...);
if (env->ExceptionCheck()) {
throw NotImplementedException("Java exception raised during JNI byte call");
}
return result;
}
template<typename... Args>
static jshort callShortMethodChecked(JNIEnv* env, jobject object, jmethodID method, Args... args) {
auto result = env->CallShortMethod(object, method, args...);
if (env->ExceptionCheck()) {
throw NotImplementedException("Java exception raised during JNI short call");
}
return result;
}
template<typename... Args>
static jint callIntMethodChecked(JNIEnv* env, jobject object, jmethodID method, Args... args) {
auto result = env->CallIntMethod(object, method, args...);
if (env->ExceptionCheck()) {
throw NotImplementedException("Java exception raised during JNI int call");
}
return result;
}
template<typename... Args>
static jlong callLongMethodChecked(JNIEnv* env, jobject object, jmethodID method, Args... args) {
auto result = env->CallLongMethod(object, method, args...);
if (env->ExceptionCheck()) {
throw NotImplementedException("Java exception raised during JNI long call");
}
return result;
}
template<typename... Args>
static jfloat callFloatMethodChecked(JNIEnv* env, jobject object, jmethodID method, Args... args) {
auto result = env->CallFloatMethod(object, method, args...);
if (env->ExceptionCheck()) {
throw NotImplementedException("Java exception raised during JNI float call");
}
return result;
}
template<typename... Args>
static jdouble callDoubleMethodChecked(JNIEnv* env, jobject object, jmethodID method,
Args... args) {
auto result = env->CallDoubleMethod(object, method, args...);
if (env->ExceptionCheck()) {
throw NotImplementedException("Java exception raised during JNI double call");
}
return result;
}
static std::string jstringToUtf8String(JNIEnv* env, jstring value) {
if (value == nullptr) {
return "";
}
auto* charset = env->NewStringUTF("UTF-8");
if (charset == nullptr) {
throw NotImplementedException("Failed to create UTF-8 charset string");
}
jbyteArray byteArr =
(jbyteArray)callObjectMethodChecked(env, value, J_C_String_M_getBytes, charset);
env->DeleteLocalRef(charset);
size_t length = env->GetArrayLength(byteArr);
jbyte* bytes = env->GetByteArrayElements(byteArr, nullptr);
std::string result((char*)bytes, length);
env->ReleaseByteArrayElements(byteArr, bytes, JNI_ABORT);
env->DeleteLocalRef(byteArr);
return result;
}
static jstring utf8StringToJstring(JNIEnv* env, std::string str) {
jbyteArray byteArr = env->NewByteArray(str.size());
env->SetByteArrayRegion(byteArr, 0, str.size(), reinterpret_cast<const jbyte*>(str.data()));
jstring ret =
(jstring)env->NewObject(J_C_String, J_C_String_M_ctor, byteArr, env->NewStringUTF("UTF-8"));
return ret;
}
jobject createJavaObject(JNIEnv* env, void* memAddress, jclass javaClass, jfieldID refID) {
try {
auto address = reinterpret_cast<uint64_t>(memAddress);
auto ref = static_cast<jlong>(address);
jobject newObject = env->AllocObject(javaClass);
env->SetLongField(newObject, refID, ref);
return newObject;
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return jobject();
}
lbug_database* getDatabase(JNIEnv* env, jobject thisDB) {
try {
jlong fieldValue = env->GetLongField(thisDB, J_C_Database_db_ref);
uint64_t address = static_cast<uint64_t>(fieldValue);
auto* db = reinterpret_cast<lbug_database*>(address);
return db;
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return nullptr;
}
lbug_connection* getConnection(JNIEnv* env, jobject thisConn) {
try {
jlong fieldValue = env->GetLongField(thisConn, J_C_Connection_F_conn_ref);
uint64_t address = static_cast<uint64_t>(fieldValue);
auto* conn = reinterpret_cast<lbug_connection*>(address);
return conn;
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return nullptr;
}
lbug_prepared_statement* getPreparedStatement(JNIEnv* env, jobject thisPS) {
try {
jlong fieldValue = env->GetLongField(thisPS, J_C_PreparedStatement_F_ps_ref);
uint64_t address = static_cast<uint64_t>(fieldValue);
auto* ps = reinterpret_cast<lbug_prepared_statement*>(address);
return ps;
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return nullptr;
}
lbug_query_result* getQueryResult(JNIEnv* env, jobject thisQR) {
try {
jlong fieldValue = env->GetLongField(thisQR, J_C_QueryResult_F_qr_ref);
uint64_t address = static_cast<uint64_t>(fieldValue);
auto* qr = reinterpret_cast<lbug_query_result*>(address);
return qr;
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return nullptr;
}
lbug_flat_tuple* getFlatTuple(JNIEnv* env, jobject thisFT) {
try {
jlong fieldValue = env->GetLongField(thisFT, J_C_FlatTuple_F_ft_ref);
uint64_t address = static_cast<uint64_t>(fieldValue);
return reinterpret_cast<lbug_flat_tuple*>(address);
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return nullptr;
}
lbug_logical_type* getDataType(JNIEnv* env, jobject thisDT) {
try {
jlong fieldValue = env->GetLongField(thisDT, J_C_DataType_F_dt_ref);
uint64_t address = static_cast<uint64_t>(fieldValue);
return reinterpret_cast<lbug_logical_type*>(address);
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return nullptr;
}
lbug_value* getValue(JNIEnv* env, jobject thisValue) {
try {
jlong fieldValue = env->GetLongField(thisValue, J_C_Value_F_v_ref);
uint64_t address = static_cast<uint64_t>(fieldValue);
return reinterpret_cast<lbug_value*>(address);
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return nullptr;
}
lbug_internal_id_t getInternalID(JNIEnv* env, jobject id) {
try {
auto table_id = static_cast<uint64_t>(env->GetLongField(id, J_C_InternalID_F_tableId));
auto offset = static_cast<uint64_t>(env->GetLongField(id, J_C_InternalID_F_offset));
return {.table_id = table_id, .offset = offset};
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return {};
}
void throwIfError(lbug_state state, const char* message) {
if (state != LbugSuccess) {
throw NotImplementedException(message);
}
}
std::string takeOwnedCString(char* str) {
if (str == nullptr) {
return "";
}
std::string result(str);
lbug_destroy_string(str);
return result;
}
jstring takeOwnedCStringAsJString(JNIEnv* env, char* str) {
if (str == nullptr) {
return nullptr;
}
auto result = utf8StringToJstring(env, str);
lbug_destroy_string(str);
return result;
}
std::string dataTypeToString(lbug_data_type_id dataType) {
switch (dataType) {
case LBUG_ANY:
return "ANY";
case LBUG_NODE:
return "NODE";
case LBUG_REL:
return "REL";
case LBUG_RECURSIVE_REL:
return "RECURSIVE_REL";
case LBUG_SERIAL:
return "SERIAL";
case LBUG_BOOL:
return "BOOL";
case LBUG_INT64:
return "INT64";
case LBUG_INT32:
return "INT32";
case LBUG_INT16:
return "INT16";
case LBUG_INT8:
return "INT8";
case LBUG_UINT64:
return "UINT64";
case LBUG_UINT32:
return "UINT32";
case LBUG_UINT16:
return "UINT16";
case LBUG_UINT8:
return "UINT8";
case LBUG_INT128:
return "INT128";
case LBUG_DOUBLE:
return "DOUBLE";
case LBUG_FLOAT:
return "FLOAT";
case LBUG_DATE:
return "DATE";
case LBUG_TIMESTAMP:
return "TIMESTAMP";
case LBUG_TIMESTAMP_SEC:
return "TIMESTAMP_SEC";
case LBUG_TIMESTAMP_MS:
return "TIMESTAMP_MS";
case LBUG_TIMESTAMP_NS:
return "TIMESTAMP_NS";
case LBUG_TIMESTAMP_TZ:
return "TIMESTAMP_TZ";
case LBUG_INTERVAL:
return "INTERVAL";
case LBUG_DECIMAL:
return "DECIMAL";
case LBUG_INTERNAL_ID:
return "INTERNAL_ID";
case LBUG_STRING:
return "STRING";
case LBUG_BLOB:
return "BLOB";
case LBUG_LIST:
return "LIST";
case LBUG_ARRAY:
return "ARRAY";
case LBUG_STRUCT:
return "STRUCT";
case LBUG_MAP:
return "MAP";
case LBUG_UNION:
return "UNION";
case LBUG_UUID:
return "UUID";
default:
return "ANY";
}
}
void bindJavaParamsToPreparedStatement(JNIEnv* env, lbug_prepared_statement* preparedStatement,
jobject javaMap) {
jobject set = callObjectMethodChecked(env, javaMap, J_C_Map_M_entrySet);
jobject iter = callObjectMethodChecked(env, set, J_C_Set_M_iterator);
while (callBooleanMethodChecked(env, iter, J_C_Iterator_M_hasNext)) {
jobject entry = callObjectMethodChecked(env, iter, J_C_Iterator_M_next);
jstring key = (jstring)callObjectMethodChecked(env, entry, J_C_Map$Entry_M_getKey);
jobject value = callObjectMethodChecked(env, entry, J_C_Map$Entry_M_getValue);
std::string keyStr = jstringToUtf8String(env, key);
// The Java side (Connection.coerceParams) guarantees that every entry
// is already a Value — boxed primitives are converted there before the
// JNI call. We keep the IsInstanceOf check as a cheap contract guard:
// if it ever fails, something bypassed the public API and we'd rather
// fail loud than reinterpret_cast into the void.
if (!env->IsInstanceOf(value, J_C_Value)) {
env->DeleteLocalRef(entry);
env->DeleteLocalRef(key);
env->DeleteLocalRef(value);
throwJNIException(env,
("Parameter '" + keyStr
+ "' is not a Value — Connection.execute must be used as the entry point")
.c_str());
return;
}
lbug_value* clonedValue = lbug_value_clone(getValue(env, value));
auto state =
lbug_prepared_statement_bind_value(preparedStatement, keyStr.c_str(), clonedValue);
lbug_value_destroy(clonedValue);
throwIfError(state, "Failed to bind prepared statement parameter");
env->DeleteLocalRef(entry);
env->DeleteLocalRef(key);
env->DeleteLocalRef(value);
}
}
void throwLastError(JNIEnv* env, const char* fallback) {
if (auto* errorMessage = lbug_get_last_error()) {
throwJNIException(env, errorMessage);
free(errorMessage);
} else {
throwJNIException(env, fallback);
}
}
jobject createQueryResultObject(JNIEnv* env, lbug_query_result* queryResult) {
return createJavaObject(env, queryResult, J_C_QueryResult, J_C_QueryResult_F_qr_ref);
}
/**
* All Database native functions
*/
// protected static native void lbugNativeReloadLibrary(String libPath);
JNIEXPORT void JNICALL Java_com_ladybugdb_Native_lbugNativeReloadLibrary(JNIEnv* env, jclass,
jstring libPath) {
try {
#ifdef _WIN32
// Do nothing on Windows
#else
const char* path = env->GetStringUTFChars(libPath, JNI_FALSE);
void* handle = dlopen(path, RTLD_LAZY | RTLD_GLOBAL);
env->ReleaseStringUTFChars(libPath, path);
if (handle == nullptr) {
auto error = dlerror(); // NOLINT(concurrency-mt-unsafe): load can only be executed in
// single thread.
env->ThrowNew(J_C_Exception, error);
}
#endif
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
}
JNIEXPORT jlong JNICALL Java_com_ladybugdb_Native_lbugDatabaseInitExtended(JNIEnv* env, jclass,
jstring databasePath, jlong bufferPoolSize, jlong maxNumThreads, jboolean enableCompression,
jboolean readOnly, jlong maxDbSize, jboolean autoCheckpoint, jlong checkpointThreshold,
jboolean throwOnWalReplayFailure, jboolean enableChecksums, jboolean enableMultiWrites,
jboolean enableDefaultHashIndex) {
try {
const char* path = env->GetStringUTFChars(databasePath, JNI_FALSE);
auto systemConfig = lbug_default_system_config();
if (bufferPoolSize != 0) {
systemConfig.buffer_pool_size = static_cast<uint64_t>(bufferPoolSize);
}
if (maxNumThreads != 0) {
systemConfig.max_num_threads = static_cast<uint64_t>(maxNumThreads);
}
systemConfig.enable_compression = enableCompression;
systemConfig.read_only = readOnly;
if (maxDbSize != 0) {
auto unsignedMaxDbSize = static_cast<uint64_t>(maxDbSize);
if ((unsignedMaxDbSize & (unsignedMaxDbSize - 1)) != 0) {
env->ReleaseStringUTFChars(databasePath, path);
env->ThrowNew(J_C_Exception,
"Buffer manager exception: The given max db size should be a power of 2.");
return 0;
}
systemConfig.max_db_size = static_cast<uint64_t>(maxDbSize);
}
systemConfig.auto_checkpoint = autoCheckpoint;
if (checkpointThreshold >= 0) {
systemConfig.checkpoint_threshold = static_cast<uint64_t>(checkpointThreshold);
}
systemConfig.throw_on_wal_replay_failure = throwOnWalReplayFailure;
systemConfig.enable_checksums = enableChecksums;
systemConfig.enable_multi_writes = enableMultiWrites;
systemConfig.enable_default_hash_index = enableDefaultHashIndex;
try {
auto* db = new lbug_database();
auto state = lbug_database_init(path, systemConfig, db);
env->ReleaseStringUTFChars(databasePath, path);
if (state != LbugSuccess) {
delete db;
if (auto* errorMessage = lbug_get_last_error()) {
env->ThrowNew(J_C_Exception, errorMessage);
free(errorMessage);
} else {
env->ThrowNew(J_C_Exception, "Failed to initialize database");
}
return 0;
}
return static_cast<jlong>(reinterpret_cast<uint64_t>(db));
} catch (const Exception& e) {
env->ReleaseStringUTFChars(databasePath, path);
env->ThrowNew(J_C_Exception, e.what());
}
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return 0;
}
JNIEXPORT jlong JNICALL Java_com_ladybugdb_Native_lbugDatabaseInit(JNIEnv* env, jclass clazz,
jstring databasePath, jlong bufferPoolSize, jboolean enableCompression, jboolean readOnly,
jlong maxDbSize, jboolean autoCheckpoint, jlong checkpointThreshold,
jboolean throwOnWalReplayFailure, jboolean enableChecksums) {
return Java_com_ladybugdb_Native_lbugDatabaseInitExtended(env, clazz, databasePath,
bufferPoolSize, 0, enableCompression, readOnly, maxDbSize, autoCheckpoint,
checkpointThreshold, throwOnWalReplayFailure, enableChecksums, false, true);
}
JNIEXPORT void JNICALL Java_com_ladybugdb_Native_lbugDatabaseDestroy(JNIEnv* env, jclass,
jobject thisDB) {
try {
auto* db = getDatabase(env, thisDB);
lbug_database_destroy(db);
delete db;
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
}
/**
* All Connection native functions
*/
JNIEXPORT jlong JNICALL Java_com_ladybugdb_Native_lbugConnectionInit(JNIEnv* env, jclass,
jobject db) {
try {
auto* conn_db = getDatabase(env, db);
auto* conn = new lbug_connection();
throwIfError(lbug_connection_init(conn_db, conn), "Failed to initialize connection");
return static_cast<jlong>(reinterpret_cast<uint64_t>(conn));
} catch (const Exception& e) {
throwJNIException(env, e.what());
}
return 0;
}
JNIEXPORT void JNICALL Java_com_ladybugdb_Native_lbugConnectionDestroy(JNIEnv* env, jclass,
jobject thisConn) {
try {
auto* conn = getConnection(env, thisConn);
lbug_connection_destroy(conn);
delete conn;
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
}
JNIEXPORT void JNICALL Java_com_ladybugdb_Native_lbugConnectionSetMaxNumThreadForExec(JNIEnv* env,
jclass, jobject thisConn, jlong numThreads) {
try {
auto* conn = getConnection(env, thisConn);
auto threads = static_cast<uint64_t>(numThreads);
throwIfError(lbug_connection_set_max_num_thread_for_exec(conn, threads),
"Failed to set max threads for execution");
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
}
JNIEXPORT jlong JNICALL Java_com_ladybugdb_Native_lbugConnectionGetMaxNumThreadForExec(JNIEnv* env,
jclass, jobject thisConn) {
try {
auto* conn = getConnection(env, thisConn);
uint64_t threads = 0;
throwIfError(lbug_connection_get_max_num_thread_for_exec(conn, &threads),
"Failed to get max threads for execution");
return static_cast<jlong>(threads);
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return 0;
}
JNIEXPORT jobject JNICALL Java_com_ladybugdb_Native_lbugConnectionQuery(JNIEnv* env, jclass,
jobject thisConn, jstring query) {
try {
auto* conn = getConnection(env, thisConn);
std::string cppQuery = jstringToUtf8String(env, query);
auto* queryResult = new lbug_query_result();
lbug_state state = lbug_connection_query(conn, cppQuery.c_str(), queryResult);
if (state != LbugSuccess && queryResult->_query_result == nullptr) {
// Infrastructure error: no result was produced at all.
delete queryResult;
if (auto* errorMessage = lbug_get_last_error()) {
throwJNIException(env, errorMessage);
free(errorMessage);
return jobject();
}
throwJNIException(env, "Failed to execute query");
return jobject();
}
// Query ran (may have failed logically): return result so Java can call
// isSuccess() / getErrorMessage().
return createJavaObject(env, queryResult, J_C_QueryResult, J_C_QueryResult_F_qr_ref);
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return jobject();
}
JNIEXPORT jobject JNICALL Java_com_ladybugdb_Native_lbugConnectionPrepare(JNIEnv* env, jclass,
jobject thisConn, jstring query) {
try {
auto* conn = getConnection(env, thisConn);
std::string cppQuery = jstringToUtf8String(env, query);
auto* preparedStatement = new lbug_prepared_statement();
if (lbug_connection_prepare(conn, cppQuery.c_str(), preparedStatement) != LbugSuccess) {
delete preparedStatement;
if (auto* errorMessage = lbug_get_last_error()) {
throwJNIException(env, errorMessage);
free(errorMessage);
return jobject();
}
throwJNIException(env, "Failed to prepare statement");
return jobject();
}
jobject ret = createJavaObject(env, preparedStatement, J_C_PreparedStatement,
J_C_PreparedStatement_F_ps_ref);
return ret;
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return jobject();
}
JNIEXPORT jobject JNICALL Java_com_ladybugdb_Native_lbugConnectionExecute(JNIEnv* env, jclass,
jobject thisConn, jobject preStm, jobject paramMap) {
try {
auto* conn = getConnection(env, thisConn);
auto* ps = getPreparedStatement(env, preStm);
bindJavaParamsToPreparedStatement(env, ps, paramMap);
if (env->ExceptionCheck()) {
return jobject();
}
auto* queryResult = new lbug_query_result();
lbug_state state = lbug_connection_execute(conn, ps, queryResult);
if (state != LbugSuccess && queryResult->_query_result == nullptr) {
// Infrastructure error: no result was produced at all.
delete queryResult;
if (auto* errorMessage = lbug_get_last_error()) {
throwJNIException(env, errorMessage);
free(errorMessage);
return jobject();
}
throwJNIException(env, "Failed to execute prepared statement");
return jobject();
}
// Query ran (may have failed logically): return result so Java can call
// isSuccess() / getErrorMessage().
jobject ret = createJavaObject(env, queryResult, J_C_QueryResult, J_C_QueryResult_F_qr_ref);
return ret;
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return jobject();
}
JNIEXPORT void JNICALL Java_com_ladybugdb_Native_lbugConnectionInterrupt(JNIEnv* env, jclass,
jobject thisConn) {
try {
auto* conn = getConnection(env, thisConn);
lbug_connection_interrupt(conn);
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
}
JNIEXPORT void JNICALL Java_com_ladybugdb_Native_lbugConnectionSetQueryTimeout(JNIEnv* env, jclass,
jobject thisConn, jlong timeoutInMs) {
try {
auto* conn = getConnection(env, thisConn);
auto timeout = static_cast<uint64_t>(timeoutInMs);
throwIfError(lbug_connection_set_query_timeout(conn, timeout),
"Failed to set query timeout");
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
}
JNIEXPORT jobject JNICALL Java_com_ladybugdb_Native_lbugConnectionCreateArrowTable(JNIEnv* env,
jclass, jobject thisConn, jstring tableName, jlong arrowSchemaAddress, jlong arrowArraysAddress,
jlong numArrays) {
try {
auto* conn = getConnection(env, thisConn);
std::string table = jstringToUtf8String(env, tableName);
auto* schema = reinterpret_cast<ArrowSchema*>(static_cast<uintptr_t>(arrowSchemaAddress));
auto* arrays = reinterpret_cast<ArrowArray*>(static_cast<uintptr_t>(arrowArraysAddress));
auto* queryResult = new lbug_query_result();
auto state = lbug_connection_create_arrow_table(conn, table.c_str(), schema, arrays,
static_cast<uint64_t>(numArrays), queryResult);
if (state != LbugSuccess) {
delete queryResult;
throwLastError(env, "Failed to create Arrow table");
return jobject();
}
return createQueryResultObject(env, queryResult);
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return jobject();
}
JNIEXPORT jobject JNICALL Java_com_ladybugdb_Native_lbugConnectionCreateArrowRelTable(JNIEnv* env,
jclass, jobject thisConn, jstring tableName, jstring srcTableName, jstring dstTableName,
jlong arrowSchemaAddress, jlong arrowArraysAddress, jlong numArrays) {
try {
auto* conn = getConnection(env, thisConn);
std::string table = jstringToUtf8String(env, tableName);
std::string srcTable = jstringToUtf8String(env, srcTableName);
std::string dstTable = jstringToUtf8String(env, dstTableName);
auto* schema = reinterpret_cast<ArrowSchema*>(static_cast<uintptr_t>(arrowSchemaAddress));
auto* arrays = reinterpret_cast<ArrowArray*>(static_cast<uintptr_t>(arrowArraysAddress));
auto* queryResult = new lbug_query_result();
auto state = lbug_connection_create_arrow_rel_table(conn, table.c_str(), srcTable.c_str(),
dstTable.c_str(), schema, arrays, static_cast<uint64_t>(numArrays), queryResult);
if (state != LbugSuccess) {
delete queryResult;
throwLastError(env, "Failed to create Arrow relationship table");
return jobject();
}
return createQueryResultObject(env, queryResult);
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return jobject();
}
JNIEXPORT jobject JNICALL Java_com_ladybugdb_Native_lbugConnectionCreateArrowRelTableCSR(
JNIEnv* env, jclass, jobject thisConn, jstring tableName, jstring srcTableName,
jstring dstTableName, jlong indicesSchemaAddress, jlong indicesArraysAddress,
jlong numIndicesArrays, jlong indptrSchemaAddress, jlong indptrArraysAddress,
jlong numIndptrArrays, jstring dstColumnName) {
try {
auto* conn = getConnection(env, thisConn);
std::string table = jstringToUtf8String(env, tableName);
std::string srcTable = jstringToUtf8String(env, srcTableName);
std::string dstTable = jstringToUtf8String(env, dstTableName);
std::string dstColumn = jstringToUtf8String(env, dstColumnName);
auto* indicesSchema =
reinterpret_cast<ArrowSchema*>(static_cast<uintptr_t>(indicesSchemaAddress));
auto* indicesArrays =
reinterpret_cast<ArrowArray*>(static_cast<uintptr_t>(indicesArraysAddress));
auto* indptrSchema =
reinterpret_cast<ArrowSchema*>(static_cast<uintptr_t>(indptrSchemaAddress));
auto* indptrArrays =
reinterpret_cast<ArrowArray*>(static_cast<uintptr_t>(indptrArraysAddress));
auto* queryResult = new lbug_query_result();
auto* dstColumnPtr = dstColumn.empty() ? nullptr : dstColumn.c_str();
auto state = lbug_connection_create_arrow_rel_table_csr(conn, table.c_str(),
srcTable.c_str(), dstTable.c_str(), indicesSchema, indicesArrays,
static_cast<uint64_t>(numIndicesArrays), indptrSchema, indptrArrays,
static_cast<uint64_t>(numIndptrArrays), dstColumnPtr, queryResult);
if (state != LbugSuccess) {
delete queryResult;
throwLastError(env, "Failed to create Arrow CSR relationship table");
return jobject();
}
return createQueryResultObject(env, queryResult);
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return jobject();
}
JNIEXPORT jobject JNICALL Java_com_ladybugdb_Native_lbugConnectionDropArrowTable(JNIEnv* env,
jclass, jobject thisConn, jstring tableName) {
try {
auto* conn = getConnection(env, thisConn);
std::string table = jstringToUtf8String(env, tableName);
auto* queryResult = new lbug_query_result();
auto state = lbug_connection_drop_arrow_table(conn, table.c_str(), queryResult);
if (state != LbugSuccess) {
delete queryResult;
throwLastError(env, "Failed to drop Arrow table");
return jobject();
}
return createQueryResultObject(env, queryResult);
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return jobject();
}
/**
* All PreparedStatement native functions
*/
JNIEXPORT void JNICALL Java_com_ladybugdb_Native_lbugPreparedStatementDestroy(JNIEnv* env, jclass,
jobject thisPS) {
try {
auto* ps = getPreparedStatement(env, thisPS);
lbug_prepared_statement_destroy(ps);
delete ps;
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
}
JNIEXPORT jboolean JNICALL Java_com_ladybugdb_Native_lbugPreparedStatementIsSuccess(JNIEnv* env,
jclass, jobject thisPS) {
try {
auto* ps = getPreparedStatement(env, thisPS);
return static_cast<jboolean>(lbug_prepared_statement_is_success(ps));
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return jboolean();
}
JNIEXPORT jboolean JNICALL Java_com_ladybugdb_Native_lbugPreparedStatementIsReadOnly(JNIEnv* env,
jclass, jobject thisPS) {
try {
auto* ps = getPreparedStatement(env, thisPS);
return static_cast<jboolean>(lbug_prepared_statement_is_read_only(ps));
} catch (const Exception& e) {
throwJNIException(env, e.what());
} catch (...) {
throwJNIException(env, "Unknown Error");
}
return jboolean();
}
JNIEXPORT jstring JNICALL Java_com_ladybugdb_Native_lbugPreparedStatementGetErrorMessage(
JNIEnv* env, jclass, jobject thisPS) {