4 //use rusqlite::types::ToSql;
5 //use rusqlite::{Connection, Result, NO_PARAMS};
8 //extern crate r2d2_sqlite;
9 //extern crate rusqlite;
11 use r2d2_sqlite
::SqliteConnectionManager
;
16 SqliteError(rusqlite
::Error
),
17 R2d2Error(r2d2
::Error
),
18 UnsupportedVersion(i32),
23 const CURRENT_DB_VERSION
: u32 = 1;
25 pub struct Connection
{
26 //con: rusqlite::Connection
27 pool
: Pool
<SqliteConnectionManager
>
35 impl std
::convert
::From
<rusqlite
::Error
> for DbError
{
36 fn from(error
: rusqlite
::Error
) -> Self {
37 DbError
::SqliteError(error
)
41 impl std
::convert
::From
<r2d2
::Error
> for DbError
{
42 fn from(error
: r2d2
::Error
) -> Self {
43 DbError
::R2d2Error(error
)
48 pub fn new() -> Result
<Connection
, DbError
> {
50 let data_dir
= Path
::new(consts
::DB_DIRECTORY
);
52 if !data_dir
.exists() {
53 fs
::DirBuilder
::new().create(data_dir
).unwrap();
56 let manager
= SqliteConnectionManager
::file("file.db");
57 let pool
= r2d2
::Pool
::new(manager
).unwrap();
59 let connection
= Connection
{ pool
};
60 connection
.create_or_update()?
;
65 * Called after the connection has been established for creating or updating the database.
66 * The 'Version' table tracks the current state of the database.
68 fn create_or_update(self: &Self) -> Result
<(), DbError
> {
69 // let connection = Connection::new();
70 // let mut stmt = connection.sqlite_con.prepare("SELECT * FROM versions ORDER BY date").unwrap();
71 // let mut stmt = connection.sqlite_con.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='versions'").unwrap();
73 // Check the Database version.
74 let mut con
= self.pool
.get()?
;
75 let tx
= con
.transaction()?
;
79 "SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'",
81 |row
| row
.get
::<usize, String
>(0)
83 Ok(_
) => tx
.query_row("SELECT [version] FROM [Version]", rusqlite
::NO_PARAMS
, |row
| row
.get(0)).unwrap_or_default(),
88 while Connection
::update_to_next_version(version
, &tx
)?
{
97 fn update_to_next_version(version
: i32, tx
: &rusqlite
::Transaction
) -> Result
<bool
, DbError
> {
100 println!("Update to version 1...");
102 // Initial structure.
105 CREATE TABLE [Version] (
106 [id] INTEGER PRIMARY KEY,
107 [version] INTEGER NOT NULL UNIQUE,
108 [datetime] INTEGER DATETIME
111 CREATE TABLE [Recipe] (
112 [id] INTEGER PRIMARY KEY,
113 [title] INTEGER NOT NULL,
114 [description] INTEGER DATETIME
135 Err(DbError
::UnsupportedVersion(v
)),
139 pub fn get_all_recipes() {