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
#![deny(warnings)]
//! # Sqlite support for the `bb8` connection pool.
//!
//! Library crate: [bb8-libsql]()
//!
//! Integrated with: [bb8](https://crates.io/crates/bb8)
//! and [libsql](https://crates.io/crates/libsql)
//!
//! ## Example
//!
//! ```rust,no_run
//! use std::{env, error::Error};
//! use r2d2_libsql::LibsqlConnectionManager;
//!  
//! use dotenvy::dotenv;
//!  
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn Error>> {
//!     dotenv().ok();
//!  
//!     let url = env::var("LIBSQL_CLIENT_URL").unwrap();
//!     let token = env::var("LIBSQL_CLIENT_TOKEN").unwrap();
//!  
//!     let manager = LibsqlConnectionManager::remote(&url, &token);
//!     let pool = bb8::Pool::builder()
//!         .max_size(15)
//!         .build(manager)
//!         .await
//!         .unwrap();
//!  
//!     let conn = pool.get().await?;
//!     let mut rows = conn.query("SELECT 1;", ()).await?;
//!  
//!     let value_found = rows.next().await?
//!         .map(|row| row.get::<u64>(0))
//!         .transpose()?;
//!  
//!     dbg!(value_found);
//!  
//!     Ok(())
//! }
//! ```
pub use libsql;
use async_trait::async_trait;
use libsql::Connection;
use std::fmt;
use std::path::{Path, PathBuf};

mod errors;

#[derive(Debug, Clone)]
enum Source {
    Local(PathBuf),
    Remote(String, String),
    LocalReplica(PathBuf),
    RemoteReplica(PathBuf, String, String),
}

/// An `bb8::ManageConnection` for `libsql::Connection`s.
pub struct LibsqlConnectionManager { source: Source }

impl fmt::Debug for LibsqlConnectionManager {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut builder = f.debug_struct("LibsqlConnectionManager");
        let _ = builder.field("source", &self.source);
        builder.finish()
    }
}

impl LibsqlConnectionManager {
    /// Creates a new `LibsqlConnectionManager` from local file.
    /// See `libsql::Builder::new_local`
    pub fn local<P: AsRef<Path>>(path: P) -> Self {
        Self {
            source: Source::Local(
                path.as_ref().to_path_buf()
            ),
        }
    }

    /// Creates a new `LibsqlConnectionManager` from remote.
    /// See `libsql::Builder::new_remote`
    pub fn remote(url: &str, token: &str) -> Self {
        Self {
            source: Source::Remote(
                url.to_string(), 
                token.to_string()
            ),
        }
    }

    /// Creates a new `LibsqlConnectionManager` from local replica.
    /// See `libsql::Builder::new_local_replica`
    pub fn local_replica<P: AsRef<Path>>(path: P) -> Self {
        Self {
            source: Source::LocalReplica(
                path.as_ref().to_path_buf(),
            ),
        }
    }

    /// Creates a new `LibsqlConnectionManager` from remote replica.
    /// See `libsql::Builder::new_remote_replica`
    pub fn remote_replica<P: AsRef<Path>>(path: P, url: &str, token: &str) -> Self {
        Self {
            source: Source::RemoteReplica(
                path.as_ref().to_path_buf(),
                url.to_string(),
                token.to_string(),
            ),
        }
    }
}

#[async_trait]
impl bb8::ManageConnection for LibsqlConnectionManager {
    type Connection = Connection;
    type Error = errors::ConnectionManagerError;

    async fn connect(&self) -> Result<Connection, errors::ConnectionManagerError> {
        Ok(match &self.source {
            Source::Local(ref path) => {
                libsql::Builder::new_local(path)
                    .build().await
                    .and_then(|builder| builder.connect())
            },
            Source::Remote(url, token) => {
                libsql::Builder::new_remote(url.to_string(), token.to_string())
                    .build().await
                    .and_then(|builder| builder.connect())
            },
            Source::LocalReplica(path) => {
                libsql::Builder::new_local_replica(path)
                    .build().await
                    .and_then(|builder| builder.connect())
            },
            Source::RemoteReplica(path, url, token) => {
                libsql::Builder::new_remote_replica(path, url.to_string(), token.to_string())
                    .build().await
                    .and_then(|builder| builder.connect())
            },
        }?)
    }

    async fn is_valid(&self, conn: &mut Connection) -> Result<(), errors::ConnectionManagerError> {
        Ok(conn.execute_batch("SELECT 1;").await.map(|_| ())?)
    }

    fn has_broken(&self, _: &mut Connection) -> bool { false }
}