-
Notifications
You must be signed in to change notification settings - Fork 303
/
lib.rs
1102 lines (1036 loc) · 31.6 KB
/
lib.rs
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
#![allow(clippy::missing_safety_doc)]
#![allow(non_camel_case_types)]
#[macro_use]
extern crate lazy_static;
mod types;
use crate::types::libsql_config;
use http::Uri;
use libsql::{errors, Builder, LoadExtensionGuard};
use tokio::runtime::Runtime;
use types::{
blob, libsql_connection, libsql_connection_t, libsql_database, libsql_database_t, libsql_row,
libsql_row_t, libsql_rows, libsql_rows_future_t, libsql_rows_t, libsql_stmt, libsql_stmt_t,
replicated, stmt,
};
lazy_static! {
static ref RT: Runtime = tokio::runtime::Runtime::new().unwrap();
}
fn translate_string(s: String) -> *const std::ffi::c_char {
match std::ffi::CString::new(s) {
Ok(s) => s.into_raw(),
Err(_) => std::ptr::null(),
}
}
unsafe fn set_err_msg(msg: String, output: *mut *const std::ffi::c_char) {
if !output.is_null() {
*output = translate_string(msg);
}
}
#[no_mangle]
pub unsafe extern "C" fn libsql_enable_internal_tracing() -> std::ffi::c_int {
if tracing_subscriber::fmt::try_init().is_ok() {
1
} else {
0
}
}
#[no_mangle]
pub unsafe extern "C" fn libsql_sync(
db: libsql_database_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let db = db.get_ref();
match RT.block_on(db.sync()) {
Ok(_) => 0,
Err(e) => {
set_err_msg(format!("Error syncing database: {e}"), out_err_msg);
1
}
}
}
#[no_mangle]
pub unsafe extern "C" fn libsql_sync2(
db: libsql_database_t,
out_replicated: *mut replicated,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let db = db.get_ref();
match RT.block_on(db.sync()) {
Ok(replicated) => {
if !out_replicated.is_null() {
(*out_replicated).frame_no = replicated.frame_no().unwrap_or(0) as i32;
(*out_replicated).frames_synced = replicated.frames_synced() as i32;
}
0
}
Err(e) => {
set_err_msg(format!("Error syncing database: {e}"), out_err_msg);
1
}
}
}
#[no_mangle]
pub unsafe extern "C" fn libsql_open_sync(
db_path: *const std::ffi::c_char,
primary_url: *const std::ffi::c_char,
auth_token: *const std::ffi::c_char,
read_your_writes: std::ffi::c_char,
encryption_key: *const std::ffi::c_char,
out_db: *mut libsql_database_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let config = libsql_config {
db_path,
primary_url,
auth_token,
read_your_writes,
encryption_key,
sync_interval: 0,
with_webpki: 0,
};
libsql_open_sync_with_config(config, out_db, out_err_msg)
}
#[no_mangle]
pub unsafe extern "C" fn libsql_open_sync_with_webpki(
db_path: *const std::ffi::c_char,
primary_url: *const std::ffi::c_char,
auth_token: *const std::ffi::c_char,
read_your_writes: std::ffi::c_char,
encryption_key: *const std::ffi::c_char,
out_db: *mut libsql_database_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let config = libsql_config {
db_path,
primary_url,
auth_token,
read_your_writes,
encryption_key,
sync_interval: 0,
with_webpki: 1,
};
libsql_open_sync_with_config(config, out_db, out_err_msg)
}
/// Returns a new URI with the offline query parameter removed or None if the URI does not contain the offline query parameter.
fn maybe_remove_offline_query_param(url: &str) -> anyhow::Result<Option<String>> {
let uri: Uri = url.try_into()?;
let Some(query) = uri.query() else {
return Ok(None);
};
let query = query.to_owned();
let query_segments = query.split('&').collect::<Vec<&str>>();
let segments_count = query_segments.len();
let query_segments = query_segments
.into_iter()
.filter(|s| s != &"offline" && !s.starts_with("offline="))
.collect::<Vec<&str>>();
if segments_count == query_segments.len() {
return Ok(None);
}
let query = query_segments.join("&");
let Some(query_idx) = url.find('?') else {
return Ok(None);
};
if query.is_empty() {
return Ok(Some(url[..query_idx].to_owned()));
}
Ok(Some(url[..query_idx].to_owned() + "?" + &query))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_remove_offline_query_param() {
let uri = "http://example.com";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(new_uri, None);
let uri = "http://example.com?";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(new_uri, None);
let uri = "http://example.com?foo=bar";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(new_uri, None);
let uri = "http://example.com?offline";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(new_uri.as_deref(), Some("http://example.com"));
let uri = "http://example.com?offline=bar";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(new_uri.as_deref(), Some("http://example.com"));
let uri = "http://example.com?offline&foo=bar";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(new_uri.as_deref(), Some("http://example.com?foo=bar"));
let uri = "http://example.com?offline=true&foo=bar";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(new_uri.as_deref(), Some("http://example.com?foo=bar"));
let uri = "http://example.com?foo=bar&offline";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(new_uri.as_deref(), Some("http://example.com?foo=bar"));
let uri = "http://example.com?foo=bar&offline=true";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(new_uri.as_deref(), Some("http://example.com?foo=bar"));
let uri = "http://example.com?foo=bar&offline&foo2=bar2";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(
new_uri.as_deref(),
Some("http://example.com?foo=bar&foo2=bar2")
);
let uri = "http://example.com?foo=bar&offline=true&foo2=bar2";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(
new_uri.as_deref(),
Some("http://example.com?foo=bar&foo2=bar2")
);
let uri = "http://example.com?offline&foo=bar&offline";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(new_uri.as_deref(), Some("http://example.com?foo=bar"));
let uri = "http://example.com?offline&foo=bar&offline&foo2=bar2";
let new_uri = maybe_remove_offline_query_param(uri).unwrap();
assert_eq!(
new_uri.as_deref(),
Some("http://example.com?foo=bar&foo2=bar2")
);
}
}
#[no_mangle]
pub unsafe extern "C" fn libsql_open_sync_with_config(
config: libsql_config,
out_db: *mut libsql_database_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let db_path = unsafe { std::ffi::CStr::from_ptr(config.db_path) };
let db_path = match db_path.to_str() {
Ok(url) => url,
Err(e) => {
set_err_msg(format!("Wrong URL: {e}"), out_err_msg);
return 1;
}
};
let primary_url = unsafe { std::ffi::CStr::from_ptr(config.primary_url) };
let primary_url = match primary_url.to_str() {
Ok(url) => url,
Err(e) => {
set_err_msg(format!("Wrong URL: {e}"), out_err_msg);
return 2;
}
};
let auth_token = unsafe { std::ffi::CStr::from_ptr(config.auth_token) };
let auth_token = match auth_token.to_str() {
Ok(token) => token,
Err(e) => {
set_err_msg(format!("Wrong Auth Token: {e}"), out_err_msg);
return 3;
}
};
let primary_url_with_offline_removed = match maybe_remove_offline_query_param(&primary_url) {
Ok(url) => url,
Err(e) => {
set_err_msg(format!("Wrong primary URL: {e}"), out_err_msg);
return 100;
}
};
if let Some(primary_url) = primary_url_with_offline_removed {
let mut builder =
Builder::new_synced_database(db_path, primary_url.to_owned(), auth_token.to_owned());
if config.with_webpki != 0 {
let https = hyper_rustls::HttpsConnectorBuilder::new()
.with_webpki_roots()
.https_or_http()
.enable_http1()
.build();
builder = builder.connector(https);
}
match RT.block_on(builder.build()) {
Ok(db) => {
let db = Box::leak(Box::new(libsql_database { db }));
*out_db = libsql_database_t::from(db);
return 0;
}
Err(e) => {
set_err_msg(
format!(
"Error opening offline db path {db_path}, primary url {primary_url}: {e}"
),
out_err_msg,
);
return 101;
}
}
}
let mut builder = libsql::Builder::new_remote_replica(
db_path,
primary_url.to_string(),
auth_token.to_string(),
);
if config.with_webpki != 0 {
let https = hyper_rustls::HttpsConnectorBuilder::new()
.with_webpki_roots()
.https_or_http()
.enable_http1()
.build();
builder = builder.connector(https);
}
if config.sync_interval > 0 {
let interval = match config.sync_interval.try_into() {
Ok(d) => d,
Err(e) => {
set_err_msg(format!("Wrong periodic sync interval: {e}"), out_err_msg);
return 4;
}
};
builder = builder.sync_interval(std::time::Duration::from_secs(interval));
}
builder = builder.read_your_writes(config.read_your_writes != 0);
if !config.encryption_key.is_null() {
let key = unsafe { std::ffi::CStr::from_ptr(config.encryption_key) };
let key = match key.to_str() {
Ok(k) => k,
Err(e) => {
set_err_msg(format!("Wrong encryption key: {e}"), out_err_msg);
return 5;
}
};
let key = bytes::Bytes::copy_from_slice(key.as_bytes());
let config = libsql::EncryptionConfig::new(libsql::Cipher::Aes256Cbc, key);
builder = builder.encryption_config(config)
};
match RT.block_on(builder.build()) {
Ok(db) => {
let db = Box::leak(Box::new(libsql_database { db }));
*out_db = libsql_database_t::from(db);
0
}
Err(e) => {
set_err_msg(
format!("Error opening db path {db_path}, primary url {primary_url}: {e}"),
out_err_msg,
);
6
}
}
}
#[no_mangle]
pub unsafe extern "C" fn libsql_open_ext(
url: *const std::ffi::c_char,
out_db: *mut libsql_database_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
libsql_open_file(url, out_db, out_err_msg)
}
#[no_mangle]
pub unsafe extern "C" fn libsql_open_file(
url: *const std::ffi::c_char,
out_db: *mut libsql_database_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let url = unsafe { std::ffi::CStr::from_ptr(url) };
let url = match url.to_str() {
Ok(url) => url,
Err(e) => {
set_err_msg(format!("Wrong URL: {e}"), out_err_msg);
return 1;
}
};
match RT.block_on(libsql::Builder::new_local(url).build()) {
Ok(db) => {
let db = Box::leak(Box::new(libsql_database { db }));
*out_db = libsql_database_t::from(db);
0
}
Err(e) => {
set_err_msg(format!("Error opening URL {url}: {e}"), out_err_msg);
1
}
}
}
#[no_mangle]
pub unsafe extern "C" fn libsql_open_remote(
url: *const std::ffi::c_char,
auth_token: *const std::ffi::c_char,
out_db: *mut libsql_database_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
libsql_open_remote_internal(url, auth_token, false, out_db, out_err_msg)
}
#[no_mangle]
pub unsafe extern "C" fn libsql_open_remote_with_webpki(
url: *const std::ffi::c_char,
auth_token: *const std::ffi::c_char,
out_db: *mut libsql_database_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
libsql_open_remote_internal(url, auth_token, true, out_db, out_err_msg)
}
unsafe fn libsql_open_remote_internal(
url: *const std::ffi::c_char,
auth_token: *const std::ffi::c_char,
with_webpki: bool,
out_db: *mut libsql_database_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let url = unsafe { std::ffi::CStr::from_ptr(url) };
let url = match url.to_str() {
Ok(url) => url,
Err(e) => {
set_err_msg(format!("Wrong URL: {e}"), out_err_msg);
return 1;
}
};
let auth_token = unsafe { std::ffi::CStr::from_ptr(auth_token) };
let auth_token = match auth_token.to_str() {
Ok(token) => token,
Err(e) => {
set_err_msg(format!("Wrong Auth Token: {e}"), out_err_msg);
return 2;
}
};
let mut builder = libsql::Builder::new_remote(url.to_string(), auth_token.to_string());
if with_webpki {
let https = hyper_rustls::HttpsConnectorBuilder::new()
.with_webpki_roots()
.https_or_http()
.enable_http1()
.build();
builder = builder.connector(https);
}
match RT.block_on(builder.build()) {
Ok(db) => {
let db = Box::leak(Box::new(libsql_database { db }));
*out_db = libsql_database_t::from(db);
0
}
Err(e) => {
set_err_msg(format!("Error opening URL {url}: {e}"), out_err_msg);
1
}
}
}
#[no_mangle]
pub unsafe extern "C" fn libsql_close(db: libsql_database_t) {
if db.is_null() {
return;
}
let _db = unsafe { Box::from_raw(db.get_ref_mut()) };
// TODO close db
}
#[no_mangle]
pub unsafe extern "C" fn libsql_connect(
db: libsql_database_t,
out_conn: *mut libsql_connection_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let db = db.get_ref();
let conn = match db.connect() {
Ok(conn) => conn,
Err(err) => {
set_err_msg(format!("Unable to connect: {}", err), out_err_msg);
return 1;
}
};
let conn = Box::leak(Box::new(libsql_connection { conn }));
*out_conn = libsql_connection_t::from(conn);
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_load_extension(
conn: libsql_connection_t,
path: *const std::ffi::c_char,
entry_point: *const std::ffi::c_char,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
if path.is_null() {
set_err_msg("Null path".to_string(), out_err_msg);
return 1;
}
let path = unsafe { std::ffi::CStr::from_ptr(path) };
let path = match path.to_str() {
Ok(path) => path,
Err(e) => {
set_err_msg(format!("Wrong path: {}", e), out_err_msg);
return 2;
}
};
let mut entry_point_option = None;
if !entry_point.is_null() {
let entry_point = unsafe { std::ffi::CStr::from_ptr(entry_point) };
entry_point_option = match entry_point.to_str() {
Ok(entry_point) => Some(entry_point),
Err(e) => {
set_err_msg(format!("Wrong entry point: {}", e), out_err_msg);
return 4;
}
};
}
if conn.is_null() {
set_err_msg("Null connection".to_string(), out_err_msg);
return 5;
}
let conn = conn.get_ref();
match RT.block_on(async move {
let _guard = LoadExtensionGuard::new(conn)?;
conn.load_extension(path, entry_point_option)?;
Ok::<(), errors::Error>(())
}) {
Ok(()) => {}
Err(e) => {
set_err_msg(format!("Error loading extension: {}", e), out_err_msg);
return 6;
}
};
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_reset(
conn: libsql_connection_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
if conn.is_null() {
set_err_msg("Null connection".to_string(), out_err_msg);
return 1;
}
let conn = conn.get_ref();
RT.block_on(conn.reset());
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_disconnect(conn: libsql_connection_t) {
if conn.is_null() {
return;
}
let conn = unsafe { Box::from_raw(conn.get_ref_mut()) };
RT.spawn_blocking(|| {
drop(conn);
});
}
#[no_mangle]
pub unsafe extern "C" fn libsql_prepare(
conn: libsql_connection_t,
sql: *const std::ffi::c_char,
out_stmt: *mut libsql_stmt_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let sql = unsafe { std::ffi::CStr::from_ptr(sql) };
let sql = match sql.to_str() {
Ok(sql) => sql,
Err(e) => {
set_err_msg(format!("Wrong SQL: {}", e), out_err_msg);
return 1;
}
};
if conn.is_null() {
set_err_msg("Null connection".to_string(), out_err_msg);
return 2;
}
let conn = conn.get_ref();
match RT.block_on(conn.prepare(sql)) {
Ok(stmt) => {
let stmt = Box::leak(Box::new(libsql_stmt {
stmt: stmt {
stmt,
params: vec![],
},
}));
*out_stmt = libsql_stmt_t::from(stmt);
}
Err(e) => {
set_err_msg(format!("Error preparing statement: {}", e), out_err_msg);
return 3;
}
};
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_bind_int(
stmt: libsql_stmt_t,
idx: std::ffi::c_int,
value: std::ffi::c_longlong,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let idx: usize = match idx.try_into() {
Ok(x) => x,
Err(e) => {
set_err_msg(format!("Wrong param index: {}", e), out_err_msg);
return 1;
}
};
let stmt = stmt.get_ref_mut();
if stmt.params.len() < idx {
stmt.params.resize(idx, libsql::Value::Null);
}
stmt.params[idx - 1] = value.into();
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_bind_float(
stmt: libsql_stmt_t,
idx: std::ffi::c_int,
value: std::ffi::c_double,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let idx: usize = match idx.try_into() {
Ok(x) => x,
Err(e) => {
set_err_msg(format!("Wrong param index: {}", e), out_err_msg);
return 1;
}
};
let stmt = stmt.get_ref_mut();
if stmt.params.len() < idx {
stmt.params.resize(idx, libsql::Value::Null);
}
stmt.params[idx - 1] = value.into();
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_bind_null(
stmt: libsql_stmt_t,
idx: std::ffi::c_int,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let idx: usize = match idx.try_into() {
Ok(x) => x,
Err(e) => {
set_err_msg(format!("Wrong param index: {}", e), out_err_msg);
return 1;
}
};
let stmt = stmt.get_ref_mut();
if stmt.params.len() < idx {
stmt.params.resize(idx, libsql::Value::Null);
}
stmt.params[idx - 1] = libsql::Value::Null;
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_bind_string(
stmt: libsql_stmt_t,
idx: std::ffi::c_int,
value: *const std::ffi::c_char,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let idx: usize = match idx.try_into() {
Ok(x) => x,
Err(e) => {
set_err_msg(format!("Wrong param index: {}", e), out_err_msg);
return 1;
}
};
let value = unsafe { std::ffi::CStr::from_ptr(value) };
let value = match value.to_str() {
Ok(v) => v,
Err(e) => {
set_err_msg(format!("Wrong param value: {}", e), out_err_msg);
return 2;
}
};
let stmt = stmt.get_ref_mut();
if stmt.params.len() < idx {
stmt.params.resize(idx, libsql::Value::Null);
}
stmt.params[idx - 1] = value.to_string().into();
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_bind_blob(
stmt: libsql_stmt_t,
idx: std::ffi::c_int,
value: *const std::ffi::c_uchar,
value_len: std::ffi::c_int,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let idx: usize = match idx.try_into() {
Ok(x) => x,
Err(e) => {
set_err_msg(format!("Wrong param index: {}", e), out_err_msg);
return 1;
}
};
let value_len: usize = match value_len.try_into() {
Ok(v) => v,
Err(e) => {
set_err_msg(format!("Wrong param value len: {}", e), out_err_msg);
return 2;
}
};
let value = unsafe { core::slice::from_raw_parts(value, value_len) };
let value = Vec::from(value);
let stmt = stmt.get_ref_mut();
if stmt.params.len() < idx {
stmt.params.resize(idx, libsql::Value::Null);
}
stmt.params[idx - 1] = value.into();
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_query_stmt(
stmt: libsql_stmt_t,
out_rows: *mut libsql_rows_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
if stmt.is_null() {
set_err_msg("Null statement".to_string(), out_err_msg);
return 1;
}
let stmt = stmt.get_ref_mut();
match RT.block_on(stmt.stmt.query(stmt.params.clone())) {
Ok(rows) => {
let rows = Box::leak(Box::new(libsql_rows { result: rows }));
*out_rows = libsql_rows_t::from(rows);
}
Err(e) => {
set_err_msg(format!("Error executing statement: {}", e), out_err_msg);
return 1;
}
};
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_execute_stmt(
stmt: libsql_stmt_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
if stmt.is_null() {
set_err_msg("Null statement".to_string(), out_err_msg);
return 1;
}
let stmt = stmt.get_ref_mut();
match RT.block_on(stmt.stmt.execute(stmt.params.clone())) {
Ok(_) => 0,
Err(e) => {
set_err_msg(format!("Error executing statement: {}", e), out_err_msg);
2
}
}
}
#[no_mangle]
pub unsafe extern "C" fn libsql_reset_stmt(
stmt: libsql_stmt_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
if stmt.is_null() {
set_err_msg("Null statement".to_string(), out_err_msg);
return 1;
}
let stmt = stmt.get_ref_mut();
stmt.params.clear();
stmt.stmt.reset();
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_free_stmt(stmt: libsql_stmt_t) {
if stmt.is_null() {
return;
}
let _ = unsafe { Box::from_raw(stmt.get_ref_mut()) };
}
#[no_mangle]
pub unsafe extern "C" fn libsql_query(
conn: libsql_connection_t,
sql: *const std::ffi::c_char,
out_rows: *mut libsql_rows_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let sql = unsafe { std::ffi::CStr::from_ptr(sql) };
let sql = match sql.to_str() {
Ok(sql) => sql,
Err(e) => {
set_err_msg(format!("Wrong SQL: {}", e), out_err_msg);
return 1;
}
};
let conn = conn.get_ref();
match RT.block_on(conn.query(sql, ())) {
Ok(rows) => {
let rows = Box::leak(Box::new(libsql_rows { result: rows }));
*out_rows = libsql_rows_t::from(rows);
}
Err(e) => {
set_err_msg(format!("Error executing statement: {}", e), out_err_msg);
return 1;
}
};
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_execute(
conn: libsql_connection_t,
sql: *const std::ffi::c_char,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let sql = unsafe { std::ffi::CStr::from_ptr(sql) };
let sql = match sql.to_str() {
Ok(sql) => sql,
Err(e) => {
set_err_msg(format!("Wrong SQL: {}", e), out_err_msg);
return 1;
}
};
let conn = conn.get_ref();
match RT.block_on(conn.execute(sql, ())) {
Ok(_) => 0,
Err(e) => {
set_err_msg(format!("Error executing statement: {}", e), out_err_msg);
2
}
}
}
#[no_mangle]
pub unsafe extern "C" fn libsql_free_rows(res: libsql_rows_t) {
if res.is_null() {
return;
}
let _ = unsafe { Box::from_raw(res.get_ref_mut()) };
}
#[no_mangle]
pub unsafe extern "C" fn libsql_free_rows_future(res: libsql_rows_future_t) {
if res.is_null() {
return;
}
let mut res = unsafe { Box::from_raw(res.get_ref_mut()) };
res.wait().unwrap();
}
#[no_mangle]
pub unsafe extern "C" fn libsql_wait_result(res: libsql_rows_future_t) {
let res = res.get_ref_mut();
res.wait().unwrap();
}
#[no_mangle]
pub unsafe extern "C" fn libsql_column_count(res: libsql_rows_t) -> std::ffi::c_int {
let res = res.get_ref();
res.column_count()
}
#[no_mangle]
pub unsafe extern "C" fn libsql_column_name(
res: libsql_rows_t,
col: std::ffi::c_int,
out_name: *mut *const std::ffi::c_char,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let res = res.get_ref();
if col >= res.column_count() {
set_err_msg(
format!(
"Column index too big - got index {} with {} columns",
col,
res.column_count()
),
out_err_msg,
);
return 1;
}
let name = res
.column_name(col)
.expect("Column should have valid index");
match std::ffi::CString::new(name) {
Ok(name) => {
*out_name = name.into_raw();
0
}
Err(e) => {
set_err_msg(format!("Invalid name: {}", e), out_err_msg);
1
}
}
}
#[no_mangle]
pub unsafe extern "C" fn libsql_column_type(
res: libsql_rows_t,
row: libsql_row_t,
col: std::ffi::c_int,
out_type: *mut std::ffi::c_int,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let res = res.get_ref();
if col >= res.column_count() {
set_err_msg(
format!(
"Column index too big - got index {} with {} columns",
col,
res.column_count()
),
out_err_msg,
);
return 1;
}
let row = row.get_ref();
match row.get_value(col) {
Ok(libsql::Value::Null) => {
*out_type = types::LIBSQL_NULL as i32;
}
Ok(libsql::Value::Text(_)) => {
*out_type = types::LIBSQL_TEXT as i32;
}
Ok(libsql::Value::Integer(_)) => {
*out_type = types::LIBSQL_INT as i32;
}
Ok(libsql::Value::Real(_)) => {
*out_type = types::LIBSQL_FLOAT as i32;
}
Ok(libsql::Value::Blob(_)) => {
*out_type = types::LIBSQL_BLOB as i32;
}
Err(e) => {
set_err_msg(format!("Error fetching value: {e}"), out_err_msg);
return 2;
}
};
0
}
#[no_mangle]
pub unsafe extern "C" fn libsql_changes(conn: libsql_connection_t) -> u64 {
let conn = conn.get_ref();
conn.changes()
}
#[no_mangle]
pub unsafe extern "C" fn libsql_last_insert_rowid(conn: libsql_connection_t) -> i64 {
let conn = conn.get_ref();
conn.last_insert_rowid()
}
#[no_mangle]
pub unsafe extern "C" fn libsql_next_row(
res: libsql_rows_t,
out_row: *mut libsql_row_t,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
if res.is_null() {
*out_row = libsql_row_t::null();
return 0;
}
let rows = res.get_ref_mut();
let res = RT.block_on(rows.next());
match res {
Ok(Some(row)) => {
let row = Box::leak(Box::new(libsql_row { result: row }));
*out_row = libsql_row_t::from(row);
0
}
Ok(None) => {
*out_row = libsql_row_t::null();
0
}
Err(e) => {
*out_row = libsql_row_t::null();
set_err_msg(format!("Error fetching next row: {}", e), out_err_msg);
1
}
}
}
#[no_mangle]
pub unsafe extern "C" fn libsql_free_row(res: libsql_row_t) {
if res.is_null() {
return;
}
let _ = unsafe { Box::from_raw(res.get_ref_mut()) };
}
#[no_mangle]
pub unsafe extern "C" fn libsql_get_string(
res: libsql_row_t,
col: std::ffi::c_int,
out_value: *mut *const std::ffi::c_char,
out_err_msg: *mut *const std::ffi::c_char,
) -> std::ffi::c_int {
let res = res.get_ref();
match res.get_value(col) {
Ok(libsql::Value::Text(s)) => {
*out_value = translate_string(s);
0
}
Ok(_) => {
set_err_msg("Value not a string".into(), out_err_msg);
1