Debian Codegraph @

third_party/rust/rusqlite/src/collation.rs

raw
1 //! Add, remove, or modify a collation
2 use std::cmp::Ordering;
3 use std::os::raw::{c_char, c_int, c_void};
4 use std::panic::catch_unwind;
5 use std::ptr;
6 use std::slice;
7
8 use crate::ffi;
9 use crate::{str_to_cstring, Connection, InnerConnection, Result};
10
11 // FIXME copy/paste from function.rs
12 unsafe extern "C" fn free_boxed_value<T>(p: *mut c_void) {
13 drop(Box::from_raw(p.cast::<T>()));
14 }
15
16 impl Connection {
17 /// Add or modify a collation.
18 #[inline]
19 pub fn create_collation<C>(&self, collation_name: &str, x_compare: C) -> Result<()>
20 where
21 C: Fn(&str, &str) -> Ordering + Send + 'static,
22 {
23 self.db
24 .borrow_mut()
25 .create_collation(collation_name, x_compare)
26 }
27
28 /// Collation needed callback
29 #[inline]
30 pub fn collation_needed(&self, x_coll_needed: fn(&Self, &str) -> Result<()>) -> Result<()> {
31 self.db.borrow_mut().collation_needed(x_coll_needed)
32 }
33
34 /// Remove collation.
35 #[inline]
36 pub fn remove_collation(&self, collation_name: &str) -> Result<()> {
37 self.db.borrow_mut().remove_collation(collation_name)
38 }
39 }
40
41 impl InnerConnection {
42 /// ```compile_fail
43 /// use rusqlite::{Connection, Result};
44 /// fn main() -> Result<()> {
45 /// let db = Connection::open_in_memory()?;
46 /// {
47 /// let mut called = std::sync::atomic::AtomicBool::new(false);
48 /// db.create_collation("foo", |_, _| {
49 /// called.store(true, std::sync::atomic::Ordering::Relaxed);
50 /// std::cmp::Ordering::Equal
51 /// })?;
52 /// }
53 /// let value: String = db.query_row(
54 /// "WITH cte(bar) AS
55 /// (VALUES ('v1'),('v2'),('v3'),('v4'),('v5'))
56 /// SELECT DISTINCT bar COLLATE foo FROM cte;",
57 /// [],
58 /// |row| row.get(0),
59 /// )?;
60 /// assert_eq!(value, "v1");
61 /// Ok(())
62 /// }
63 /// ```
64 fn create_collation<C>(&mut self, collation_name: &str, x_compare: C) -> Result<()>
65 where
66 C: Fn(&str, &str) -> Ordering + Send + 'static,
67 {
68 unsafe extern "C" fn call_boxed_closure<C>(
69 arg1: *mut c_void,
70 arg2: c_int,
71 arg3: *const c_void,
72 arg4: c_int,
73 arg5: *const c_void,
74 ) -> c_int
75 where
76 C: Fn(&str, &str) -> Ordering,
77 {
78 let r = catch_unwind(|| {
79 let boxed_f: *mut C = arg1.cast::<C>();
80 assert!(!boxed_f.is_null(), "Internal error - null function pointer");
81 let s1 = {
82 let c_slice = slice::from_raw_parts(arg3.cast::<u8>(), arg2 as usize);
83 String::from_utf8_lossy(c_slice)
84 };
85 let s2 = {
86 let c_slice = slice::from_raw_parts(arg5.cast::<u8>(), arg4 as usize);
87 String::from_utf8_lossy(c_slice)
88 };
89 (*boxed_f)(s1.as_ref(), s2.as_ref())
90 });
91 let t = match r {
92 Err(_) => {
93 return -1; // FIXME How ?
94 }
95 Ok(r) => r,
96 };
97
98 match t {
99 Ordering::Less => -1,
100 Ordering::Equal => 0,
101 Ordering::Greater => 1,
102 }
103 }
104
105 let boxed_f: *mut C = Box::into_raw(Box::new(x_compare));
106 let c_name = str_to_cstring(collation_name)?;
107 let flags = ffi::SQLITE_UTF8;
108 let r = unsafe {
109 ffi::sqlite3_create_collation_v2(
110 self.db(),
111 c_name.as_ptr(),
112 flags,
113 boxed_f.cast::<c_void>(),
114 Some(call_boxed_closure::<C>),
115 Some(free_boxed_value::<C>),
116 )
117 };
118 let res = self.decode_result(r);
119 // The xDestroy callback is not called if the sqlite3_create_collation_v2()
120 // function fails.
121 if res.is_err() {
122 drop(unsafe { Box::from_raw(boxed_f) });
123 }
124 res
125 }
126
127 fn collation_needed(
128 &mut self,
129 x_coll_needed: fn(&Connection, &str) -> Result<()>,
130 ) -> Result<()> {
131 use std::mem;
132 #[expect(clippy::needless_return)]
133 unsafe extern "C" fn collation_needed_callback(
134 arg1: *mut c_void,
135 arg2: *mut ffi::sqlite3,
136 e_text_rep: c_int,
137 arg3: *const c_char,
138 ) {
139 use std::ffi::CStr;
140 use std::str;
141
142 if e_text_rep != ffi::SQLITE_UTF8 {
143 // TODO: validate
144 return;
145 }
146
147 let callback: fn(&Connection, &str) -> Result<()> = mem::transmute(arg1);
148 let res = catch_unwind(|| {
149 let conn = Connection::from_handle(arg2).unwrap();
150 let collation_name = CStr::from_ptr(arg3)
151 .to_str()
152 .expect("illegal collation sequence name");
153 callback(&conn, collation_name)
154 });
155 if res.is_err() {
156 return; // FIXME How ?
157 }
158 }
159
160 let r = unsafe {
161 ffi::sqlite3_collation_needed(
162 self.db(),
163 x_coll_needed as *mut c_void,
164 Some(collation_needed_callback),
165 )
166 };
167 self.decode_result(r)
168 }
169
170 #[inline]
171 fn remove_collation(&mut self, collation_name: &str) -> Result<()> {
172 let c_name = str_to_cstring(collation_name)?;
173 let r = unsafe {
174 ffi::sqlite3_create_collation_v2(
175 self.db(),
176 c_name.as_ptr(),
177 ffi::SQLITE_UTF8,
178 ptr::null_mut(),
179 None,
180 None,
181 )
182 };
183 self.decode_result(r)
184 }
185 }
186
187 #[cfg(test)]
188 mod test {
189 use crate::{Connection, Result};
190 use fallible_streaming_iterator::FallibleStreamingIterator;
191 use std::cmp::Ordering;
192 use unicase::UniCase;
193
194 fn unicase_compare(s1: &str, s2: &str) -> Ordering {
195 UniCase::new(s1).cmp(&UniCase::new(s2))
196 }
197
198 #[test]
199 fn test_unicase() -> Result<()> {
200 let db = Connection::open_in_memory()?;
201 db.create_collation("unicase", unicase_compare)?;
202 collate(db)
203 }
204
205 fn collate(db: Connection) -> Result<()> {
206 db.execute_batch(
207 "CREATE TABLE foo (bar);
208 INSERT INTO foo (bar) VALUES ('Maße');
209 INSERT INTO foo (bar) VALUES ('MASSE');",
210 )?;
211 let mut stmt = db.prepare("SELECT DISTINCT bar COLLATE unicase FROM foo ORDER BY 1")?;
212 let rows = stmt.query([])?;
213 assert_eq!(rows.count()?, 1);
214 Ok(())
215 }
216
217 fn collation_needed(db: &Connection, collation_name: &str) -> Result<()> {
218 if "unicase" == collation_name {
219 db.create_collation(collation_name, unicase_compare)
220 } else {
221 Ok(())
222 }
223 }
224
225 #[test]
226 fn test_collation_needed() -> Result<()> {
227 let db = Connection::open_in_memory()?;
228 db.collation_needed(collation_needed)?;
229 collate(db)
230 }
231
232 #[test]
233 fn remove_collation() -> Result<()> {
234 let db = Connection::open_in_memory()?;
235 db.create_collation("unicase", unicase_compare)?;
236 db.remove_collation("unicase")
237 }
238 }