Skip to main content

rusqlite/
collation.rs

1//! Add, remove, or modify a collation
2use std::cmp::Ordering;
3use std::ffi::{CStr, c_char, c_int, c_void};
4use std::panic::catch_unwind;
5use std::ptr;
6use std::slice;
7
8use crate::ffi;
9use crate::util::free_boxed_value;
10use crate::{Connection, Error, InnerConnection, Name, Result};
11
12impl Connection {
13    /// Add or modify a collation.
14    #[inline]
15    pub fn create_collation<C, N: Name>(&self, collation_name: N, x_compare: C) -> Result<()>
16    where
17        C: Fn(&str, &str) -> Ordering + Send + 'static,
18    {
19        self.db
20            .borrow_mut()
21            .create_collation(collation_name, x_compare)
22    }
23
24    /// Collation needed callback
25    #[inline]
26    pub fn collation_needed(&self, x_coll_needed: fn(&Self, &str) -> Result<()>) -> Result<()> {
27        self.db.borrow_mut().collation_needed(x_coll_needed)
28    }
29
30    /// Remove collation.
31    #[inline]
32    pub fn remove_collation<N: Name>(&self, collation_name: N) -> Result<()> {
33        self.db.borrow_mut().remove_collation(collation_name)
34    }
35}
36
37impl InnerConnection {
38    /// ```compile_fail
39    /// use rusqlite::{Connection, Result};
40    /// fn main() -> Result<()> {
41    ///     let db = Connection::open_in_memory()?;
42    ///     {
43    ///         let mut called = std::sync::atomic::AtomicBool::new(false);
44    ///         db.create_collation("foo", |_, _| {
45    ///             called.store(true, std::sync::atomic::Ordering::Relaxed);
46    ///             std::cmp::Ordering::Equal
47    ///         })?;
48    ///     }
49    ///     let value: String = db.query_row(
50    ///         "WITH cte(bar) AS
51    ///        (VALUES ('v1'),('v2'),('v3'),('v4'),('v5'))
52    ///         SELECT DISTINCT bar COLLATE foo FROM cte;",
53    ///         [],
54    ///         |row| row.get(0),
55    ///     )?;
56    ///     assert_eq!(value, "v1");
57    ///     Ok(())
58    /// }
59    /// ```
60    fn create_collation<C, N: Name>(&mut self, collation_name: N, x_compare: C) -> Result<()>
61    where
62        C: Fn(&str, &str) -> Ordering + Send + 'static,
63    {
64        unsafe extern "C" fn call_boxed_closure<C>(
65            arg1: *mut c_void,
66            arg2: c_int,
67            arg3: *const c_void,
68            arg4: c_int,
69            arg5: *const c_void,
70        ) -> c_int
71        where
72            C: Fn(&str, &str) -> Ordering,
73        {
74            let r = unsafe {
75                catch_unwind(|| {
76                    let boxed_f: *mut C = arg1.cast::<C>();
77                    assert!(!boxed_f.is_null(), "Internal error - null function pointer");
78                    let s1 = {
79                        let c_slice = slice::from_raw_parts(arg3.cast::<u8>(), arg2 as usize);
80                        String::from_utf8_lossy(c_slice)
81                    };
82                    let s2 = {
83                        let c_slice = slice::from_raw_parts(arg5.cast::<u8>(), arg4 as usize);
84                        String::from_utf8_lossy(c_slice)
85                    };
86                    (*boxed_f)(s1.as_ref(), s2.as_ref())
87                })
88            };
89            let Ok(t) = r else {
90                return -1; // FIXME How ?
91            };
92
93            match t {
94                Ordering::Less => -1,
95                Ordering::Equal => 0,
96                Ordering::Greater => 1,
97            }
98        }
99
100        let boxed_f: *mut C = Box::into_raw(Box::new(x_compare));
101        let c_name = collation_name.as_cstr()?;
102        let flags = ffi::SQLITE_UTF8;
103        let r = unsafe {
104            ffi::sqlite3_create_collation_v2(
105                self.db(),
106                c_name.as_ptr(),
107                flags,
108                boxed_f.cast::<c_void>(),
109                Some(call_boxed_closure::<C>),
110                Some(free_boxed_value::<C>),
111            )
112        };
113        let res = self.decode_result(r);
114        // The xDestroy callback is not called if the sqlite3_create_collation_v2()
115        // function fails.
116        if res.is_err() {
117            drop(unsafe { Box::from_raw(boxed_f) });
118        }
119        res
120    }
121
122    fn collation_needed(
123        &mut self,
124        x_coll_needed: fn(&Connection, &str) -> Result<()>,
125    ) -> Result<()> {
126        use std::mem;
127        #[expect(clippy::needless_return)]
128        unsafe extern "C" fn collation_needed_callback(
129            arg1: *mut c_void,
130            arg2: *mut ffi::sqlite3,
131            e_text_rep: c_int,
132            arg3: *const c_char,
133        ) {
134            use std::str;
135
136            if e_text_rep != ffi::SQLITE_UTF8 {
137                // TODO: validate
138                return;
139            }
140            unsafe {
141                let callback: fn(&Connection, &str) -> Result<()> = mem::transmute(arg1);
142                let res = catch_unwind(|| {
143                    let conn = Connection::from_handle(arg2).unwrap();
144                    let collation_name = CStr::from_ptr(arg3)
145                        .to_str()
146                        .expect("illegal collation sequence name");
147                    callback(&conn, collation_name)
148                })
149                .unwrap_or_else(|_| Err(Error::UnwindingPanic));
150                if let Err(err) = res {
151                    #[cfg(feature = "modern_sqlite")]
152                    // 3.51.0
153                    if let Ok(msg) = std::ffi::CString::new(format!("{err}")) {
154                        let _ = crate::error::set_errmsg(
155                            arg2,
156                            err.sqlite_extended_error_code()
157                                .unwrap_or(ffi::SQLITE_ERROR),
158                            Some(&msg),
159                        );
160                    }
161                    return;
162                }
163            }
164        }
165
166        let r = unsafe {
167            ffi::sqlite3_collation_needed(
168                self.db(),
169                x_coll_needed as *mut c_void,
170                Some(collation_needed_callback),
171            )
172        };
173        self.decode_result(r)
174    }
175
176    #[inline]
177    fn remove_collation<N: Name>(&mut self, collation_name: N) -> Result<()> {
178        let c_name = collation_name.as_cstr()?;
179        let r = unsafe {
180            ffi::sqlite3_create_collation_v2(
181                self.db(),
182                c_name.as_ptr(),
183                ffi::SQLITE_UTF8,
184                ptr::null_mut(),
185                None,
186                None,
187            )
188        };
189        self.decode_result(r)
190    }
191}