connectorx/sources/sqlite/
mod.rs1mod errors;
4mod typesystem;
5
6pub use self::errors::SQLiteSourceError;
7use crate::utils::OwningHandle;
8use crate::{
9 data_order::DataOrder,
10 errors::ConnectorXError,
11 sources::{PartitionParser, Produce, Source, SourcePartition},
12 sql::{count_query, limit1_query, CXQuery},
13 utils::DummyBox,
14};
15use anyhow::anyhow;
16use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
17use fallible_streaming_iterator::FallibleStreamingIterator;
18use fehler::{throw, throws};
19use log::debug;
20use r2d2::{Pool, PooledConnection};
21use r2d2_sqlite::SqliteConnectionManager;
22use rusqlite::{Row, Rows, Statement};
23use sqlparser::dialect::SQLiteDialect;
24use std::convert::TryFrom;
25pub use typesystem::SQLiteTypeSystem;
26use urlencoding::decode;
27
28pub struct SQLiteSource {
30 pool: Pool<SqliteConnectionManager>,
31 origin_query: Option<String>,
32 queries: Vec<CXQuery<String>>,
33 names: Vec<String>,
34 schema: Vec<SQLiteTypeSystem>,
35}
36
37impl SQLiteSource {
38 #[throws(SQLiteSourceError)]
40 pub fn new(conn: &str, nconn: usize) -> Self {
41 let decoded_conn = decode(conn)?.into_owned();
42 debug!("decoded conn: {}", decoded_conn);
43 let manager = SqliteConnectionManager::file(decoded_conn);
44 let pool = r2d2::Pool::builder()
45 .max_size(nconn as u32)
46 .build(manager)?;
47
48 Self {
49 pool,
50 origin_query: None,
51 queries: vec![],
52 names: vec![],
53 schema: vec![],
54 }
55 }
56}
57
58impl Source for SQLiteSource
59where
60 SQLiteSourcePartition: SourcePartition<TypeSystem = SQLiteTypeSystem>,
61{
62 const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::RowMajor];
63 type Partition = SQLiteSourcePartition;
64 type TypeSystem = SQLiteTypeSystem;
65 type Error = SQLiteSourceError;
66
67 #[throws(SQLiteSourceError)]
68 fn set_data_order(&mut self, data_order: DataOrder) {
69 if !matches!(data_order, DataOrder::RowMajor) {
70 throw!(ConnectorXError::UnsupportedDataOrder(data_order));
71 }
72 }
73
74 fn set_queries<Q: ToString>(&mut self, queries: &[CXQuery<Q>]) {
75 self.queries = queries.iter().map(|q| q.map(Q::to_string)).collect();
76 }
77
78 fn set_origin_query(&mut self, query: Option<String>) {
79 self.origin_query = query;
80 }
81
82 #[throws(SQLiteSourceError)]
83 fn fetch_metadata(&mut self) {
84 assert!(!self.queries.is_empty());
85 let conn = self.pool.get()?;
86
87 let stmt = conn.prepare(self.queries[0].as_str())?;
91 let columns = stmt.columns();
92
93 let mut names: Vec<String> = Vec::with_capacity(columns.len());
94 let mut types: Vec<Option<SQLiteTypeSystem>> = Vec::with_capacity(columns.len());
95
96 for col in &columns {
97 names.push(col.name().to_string());
98 let decl_type = col.decl_type();
99 match SQLiteTypeSystem::try_from((decl_type, rusqlite::types::Type::Null)) {
100 Ok(t) => types.push(Some(t)),
101 Err(_) => types.push(None),
102 }
103 }
104
105 if !types.contains(&None) {
107 self.names = names;
108 self.schema = types.into_iter().map(|t| t.unwrap()).collect();
109 return;
110 }
111
112 drop(columns);
115 drop(stmt);
116
117 let mut num_empty = 0;
118 for (i, query) in self.queries.iter().enumerate() {
119 let l1query = limit1_query(query, &SQLiteDialect {})?;
120
121 let is_success = conn.query_row(l1query.as_str(), [], |row| {
122 for (j, col) in row.as_ref().columns().iter().enumerate() {
123 if types[j].is_none() {
124 let vr = row.get_ref(j)?;
125 if let Ok(t) = SQLiteTypeSystem::try_from((col.decl_type(), vr.data_type()))
126 {
127 types[j] = Some(t);
128 }
129 }
130 }
131 Ok(())
132 });
133
134 match is_success {
135 Ok(()) => {
136 if !types.contains(&None) {
137 self.names = names;
138 self.schema = types.into_iter().map(|t| t.unwrap()).collect();
139 return;
140 } else if i == self.queries.len() - 1 {
141 debug!(
142 "cannot get metadata for '{}' due to null value: {:?}",
143 query, types
144 );
145 throw!(SQLiteSourceError::InferTypeFromNull);
146 }
147 }
148 Err(e) => {
149 if let rusqlite::Error::QueryReturnedNoRows = e {
150 num_empty += 1;
151 }
152 if i == self.queries.len() - 1 && num_empty < self.queries.len() {
153 debug!("cannot get metadata for '{}': {}", query, e);
154 throw!(e)
155 }
156 }
157 }
158 }
159
160 self.names = names;
163 self.schema = types
164 .into_iter()
165 .map(|t| t.unwrap_or(SQLiteTypeSystem::Text(false)))
166 .collect();
167 }
168
169 #[throws(SQLiteSourceError)]
170 fn result_rows(&mut self) -> Option<usize> {
171 match &self.origin_query {
172 Some(q) => {
173 let cxq = CXQuery::Naked(q.clone());
174 let conn = self.pool.get()?;
175 let nrows =
176 conn.query_row(count_query(&cxq, &SQLiteDialect {})?.as_str(), [], |row| {
177 Ok(row.get::<_, i64>(0)? as usize)
178 })?;
179 Some(nrows)
180 }
181 None => None,
182 }
183 }
184
185 fn names(&self) -> Vec<String> {
186 self.names.clone()
187 }
188
189 fn schema(&self) -> Vec<Self::TypeSystem> {
190 self.schema.clone()
191 }
192
193 #[throws(SQLiteSourceError)]
194 fn partition(self) -> Vec<Self::Partition> {
195 let mut ret = vec![];
196 for query in self.queries {
197 let conn = self.pool.get()?;
198
199 ret.push(SQLiteSourcePartition::new(conn, &query, &self.schema));
200 }
201 ret
202 }
203}
204
205pub struct SQLiteSourcePartition {
207 conn: PooledConnection<SqliteConnectionManager>,
208 query: CXQuery<String>,
209 schema: Vec<SQLiteTypeSystem>,
210 nrows: usize,
211 ncols: usize,
212}
213
214impl SQLiteSourcePartition {
215 pub fn new(
217 conn: PooledConnection<SqliteConnectionManager>,
218 query: &CXQuery<String>,
219 schema: &[SQLiteTypeSystem],
220 ) -> Self {
221 Self {
222 conn,
223 query: query.clone(),
224 schema: schema.to_vec(),
225 nrows: 0,
226 ncols: schema.len(),
227 }
228 }
229}
230
231impl SourcePartition for SQLiteSourcePartition {
232 type TypeSystem = SQLiteTypeSystem;
233 type Parser<'a> = SQLiteSourcePartitionParser<'a>;
234 type Error = SQLiteSourceError;
235
236 #[throws(SQLiteSourceError)]
237 fn result_rows(&mut self) {
238 self.nrows = self.conn.query_row(
239 count_query(&self.query, &SQLiteDialect {})?.as_str(),
240 [],
241 |row| Ok(row.get::<_, i64>(0)? as usize),
242 )?;
243 }
244
245 #[throws(SQLiteSourceError)]
246 fn parser(&mut self) -> Self::Parser<'_> {
247 SQLiteSourcePartitionParser::new(&self.conn, self.query.as_str(), &self.schema)?
248 }
249
250 fn nrows(&self) -> usize {
251 self.nrows
252 }
253
254 fn ncols(&self) -> usize {
255 self.ncols
256 }
257}
258
259unsafe impl<'a> Send for SQLiteSourcePartitionParser<'a> {}
260
261pub struct SQLiteSourcePartitionParser<'a> {
263 rows: OwningHandle<Statement<'a>, DummyBox<Rows<'a>>>,
264 ncols: usize,
265 current_col: usize,
266 current_consumed: bool,
267 is_finished: bool,
268}
269
270impl<'a> SQLiteSourcePartitionParser<'a> {
271 #[throws(SQLiteSourceError)]
273 pub fn new(
274 conn: &'a PooledConnection<SqliteConnectionManager>,
275 query: &str,
276 schema: &[SQLiteTypeSystem],
277 ) -> Self {
278 let stmt: Statement<'a> = conn.prepare(query)?;
279
280 let rows: OwningHandle<Statement<'a>, DummyBox<Rows<'a>>> =
284 OwningHandle::new_with_fn(Box::new(stmt), |stmt: *const Statement<'a>| unsafe {
285 DummyBox((*(stmt as *mut Statement<'_>)).query([]).unwrap())
286 });
287 Self {
288 rows,
289 ncols: schema.len(),
290 current_col: 0,
291 current_consumed: true,
292 is_finished: false,
293 }
294 }
295
296 #[throws(SQLiteSourceError)]
297 fn next_loc(&mut self) -> (&Row<'_>, usize) {
298 self.current_consumed = true;
299 let row: &Row = (*self.rows)
300 .get()
301 .ok_or_else(|| anyhow!("Sqlite empty current row"))?;
302 let col = self.current_col;
303 self.current_col = (self.current_col + 1) % self.ncols;
304 (row, col)
305 }
306}
307
308impl<'a> PartitionParser<'a> for SQLiteSourcePartitionParser<'a> {
309 type TypeSystem = SQLiteTypeSystem;
310 type Error = SQLiteSourceError;
311
312 #[throws(SQLiteSourceError)]
313 fn fetch_next(&mut self) -> (usize, bool) {
314 assert!(self.current_col == 0);
315
316 if !self.current_consumed {
317 return (1, false);
318 } else if self.is_finished {
319 return (0, true);
320 }
321
322 match (*self.rows).next()? {
323 Some(_) => {
324 self.current_consumed = false;
325 (1, false)
326 }
327 None => {
328 self.is_finished = true;
329 (0, true)
330 }
331 }
332 }
333}
334
335macro_rules! impl_produce {
336 ($($t: ty,)+) => {
337 $(
338 impl<'r, 'a> Produce<'r, $t> for SQLiteSourcePartitionParser<'a> {
339 type Error = SQLiteSourceError;
340
341 #[throws(SQLiteSourceError)]
342 fn produce(&'r mut self) -> $t {
343 let (row, col) = self.next_loc()?;
344 let val = row.get(col)?;
345 val
346 }
347 }
348
349 impl<'r, 'a> Produce<'r, Option<$t>> for SQLiteSourcePartitionParser<'a> {
350 type Error = SQLiteSourceError;
351
352 #[throws(SQLiteSourceError)]
353 fn produce(&'r mut self) -> Option<$t> {
354 let (row, col) = self.next_loc()?;
355 let val = row.get(col)?;
356 val
357 }
358 }
359 )+
360 };
361}
362
363impl_produce!(
364 bool,
365 i64,
366 i32,
367 i16,
368 f64,
369 Box<str>,
370 NaiveDate,
371 NaiveTime,
372 NaiveDateTime,
373 Vec<u8>,
374);
375
376#[cfg(all(test, feature = "dst_arrow"))]
377mod tests;