forked from OP-Engineering/op-sqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge.cpp
More file actions
772 lines (609 loc) · 23.2 KB
/
bridge.cpp
File metadata and controls
772 lines (609 loc) · 23.2 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
#include "bridge.h"
#include "DumbHostObject.h"
#include "SmartHostObject.h"
#include "libsql.h"
#include "logs.h"
#include "utils.h"
#include <filesystem>
#include <iostream>
#include <unordered_map>
#include <variant>
namespace opsqlite {
// _____ _____
// /\ | __ \_ _|
// / \ | |__) || |
// / /\ \ | ___/ | |
// / ____ \| | _| |_
// /_/ \_\_| |_____|
/// Returns the completely formed db path, but it also creates any sub-folders
/// along the way
std::string opsqlite_get_db_path(std::string const &db_name,
std::string const &location) {
if (location == ":memory:") {
return location;
}
// Will return false if the directory already exists, no need to check
std::filesystem::create_directories(location);
if (!location.empty() && location.back() != '/') {
return location + "/" + db_name;
}
return location + db_name;
}
DB opsqlite_libsql_open_sync(std::string const &name,
std::string const &base_path,
std::string const &url,
std::string const &auth_token, int sync_interval,
bool offline, std::string const &encryption_key,
std::string const &remote_encryption_key) {
std::string path = opsqlite_get_db_path(name, base_path);
int status;
libsql_database_t db;
libsql_connection_t c;
const char *err = nullptr;
libsql_config config = {
.db_path = path.c_str(),
.primary_url = url.c_str(),
.auth_token = auth_token.c_str(),
.read_your_writes = '1',
.encryption_key =
encryption_key.empty() ? nullptr : encryption_key.c_str(),
.remote_encryption_key = remote_encryption_key.empty()
? nullptr
: remote_encryption_key.c_str(),
.sync_interval = sync_interval,
.with_webpki = '1',
.offline = offline,
};
status = libsql_open_sync_with_config(config, &db, &err);
if (status != 0) {
throw std::runtime_error(err);
}
status = libsql_connect(db, &c, &err);
if (status != 0) {
throw std::runtime_error(err);
}
return {.db = db, .c = c};
}
DB opsqlite_libsql_open(std::string const &name, std::string const &last_path,
std::string const &crsqlitePath) {
std::string path = opsqlite_get_db_path(name, last_path);
int status;
libsql_database_t db;
libsql_connection_t c;
const char *err = nullptr;
status = libsql_open_file(path.c_str(), &db, &err);
if (status != 0) {
throw std::runtime_error(err);
}
status = libsql_connect(db, &c, &err);
if (status != 0) {
throw std::runtime_error(err);
}
#ifdef OP_SQLITE_USE_CRSQLITE
const char *errMsg;
const char *crsqliteEntryPoint = "sqlite3_crsqlite_init";
status = libsql_load_extension(c, crsqlitePath.c_str(), crsqliteEntryPoint,
&errMsg);
if (status != 0) {
throw std::runtime_error(errMsg);
} else {
LOGI("Loaded CRSQlite successfully");
}
#endif
return {.db = db, .c = c};
}
DB opsqlite_libsql_open_remote(std::string const &url,
std::string const &auth_token) {
int status;
libsql_database_t db;
libsql_connection_t c;
const char *err = nullptr;
status = libsql_open_remote_with_webpki(url.c_str(), auth_token.c_str(),
&db, &err);
if (status != 0) {
throw std::runtime_error(err);
}
status = libsql_connect(db, &c, &err);
if (status != 0) {
throw std::runtime_error(err);
}
return {.db = db, .c = c};
}
void opsqlite_libsql_close(DB &db) {
if (db.c != nullptr) {
libsql_disconnect(db.c);
db.c = nullptr;
}
if (db.db != nullptr) {
libsql_close(db.db);
db.db = nullptr;
}
}
void opsqlite_libsql_attach(DB const &db, std::string const &docPath,
std::string const &databaseToAttach,
std::string const &alias) {
std::string dbPath = opsqlite_get_db_path(databaseToAttach, docPath);
std::string statement = "ATTACH DATABASE '" + dbPath + "' AS " + alias;
opsqlite_libsql_execute(db, statement, nullptr);
}
void opsqlite_libsql_detach(DB const &db, std::string const &alias) {
std::string statement = "DETACH DATABASE " + alias;
opsqlite_libsql_execute(db, statement, nullptr);
}
int32_t opsqlite_libsql_get_reserved_bytes(DB const &db) {
const char *err = nullptr;
int32_t reserved_bytes = 0;
int status = libsql_get_reserved_bytes(db.c, &reserved_bytes, &err);
if (status != 0) {
throw std::runtime_error(err);
}
return reserved_bytes;
}
void opsqlite_libsql_set_reserved_bytes(DB const &db, int32_t reserved_bytes) {
const char *err = nullptr;
int status = libsql_set_reserved_bytes(db.c, reserved_bytes, &err);
if (status != 0) {
throw std::runtime_error(err);
}
}
void opsqlite_libsql_sync(DB const &db) {
const char *err = nullptr;
int status = libsql_sync(db.db, &err);
if (status != 0) {
throw std::runtime_error(err);
}
}
void opsqlite_libsql_remove(DB &db, std::string const &name,
std::string const &path) {
opsqlite_libsql_close(db);
std::string full_path = opsqlite_get_db_path(name, path);
if (!file_exists(full_path)) {
throw std::runtime_error("[op-sqlite]: Database file not found" +
full_path);
}
remove(full_path.c_str());
}
void opsqlite_libsql_bind_statement(libsql_stmt_t statement,
const std::vector<JSVariant> *values) {
const char *err;
size_t size = values->size();
for (int ii = 0; ii < size; ii++) {
int index = ii + 1;
JSVariant value = values->at(ii);
int status;
if (std::holds_alternative<bool>(value)) {
status =
libsql_bind_int(statement, index,
static_cast<int>(std::get<bool>(value)), &err);
} else if (std::holds_alternative<int>(value)) {
status =
libsql_bind_int(statement, index, std::get<int>(value), &err);
} else if (std::holds_alternative<long long>(value)) {
status = libsql_bind_int(statement, index,
std::get<long long>(value), &err);
} else if (std::holds_alternative<double>(value)) {
status = libsql_bind_float(statement, index,
std::get<double>(value), &err);
} else if (std::holds_alternative<std::string>(value)) {
std::string str = std::get<std::string>(value);
status = libsql_bind_string(statement, index, str.c_str(), &err);
} else if (std::holds_alternative<ArrayBuffer>(value)) {
ArrayBuffer buffer = std::get<ArrayBuffer>(value);
status = libsql_bind_blob(statement, index, buffer.data.get(),
static_cast<int>(buffer.size), &err);
} else {
status = libsql_bind_null(statement, index, &err);
}
if (status != 0) {
throw std::runtime_error(err);
}
}
}
BridgeResult opsqlite_libsql_execute_prepared_statement(
DB const &db, libsql_stmt_t stmt, std::vector<DumbHostObject> *results,
const std::shared_ptr<std::vector<SmartHostObject>> &metadatas) {
libsql_rows_t rows;
libsql_row_t row;
int status;
const char *err = nullptr;
status = libsql_query_stmt(stmt, &rows, &err);
if (status != 0) {
throw std::runtime_error(err);
}
bool metadata_set = false;
int num_cols = libsql_column_count(rows);
while ((status = libsql_next_row(rows, &row, &err)) == 0) {
if (!err && !row) {
break;
}
DumbHostObject row_host_object = DumbHostObject(metadatas);
for (int col = 0; col < num_cols; col++) {
int type;
libsql_column_type(rows, row, col, &type, &err);
switch (type) {
case LIBSQL_INT:
long long int_value;
status = libsql_get_int(row, col, &int_value, &err);
row_host_object.values.emplace_back(int_value);
break;
case LIBSQL_FLOAT:
double float_value;
status = libsql_get_float(row, col, &float_value, &err);
row_host_object.values.emplace_back(float_value);
break;
case LIBSQL_TEXT:
const char *text_value;
status = libsql_get_string(row, col, &text_value, &err);
row_host_object.values.emplace_back(text_value);
break;
case LIBSQL_BLOB: {
blob value_blob;
libsql_get_blob(row, col, &value_blob, &err);
auto *data = new uint8_t[value_blob.len];
// You cannot share raw memory between native and JS
// always copy the data
memcpy(data, value_blob.ptr, value_blob.len);
libsql_free_blob(value_blob);
row_host_object.values.emplace_back(
ArrayBuffer{.data = std::shared_ptr<uint8_t>{data},
.size = static_cast<size_t>(value_blob.len)});
break;
}
case LIBSQL_NULL:
// intentional fall-through
default:
row_host_object.values.emplace_back(nullptr);
break;
}
if (status != 0) {
fprintf(stderr, "%s\n", err);
throw std::runtime_error("libsql error");
}
// On the first interation through the columns, set the metadata
if (!metadata_set && metadatas != nullptr) {
const char *col_name;
status = libsql_column_name(rows, col, &col_name, &err);
auto metadata = SmartHostObject();
metadata.fields.emplace_back("name", col_name);
metadata.fields.emplace_back("index", col);
metadata.fields.emplace_back("type", "UNKNOWN");
// metadata.fields.push_back(
// std::make_pair("type", type == -1 ?
// "UNKNOWN" : type));
metadatas->push_back(metadata);
}
}
if (results != nullptr) {
results->push_back(row_host_object);
}
metadata_set = true;
err = nullptr;
}
if (status != 0) {
fprintf(stderr, "%s\n", err);
}
libsql_free_rows(rows);
unsigned long long changes = libsql_changes(db.c);
long long insert_row_id = libsql_last_insert_rowid(db.c);
libsql_reset_stmt(stmt, &err);
return {.affectedRows = static_cast<int>(changes),
.insertId = static_cast<double>(insert_row_id)};
}
libsql_stmt_t opsqlite_libsql_prepare_statement(DB const &db,
std::string const &query) {
libsql_stmt_t stmt;
const char *err;
int status = libsql_prepare(db.c, query.c_str(), &stmt, &err);
if (status != 0) {
throw std::runtime_error(err);
}
return stmt;
}
BridgeResult opsqlite_libsql_execute(DB const &db, std::string const &query,
const std::vector<JSVariant> *params) {
std::vector<std::string> column_names;
std::vector<std::vector<JSVariant>> out_rows;
std::vector<JSVariant> out_row;
libsql_rows_t rows;
libsql_row_t row;
libsql_stmt_t stmt;
int status;
const char *err = nullptr;
status = libsql_prepare(db.c, query.c_str(), &stmt, &err);
if (status != 0) {
throw std::runtime_error(err);
}
if (params != nullptr && !params->empty()) {
opsqlite_libsql_bind_statement(stmt, params);
}
status = libsql_query_stmt(stmt, &rows, &err);
if (status != 0) {
throw std::runtime_error(err);
}
// Get the column names on the first pass
int column_count = libsql_column_count(rows);
const char *col_name;
for (int i = 0; i < column_count; i++) {
status = libsql_column_name(rows, i, &col_name, &err);
if (status != 0) {
throw std::runtime_error(err);
}
column_names.emplace_back(col_name);
}
long long int_value;
double float_value;
const char *text_value;
blob blob_value;
status = libsql_next_row(rows, &row, &err);
while (status == 0) {
out_row = std::vector<JSVariant>();
if (!err && !row) {
break;
}
for (int col = 0; col < column_count; col++) {
int type;
libsql_column_type(rows, row, col, &type, &err);
switch (type) {
case LIBSQL_INT:
status = libsql_get_int(row, col, &int_value, &err);
out_row.emplace_back(int_value);
break;
case LIBSQL_FLOAT:
status = libsql_get_float(row, col, &float_value, &err);
out_row.emplace_back(float_value);
break;
case LIBSQL_TEXT:
status = libsql_get_string(row, col, &text_value, &err);
out_row.emplace_back(text_value);
break;
case LIBSQL_BLOB: {
libsql_get_blob(row, col, &blob_value, &err);
auto data = new uint8_t[blob_value.len];
// You cannot share raw memory between native and JS
// always copy the data
memcpy(data, blob_value.ptr, blob_value.len);
libsql_free_blob(blob_value);
out_row.emplace_back(
ArrayBuffer{.data = std::shared_ptr<uint8_t>{data},
.size = static_cast<size_t>(blob_value.len)});
break;
}
case LIBSQL_NULL:
// intentional fall-through
default:
out_row.emplace_back(nullptr);
break;
}
if (status != 0) {
throw std::runtime_error(err);
}
}
out_rows.emplace_back(out_row);
err = nullptr;
status = libsql_next_row(rows, &row, &err);
}
libsql_free_rows(rows);
libsql_free_stmt(stmt);
unsigned long long changes = libsql_changes(db.c);
long long insert_row_id = libsql_last_insert_rowid(db.c);
return {.affectedRows = static_cast<int>(changes),
.insertId = static_cast<double>(insert_row_id),
.rows = std::move(out_rows),
.column_names = std::move(column_names)};
}
BridgeResult opsqlite_libsql_execute_with_host_objects(
DB const &db, std::string const &query,
const std::vector<JSVariant> *params, std::vector<DumbHostObject> *results,
const std::shared_ptr<std::vector<SmartHostObject>> &metadatas) {
libsql_rows_t rows;
libsql_row_t row;
libsql_stmt_t stmt;
int status;
const char *err = nullptr;
status = libsql_prepare(db.c, query.c_str(), &stmt, &err);
if (status != 0) {
throw std::runtime_error(err);
}
if (params != nullptr && !params->empty()) {
opsqlite_libsql_bind_statement(stmt, params);
}
status = libsql_query_stmt(stmt, &rows, &err);
if (status != 0) {
throw std::runtime_error(err);
}
bool metadata_set = false;
int num_cols = libsql_column_count(rows);
while ((status = libsql_next_row(rows, &row, &err)) == 0) {
if (!err && !row) {
break;
}
DumbHostObject row_host_object = DumbHostObject(metadatas);
for (int col = 0; col < num_cols; col++) {
int type;
libsql_column_type(rows, row, col, &type, &err);
switch (type) {
case LIBSQL_INT:
long long int_value;
status = libsql_get_int(row, col, &int_value, &err);
row_host_object.values.emplace_back(int_value);
break;
case LIBSQL_FLOAT:
double float_value;
status = libsql_get_float(row, col, &float_value, &err);
row_host_object.values.emplace_back(float_value);
break;
case LIBSQL_TEXT:
const char *text_value;
status = libsql_get_string(row, col, &text_value, &err);
row_host_object.values.emplace_back(text_value);
break;
case LIBSQL_BLOB: {
blob value_blob;
libsql_get_blob(row, col, &value_blob, &err);
auto *data = new uint8_t[value_blob.len];
// You cannot share raw memory between native and JS
// always copy the data
memcpy(data, value_blob.ptr, value_blob.len);
libsql_free_blob(value_blob);
row_host_object.values.emplace_back(
ArrayBuffer{.data = std::shared_ptr<uint8_t>{data},
.size = static_cast<size_t>(value_blob.len)});
break;
}
case LIBSQL_NULL:
// intentional fall-through
default:
row_host_object.values.emplace_back(nullptr);
break;
}
if (status != 0) {
fprintf(stderr, "%s\n", err);
throw std::runtime_error(err);
}
// On the first interation through the columns, set the metadata
if (!metadata_set && metadatas != nullptr) {
const char *col_name;
status = libsql_column_name(rows, col, &col_name, &err);
auto metadata = SmartHostObject();
metadata.fields.emplace_back("name", col_name);
metadata.fields.emplace_back("index", col);
metadata.fields.emplace_back("type", "UNKNOWN");
// metadata.fields.push_back(
// std::make_pair("type", type == -1 ?
// "UNKNOWN" : type));
metadatas->push_back(metadata);
}
}
if (results != nullptr) {
results->push_back(row_host_object);
}
metadata_set = true;
err = nullptr;
}
if (status != 0) {
fprintf(stderr, "%s\n", err);
}
libsql_free_rows(rows);
libsql_free_stmt(stmt);
unsigned long long changes = libsql_changes(db.c);
long long insert_row_id = libsql_last_insert_rowid(db.c);
return {.affectedRows = static_cast<int>(changes),
.insertId = static_cast<double>(insert_row_id)};
}
/// Executes returning data in raw arrays, a small performance optimization
/// for certain use cases
BridgeResult
opsqlite_libsql_execute_raw(DB const &db, std::string const &query,
const std::vector<JSVariant> *params,
std::vector<std::vector<JSVariant>> *results) {
libsql_rows_t rows;
libsql_row_t row;
libsql_stmt_t stmt;
int status;
const char *err = nullptr;
status = libsql_prepare(db.c, query.c_str(), &stmt, &err);
if (status != 0) {
throw std::runtime_error(err);
}
if (params != nullptr && !params->empty()) {
opsqlite_libsql_bind_statement(stmt, params);
}
status = libsql_query_stmt(stmt, &rows, &err);
if (status != 0) {
throw std::runtime_error(err);
}
int num_cols = libsql_column_count(rows);
while ((status = libsql_next_row(rows, &row, &err)) == 0) {
if (!err && !row) {
break;
}
std::vector<JSVariant> row_vector;
for (int col = 0; col < num_cols; col++) {
int type;
libsql_column_type(rows, row, col, &type, &err);
switch (type) {
case LIBSQL_INT:
long long int_value;
status = libsql_get_int(row, col, &int_value, &err);
row_vector.emplace_back(int_value);
break;
case LIBSQL_FLOAT:
double float_value;
status = libsql_get_float(row, col, &float_value, &err);
row_vector.emplace_back(float_value);
break;
case LIBSQL_TEXT:
const char *text_value;
status = libsql_get_string(row, col, &text_value, &err);
row_vector.emplace_back(text_value);
break;
case LIBSQL_BLOB: {
blob value_blob;
libsql_get_blob(row, col, &value_blob, &err);
auto *data = new uint8_t[value_blob.len];
// You cannot share raw memory between native and JS
// always copy the data
memcpy(data, value_blob.ptr, value_blob.len);
libsql_free_blob(value_blob);
row_vector.emplace_back(
ArrayBuffer{.data = std::shared_ptr<uint8_t>{data},
.size = static_cast<size_t>(value_blob.len)});
break;
}
case LIBSQL_NULL:
// intentional fall-through
default:
row_vector.emplace_back(nullptr);
break;
}
if (status != 0) {
fprintf(stderr, "%s\n", err);
throw std::runtime_error("libsql error");
}
}
if (results != nullptr) {
results->push_back(row_vector);
}
err = nullptr;
}
if (status != 0) {
fprintf(stderr, "%s\n", err);
}
libsql_free_rows(rows);
libsql_free_stmt(stmt);
unsigned long long changes = libsql_changes(db.c);
long long insert_row_id = libsql_last_insert_rowid(db.c);
return {.affectedRows = static_cast<int>(changes),
.insertId = static_cast<double>(insert_row_id)};
}
BatchResult
opsqlite_libsql_execute_batch(DB const &db,
const std::vector<BatchArguments> *commands) {
size_t commandCount = commands->size();
if (commandCount <= 0) {
throw std::runtime_error("No SQL commands provided");
}
try {
int affectedRows = 0;
// opsqlite_libsql_execute(db, "BEGIN EXCLUSIVE TRANSACTION", nullptr);
for (int i = 0; i < commandCount; i++) {
auto command = commands->at(i);
// We do not provide a datastructure to receive query data because
// we don't need/want to handle this results in a batch execution
auto result =
opsqlite_libsql_execute(db, command.sql, &command.params);
affectedRows += result.affectedRows;
}
// opsqlite_libsql_execute(db, "COMMIT", nullptr);
return BatchResult{
.affectedRows = affectedRows,
.commands = static_cast<int>(commandCount),
};
} catch (std::exception &exc) {
// opsqlite_libsql_execute(db, "ROLLBACK", nullptr);
return BatchResult{
.message = exc.what(),
};
}
}
} // namespace opsqlite