1use std::rc::Rc;
2
3use itertools::Itertools;
4use rusqlite::{Connection, Params, Result as SQLResult, Row, limits::Limit, params, types::Value};
5
6use crate::errors::QueryError;
7
8pub fn sqlite_parameter_limit(conn: &Connection) -> usize {
10 let limit = conn.limit(Limit::SQLITE_LIMIT_VARIABLE_NUMBER);
11 usize::try_from(limit).expect("SQLite parameter limit should be positive")
12}
13
14pub fn max_rows_per_batch(conn: &Connection, params_per_row: usize) -> usize {
16 let params_per_row = params_per_row.max(1);
17 let max_params = sqlite_parameter_limit(conn);
18 (max_params / params_per_row).max(1)
19}
20
21pub trait Query {
22 type Model;
23 const PRIMARY_KEY: &'static str = "id";
24 const TABLE_NAME: &'static str;
25
26 fn query(conn: &Connection, query: &str, params: impl Params) -> Vec<Self::Model> {
27 let mut stmt = conn.prepare(query).unwrap();
28 let rows = stmt
29 .query_map(params, |row| Ok(Self::process_row(row)))
30 .unwrap();
31 let mut objs = vec![];
32 for row in rows {
33 objs.push(row.unwrap());
34 }
35 objs
36 }
37
38 fn try_query(
39 conn: &Connection,
40 query: &str,
41 params: impl Params,
42 ) -> Result<Vec<Self::Model>, QueryError> {
43 let mut stmt = conn.prepare(query)?;
44 let rows = stmt.query_map(params, |row| Ok(Self::process_row(row)))?;
45 let mut objs = vec![];
46 for row in rows {
47 objs.push(row?);
48 }
49 Ok(objs)
50 }
51
52 fn get(conn: &Connection, query: &str, params: impl Params) -> SQLResult<Self::Model> {
53 let mut stmt = conn.prepare(query).unwrap();
54 stmt.query_row(params, |row| Ok(Self::process_row(row)))
55 }
56
57 fn get_by_id<'a, T>(conn: &Connection, id: &'a T) -> Option<Self::Model>
58 where
59 T: Clone + 'a,
60 Value: From<T>,
61 {
62 Self::query(
63 conn,
64 &format!(
65 "select * from {} where {} = ?1",
66 Self::TABLE_NAME,
67 Self::PRIMARY_KEY
68 ),
69 params![Value::from(id.clone())],
70 )
71 .pop()
72 }
73
74 fn query_by_ids<'a, I: ?Sized, T>(conn: &Connection, ids: &'a I) -> Vec<Self::Model>
75 where
76 &'a I: IntoIterator<Item = &'a T>,
77 T: Clone + 'a,
78 Value: From<T>,
79 {
80 let mut results = vec![];
81 let batch_size = max_rows_per_batch(conn, 1);
82 for chunk in &ids.into_iter().chunks(batch_size) {
83 let values: Vec<Value> = chunk
84 .map(|value: &'a T| Value::from(value.clone()))
85 .collect();
86 results.append(&mut Self::query(
87 conn,
88 &format!(
91 "
92 WITH arr AS (
93 SELECT value, rowid AS pos
94 FROM rarray(?1)
95 )
96 SELECT {}.*
97 FROM {}
98 JOIN arr ON {}.{} = arr.value
99 ORDER BY arr.pos;
100 ",
101 Self::TABLE_NAME,
102 Self::TABLE_NAME,
103 Self::TABLE_NAME,
104 Self::PRIMARY_KEY
105 ),
106 params!(Rc::new(values)),
107 ))
108 }
109 results
110 }
111
112 fn delete_by_ids<'a, I: ?Sized, T>(conn: &Connection, ids: &'a I) -> Vec<Self::Model>
113 where
114 &'a I: IntoIterator<Item = &'a T>,
115 T: Clone + 'a,
116 Value: From<T>,
117 {
118 let mut results = vec![];
119 let batch_size = max_rows_per_batch(conn, 1);
120 for chunk in &ids.into_iter().chunks(batch_size) {
121 let values: Vec<Value> = chunk
122 .map(|value: &'a T| Value::from(value.clone()))
123 .collect();
124 results.append(&mut Self::query(
125 conn,
126 &format!(
127 "delete from {} where {} in rarray(?1)",
128 Self::TABLE_NAME,
129 Self::PRIMARY_KEY
130 ),
131 params!(Rc::new(values)),
132 ))
133 }
134 results
135 }
136
137 fn process_row(row: &Row) -> Self::Model;
138
139 fn table_name() -> &'static str {
140 Self::TABLE_NAME
141 }
142
143 fn all(conn: &Connection) -> Vec<Self::Model> {
144 let query = format!("SELECT * FROM {}", Self::TABLE_NAME);
145 Self::query(conn, &query, [])
146 }
147
148 fn all_with_limit(conn: &Connection, limit: usize) -> Vec<Self::Model> {
149 let query = format!("SELECT * FROM {} LIMIT {}", Self::TABLE_NAME, limit);
150 Self::query(conn, &query, [])
151 }
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157 use crate::{collection::Collection, test_helpers::get_connection};
158
159 #[test]
160 fn test_all_method() {
161 let conn = get_connection(None).expect("Failed to get connection");
162
163 let empty_results = Collection::all(&conn);
165 assert!(empty_results.is_empty());
166
167 let collection_names = vec![
169 "test_collection_1",
170 "test_collection_2",
171 "test_collection_3",
172 ];
173 for name in &collection_names {
174 Collection::create(&conn, name).unwrap();
175 }
176
177 let all_results = Collection::all(&conn);
178 assert_eq!(all_results.len(), collection_names.len());
179
180 let returned_names: Vec<String> = all_results.iter().map(|c| c.name.clone()).collect();
181 for name in &collection_names {
182 assert!(returned_names.contains(&name.to_string()));
183 }
184 }
185
186 #[test]
187 fn test_all_with_limit_method() {
188 let conn = get_connection(None).expect("Failed to get connection");
189
190 for i in 0..10 {
191 Collection::create(&conn, &format!("test_collection_{}", i)).unwrap();
192 }
193
194 let limited_results = Collection::all_with_limit(&conn, 5);
195 assert_eq!(limited_results.len(), 5);
196
197 let all_results = Collection::all(&conn);
199 let large_limit_results = Collection::all_with_limit(&conn, all_results.len() + 20);
200 assert_eq!(large_limit_results.len(), all_results.len());
201
202 let zero_limit_results = Collection::all_with_limit(&conn, 0);
204 assert!(zero_limit_results.is_empty());
205
206 let one_limit_results = Collection::all_with_limit(&conn, 1);
208 assert_eq!(one_limit_results.len(), 1);
209 }
210}