ng-oxigraph 0.4.0-alpha.8-ngalpha

a SPARQL database and RDF toolkit. fork for NextGraph
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
// partial Copyright (c) 2022-2025 Niko Bonnieure, Par le Peuple, NextGraph.org developers
// All rights reserved.
// partial Copyright (c) 2018 Oxigraph developers
// All work licensed under the Apache License, Version 2.0
// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice or not, may not be copied, modified, or distributed except
// according to those terms.

//! Code inspired by [Rust RocksDB](https://github.com/rust-rocksdb/rust-rocksdb) under Apache License 2.0.

#![allow(
    unsafe_code,
    trivial_casts,
    clippy::undocumented_unsafe_blocks,
    clippy::panic_in_result_fn,
    clippy::unwrap_in_result
)]

use super::super::numeric_encoder::StrHash;
use crate::oxigraph::storage::error::{CorruptionError, StorageError};
use libc::{c_char, c_void};
use ng_rocksdb::ffi::*;
use rand::random;
use std::borrow::Borrow;
#[cfg(unix)]
use std::cmp::min;
use std::collections::{HashMap, HashSet};
use std::env::temp_dir;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fs::remove_dir_all;
use std::marker::PhantomData;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::rc::{Rc, Weak};
use std::sync::{Arc, RwLock};
use std::thread::{available_parallelism, yield_now};
use std::{fmt, io, ptr, slice};

pub fn opt_bytes_to_ptr<T: AsRef<[u8]>>(opt: Option<T>) -> *const c_char {
    match opt {
        Some(v) => v.as_ref().as_ptr() as *const c_char,
        None => ptr::null(),
    }
}

macro_rules! ffi_result {
    ( $($function:ident)::*( $arg1:expr $(, $arg:expr)* $(,)? ) ) => {{
        let mut status = rocksdb_status_t {
            code: rocksdb_status_code_t_rocksdb_status_code_ok,
            subcode: rocksdb_status_subcode_t_rocksdb_status_subcode_none,
            severity: rocksdb_status_severity_t_rocksdb_status_severity_none,
            string: ptr::null()
        };
        let result = $($function)::*($arg1 $(, $arg)* , &mut status);
        if status.code == rocksdb_status_code_t_rocksdb_status_code_ok {
            Ok(result)
        } else {
            Err(ErrorStatus(status))
        }
    }}
}

pub struct ColumnFamilyDefinition {
    pub name: &'static str,
    pub use_iter: bool,
    pub min_prefix_size: usize,
    pub unordered_writes: bool,
}

#[derive(Clone)]
pub struct Db {
    inner: DbKind,
}

#[derive(Clone)]
enum DbKind {
    ReadOnly(Arc<RoDbHandler>),
    ReadWrite(Arc<RwDbHandler>),
}

impl Db {
    pub(crate) fn past_commits_cache(
        &self,
    ) -> Arc<RwLock<HashMap<StrHash, Arc<HashSet<StrHash>>>>> {
        match &self.inner {
            DbKind::ReadWrite(rw) => Arc::clone(&rw.past_commits_cache),
            _ => panic!("rw not implemented for read only DbKind"),
        }
    }
}

struct RwDbHandler {
    db: *mut rocksdb_transactiondb_t,
    env: UnsafeEnv,
    options: *mut rocksdb_options_t,
    transaction_options: *mut rocksdb_transaction_options_t,
    transactiondb_options: *mut rocksdb_transactiondb_options_t,
    read_options: *mut rocksdb_readoptions_t,
    write_options: *mut rocksdb_writeoptions_t,
    flush_options: *mut rocksdb_flushoptions_t,
    env_options: *mut rocksdb_envoptions_t,
    ingest_external_file_options: *mut rocksdb_ingestexternalfileoptions_t,
    compaction_options: *mut rocksdb_compactoptions_t,
    block_based_table_options: *mut rocksdb_block_based_table_options_t,
    column_family_names: Vec<&'static str>,
    cf_handles: Vec<*mut rocksdb_column_family_handle_t>,
    cf_options: Vec<*mut rocksdb_options_t>,
    in_memory: bool,
    path: PathBuf,
    past_commits_cache: Arc<RwLock<HashMap<StrHash, Arc<HashSet<StrHash>>>>>,
}

unsafe impl Send for RwDbHandler {}

unsafe impl Sync for RwDbHandler {}

impl Drop for RwDbHandler {
    fn drop(&mut self) {
        unsafe {
            for cf_handle in &self.cf_handles {
                rocksdb_column_family_handle_destroy(*cf_handle);
            }
            rocksdb_transactiondb_close(self.db);
            for cf_option in &self.cf_options {
                rocksdb_options_destroy(*cf_option);
            }
            rocksdb_readoptions_destroy(self.read_options);
            rocksdb_writeoptions_destroy(self.write_options);
            rocksdb_flushoptions_destroy(self.flush_options);
            rocksdb_envoptions_destroy(self.env_options);
            rocksdb_ingestexternalfileoptions_destroy(self.ingest_external_file_options);
            rocksdb_compactoptions_destroy(self.compaction_options);
            rocksdb_transaction_options_destroy(self.transaction_options);
            rocksdb_transactiondb_options_destroy(self.transactiondb_options);
            rocksdb_options_destroy(self.options);
            rocksdb_block_based_options_destroy(self.block_based_table_options);
            rocksdb_env_destroy(self.env.0);
        }
        if self.in_memory {
            drop(remove_dir_all(&self.path));
        }
    }
}

struct RoDbHandler {
    db: *mut rocksdb_t,
    env: UnsafeEnv,
    options: *mut rocksdb_options_t,
    read_options: *mut rocksdb_readoptions_t,
    column_family_names: Vec<&'static str>,
    cf_handles: Vec<*mut rocksdb_column_family_handle_t>,
    cf_options: Vec<*mut rocksdb_options_t>,
    is_secondary: bool,
    path_to_remove: Option<PathBuf>,
}

unsafe impl Send for RoDbHandler {}

unsafe impl Sync for RoDbHandler {}

impl Drop for RoDbHandler {
    fn drop(&mut self) {
        unsafe {
            for cf_handle in &self.cf_handles {
                rocksdb_column_family_handle_destroy(*cf_handle);
            }
            rocksdb_close(self.db);
            for cf_option in &self.cf_options {
                rocksdb_options_destroy(*cf_option);
            }
            rocksdb_readoptions_destroy(self.read_options);
            rocksdb_options_destroy(self.options);
            rocksdb_env_destroy(self.env.0);
        }
        if let Some(path) = &self.path_to_remove {
            drop(remove_dir_all(path));
        }
    }
}

impl Db {
    pub fn new(column_families: Vec<ColumnFamilyDefinition>) -> Result<Self, StorageError> {
        Self::open_read_write(None, column_families, None)
    }

    pub fn open_read_write(
        path: Option<&Path>,
        column_families: Vec<ColumnFamilyDefinition>,
        key: Option<[u8; 32]>,
    ) -> Result<Self, StorageError> {
        let (path, in_memory) = if let Some(path) = path {
            (path.to_path_buf(), false)
        } else {
            (tmp_path(), true)
        };
        let c_path = path_to_cstring(&path)?;
        unsafe {
            let unsafe_env = Self::create_env(in_memory, key);
            let options = Self::db_options(true, &unsafe_env)?;
            rocksdb_options_set_create_if_missing(options, 1);
            rocksdb_options_set_create_missing_column_families(options, 1);
            rocksdb_options_set_compression(
                options,
                if in_memory {
                    rocksdb_no_compression
                } else {
                    rocksdb_lz4_compression
                }
                .try_into()
                .unwrap(),
            );
            let block_based_table_options = rocksdb_block_based_options_create();
            assert!(
                !block_based_table_options.is_null(),
                "rocksdb_block_based_options_create returned null"
            );
            rocksdb_block_based_options_set_format_version(block_based_table_options, 5);
            rocksdb_block_based_options_set_index_block_restart_interval(
                block_based_table_options,
                16,
            );
            rocksdb_options_set_block_based_table_factory(options, block_based_table_options);
            #[cfg(feature = "rocksdb-debug")]
            {
                rocksdb_options_set_info_log_level(options, 0);
                rocksdb_options_enable_statistics(options);
                rocksdb_options_set_stats_dump_period_sec(options, 60);
            }

            let (column_family_names, c_column_family_names, cf_options) =
                Self::column_families_names_and_options(column_families, options);
            let mut cf_handles: Vec<*mut rocksdb_column_family_handle_t> =
                vec![ptr::null_mut(); column_family_names.len()];
            let c_num_column_families = c_column_family_names.len().try_into().unwrap();

            let transactiondb_options = rocksdb_transactiondb_options_create();
            assert!(
                !transactiondb_options.is_null(),
                "rocksdb_transactiondb_options_create returned null"
            );

            let db = ffi_result!(rocksdb_transactiondb_open_column_families_with_status(
                options,
                transactiondb_options,
                c_path.as_ptr(),
                c_num_column_families,
                c_column_family_names
                    .iter()
                    .map(|cf| cf.as_ptr())
                    .collect::<Vec<_>>()
                    .as_ptr(),
                cf_options.as_ptr().cast(),
                cf_handles.as_mut_ptr(),
            ))
            .map_err(|e| {
                rocksdb_transactiondb_options_destroy(transactiondb_options);
                for cf_option in &cf_options {
                    rocksdb_options_destroy(*cf_option);
                }
                rocksdb_options_destroy(options);
                rocksdb_block_based_options_destroy(block_based_table_options);
                e
            })?;
            assert!(!db.is_null(), "rocksdb_create returned null");
            for handle in &cf_handles {
                assert!(
                    !handle.is_null(),
                    "rocksdb_readoptions_create returned a null column family"
                );
            }

            let read_options = rocksdb_readoptions_create();
            assert!(
                !read_options.is_null(),
                "rocksdb_readoptions_create returned null"
            );

            let write_options = rocksdb_writeoptions_create();
            assert!(
                !write_options.is_null(),
                "rocksdb_writeoptions_create returned null"
            );

            if in_memory {
                rocksdb_writeoptions_disable_WAL(write_options, 1); // No need for WAL
            } else {
                rocksdb_writeoptions_set_sync(write_options, 1);
            }

            let transaction_options = rocksdb_transaction_options_create();
            assert!(
                !transaction_options.is_null(),
                "rocksdb_transaction_options_create returned null"
            );
            rocksdb_transaction_options_set_set_snapshot(transaction_options, 1);

            let flush_options = rocksdb_flushoptions_create();
            assert!(
                !flush_options.is_null(),
                "rocksdb_flushoptions_create returned null"
            );

            let env_options = rocksdb_envoptions_create();
            assert!(
                !env_options.is_null(),
                "rocksdb_envoptions_create returned null"
            );

            let ingest_external_file_options = rocksdb_ingestexternalfileoptions_create();
            assert!(
                !ingest_external_file_options.is_null(),
                "rocksdb_ingestexternalfileoptions_create returned null"
            );

            let compaction_options = rocksdb_compactoptions_create();
            assert!(
                !compaction_options.is_null(),
                "rocksdb_compactoptions_create returned null"
            );

            Ok(Self {
                inner: DbKind::ReadWrite(Arc::new(RwDbHandler {
                    db,
                    env: unsafe_env,
                    options,
                    transaction_options,
                    transactiondb_options,
                    read_options,
                    write_options,
                    flush_options,
                    env_options,
                    ingest_external_file_options,
                    compaction_options,
                    block_based_table_options,
                    column_family_names,
                    cf_handles,
                    cf_options,
                    in_memory,
                    path,
                    past_commits_cache: Arc::new(RwLock::new(HashMap::new())),
                })),
            })
        }
    }

    // pub fn open_secondary(
    //     primary_path: &Path,
    //     secondary_path: Option<&Path>,
    //     column_families: Vec<ColumnFamilyDefinition>,
    // ) -> Result<Self, StorageError> {
    //     let c_primary_path = path_to_cstring(primary_path)?;
    //     let (secondary_path, in_memory) = if let Some(path) = secondary_path {
    //         (path.to_path_buf(), false)
    //     } else {
    //         (tmp_path(), true)
    //     };
    //     let c_secondary_path = path_to_cstring(&secondary_path)?;
    //     unsafe {
    //         let options = Self::db_options(false, false)?;
    //         let (column_family_names, c_column_family_names, cf_options) =
    //             Self::column_families_names_and_options(column_families, options);
    //         let mut cf_handles: Vec<*mut rocksdb_column_family_handle_t> =
    //             vec![ptr::null_mut(); column_family_names.len()];
    //         let c_num_column_families = c_column_family_names.len().try_into().unwrap();
    //         let db = ffi_result!(rocksdb_open_as_secondary_column_families_with_status(
    //             options,
    //             c_primary_path.as_ptr(),
    //             c_secondary_path.as_ptr(),
    //             c_num_column_families,
    //             c_column_family_names
    //                 .iter()
    //                 .map(|cf| cf.as_ptr())
    //                 .collect::<Vec<_>>()
    //                 .as_ptr(),
    //             cf_options.as_ptr().cast(),
    //             cf_handles.as_mut_ptr(),
    //         ))
    //         .map_err(|e| {
    //             for cf_option in &cf_options {
    //                 rocksdb_options_destroy(*cf_option);
    //             }
    //             rocksdb_options_destroy(options);
    //             e
    //         })?;
    //         assert!(
    //             !db.is_null(),
    //             "rocksdb_open_for_read_only_column_families_with_status returned null"
    //         );
    //         for handle in &cf_handles {
    //             assert!(
    //                 !handle.is_null(),
    //                 "rocksdb_open_for_read_only_column_families_with_status returned a null column family"
    //             );
    //         }
    //         let read_options = rocksdb_readoptions_create();
    //         assert!(
    //             !read_options.is_null(),
    //             "rocksdb_readoptions_create returned null"
    //         );
    //         Ok(Self {
    //             inner: DbKind::ReadOnly(Arc::new(RoDbHandler {
    //                 db,
    //                 options,
    //                 read_options,
    //                 column_family_names,
    //                 cf_handles,
    //                 cf_options,
    //                 is_secondary: true,
    //                 path_to_remove: in_memory.then_some(secondary_path),
    //             })),
    //         })
    //     }
    // }

    pub fn open_read_only(
        path: &Path,
        column_families: Vec<ColumnFamilyDefinition>,
        key: Option<[u8; 32]>,
    ) -> Result<Self, StorageError> {
        unsafe {
            let c_path = path_to_cstring(path)?;
            let unsafe_env = Self::create_env(false, key);
            let options = Self::db_options(true, &unsafe_env)?;
            let (column_family_names, c_column_family_names, cf_options) =
                Self::column_families_names_and_options(column_families, options);
            let mut cf_handles: Vec<*mut rocksdb_column_family_handle_t> =
                vec![ptr::null_mut(); column_family_names.len()];
            let c_num_column_families = c_column_family_names.len().try_into().unwrap();
            let db = ffi_result!(rocksdb_open_for_read_only_column_families_with_status(
                options,
                c_path.as_ptr(),
                c_num_column_families,
                c_column_family_names
                    .iter()
                    .map(|cf| cf.as_ptr())
                    .collect::<Vec<_>>()
                    .as_ptr(),
                cf_options.as_ptr().cast(),
                cf_handles.as_mut_ptr(),
                0, // false
            ))
            .map_err(|e| {
                for cf_option in &cf_options {
                    rocksdb_options_destroy(*cf_option);
                }
                rocksdb_options_destroy(options);
                e
            })?;
            assert!(
                !db.is_null(),
                "rocksdb_open_for_read_only_column_families_with_status returned null"
            );
            for handle in &cf_handles {
                assert!(
                    !handle.is_null(),
                    "rocksdb_open_for_read_only_column_families_with_status returned a null column family"
                );
            }
            let read_options = rocksdb_readoptions_create();
            assert!(
                !read_options.is_null(),
                "rocksdb_readoptions_create returned null"
            );

            Ok(Self {
                inner: DbKind::ReadOnly(Arc::new(RoDbHandler {
                    db,
                    env: unsafe_env,
                    options,
                    read_options,
                    column_family_names,
                    cf_handles,
                    cf_options,
                    is_secondary: false,
                    path_to_remove: None,
                })),
            })
        }
    }

    fn create_env(in_memory: bool, key: Option<[u8; 32]>) -> UnsafeEnv {
        unsafe {
            if in_memory {
                let env = rocksdb_create_mem_env();
                assert!(!env.is_null(), "rocksdb_create_mem_env returned null");
                UnsafeEnv(env)
            } else {
                let env = match key {
                    Some(_) => rocksdb_create_encrypted_env(opt_bytes_to_ptr(key.as_ref())),
                    None => rocksdb_create_default_env(),
                };
                assert!(!env.is_null(), "rocksdb_create_encrypted_env returned null");
                UnsafeEnv(env)
            }
        }
    }

    fn db_options(
        limit_max_open_files: bool,
        unsafe_env: &UnsafeEnv,
    ) -> Result<*mut rocksdb_options_t, StorageError> {
        unsafe {
            let options = rocksdb_options_create();
            assert!(!options.is_null(), "rocksdb_options_create returned null");
            rocksdb_options_optimize_level_style_compaction(options, 512 * 1024 * 1024);
            rocksdb_options_increase_parallelism(
                options,
                available_parallelism()?.get().try_into().unwrap(),
            );
            if limit_max_open_files {
                if let Some(available_fd) = available_file_descriptors()? {
                    if available_fd < 96 {
                        rocksdb_options_destroy(options);
                        return Err(io::Error::new(
                            io::ErrorKind::Other,
                            format!(
                                "Oxigraph needs at least 96 file descriptors, \
                                    only {available_fd} allowed. \
                                    Run e.g. `ulimit -n 512` to allow 512 opened files"
                            ),
                        )
                        .into());
                    }
                    rocksdb_options_set_max_open_files(
                        options,
                        (available_fd - 48).try_into().unwrap(),
                    )
                }
            } else {
                rocksdb_options_set_max_open_files(options, -1);
            }
            rocksdb_options_set_info_log_level(options, 2); // We only log warnings
            rocksdb_options_set_max_log_file_size(options, 1024 * 1024); // Only 1MB log size
            rocksdb_options_set_recycle_log_file_num(options, 10); // We do not keep more than 10 log files
            rocksdb_options_set_env(options, unsafe_env.0);
            Ok(options)
        }
    }

    fn column_families_names_and_options(
        mut column_families: Vec<ColumnFamilyDefinition>,
        base_options: *mut rocksdb_options_t,
    ) -> (Vec<&'static str>, Vec<CString>, Vec<*mut rocksdb_options_t>) {
        if !column_families.iter().any(|c| c.name == "default") {
            column_families.push(ColumnFamilyDefinition {
                name: "default",
                use_iter: true,
                min_prefix_size: 0,
                unordered_writes: false,
            })
        }
        let column_family_names = column_families.iter().map(|c| c.name).collect::<Vec<_>>();
        let c_column_family_names = column_family_names
            .iter()
            .map(|name| CString::new(*name).unwrap())
            .collect();

        let cf_options = column_families
            .into_iter()
            .map(|cf| unsafe {
                let options = rocksdb_options_create_copy(base_options);
                if !cf.use_iter {
                    rocksdb_options_optimize_for_point_lookup(options, 128);
                }
                if cf.min_prefix_size > 0 {
                    rocksdb_options_set_prefix_extractor(
                        options,
                        rocksdb_slicetransform_create_fixed_prefix(cf.min_prefix_size),
                    );
                }
                if cf.unordered_writes {
                    rocksdb_options_set_unordered_write(options, 1);
                }
                options
            })
            .collect::<Vec<_>>();
        (column_family_names, c_column_family_names, cf_options)
    }

    pub fn column_family(&self, name: &'static str) -> Result<ColumnFamily, StorageError> {
        let (column_family_names, cf_handles) = match &self.inner {
            DbKind::ReadOnly(db) => (&db.column_family_names, &db.cf_handles),
            DbKind::ReadWrite(db) => (&db.column_family_names, &db.cf_handles),
        };
        for (cf, cf_handle) in column_family_names.iter().zip(cf_handles) {
            if *cf == name {
                return Ok(ColumnFamily(*cf_handle));
            }
        }
        Err(CorruptionError::from_missing_column_family_name(name).into())
    }

    #[must_use]
    pub fn snapshot(&self) -> Reader {
        unsafe {
            match &self.inner {
                DbKind::ReadOnly(db) => {
                    if db.is_secondary {
                        // We try to refresh (and ignore the errors)
                        drop(ffi_result!(rocksdb_try_catch_up_with_primary_with_status(
                            db.db
                        )));
                    }
                    let options = rocksdb_readoptions_create_copy(db.read_options);
                    Reader {
                        inner: InnerReader::PlainDb(Arc::clone(db)),
                        options,
                    }
                }
                DbKind::ReadWrite(db) => {
                    let options = rocksdb_readoptions_create_copy(db.read_options);
                    let snapshot = rocksdb_transactiondb_create_snapshot(db.db);
                    assert!(
                        !snapshot.is_null(),
                        "rocksdb_transactiondb_create_snapshot returned null"
                    );
                    rocksdb_readoptions_set_snapshot(options, snapshot);
                    Reader {
                        inner: InnerReader::TransactionalSnapshot(Rc::new(TransactionalSnapshot {
                            db: Arc::clone(db),
                            snapshot,
                        })),
                        options,
                    }
                }
            }
        }
    }

    pub fn transaction<'a, 'b: 'a, T, E: Error + 'static + From<StorageError>>(
        &'b self,
        f: impl Fn(Transaction<'a>) -> Result<T, E>,
    ) -> Result<T, E> {
        if let DbKind::ReadWrite(db) = &self.inner {
            loop {
                let transaction = unsafe {
                    let transaction = rocksdb_transaction_begin(
                        db.db,
                        db.write_options,
                        db.transaction_options,
                        ptr::null_mut(),
                    );
                    assert!(
                        !transaction.is_null(),
                        "rocksdb_transaction_begin returned null"
                    );
                    transaction
                };
                let (read_options, snapshot) = unsafe {
                    let options = rocksdb_readoptions_create_copy(db.read_options);
                    let snapshot = rocksdb_transaction_get_snapshot(transaction);
                    rocksdb_readoptions_set_snapshot(options, snapshot);
                    (options, snapshot)
                };
                let result = f(Transaction {
                    inner: Rc::new(transaction),
                    read_options,
                    _lifetime: PhantomData,
                });
                match result {
                    Ok(result) => {
                        unsafe {
                            let r =
                                ffi_result!(rocksdb_transaction_rollback_with_status(transaction));
                            rocksdb_transaction_destroy(transaction);
                            rocksdb_readoptions_destroy(read_options);
                            rocksdb_free(snapshot as *mut c_void);
                            r.map_err(StorageError::from)?; // We make sure to also run destructors if the commit fails
                        }
                        return Ok(result);
                    }
                    Err(e) => {
                        unsafe {
                            let r =
                                ffi_result!(rocksdb_transaction_rollback_with_status(transaction));
                            rocksdb_transaction_destroy(transaction);
                            rocksdb_readoptions_destroy(read_options);
                            rocksdb_free(snapshot as *mut c_void);
                            r.map_err(StorageError::from)?; // We make sure to also run destructors if the commit fails
                        }
                        // We look for the root error
                        let mut error: &(dyn Error + 'static) = &e;
                        while let Some(e) = error.source() {
                            error = e;
                        }
                        let is_conflict_error =
                            error.downcast_ref::<ErrorStatus>().map_or(false, |e| {
                                e.0.code == rocksdb_status_code_t_rocksdb_status_code_busy
                                    || e.0.code
                                        == rocksdb_status_code_t_rocksdb_status_code_timed_out
                                    || e.0.code
                                        == rocksdb_status_code_t_rocksdb_status_code_try_again
                            });
                        if is_conflict_error {
                            // We give a chance to the OS to do something else before retrying in order to help avoiding another conflict
                            yield_now();
                        } else {
                            // We raise the error
                            return Err(e);
                        }
                    }
                }
            }
        } else {
            Err(
                StorageError::Other("Transaction are only possible on read-write instances".into())
                    .into(),
            )
        }
    }

    pub fn ng_transaction<'a, 'b: 'a, T, E: Error + 'static + From<StorageError>>(
        &'b self,
        mut f: impl FnMut(Transaction<'a>) -> Result<T, E>,
    ) -> Result<T, E> {
        if let DbKind::ReadWrite(db) = &self.inner {
            loop {
                let transaction = unsafe {
                    let transaction = rocksdb_transaction_begin(
                        db.db,
                        db.write_options,
                        db.transaction_options,
                        ptr::null_mut(),
                    );
                    assert!(
                        !transaction.is_null(),
                        "rocksdb_transaction_begin returned null"
                    );
                    transaction
                };
                let (read_options, snapshot) = unsafe {
                    let options = rocksdb_readoptions_create_copy(db.read_options);
                    let snapshot = rocksdb_transaction_get_snapshot(transaction);
                    rocksdb_readoptions_set_snapshot(options, snapshot);
                    (options, snapshot)
                };
                let result = f(Transaction {
                    inner: Rc::new(transaction),
                    read_options,
                    _lifetime: PhantomData,
                });
                match result {
                    Ok(result) => {
                        unsafe {
                            let r =
                                ffi_result!(rocksdb_transaction_commit_with_status(transaction));
                            rocksdb_transaction_destroy(transaction);
                            rocksdb_readoptions_destroy(read_options);
                            rocksdb_free(snapshot as *mut c_void);
                            r.map_err(StorageError::from)?; // We make sure to also run destructors if the commit fails
                        }
                        return Ok(result);
                    }
                    Err(e) => {
                        unsafe {
                            let r =
                                ffi_result!(rocksdb_transaction_rollback_with_status(transaction));
                            rocksdb_transaction_destroy(transaction);
                            rocksdb_readoptions_destroy(read_options);
                            rocksdb_free(snapshot as *mut c_void);
                            r.map_err(StorageError::from)?; // We make sure to also run destructors if the commit fails
                        }
                        // We look for the root error
                        let mut error: &(dyn Error + 'static) = &e;
                        while let Some(e) = error.source() {
                            error = e;
                        }
                        let is_conflict_error =
                            error.downcast_ref::<ErrorStatus>().map_or(false, |e| {
                                e.0.code == rocksdb_status_code_t_rocksdb_status_code_busy
                                    || e.0.code
                                        == rocksdb_status_code_t_rocksdb_status_code_timed_out
                                    || e.0.code
                                        == rocksdb_status_code_t_rocksdb_status_code_try_again
                            });
                        if is_conflict_error {
                            // We give a chance to the OS to do something else before retrying in order to help avoiding another conflict
                            yield_now();
                        } else {
                            // We raise the error
                            return Err(e);
                        }
                    }
                }
            }
        } else {
            Err(
                StorageError::Other("Transaction are only possible on read-write instances".into())
                    .into(),
            )
        }
    }

    pub fn get(
        &self,
        column_family: &ColumnFamily,
        key: &[u8],
    ) -> Result<Option<PinnableSlice>, StorageError> {
        unsafe {
            let slice = match &self.inner {
                DbKind::ReadOnly(db) => {
                    ffi_result!(rocksdb_get_pinned_cf_with_status(
                        db.db,
                        db.read_options,
                        column_family.0,
                        key.as_ptr().cast(),
                        key.len(),
                    ))
                }
                DbKind::ReadWrite(db) => {
                    ffi_result!(rocksdb_transactiondb_get_pinned_cf_with_status(
                        db.db,
                        db.read_options,
                        column_family.0,
                        key.as_ptr().cast(),
                        key.len()
                    ))
                }
            }?;
            Ok(if slice.is_null() {
                None
            } else {
                Some(PinnableSlice(slice))
            })
        }
    }

    pub fn contains_key(
        &self,
        column_family: &ColumnFamily,
        key: &[u8],
    ) -> Result<bool, StorageError> {
        Ok(self.get(column_family, key)?.is_some()) // TODO: optimize
    }

    pub fn insert(
        &self,
        column_family: &ColumnFamily,
        key: &[u8],
        value: &[u8],
    ) -> Result<(), StorageError> {
        if let DbKind::ReadWrite(db) = &self.inner {
            unsafe {
                ffi_result!(rocksdb_transactiondb_put_cf_with_status(
                    db.db,
                    db.write_options,
                    column_family.0,
                    key.as_ptr().cast(),
                    key.len(),
                    value.as_ptr().cast(),
                    value.len(),
                ))
            }?;
            Ok(())
        } else {
            Err(StorageError::Other(
                "Inserts are only possible on read-write instances".into(),
            ))
        }
    }

    pub fn flush(&self) -> Result<(), StorageError> {
        if let DbKind::ReadWrite(db) = &self.inner {
            unsafe {
                ffi_result!(rocksdb_transactiondb_flush_cfs_with_status(
                    db.db,
                    db.flush_options,
                    db.cf_handles.as_ptr().cast_mut(),
                    db.cf_handles.len().try_into().unwrap()
                ))
            }?;
            Ok(())
        } else {
            Err(StorageError::Other(
                "Flush is only possible on read-write instances".into(),
            ))
        }
    }

    pub fn compact(&self, column_family: &ColumnFamily) -> Result<(), StorageError> {
        if let DbKind::ReadWrite(db) = &self.inner {
            unsafe {
                ffi_result!(rocksdb_transactiondb_compact_range_cf_opt_with_status(
                    db.db,
                    column_family.0,
                    db.compaction_options,
                    ptr::null(),
                    0,
                    ptr::null(),
                    0,
                ))
            }?;
            Ok(())
        } else {
            Err(StorageError::Other(
                "Compaction is only possible on read-write instances".into(),
            ))
        }
    }

    pub fn new_sst_file(&self) -> Result<SstFileWriter, StorageError> {
        if let DbKind::ReadWrite(db) = &self.inner {
            let path = db.path.join(random::<u128>().to_string());
            unsafe {
                let writer = rocksdb_sstfilewriter_create(db.env_options, db.options);
                ffi_result!(rocksdb_sstfilewriter_open_with_status(
                    writer,
                    path_to_cstring(&path)?.as_ptr()
                ))
                .map_err(|e| {
                    rocksdb_sstfilewriter_destroy(writer);
                    e
                })?;
                Ok(SstFileWriter { writer, path })
            }
        } else {
            Err(StorageError::Other(
                "SST creation is only possible on read-write instances".into(),
            ))
        }
    }

    pub fn insert_stt_files(
        &self,
        ssts_for_cf: &[(&ColumnFamily, PathBuf)],
    ) -> Result<(), StorageError> {
        if ssts_for_cf.is_empty() {
            return Ok(()); // Rocksdb does not support empty lists
        }
        if let DbKind::ReadWrite(db) = &self.inner {
            let mut paths_by_cf = HashMap::<_, Vec<_>>::new();
            for (cf, path) in ssts_for_cf {
                paths_by_cf
                    .entry(*cf)
                    .or_default()
                    .push(path_to_cstring(path)?);
            }
            let cpaths_by_cf = paths_by_cf
                .iter()
                .map(|(cf, paths)| (*cf, paths.iter().map(|p| p.as_ptr()).collect::<Vec<_>>()))
                .collect::<Vec<_>>();
            let args = cpaths_by_cf
                .iter()
                .map(|(cf, p)| rocksdb_ingestexternalfilearg_t {
                    column_family: cf.0,
                    external_files: p.as_ptr(),
                    external_files_len: p.len(),
                    options: db.ingest_external_file_options,
                })
                .collect::<Vec<_>>();
            unsafe {
                ffi_result!(rocksdb_transactiondb_ingest_external_files_with_status(
                    db.db,
                    args.as_ptr(),
                    args.len()
                ))?;
            }
            Ok(())
        } else {
            Err(StorageError::Other(
                "SST ingestion is only possible on read-write instances".into(),
            ))
        }
    }

    pub fn backup(&self, target_directory: &Path) -> Result<(), StorageError> {
        let path = path_to_cstring(target_directory)?;
        match &self.inner {
            DbKind::ReadOnly(db) => unsafe {
                if db.is_secondary {
                    ffi_result!(rocksdb_try_catch_up_with_primary_with_status(db.db))?;
                }
                ffi_result!(rocksdb_create_checkpoint_with_status(db.db, path.as_ptr()))
            },
            DbKind::ReadWrite(db) => {
                if db.in_memory {
                    return Err(StorageError::Other(
                        "It is not possible to backup an in-memory database".into(),
                    ));
                }
                unsafe {
                    ffi_result!(rocksdb_transactiondb_create_checkpoint_with_status(
                        db.db,
                        path.as_ptr()
                    ))
                }
            }
        }?;
        Ok(())
    }
}

// It is fine to not keep a lifetime: there is no way to use this type without the database being still in scope.
// So, no use after free possible.
#[derive(Clone, Eq, PartialEq, Hash)]
pub struct ColumnFamily(*mut rocksdb_column_family_handle_t);

unsafe impl Send for ColumnFamily {}
unsafe impl Sync for ColumnFamily {}

pub struct Reader {
    inner: InnerReader,
    options: *mut rocksdb_readoptions_t,
}

#[derive(Clone)]
enum InnerReader {
    TransactionalSnapshot(Rc<TransactionalSnapshot>),
    Transaction(Weak<*mut rocksdb_transaction_t>),
    PlainDb(Arc<RoDbHandler>),
}

struct TransactionalSnapshot {
    db: Arc<RwDbHandler>,
    snapshot: *const rocksdb_snapshot_t,
}

impl Drop for TransactionalSnapshot {
    fn drop(&mut self) {
        unsafe { rocksdb_transactiondb_release_snapshot(self.db.db, self.snapshot) }
    }
}

impl Clone for Reader {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            options: unsafe { rocksdb_readoptions_create_copy(self.options) },
        }
    }
}

impl Drop for Reader {
    fn drop(&mut self) {
        unsafe { rocksdb_readoptions_destroy(self.options) }
    }
}

impl Reader {
    pub fn get(
        &self,
        column_family: &ColumnFamily,
        key: &[u8],
    ) -> Result<Option<PinnableSlice>, StorageError> {
        unsafe {
            let slice = match &self.inner {
                InnerReader::TransactionalSnapshot(inner) => {
                    ffi_result!(rocksdb_transactiondb_get_pinned_cf_with_status(
                        inner.db.db,
                        self.options,
                        column_family.0,
                        key.as_ptr().cast(),
                        key.len()
                    ))
                }
                InnerReader::Transaction(inner) => {
                    let Some(inner) = inner.upgrade() else {
                        return Err(StorageError::Other(
                            "The transaction is already ended".into(),
                        ));
                    };
                    ffi_result!(rocksdb_transaction_get_pinned_cf_with_status(
                        *inner,
                        self.options,
                        column_family.0,
                        key.as_ptr().cast(),
                        key.len()
                    ))
                }
                InnerReader::PlainDb(inner) => {
                    ffi_result!(rocksdb_get_pinned_cf_with_status(
                        inner.db,
                        self.options,
                        column_family.0,
                        key.as_ptr().cast(),
                        key.len()
                    ))
                }
            }?;
            Ok(if slice.is_null() {
                None
            } else {
                Some(PinnableSlice(slice))
            })
        }
    }

    pub fn contains_key(
        &self,
        column_family: &ColumnFamily,
        key: &[u8],
    ) -> Result<bool, StorageError> {
        Ok(self.get(column_family, key)?.is_some()) // TODO: optimize
    }

    #[allow(clippy::iter_not_returning_iterator)]
    pub fn iter(&self, column_family: &ColumnFamily) -> Result<Iter, StorageError> {
        self.scan_prefix(column_family, &[])
    }

    pub fn scan_prefix(
        &self,
        column_family: &ColumnFamily,
        prefix: &[u8],
    ) -> Result<Iter, StorageError> {
        // We generate the upper bound
        let upper_bound = {
            let mut bound = prefix.to_vec();
            let mut found = false;
            for c in bound.iter_mut().rev() {
                if *c < u8::MAX {
                    *c += 1;
                    found = true;
                    break;
                }
            }
            found.then_some(bound)
        };

        unsafe {
            let options = rocksdb_readoptions_create_copy(self.options);
            assert!(
                !options.is_null(),
                "rocksdb_readoptions_create returned null"
            );
            if let Some(upper_bound) = &upper_bound {
                rocksdb_readoptions_set_iterate_upper_bound(
                    options,
                    upper_bound.as_ptr().cast(),
                    upper_bound.len(),
                );
            }
            let iter = match &self.inner {
                InnerReader::TransactionalSnapshot(inner) => {
                    rocksdb_transactiondb_create_iterator_cf(inner.db.db, options, column_family.0)
                }
                InnerReader::Transaction(inner) => {
                    let Some(inner) = inner.upgrade() else {
                        return Err(StorageError::Other(
                            "The transaction is already ended".into(),
                        ));
                    };
                    rocksdb_transaction_create_iterator_cf(*inner, options, column_family.0)
                }
                InnerReader::PlainDb(inner) => {
                    rocksdb_create_iterator_cf(inner.db, options, column_family.0)
                }
            };
            assert!(!iter.is_null(), "rocksdb_create_iterator returned null");
            if prefix.is_empty() {
                rocksdb_iter_seek_to_first(iter);
            } else {
                rocksdb_iter_seek(iter, prefix.as_ptr().cast(), prefix.len());
            }
            let is_currently_valid = rocksdb_iter_valid(iter) != 0;
            Ok(Iter {
                inner: iter,
                options,
                _upper_bound: upper_bound,
                _reader: self.clone(),
                is_currently_valid,
            })
        }
    }

    pub fn len(&self, column_family: &ColumnFamily) -> Result<usize, StorageError> {
        let mut count = 0;
        let mut iter = self.iter(column_family)?;
        while iter.is_valid() {
            count += 1;
            iter.next();
        }
        iter.status()?; // We makes sure there is no read problem
        Ok(count)
    }

    pub fn is_empty(&self, column_family: &ColumnFamily) -> Result<bool, StorageError> {
        let iter = self.iter(column_family)?;
        iter.status()?; // We makes sure there is no read problem
        Ok(!iter.is_valid())
    }
}

pub struct Transaction<'a> {
    inner: Rc<*mut rocksdb_transaction_t>,
    read_options: *mut rocksdb_readoptions_t,
    _lifetime: PhantomData<&'a ()>,
}

impl Transaction<'_> {
    pub fn reader(&self) -> Reader {
        Reader {
            inner: InnerReader::Transaction(Rc::downgrade(&self.inner)),
            options: unsafe { rocksdb_readoptions_create_copy(self.read_options) },
        }
    }

    pub fn get_for_update(
        &self,
        column_family: &ColumnFamily,
        key: &[u8],
    ) -> Result<Option<PinnableSlice>, StorageError> {
        unsafe {
            let slice = ffi_result!(rocksdb_transaction_get_for_update_pinned_cf_with_status(
                *self.inner,
                self.read_options,
                column_family.0,
                key.as_ptr().cast(),
                key.len()
            ))?;
            Ok(if slice.is_null() {
                None
            } else {
                Some(PinnableSlice(slice))
            })
        }
    }

    pub fn contains_key_for_update(
        &self,
        column_family: &ColumnFamily,
        key: &[u8],
    ) -> Result<bool, StorageError> {
        Ok(self.get_for_update(column_family, key)?.is_some()) // TODO: optimize
    }

    pub fn insert(
        &mut self,
        column_family: &ColumnFamily,
        key: &[u8],
        value: &[u8],
    ) -> Result<(), StorageError> {
        unsafe {
            ffi_result!(rocksdb_transaction_put_cf_with_status(
                *self.inner,
                column_family.0,
                key.as_ptr().cast(),
                key.len(),
                value.as_ptr().cast(),
                value.len(),
            ))?;
        }
        Ok(())
    }

    pub fn insert_empty(
        &mut self,
        column_family: &ColumnFamily,
        key: &[u8],
    ) -> Result<(), StorageError> {
        self.insert(column_family, key, &[])
    }

    pub fn remove(&mut self, column_family: &ColumnFamily, key: &[u8]) -> Result<(), StorageError> {
        unsafe {
            ffi_result!(rocksdb_transaction_delete_cf_with_status(
                *self.inner,
                column_family.0,
                key.as_ptr().cast(),
                key.len(),
            ))?;
        }
        Ok(())
    }
}

pub struct PinnableSlice(*mut rocksdb_pinnableslice_t);

impl Drop for PinnableSlice {
    fn drop(&mut self) {
        unsafe {
            rocksdb_pinnableslice_destroy(self.0);
        }
    }
}

impl Deref for PinnableSlice {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        unsafe {
            let mut len = 0;
            let val = rocksdb_pinnableslice_value(self.0, &mut len);
            slice::from_raw_parts(val.cast(), len)
        }
    }
}

impl AsRef<[u8]> for PinnableSlice {
    fn as_ref(&self) -> &[u8] {
        self
    }
}

impl Borrow<[u8]> for PinnableSlice {
    fn borrow(&self) -> &[u8] {
        self
    }
}

impl From<PinnableSlice> for Vec<u8> {
    fn from(value: PinnableSlice) -> Self {
        value.to_vec()
    }
}

pub struct Buffer {
    base: *mut u8,
    len: usize,
}

impl Drop for Buffer {
    fn drop(&mut self) {
        unsafe {
            rocksdb_free(self.base.cast());
        }
    }
}

impl Deref for Buffer {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        unsafe { slice::from_raw_parts(self.base, self.len) }
    }
}

impl AsRef<[u8]> for Buffer {
    fn as_ref(&self) -> &[u8] {
        self
    }
}

impl Borrow<[u8]> for Buffer {
    fn borrow(&self) -> &[u8] {
        self
    }
}

impl From<Buffer> for Vec<u8> {
    fn from(value: Buffer) -> Self {
        value.to_vec()
    }
}

pub struct Iter {
    inner: *mut rocksdb_iterator_t,
    is_currently_valid: bool,
    _upper_bound: Option<Vec<u8>>,
    _reader: Reader, // needed to ensure that DB still lives while iter is used
    options: *mut rocksdb_readoptions_t, /* needed to ensure that options still lives while iter is used */
}

impl Drop for Iter {
    fn drop(&mut self) {
        unsafe {
            rocksdb_iter_destroy(self.inner);
            rocksdb_readoptions_destroy(self.options);
        }
    }
}

#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for Iter {}

unsafe impl Sync for Iter {}

impl Iter {
    pub fn is_valid(&self) -> bool {
        self.is_currently_valid
    }

    pub fn status(&self) -> Result<(), StorageError> {
        unsafe {
            ffi_result!(rocksdb_iter_get_status(self.inner))?;
        }
        Ok(())
    }

    pub fn next(&mut self) {
        unsafe {
            rocksdb_iter_next(self.inner);
            self.is_currently_valid = rocksdb_iter_valid(self.inner) != 0;
        }
    }

    pub fn key(&self) -> Option<&[u8]> {
        if self.is_valid() {
            unsafe {
                let mut len = 0;
                let val = rocksdb_iter_key(self.inner, &mut len);
                Some(slice::from_raw_parts(val.cast(), len))
            }
        } else {
            None
        }
    }

    pub fn value(&self) -> Option<&[u8]> {
        if self.is_valid() {
            unsafe {
                let mut len = 0;
                let val = rocksdb_iter_value(self.inner, &mut len);
                Some(slice::from_raw_parts(val.cast(), len))
            }
        } else {
            None
        }
    }
}

pub struct SstFileWriter {
    writer: *mut rocksdb_sstfilewriter_t,
    path: PathBuf,
}

impl Drop for SstFileWriter {
    fn drop(&mut self) {
        unsafe {
            rocksdb_sstfilewriter_destroy(self.writer);
        }
    }
}

impl SstFileWriter {
    pub fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<(), StorageError> {
        unsafe {
            ffi_result!(rocksdb_sstfilewriter_put_with_status(
                self.writer,
                key.as_ptr().cast(),
                key.len(),
                value.as_ptr().cast(),
                value.len(),
            ))?;
        }
        Ok(())
    }

    pub fn insert_empty(&mut self, key: &[u8]) -> Result<(), StorageError> {
        self.insert(key, &[])
    }

    pub fn finish(self) -> Result<PathBuf, StorageError> {
        unsafe {
            ffi_result!(rocksdb_sstfilewriter_finish_with_status(self.writer))?;
        }
        Ok(self.path.clone())
    }
}

#[derive(thiserror::Error)]
#[error("{}", self.message())]
struct ErrorStatus(rocksdb_status_t);

unsafe impl Send for ErrorStatus {}
unsafe impl Sync for ErrorStatus {}

impl Drop for ErrorStatus {
    fn drop(&mut self) {
        if !self.0.string.is_null() {
            unsafe {
                rocksdb_free(self.0.string as *mut c_void);
            }
        }
    }
}

impl ErrorStatus {
    fn message(&self) -> &str {
        if self.0.string.is_null() {
            "Unknown error"
        } else {
            unsafe { CStr::from_ptr(self.0.string) }
                .to_str()
                .unwrap_or("Invalid error message")
        }
    }
}

impl fmt::Debug for ErrorStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ErrorStatus")
            .field("code", &self.0.code)
            .field("subcode", &self.0.subcode)
            .field("severity", &self.0.severity)
            .field("message", &self.message())
            .finish()
    }
}

impl From<ErrorStatus> for StorageError {
    fn from(status: ErrorStatus) -> Self {
        if status.0.code == rocksdb_status_code_t_rocksdb_status_code_io_error {
            let kind =
                if status.0.subcode == rocksdb_status_subcode_t_rocksdb_status_subcode_no_space {
                    io::ErrorKind::Other // TODO ErrorKind::StorageFull
                } else if status.0.subcode
                    == rocksdb_status_subcode_t_rocksdb_status_subcode_path_not_found
                {
                    io::ErrorKind::NotFound
                } else {
                    io::ErrorKind::Other
                };
            Self::Io(io::Error::new(kind, status))
        } else if status.0.code == rocksdb_status_code_t_rocksdb_status_code_corruption {
            Self::Corruption(CorruptionError::new(status))
        } else {
            Self::Other(Box::new(status))
        }
    }
}

struct UnsafeEnv(*mut rocksdb_env_t);

// Hack for OnceCell. OK because only written in OnceCell and used in a thread-safe way by RocksDB
unsafe impl Send for UnsafeEnv {}
unsafe impl Sync for UnsafeEnv {}

fn path_to_cstring(path: &Path) -> Result<CString, StorageError> {
    Ok(CString::new(path.to_str().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            "The DB path is not valid UTF-8",
        )
    })?)
    .map_err(|e| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("The DB path contains null bytes: {e}"),
        )
    })?)
}

#[cfg(unix)]
fn available_file_descriptors() -> io::Result<Option<libc::rlim_t>> {
    let mut rlimit = libc::rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlimit) } == 0 {
        Ok(Some(min(rlimit.rlim_cur, rlimit.rlim_max)))
    } else {
        Err(io::Error::last_os_error())
    }
}

#[cfg(windows)]
fn available_file_descriptors() -> io::Result<Option<libc::c_int>> {
    Ok(Some(512)) // https://docs.microsoft.com/en-us/cpp/c-runtime-library/file-handling
}

#[cfg(not(any(unix, windows)))]
fn available_file_descriptors() -> io::Result<Option<libc::c_int>> {
    Ok(None)
}

fn tmp_path() -> PathBuf {
    if cfg!(target_os = "linux") {
        "/dev/shm/".into()
    } else {
        temp_dir()
    }
    .join(format!("oxigraph-rocksdb-{}", random::<u128>()))
}