1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
extern crate libsqlite3_sys as ffi;
mod functions;
#[doc(hidden)]
pub mod raw;
mod serialized_value;
mod sqlite_value;
mod statement_iterator;
mod stmt;
pub use self::sqlite_value::SqliteValue;
use std::os::raw as libc;
use self::raw::RawConnection;
use self::statement_iterator::*;
use self::stmt::{Statement, StatementUse};
use connection::*;
use deserialize::{Queryable, QueryableByName};
use query_builder::bind_collector::RawBytesBindCollector;
use query_builder::*;
use result::*;
use serialize::ToSql;
use sql_types::HasSqlType;
use sqlite::Sqlite;
#[allow(missing_debug_implementations)]
pub struct SqliteConnection {
statement_cache: StatementCache<Sqlite, Statement>,
raw_connection: RawConnection,
transaction_manager: AnsiTransactionManager,
}
unsafe impl Send for SqliteConnection {}
impl SimpleConnection for SqliteConnection {
fn batch_execute(&self, query: &str) -> QueryResult<()> {
self.raw_connection.exec(query)
}
}
impl Connection for SqliteConnection {
type Backend = Sqlite;
type TransactionManager = AnsiTransactionManager;
fn establish(database_url: &str) -> ConnectionResult<Self> {
use result::ConnectionError::CouldntSetupConfiguration;
let raw_connection = RawConnection::establish(database_url)?;
let conn = Self {
statement_cache: StatementCache::new(),
raw_connection,
transaction_manager: AnsiTransactionManager::new(),
};
conn.register_diesel_sql_functions()
.map_err(CouldntSetupConfiguration)?;
Ok(conn)
}
#[doc(hidden)]
fn execute(&self, query: &str) -> QueryResult<usize> {
self.batch_execute(query)?;
Ok(self.raw_connection.rows_affected_by_last_query())
}
#[doc(hidden)]
fn query_by_index<T, U>(&self, source: T) -> QueryResult<Vec<U>>
where
T: AsQuery,
T::Query: QueryFragment<Self::Backend> + QueryId,
Self::Backend: HasSqlType<T::SqlType>,
U: Queryable<T::SqlType, Self::Backend>,
{
let mut statement = self.prepare_query(&source.as_query())?;
let statement_use = StatementUse::new(&mut statement);
let iter = StatementIterator::new(statement_use);
iter.collect()
}
#[doc(hidden)]
fn query_by_name<T, U>(&self, source: &T) -> QueryResult<Vec<U>>
where
T: QueryFragment<Self::Backend> + QueryId,
U: QueryableByName<Self::Backend>,
{
let mut statement = self.prepare_query(source)?;
let statement_use = StatementUse::new(&mut statement);
let iter = NamedStatementIterator::new(statement_use)?;
iter.collect()
}
#[doc(hidden)]
fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize>
where
T: QueryFragment<Self::Backend> + QueryId,
{
let mut statement = self.prepare_query(source)?;
let mut statement_use = StatementUse::new(&mut statement);
statement_use.run()?;
Ok(self.raw_connection.rows_affected_by_last_query())
}
#[doc(hidden)]
fn transaction_manager(&self) -> &Self::TransactionManager {
&self.transaction_manager
}
}
impl SqliteConnection {
pub fn immediate_transaction<T, E, F>(&self, f: F) -> Result<T, E>
where
F: FnOnce() -> Result<T, E>,
E: From<Error>,
{
self.transaction_sql(f, "BEGIN IMMEDIATE")
}
pub fn exclusive_transaction<T, E, F>(&self, f: F) -> Result<T, E>
where
F: FnOnce() -> Result<T, E>,
E: From<Error>,
{
self.transaction_sql(f, "BEGIN EXCLUSIVE")
}
fn transaction_sql<T, E, F>(&self, f: F, sql: &str) -> Result<T, E>
where
F: FnOnce() -> Result<T, E>,
E: From<Error>,
{
let transaction_manager = self.transaction_manager();
transaction_manager.begin_transaction_sql(self, sql)?;
match f() {
Ok(value) => {
transaction_manager.commit_transaction(self)?;
Ok(value)
}
Err(e) => {
transaction_manager.rollback_transaction(self)?;
Err(e)
}
}
}
fn prepare_query<T: QueryFragment<Sqlite> + QueryId>(
&self,
source: &T,
) -> QueryResult<MaybeCached<Statement>> {
let mut statement = self.cached_prepared_statement(source)?;
let mut bind_collector = RawBytesBindCollector::<Sqlite>::new();
source.collect_binds(&mut bind_collector, &())?;
let metadata = bind_collector.metadata;
let binds = bind_collector.binds;
for (tpe, value) in metadata.into_iter().zip(binds) {
statement.bind(tpe, value)?;
}
Ok(statement)
}
fn cached_prepared_statement<T: QueryFragment<Sqlite> + QueryId>(
&self,
source: &T,
) -> QueryResult<MaybeCached<Statement>> {
self.statement_cache.cached_statement(source, &[], |sql| {
Statement::prepare(&self.raw_connection, sql)
})
}
#[doc(hidden)]
pub fn register_sql_function<ArgsSqlType, RetSqlType, Args, Ret, F>(
&self,
fn_name: &str,
deterministic: bool,
mut f: F,
) -> QueryResult<()>
where
F: FnMut(Args) -> Ret + Send + 'static,
Args: Queryable<ArgsSqlType, Sqlite>,
Ret: ToSql<RetSqlType, Sqlite>,
Sqlite: HasSqlType<RetSqlType>,
{
functions::register(
&self.raw_connection,
fn_name,
deterministic,
move |_, args| f(args),
)
}
fn register_diesel_sql_functions(&self) -> QueryResult<()> {
use sql_types::{Integer, Text};
functions::register::<Text, Integer, _, _, _>(
&self.raw_connection,
"diesel_manage_updated_at",
false,
|conn, table_name: String| {
conn.exec(&format!(
include_str!("diesel_manage_updated_at.sql"),
table_name = table_name
))
.expect("Failed to create trigger");
0
},
)
}
}
fn error_message(err_code: libc::c_int) -> &'static str {
ffi::code_to_str(err_code)
}
#[cfg(test)]
mod tests {
use super::*;
use dsl::sql;
use prelude::*;
use sql_types::Integer;
#[test]
fn prepared_statements_are_cached_when_run() {
let connection = SqliteConnection::establish(":memory:").unwrap();
let query = ::select(1.into_sql::<Integer>());
assert_eq!(Ok(1), query.get_result(&connection));
assert_eq!(Ok(1), query.get_result(&connection));
assert_eq!(1, connection.statement_cache.len());
}
#[test]
fn sql_literal_nodes_are_not_cached() {
let connection = SqliteConnection::establish(":memory:").unwrap();
let query = ::select(sql::<Integer>("1"));
assert_eq!(Ok(1), query.get_result(&connection));
assert_eq!(0, connection.statement_cache.len());
}
#[test]
fn queries_containing_sql_literal_nodes_are_not_cached() {
let connection = SqliteConnection::establish(":memory:").unwrap();
let one_as_expr = 1.into_sql::<Integer>();
let query = ::select(one_as_expr.eq(sql::<Integer>("1")));
assert_eq!(Ok(true), query.get_result(&connection));
assert_eq!(0, connection.statement_cache.len());
}
#[test]
fn queries_containing_in_with_vec_are_not_cached() {
let connection = SqliteConnection::establish(":memory:").unwrap();
let one_as_expr = 1.into_sql::<Integer>();
let query = ::select(one_as_expr.eq_any(vec![1, 2, 3]));
assert_eq!(Ok(true), query.get_result(&connection));
assert_eq!(0, connection.statement_cache.len());
}
#[test]
fn queries_containing_in_with_subselect_are_cached() {
let connection = SqliteConnection::establish(":memory:").unwrap();
let one_as_expr = 1.into_sql::<Integer>();
let query = ::select(one_as_expr.eq_any(::select(one_as_expr)));
assert_eq!(Ok(true), query.get_result(&connection));
assert_eq!(1, connection.statement_cache.len());
}
use sql_types::Text;
sql_function!(fn fun_case(x: Text) -> Text);
#[test]
fn register_custom_function() {
let connection = SqliteConnection::establish(":memory:").unwrap();
fun_case::register_impl(&connection, |x: String| {
x.chars()
.enumerate()
.map(|(i, c)| {
if i % 2 == 0 {
c.to_lowercase().to_string()
} else {
c.to_uppercase().to_string()
}
})
.collect::<String>()
})
.unwrap();
let mapped_string = ::select(fun_case("foobar"))
.get_result::<String>(&connection)
.unwrap();
assert_eq!("fOoBaR", mapped_string);
}
sql_function!(fn my_add(x: Integer, y: Integer) -> Integer);
#[test]
fn register_multiarg_function() {
let connection = SqliteConnection::establish(":memory:").unwrap();
my_add::register_impl(&connection, |x: i32, y: i32| x + y).unwrap();
let added = ::select(my_add(1, 2)).get_result::<i32>(&connection);
assert_eq!(Ok(3), added);
}
sql_function!(fn add_counter(x: Integer) -> Integer);
#[test]
fn register_nondeterministic_function() {
let connection = SqliteConnection::establish(":memory:").unwrap();
let mut y = 0;
add_counter::register_nondeterministic_impl(&connection, move |x: i32| {
y += 1;
x + y
})
.unwrap();
let added = ::select((add_counter(1), add_counter(1), add_counter(1)))
.get_result::<(i32, i32, i32)>(&connection);
assert_eq!(Ok((2, 3, 4)), added);
}
}