1use std::ffi::{c_int, CString};
2use std::marker::PhantomData;
3use std::{slice, str};
4
5use anyhow::{anyhow, Context, Result};
6use libsqlite3_sys::*;
7
8use crate::bindable::{Bind, Column};
9use crate::connection::Connection;
10
11pub struct Statement<'a> {
12 raw_statement: *mut sqlite3_stmt,
13 connection: &'a Connection,
14 phantom: PhantomData<sqlite3_stmt>,
15}
16
17#[derive(Clone, Copy, PartialEq, Eq, Debug)]
18pub enum StepResult {
19 Row,
20 Done,
21 Misuse,
22 Other(i32),
23}
24
25#[derive(Clone, Copy, PartialEq, Eq, Debug)]
26pub enum SqlType {
27 Text,
28 Integer,
29 Blob,
30 Float,
31 Null,
32}
33
34impl<'a> Statement<'a> {
35 pub fn prepare<T: AsRef<str>>(connection: &'a Connection, query: T) -> Result<Self> {
36 let mut statement = Self {
37 raw_statement: 0 as *mut _,
38 connection,
39 phantom: PhantomData,
40 };
41
42 unsafe {
43 sqlite3_prepare_v2(
44 connection.sqlite3,
45 CString::new(query.as_ref())?.as_ptr(),
46 -1,
47 &mut statement.raw_statement,
48 0 as *mut _,
49 );
50
51 connection.last_error().context("Prepare call failed.")?;
52 }
53
54 Ok(statement)
55 }
56
57 pub fn reset(&mut self) {
58 unsafe {
59 sqlite3_reset(self.raw_statement);
60 }
61 }
62
63 pub fn parameter_count(&self) -> i32 {
64 unsafe { sqlite3_bind_parameter_count(self.raw_statement) }
65 }
66
67 pub fn bind_blob(&self, index: i32, blob: &[u8]) -> Result<()> {
68 let index = index as c_int;
69 let blob_pointer = blob.as_ptr() as *const _;
70 let len = blob.len() as c_int;
71 unsafe {
72 sqlite3_bind_blob(
73 self.raw_statement,
74 index,
75 blob_pointer,
76 len,
77 SQLITE_TRANSIENT(),
78 );
79 }
80 self.connection.last_error()
81 }
82
83 pub fn column_blob<'b>(&'b mut self, index: i32) -> Result<&'b [u8]> {
84 let index = index as c_int;
85 let pointer = unsafe { sqlite3_column_blob(self.raw_statement, index) };
86
87 self.connection.last_error()?;
88 if pointer.is_null() {
89 return Ok(&[]);
90 }
91 let len = unsafe { sqlite3_column_bytes(self.raw_statement, index) as usize };
92 self.connection.last_error()?;
93 unsafe { Ok(slice::from_raw_parts(pointer as *const u8, len)) }
94 }
95
96 pub fn bind_double(&self, index: i32, double: f64) -> Result<()> {
97 let index = index as c_int;
98
99 unsafe {
100 sqlite3_bind_double(self.raw_statement, index, double);
101 }
102 self.connection.last_error()
103 }
104
105 pub fn column_double(&self, index: i32) -> Result<f64> {
106 let index = index as c_int;
107 let result = unsafe { sqlite3_column_double(self.raw_statement, index) };
108 self.connection.last_error()?;
109 Ok(result)
110 }
111
112 pub fn bind_int(&self, index: i32, int: i32) -> Result<()> {
113 let index = index as c_int;
114
115 unsafe {
116 sqlite3_bind_int(self.raw_statement, index, int);
117 };
118 self.connection.last_error()
119 }
120
121 pub fn column_int(&self, index: i32) -> Result<i32> {
122 let index = index as c_int;
123 let result = unsafe { sqlite3_column_int(self.raw_statement, index) };
124 self.connection.last_error()?;
125 Ok(result)
126 }
127
128 pub fn bind_int64(&self, index: i32, int: i64) -> Result<()> {
129 let index = index as c_int;
130 unsafe {
131 sqlite3_bind_int64(self.raw_statement, index, int);
132 }
133 self.connection.last_error()
134 }
135
136 pub fn column_int64(&self, index: i32) -> Result<i64> {
137 let index = index as c_int;
138 let result = unsafe { sqlite3_column_int64(self.raw_statement, index) };
139 self.connection.last_error()?;
140 Ok(result)
141 }
142
143 pub fn bind_null(&self, index: i32) -> Result<()> {
144 let index = index as c_int;
145 unsafe {
146 sqlite3_bind_null(self.raw_statement, index);
147 }
148 self.connection.last_error()
149 }
150
151 pub fn bind_text(&self, index: i32, text: &str) -> Result<()> {
152 let index = index as c_int;
153 let text_pointer = text.as_ptr() as *const _;
154 let len = text.len() as c_int;
155 unsafe {
156 sqlite3_bind_blob(
157 self.raw_statement,
158 index,
159 text_pointer,
160 len,
161 SQLITE_TRANSIENT(),
162 );
163 }
164 self.connection.last_error()
165 }
166
167 pub fn column_text<'b>(&'b mut self, index: i32) -> Result<&'b str> {
168 let index = index as c_int;
169 let pointer = unsafe { sqlite3_column_text(self.raw_statement, index) };
170
171 self.connection.last_error()?;
172 if pointer.is_null() {
173 return Ok("");
174 }
175 let len = unsafe { sqlite3_column_bytes(self.raw_statement, index) as usize };
176 self.connection.last_error()?;
177
178 let slice = unsafe { slice::from_raw_parts(pointer as *const u8, len) };
179 Ok(str::from_utf8(slice)?)
180 }
181
182 pub fn bind<T: Bind>(&self, value: T, index: i32) -> Result<i32> {
183 debug_assert!(index > 0);
184 value.bind(self, index)
185 }
186
187 pub fn column<T: Column>(&mut self) -> Result<T> {
188 let (result, _) = T::column(self, 0)?;
189 Ok(result)
190 }
191
192 pub fn column_type(&mut self, index: i32) -> Result<SqlType> {
193 let result = unsafe { sqlite3_column_type(self.raw_statement, index) }; // SELECT <FRIEND> FROM TABLE
194 self.connection.last_error()?;
195 match result {
196 SQLITE_INTEGER => Ok(SqlType::Integer),
197 SQLITE_FLOAT => Ok(SqlType::Float),
198 SQLITE_TEXT => Ok(SqlType::Text),
199 SQLITE_BLOB => Ok(SqlType::Blob),
200 SQLITE_NULL => Ok(SqlType::Null),
201 _ => Err(anyhow!("Column type returned was incorrect ")),
202 }
203 }
204
205 pub fn with_bindings(&mut self, bindings: impl Bind) -> Result<&mut Self> {
206 self.bind(bindings, 1)?;
207 Ok(self)
208 }
209
210 fn step(&mut self) -> Result<StepResult> {
211 unsafe {
212 match sqlite3_step(self.raw_statement) {
213 SQLITE_ROW => Ok(StepResult::Row),
214 SQLITE_DONE => Ok(StepResult::Done),
215 SQLITE_MISUSE => Ok(StepResult::Misuse),
216 other => self
217 .connection
218 .last_error()
219 .map(|_| StepResult::Other(other)),
220 }
221 }
222 }
223
224 pub fn insert(&mut self) -> Result<i64> {
225 self.exec()?;
226 Ok(self.connection.last_insert_id())
227 }
228
229 pub fn exec(&mut self) -> Result<()> {
230 fn logic(this: &mut Statement) -> Result<()> {
231 while this.step()? == StepResult::Row {}
232 Ok(())
233 }
234 let result = logic(self);
235 self.reset();
236 result
237 }
238
239 pub fn map<R>(&mut self, callback: impl FnMut(&mut Statement) -> Result<R>) -> Result<Vec<R>> {
240 fn logic<R>(
241 this: &mut Statement,
242 mut callback: impl FnMut(&mut Statement) -> Result<R>,
243 ) -> Result<Vec<R>> {
244 let mut mapped_rows = Vec::new();
245 while this.step()? == StepResult::Row {
246 mapped_rows.push(callback(this)?);
247 }
248 Ok(mapped_rows)
249 }
250
251 let result = logic(self, callback);
252 self.reset();
253 result
254 }
255
256 pub fn rows<R: Column>(&mut self) -> Result<Vec<R>> {
257 self.map(|s| s.column::<R>())
258 }
259
260 pub fn single<R>(&mut self, callback: impl FnOnce(&mut Statement) -> Result<R>) -> Result<R> {
261 fn logic<R>(
262 this: &mut Statement,
263 callback: impl FnOnce(&mut Statement) -> Result<R>,
264 ) -> Result<R> {
265 if this.step()? != StepResult::Row {
266 return Err(anyhow!(
267 "Single(Map) called with query that returns no rows."
268 ));
269 }
270 callback(this)
271 }
272 let result = logic(self, callback);
273 self.reset();
274 result
275 }
276
277 pub fn row<R: Column>(&mut self) -> Result<R> {
278 self.single(|this| this.column::<R>())
279 }
280
281 pub fn maybe<R>(
282 &mut self,
283 callback: impl FnOnce(&mut Statement) -> Result<R>,
284 ) -> Result<Option<R>> {
285 fn logic<R>(
286 this: &mut Statement,
287 callback: impl FnOnce(&mut Statement) -> Result<R>,
288 ) -> Result<Option<R>> {
289 if this.step()? != StepResult::Row {
290 return Ok(None);
291 }
292 callback(this).map(|r| Some(r))
293 }
294 let result = logic(self, callback);
295 self.reset();
296 result
297 }
298
299 pub fn maybe_row<R: Column>(&mut self) -> Result<Option<R>> {
300 self.maybe(|this| this.column::<R>())
301 }
302}
303
304impl<'a> Drop for Statement<'a> {
305 fn drop(&mut self) {
306 unsafe {
307 sqlite3_finalize(self.raw_statement);
308 self.connection
309 .last_error()
310 .expect("sqlite3 finalize failed for statement :(");
311 };
312 }
313}
314
315#[cfg(test)]
316mod test {
317 use indoc::indoc;
318
319 use crate::{connection::Connection, statement::StepResult};
320
321 #[test]
322 fn blob_round_trips() {
323 let connection1 = Connection::open_memory("blob_round_trips");
324 connection1
325 .exec(indoc! {"
326 CREATE TABLE blobs (
327 data BLOB
328 );"})
329 .unwrap();
330
331 let blob = &[0, 1, 2, 4, 8, 16, 32, 64];
332
333 let mut write = connection1
334 .prepare("INSERT INTO blobs (data) VALUES (?);")
335 .unwrap();
336 write.bind_blob(1, blob).unwrap();
337 assert_eq!(write.step().unwrap(), StepResult::Done);
338
339 // Read the blob from the
340 let connection2 = Connection::open_memory("blob_round_trips");
341 let mut read = connection2.prepare("SELECT * FROM blobs;").unwrap();
342 assert_eq!(read.step().unwrap(), StepResult::Row);
343 assert_eq!(read.column_blob(0).unwrap(), blob);
344 assert_eq!(read.step().unwrap(), StepResult::Done);
345
346 // Delete the added blob and verify its deleted on the other side
347 connection2.exec("DELETE FROM blobs;").unwrap();
348 let mut read = connection1.prepare("SELECT * FROM blobs;").unwrap();
349 assert_eq!(read.step().unwrap(), StepResult::Done);
350 }
351}