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
|
use diesel::connection::Connection as _;
pub use barrel::backend::Sqlite as SqlGenerator;
pub use diesel::sqlite::Sqlite as Backend;
pub use diesel::sqlite::SqliteConnection as Connection;
pub struct Database {
pub db_file: &'static str,
}
impl Database {
pub fn connect(&self) -> diesel::ConnectionResult<Connection> {
Connection::establish(self.db_file)
}
}
impl Default for Database {
fn default() -> Self {
Self {
db_file: "db.sqlite3",
}
}
}
use diesel::{
no_arg_sql_function, no_arg_sql_function_body, no_arg_sql_function_body_except_to_sql, QueryId,
};
no_arg_sql_function!(
last_insert_rowid,
diesel::sql_types::BigInt,
"Represents the SQL last_insert_rowid() function"
);
use diesel::{
query_builder::{AsQuery, InsertStatement, QueryFragment, QueryId},
query_dsl::methods::{FilterDsl, LoadQuery},
sql_types::BigInt,
Column, Expression, Insertable, Queryable,
};
pub fn insert_and_retrieve<'a, Row, Table, Id>(
to_insert: &'a Row,
table: Table,
connection: &Connection,
id: Id,
) -> Row
where
&'a Row: Insertable<Table>,
Row: Queryable<Table::SqlType, Backend>,
Table: diesel::Table + AsQuery + Copy,
InsertStatement<Table, <&'a Row as Insertable<Table>>::Values>: QueryFragment<Backend>,
<Table as AsQuery>::Query: QueryFragment<Backend>
+ QueryId
+ FilterDsl<diesel::expression::operators::Eq<Id, last_insert_rowid>>,
Id: Column + Expression<SqlType = BigInt>,
<Table as FilterDsl<diesel::expression::operators::Eq<Id, last_insert_rowid>>>::Output:
LoadQuery<Connection, Row>,
{
use diesel::prelude::*;
to_insert
.insert_into(table)
.execute(connection)
.expect("error saving to database"); // TODO propagate error
diesel::QueryDsl::filter(table, id.eq(last_insert_rowid))
.get_result(connection)
.expect("error loading from database") // TODO propagate error
}
|