adbc_ffi 0.24.0

ADBC FFI and driver exporter
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#![allow(non_camel_case_types, non_snake_case)]

use std::ffi::{CStr, CString, NulError};
use std::mem::ManuallyDrop;
use std::os::raw::{c_char, c_int, c_void};
use std::ptr::{null, null_mut};

use super::methods;
use adbc_core::{
    Partitions, constants,
    error::{AdbcStatusCode, Error, Status},
};

/// A driver initialization function.
pub type FFI_AdbcDriverInitFunc =
    unsafe extern "C" fn(c_int, *mut c_void, *mut FFI_AdbcError) -> AdbcStatusCode;

#[repr(C)]
#[derive(Debug)]
pub struct FFI_AdbcError {
    pub message: *mut c_char,
    pub vendor_code: i32,
    pub sqlstate: [c_char; 5],
    pub release: Option<unsafe extern "C" fn(*mut Self)>,
    /// Added in ADBC 1.1.0.
    pub private_data: *mut c_void,
    /// Added in ADBC 1.1.0.
    pub private_driver: *const FFI_AdbcDriver,
}

#[repr(C)]
#[derive(Debug)]
pub struct FFI_AdbcErrorV100 {
    pub message: *mut c_char,
    pub vendor_code: i32,
    pub sqlstate: [c_char; 5],
    pub release: Option<unsafe extern "C" fn(*mut Self)>,
}

#[repr(C)]
#[derive(Debug)]
pub struct FFI_AdbcErrorDetail {
    /// The metadata key.
    pub key: *const c_char,
    /// The binary metadata value.
    pub value: *const u8,
    /// The length of the metadata value.
    pub value_length: usize,
}

#[repr(C)]
#[derive(Debug)]
pub struct FFI_AdbcDatabase {
    /// Opaque implementation-defined state.
    /// This field is NULLPTR iff the connection is uninitialized/freed.
    pub private_data: *mut c_void,
    /// The associated driver (used by the driver manager to help track state).
    pub private_driver: *const FFI_AdbcDriver,
}

unsafe impl Send for FFI_AdbcDatabase {}

#[repr(C)]
#[derive(Debug)]
pub struct FFI_AdbcConnection {
    /// Opaque implementation-defined state.
    /// This field is NULLPTR iff the connection is uninitialized/freed.
    pub private_data: *mut c_void,
    /// The associated driver (used by the driver manager to help track state).
    pub private_driver: *const FFI_AdbcDriver,
}

unsafe impl Send for FFI_AdbcConnection {}

#[repr(C)]
#[derive(Debug)]
pub struct FFI_AdbcStatement {
    /// Opaque implementation-defined state.
    /// This field is NULLPTR iff the connection is uninitialized/freed.
    pub private_data: *mut c_void,
    /// The associated driver (used by the driver manager to help track state).
    pub private_driver: *const FFI_AdbcDriver,
}

unsafe impl Send for FFI_AdbcStatement {}

#[repr(C)]
#[derive(Debug)]
pub struct FFI_AdbcPartitions {
    /// The number of partitions.
    pub num_partitions: usize,

    /// The partitions of the result set, where each entry (up to
    /// num_partitions entries) is an opaque identifier that can be
    /// passed to AdbcConnectionReadPartition.
    // It's defined as a const const pointer in C but we need to release it so it
    // probably needs to be mutable.
    pub partitions: *mut *mut u8,

    /// The length of each corresponding entry in partitions.
    // It's defined as a const pointer in C but we need to release it so it
    // probably needs to be mutable.
    pub partition_lengths: *mut usize,

    /// Opaque implementation-defined state.
    /// This field is NULLPTR iff the connection is uninitialized/freed.
    pub private_data: *mut c_void,

    /// Release the contained partitions.
    /// Unlike other structures, this is an embedded callback to make it
    /// easier for the driver manager and driver to cooperate.
    pub release: Option<unsafe extern "C" fn(*mut Self)>,
}

#[repr(C)]
#[derive(Debug)]
pub struct FFI_AdbcDriver {
    /// Opaque driver-defined state.
    /// This field is NULL if the driver is uninitialized/freed (but
    /// it need not have a value even if the driver is initialized).
    pub private_data: *mut c_void,
    /// Opaque driver manager-defined state.
    /// This field is NULL if the driver is uninitialized/freed (but
    /// it need not have a value even if the driver is initialized).
    pub private_manager: *const c_void,
    pub release: Option<
        unsafe extern "C" fn(driver: *mut Self, error: *mut FFI_AdbcError) -> AdbcStatusCode,
    >,
    pub DatabaseInit: Option<methods::FuncDatabaseInit>,
    pub DatabaseNew: Option<methods::FuncDatabaseNew>,
    pub DatabaseSetOption: Option<methods::FuncDatabaseSetOption>,
    pub DatabaseRelease: Option<methods::FuncDatabaseRelease>,
    pub ConnectionCommit: Option<methods::FuncConnectionCommit>,
    pub ConnectionGetInfo: Option<methods::FuncConnectionGetInfo>,
    pub ConnectionGetObjects: Option<methods::FuncConnectionGetObjects>,
    pub ConnectionGetTableSchema: Option<methods::FuncConnectionGetTableSchema>,
    pub ConnectionGetTableTypes: Option<methods::FuncConnectionGetTableTypes>,
    pub ConnectionInit: Option<methods::FuncConnectionInit>,
    pub ConnectionNew: Option<methods::FuncConnectionNew>,
    pub ConnectionSetOption: Option<methods::FuncConnectionSetOption>,
    pub ConnectionReadPartition: Option<methods::FuncConnectionReadPartition>,
    pub ConnectionRelease: Option<methods::FuncConnectionRelease>,
    pub ConnectionRollback: Option<methods::FuncConnectionRollback>,
    pub StatementBind: Option<methods::FuncStatementBind>,
    pub StatementBindStream: Option<methods::FuncStatementBindStream>,
    pub StatementExecuteQuery: Option<methods::FuncStatementExecuteQuery>,
    pub StatementExecutePartitions: Option<methods::FuncStatementExecutePartitions>,
    pub StatementGetParameterSchema: Option<methods::FuncStatementGetParameterSchema>,
    pub StatementNew: Option<methods::FuncStatementNew>,
    pub StatementPrepare: Option<methods::FuncStatementPrepare>,
    pub StatementRelease: Option<methods::FuncStatementRelease>,
    pub StatementSetOption: Option<methods::FuncStatementSetOption>,
    pub StatementSetSqlQuery: Option<methods::FuncStatementSetSqlQuery>,
    pub StatementSetSubstraitPlan: Option<methods::FuncStatementSetSubstraitPlan>,
    pub ErrorGetDetailCount: Option<methods::FuncErrorGetDetailCount>,
    pub ErrorGetDetail: Option<methods::FuncErrorGetDetail>,
    pub ErrorFromArrayStream: Option<methods::FuncErrorFromArrayStream>,
    pub DatabaseGetOption: Option<methods::FuncDatabaseGetOption>,
    pub DatabaseGetOptionBytes: Option<methods::FuncDatabaseGetOptionBytes>,
    pub DatabaseGetOptionDouble: Option<methods::FuncDatabaseGetOptionDouble>,
    pub DatabaseGetOptionInt: Option<methods::FuncDatabaseGetOptionInt>,
    pub DatabaseSetOptionBytes: Option<methods::FuncDatabaseSetOptionBytes>,
    pub DatabaseSetOptionDouble: Option<methods::FuncDatabaseSetOptionDouble>,
    pub DatabaseSetOptionInt: Option<methods::FuncDatabaseSetOptionInt>,
    pub ConnectionCancel: Option<methods::FuncConnectionCancel>,
    pub ConnectionGetOption: Option<methods::FuncConnectionGetOption>,
    pub ConnectionGetOptionBytes: Option<methods::FuncConnectionGetOptionBytes>,
    pub ConnectionGetOptionDouble: Option<methods::FuncConnectionGetOptionDouble>,
    pub ConnectionGetOptionInt: Option<methods::FuncConnectionGetOptionInt>,
    pub ConnectionGetStatistics: Option<methods::FuncConnectionGetStatistics>,
    pub ConnectionGetStatisticNames: Option<methods::FuncConnectionGetStatisticNames>,
    pub ConnectionSetOptionBytes: Option<methods::FuncConnectionSetOptionBytes>,
    pub ConnectionSetOptionDouble: Option<methods::FuncConnectionSetOptionDouble>,
    pub ConnectionSetOptionInt: Option<methods::FuncConnectionSetOptionInt>,
    pub StatementCancel: Option<methods::FuncStatementCancel>,
    pub StatementExecuteSchema: Option<methods::FuncStatementExecuteSchema>,
    pub StatementGetOption: Option<methods::FuncStatementGetOption>,
    pub StatementGetOptionBytes: Option<methods::FuncStatementGetOptionBytes>,
    pub StatementGetOptionDouble: Option<methods::FuncStatementGetOptionDouble>,
    pub StatementGetOptionInt: Option<methods::FuncStatementGetOptionInt>,
    pub StatementSetOptionBytes: Option<methods::FuncStatementSetOptionBytes>,
    pub StatementSetOptionDouble: Option<methods::FuncStatementSetOptionDouble>,
    pub StatementSetOptionInt: Option<methods::FuncStatementSetOptionInt>,
}

/// The [FFI_AdbcDriver] carries raw C pointers to the driver manager and private data that rustc
/// can not treat as [Send] and [Sync] but we trust drivers access them in a thread-safe way.
unsafe impl Send for FFI_AdbcDriver {}
unsafe impl Sync for FFI_AdbcDriver {}

#[macro_export]
macro_rules! driver_method {
    ($driver:expr, $method:ident) => {
        $driver.$method.unwrap_or($crate::methods::$method)
    };
}

impl From<FFI_AdbcPartitions> for Partitions {
    fn from(value: FFI_AdbcPartitions) -> Self {
        let mut partitions = Vec::with_capacity(value.num_partitions);
        for p in 0..value.num_partitions {
            let partition = unsafe {
                let ptr = *value.partitions.add(p);
                let len = *value.partition_lengths.add(p);
                std::slice::from_raw_parts(ptr, len)
            };
            partitions.push(partition.to_vec());
        }
        partitions
    }
}

// Taken from `Vec::into_raw_parts` which is currently nightly-only.
fn vec_into_raw_parts<T>(data: Vec<T>) -> (*mut T, usize, usize) {
    let mut md = ManuallyDrop::new(data);
    (md.as_mut_ptr(), md.len(), md.capacity())
}

// We need to store capacities to correctly release memory because the C API
// only stores lengths and so capacities are lost in translation.
struct PartitionsPrivateData {
    partitions_capacity: usize,
    partition_lengths_capacity: usize,
    partition_capacities: Vec<usize>,
}

impl From<Partitions> for FFI_AdbcPartitions {
    fn from(value: Partitions) -> Self {
        let num_partitions = value.len();
        let mut partition_lengths = Vec::with_capacity(num_partitions);
        let mut partition_capacities = Vec::with_capacity(num_partitions);
        let mut partition_ptrs = Vec::with_capacity(num_partitions);

        for partition in value.into_iter() {
            let (partition_ptr, partition_len, partition_cap) = vec_into_raw_parts(partition);
            partition_lengths.push(partition_len);
            partition_capacities.push(partition_cap);
            partition_ptrs.push(partition_ptr);
        }

        let (partition_lengths_ptr, _, partition_lengths_cap) =
            vec_into_raw_parts(partition_lengths);
        let (partitions_ptr, _, partitions_cap) = vec_into_raw_parts(partition_ptrs);
        let private_data = Box::new(PartitionsPrivateData {
            partitions_capacity: partitions_cap,
            partition_lengths_capacity: partition_lengths_cap,
            partition_capacities,
        });

        FFI_AdbcPartitions {
            num_partitions,
            partition_lengths: partition_lengths_ptr,
            partitions: partitions_ptr,
            private_data: Box::into_raw(private_data) as *mut c_void,
            release: Some(release_ffi_partitions),
        }
    }
}

unsafe extern "C" fn release_ffi_partitions(partitions: *mut FFI_AdbcPartitions) {
    match partitions.as_mut() {
        None => (),
        Some(partitions) => {
            // SAFETY: `partitions.private_data` was necessarily obtained with `Box::into_raw`.
            // Additionally, the boxed data is necessarily `PartitionsPrivateData`.
            // Finally, C should call the release function only once.
            let private_data = Box::from_raw(partitions.private_data as *mut PartitionsPrivateData);

            for p in 0..partitions.num_partitions {
                let partition_ptr = *partitions.partitions.add(p);
                let partition_len = *partitions.partition_lengths.add(p);
                let partition_cap = private_data.partition_capacities[p];
                // SAFETY: `partition_ptr`, `partition_len` and `partition_cap` has been created in
                // `From<Partitions> for FFI_AdbcPartitions` from the result of `vec_into_raw_parts`.
                let partition = Vec::from_raw_parts(partition_ptr, partition_len, partition_cap);
                drop(partition);
            }

            // SAFETY: `partitions.partition_lengths`, `partitions.num_partitions`
            // and `private_data.partition_lengths_capacity` has been created in
            // `From<Partitions> for FFI_AdbcPartitions` from the result of `vec_into_raw_parts`.
            let partition_lengths = Vec::from_raw_parts(
                partitions.partition_lengths,
                partitions.num_partitions,
                private_data.partition_lengths_capacity,
            );
            drop(partition_lengths);

            // SAFETY: `partitions.partitions`, `partitions.num_partitions` and
            // `private_data.partitions_capacity` has been created in
            // `From<Partitions> for FFI_AdbcPartitions` from the result of `vec_into_raw_parts`.
            let partitions_vec = Vec::from_raw_parts(
                partitions.partitions,
                partitions.num_partitions,
                private_data.partitions_capacity,
            );
            drop(partitions_vec);

            drop(private_data);
        }
    }
}

impl Default for FFI_AdbcDriver {
    fn default() -> Self {
        Self {
            private_data: null_mut(),
            private_manager: null_mut(),
            release: None,
            DatabaseInit: None,
            DatabaseNew: None,
            DatabaseSetOption: None,
            DatabaseRelease: None,
            ConnectionCommit: None,
            ConnectionGetInfo: None,
            ConnectionGetObjects: None,
            ConnectionGetTableSchema: None,
            ConnectionGetTableTypes: None,
            ConnectionInit: None,
            ConnectionNew: None,
            ConnectionSetOption: None,
            ConnectionReadPartition: None,
            ConnectionRelease: None,
            ConnectionRollback: None,
            StatementBind: None,
            StatementBindStream: None,
            StatementExecuteQuery: None,
            StatementExecutePartitions: None,
            StatementGetParameterSchema: None,
            StatementNew: None,
            StatementPrepare: None,
            StatementRelease: None,
            StatementSetOption: None,
            StatementSetSqlQuery: None,
            StatementSetSubstraitPlan: None,
            ErrorGetDetailCount: None,
            ErrorGetDetail: None,
            ErrorFromArrayStream: None,
            DatabaseGetOption: None,
            DatabaseGetOptionBytes: None,
            DatabaseGetOptionDouble: None,
            DatabaseGetOptionInt: None,
            DatabaseSetOptionBytes: None,
            DatabaseSetOptionDouble: None,
            DatabaseSetOptionInt: None,
            ConnectionCancel: None,
            ConnectionGetOption: None,
            ConnectionGetOptionBytes: None,
            ConnectionGetOptionDouble: None,
            ConnectionGetOptionInt: None,
            ConnectionGetStatistics: None,
            ConnectionGetStatisticNames: None,
            ConnectionSetOptionBytes: None,
            ConnectionSetOptionDouble: None,
            ConnectionSetOptionInt: None,
            StatementCancel: None,
            StatementExecuteSchema: None,
            StatementGetOption: None,
            StatementGetOptionBytes: None,
            StatementGetOptionDouble: None,
            StatementGetOptionInt: None,
            StatementSetOptionBytes: None,
            StatementSetOptionDouble: None,
            StatementSetOptionInt: None,
        }
    }
}

impl Default for FFI_AdbcError {
    fn default() -> Self {
        Self {
            message: null_mut(),
            vendor_code: constants::ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA,
            sqlstate: [0; 5],
            release: None,
            private_data: null_mut(),
            private_driver: null(),
        }
    }
}

impl Default for FFI_AdbcDatabase {
    fn default() -> Self {
        Self {
            private_data: null_mut(),
            private_driver: null_mut(),
        }
    }
}

impl Default for FFI_AdbcConnection {
    fn default() -> Self {
        Self {
            private_data: null_mut(),
            private_driver: null_mut(),
        }
    }
}

impl Default for FFI_AdbcErrorDetail {
    fn default() -> Self {
        Self {
            key: null(),
            value: null(),
            value_length: 0,
        }
    }
}

impl Default for FFI_AdbcStatement {
    fn default() -> Self {
        Self {
            private_data: null_mut(),
            private_driver: null(),
        }
    }
}

impl Default for FFI_AdbcPartitions {
    fn default() -> Self {
        Self {
            num_partitions: 0,
            partitions: null_mut(),
            partition_lengths: null_mut(),
            private_data: null_mut(),
            release: None,
        }
    }
}

impl FFI_AdbcError {
    pub fn with_driver(driver: &FFI_AdbcDriver) -> Self {
        FFI_AdbcError {
            private_driver: driver,
            ..Default::default()
        }
    }
}

impl TryFrom<&FFI_AdbcError> for Error {
    type Error = Error;

    fn try_from(value: &FFI_AdbcError) -> Result<Self, Self::Error> {
        let message = match value.message.is_null() {
            true => "<empty>".to_string(),
            false => {
                // SAFETY: we assume that C gives us a valid string.
                let message = unsafe { CStr::from_ptr(value.message) };
                let message = message.to_owned();
                message.into_string()?
            }
        };

        let mut error = Error {
            message,
            status: Status::Unknown,
            vendor_code: value.vendor_code,
            sqlstate: value.sqlstate,
            details: None,
        };

        if value.vendor_code == constants::ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA {
            if let Some(driver) = unsafe { value.private_driver.as_ref() } {
                let get_detail_count = driver_method!(driver, ErrorGetDetailCount);
                let get_detail = driver_method!(driver, ErrorGetDetail);
                let num_details = unsafe { get_detail_count(value) };
                let details = (0..num_details)
                    .map(|i| unsafe { get_detail(value, i) })
                    .filter(|d| !d.key.is_null() && !d.value.is_null())
                    .map(|d| unsafe {
                        // SAFETY: we assume that C gives us a valid string.
                        let key = CStr::from_ptr(d.key).to_string_lossy().to_string();
                        // SAFETY: we assume that C gives us valid data.
                        let value = std::slice::from_raw_parts(d.value, d.value_length);
                        (key, value.to_vec())
                    })
                    .collect();
                error.details = Some(details);
            }
        }

        Ok(error)
    }
}

impl TryFrom<FFI_AdbcError> for Error {
    type Error = Error;

    fn try_from(value: FFI_AdbcError) -> Result<Self, Self::Error> {
        (&value).try_into()
    }
}

// Invariant: keys.len() == values.len()
pub(crate) struct ErrorPrivateData {
    pub(crate) keys: Vec<CString>,
    pub(crate) values: Vec<Vec<u8>>,
}

impl From<NulError> for FFI_AdbcError {
    fn from(value: NulError) -> Self {
        let message = CString::new(format!(
            "Interior null byte was found at position {}",
            value.nul_position()
        ))
        .unwrap();
        FFI_AdbcError {
            message: message.into_raw(),
            vendor_code: constants::ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA,
            sqlstate: [0; 5],
            release: Some(release_ffi_error),
            private_data: null_mut(),
            private_driver: null(),
        }
    }
}

impl TryFrom<Error> for FFI_AdbcError {
    type Error = NulError;

    fn try_from(mut value: Error) -> Result<Self, Self::Error> {
        let message = CString::new(value.message)?;

        let private_data = match value.details.take() {
            None => null_mut(),
            Some(details) => {
                let keys = details
                    .iter()
                    .map(|(key, _)| CString::new(key.as_str()))
                    .collect::<Result<Vec<_>, _>>()?;
                let values: Vec<Vec<u8>> = details.into_iter().map(|(_, value)| value).collect();

                let private_data = Box::new(ErrorPrivateData { keys, values });
                let private_data = Box::into_raw(private_data);
                private_data as *mut c_void
            }
        };

        Ok(FFI_AdbcError {
            message: message.into_raw(),
            release: Some(release_ffi_error),
            vendor_code: value.vendor_code,
            sqlstate: value.sqlstate,
            private_data,
            private_driver: null(),
        })
    }
}

impl From<NulError> for FFI_AdbcErrorV100 {
    fn from(value: NulError) -> Self {
        let message = CString::new(format!(
            "Interior null byte was found at position {}",
            value.nul_position()
        ))
        .unwrap();
        FFI_AdbcErrorV100 {
            message: message.into_raw(),
            vendor_code: 0,
            sqlstate: [0; 5],
            release: Some(release_ffi_error_v100),
        }
    }
}

impl TryFrom<Error> for FFI_AdbcErrorV100 {
    type Error = NulError;

    fn try_from(value: Error) -> Result<Self, Self::Error> {
        // TODO: instead of dying on an interior NUL, just truncate or replace
        let message = CString::new(value.message)?;
        Ok(FFI_AdbcErrorV100 {
            message: message.into_raw(),
            release: Some(release_ffi_error_v100),
            vendor_code: value.vendor_code,
            sqlstate: value.sqlstate,
        })
    }
}

unsafe extern "C" fn release_ffi_error(error: *mut FFI_AdbcError) {
    match error.as_mut() {
        None => (),
        Some(error) => {
            if !error.message.is_null() {
                // SAFETY: `error.message` was necessarily obtained with `CString::into_raw`.
                // Additionally, C should not modify the string's length.
                drop(CString::from_raw(error.message));
                error.message = null_mut();
            }

            if !error.private_data.is_null() {
                // SAFETY: `error.private_data` was necessarily obtained with `Box::into_raw`.
                // Additionally, the boxed data is necessarily `ErrorPrivateData`.
                // Finally, C should call the release function only once.
                let private_data = Box::from_raw(error.private_data as *mut ErrorPrivateData);
                drop(private_data);
                error.private_data = null_mut();
            }
            error.release = None;
        }
    }
}

unsafe extern "C" fn release_ffi_error_v100(error: *mut FFI_AdbcErrorV100) {
    match error.as_mut() {
        None => (),
        Some(error) => {
            if !error.message.is_null() {
                // SAFETY: `error.message` was necessarily obtained with `CString::into_raw`.
                drop(CString::from_raw(error.message));
                error.message = null_mut();
            }
            error.release = None;
        }
    }
}

/// Export an error into an FFI error, accounting for the v1.0.0/v1.1.0 ABI
/// extension.
#[doc(hidden)]
pub unsafe fn export_error(err_out: *mut FFI_AdbcError, error: Error) {
    if err_out.is_null() {
        return;
    }

    let is_v110 = (*err_out).vendor_code == constants::ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA;
    if let Some(release) = (*err_out).release {
        release(err_out);
    }
    if is_v110 {
        let mut ffi_error = FFI_AdbcError::try_from(error).unwrap_or_else(Into::into);
        ffi_error.vendor_code = constants::ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA;
        ffi_error.private_driver = (*err_out).private_driver;
        std::ptr::write_unaligned(err_out, ffi_error);
    } else {
        let ffi_error = FFI_AdbcErrorV100::try_from(error).unwrap_or_else(Into::into);
        let out = &mut *(err_out as *mut FFI_AdbcErrorV100);
        std::ptr::write_unaligned(out, ffi_error);
    }
}

impl Drop for FFI_AdbcError {
    fn drop(&mut self) {
        if let Some(release) = self.release {
            unsafe { release(self) };
        }
    }
}

impl Drop for FFI_AdbcDriver {
    fn drop(&mut self) {
        if let Some(release) = self.release {
            // TODO(alexandreyc): how should we handle `release` failing?
            // See: https://github.com/apache/arrow-adbc/pull/1742#discussion_r1574388409
            unsafe { release(self, null_mut()) };
        }
    }
}

impl Drop for FFI_AdbcPartitions {
    fn drop(&mut self) {
        if let Some(release) = self.release {
            unsafe { release(self) };
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_roundtrip() {
        let error_expected: Error = Error {
            message: "Hello world!".into(),
            status: Status::Unknown,
            vendor_code: constants::ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA,
            sqlstate: [1, 2, 3, 4, 5],
            details: None, // Details are not transferred here because there is no driver
        };
        let error_ffi: FFI_AdbcError = error_expected.clone().try_into().unwrap();
        let error_actual: Error = error_ffi.try_into().unwrap();
        assert_eq!(error_expected, error_actual);
    }

    #[test]
    fn test_partitions_roundtrip() {
        let partitions_expected: Partitions = vec![b"A".into(), b"BB".into(), b"CCC".into()];
        let partitions_ffi: FFI_AdbcPartitions = partitions_expected.clone().into();
        let partitions_actual: Partitions = partitions_ffi.into();
        assert_eq!(partitions_expected, partitions_actual);
    }

    #[test]
    fn test_release_ffi_error_nulls_fields() {
        // Use details to ensure private_data is non-null before release.
        let error = Error {
            message: "test error".into(),
            status: Status::Unknown,
            vendor_code: 0,
            sqlstate: [0; 5],
            details: Some(vec![("key".to_string(), b"value".to_vec())]),
        };
        let mut ffi_error: FFI_AdbcError = error.try_into().unwrap();
        assert!(!ffi_error.message.is_null());
        assert!(!ffi_error.private_data.is_null());

        unsafe { release_ffi_error(&mut ffi_error) };

        assert!(ffi_error.message.is_null());
        assert!(ffi_error.private_data.is_null());
        assert!(ffi_error.release.is_none());
        // Drop here is a no-op because release is None.
    }

    #[test]
    fn test_release_ffi_error_idempotent() {
        // Calling release twice must not double-free the message pointer.
        let error = Error {
            message: "test error".into(),
            status: Status::Unknown,
            vendor_code: 0,
            sqlstate: [0; 5],
            details: None,
        };
        let mut ffi_error: FFI_AdbcError = error.try_into().unwrap();

        unsafe {
            release_ffi_error(&mut ffi_error);
            release_ffi_error(&mut ffi_error);
        }
        // Drop here is a no-op because release is None.
    }

    #[test]
    fn test_release_ffi_error_null_message() {
        // A null message must not cause UB or a panic during release.
        let mut ffi_error = FFI_AdbcError {
            message: null_mut(),
            vendor_code: 0,
            sqlstate: [0; 5],
            release: Some(release_ffi_error),
            private_data: null_mut(),
            private_driver: null(),
        };

        unsafe { release_ffi_error(&mut ffi_error) };

        assert!(ffi_error.message.is_null());
        assert!(ffi_error.release.is_none());
        // Drop here is a no-op because release is None.
    }

    #[test]
    fn test_set_error_out_preserves_caller_private_fields() {
        // A caller that did not opt into the 1.1.0 layout leaves `vendor_code` at
        // something other than the sentinel. `export_error` must then leave
        // `private_data` / `private_driver` untouched, even when the error carries
        // details that would otherwise be stashed in `private_data`. This mirrors
        // the C++ validation suite's `StatementTest.ErrorCompatibility`.
        let mut canary_data = 0x1234;
        let canary_ptr = (&raw mut canary_data) as *mut c_void;
        let canary_driver: FFI_AdbcDriver = Default::default();
        let mut out = FFI_AdbcError {
            message: null_mut(),
            vendor_code: 0,
            sqlstate: [0; 5],
            release: None,
            private_data: canary_ptr,
            private_driver: &raw const canary_driver,
        };

        let error = Error {
            message: "boom".into(),
            status: Status::Internal,
            vendor_code: 0,
            sqlstate: [0; 5],
            details: Some(vec![("key".to_string(), b"value".to_vec())]),
        };
        unsafe { export_error(&mut out, error) };

        // The extended fields are untouched.
        assert_eq!(out.private_data, canary_ptr);
        assert_eq!(out.private_driver, &raw const canary_driver);
        // The message was written and a message-only release installed.
        assert!(!out.message.is_null());
        assert!(out.release.is_some());

        // Releasing frees only the message and must not touch the canary.
        unsafe { (out.release.unwrap())(&mut out) };
        assert!(out.message.is_null());
        assert!(out.release.is_none());
        assert_eq!(out.private_data, canary_ptr);
        assert_eq!(out.private_driver, &raw const canary_driver);
        // Drop here is a no-op because release is None.
    }

    #[test]
    fn test_set_error_out_extended_layout_overwrites() {
        // A caller that opted in (vendor_code == sentinel) gets the full struct,
        // including details in `private_data`; `private_driver` is preserved so the
        // driver manager keeps its handle.
        let canary_driver: FFI_AdbcDriver = Default::default();
        let mut out = FFI_AdbcError {
            message: null_mut(),
            vendor_code: constants::ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA,
            sqlstate: [0; 5],
            release: None,
            private_data: null_mut(),
            private_driver: &raw const canary_driver,
        };

        let error = Error {
            message: "boom".into(),
            status: Status::Internal,
            vendor_code: 0,
            sqlstate: [0; 5],
            details: Some(vec![("key".to_string(), b"value".to_vec())]),
        };
        unsafe { export_error(&mut out, error) };

        assert!(!out.message.is_null());
        assert!(!out.private_data.is_null()); // details stashed here
        assert_eq!(out.private_driver, &raw const canary_driver); // preserved
        // The sentinel survives: consumers may only read private_data while
        // vendor_code holds it (adbc.h), so the details above stay reachable.
        assert_eq!(
            out.vendor_code,
            constants::ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA
        );
        assert!(out.release.is_some());

        // The full release frees both the message and the details in private_data.
        unsafe { (out.release.unwrap())(&mut out) };
        assert!(out.message.is_null());
        assert!(out.private_data.is_null());
        // Drop here is a no-op because release is None.
    }

    #[test]
    fn test_set_error_out_releases_a_previous_error_on_reuse() {
        // Writing into a struct that still holds an earlier error releases it
        // first (as the C reference does), instead of leaking its message.
        let mut out = FFI_AdbcError {
            message: null_mut(),
            vendor_code: 0,
            sqlstate: [0; 5],
            release: None,
            private_data: null_mut(),
            private_driver: null(),
        };
        let error = |msg: &str| Error {
            message: msg.into(),
            status: Status::Internal,
            vendor_code: 0,
            sqlstate: [0; 5],
            details: None,
        };

        unsafe { export_error(&mut out, error("first")) };
        let first_message = out.message;
        assert!(!first_message.is_null());

        unsafe { export_error(&mut out, error("second")) };
        assert!(!out.message.is_null());
        let message = unsafe { CStr::from_ptr(out.message) };
        assert_eq!(message.to_str().unwrap(), "second");

        unsafe { (out.release.unwrap())(&mut out) };
        assert!(out.message.is_null());
    }
}