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
use std::collections::BTreeMap;
use surrealdb::{sql::Value, Datastore, Error, Response, Session};

pub struct Connection {
    ds: Datastore,
    ses: Session,
}

impl Connection {
    pub async fn execute(
        &self,
        txt: impl AsRef<str>,
        vars: Option<BTreeMap<String, Value>>,
        strict: bool,
    ) -> Result<Vec<Response>, Error> {
        Ok(self
            .ds
            .execute(txt.as_ref(), &self.ses, vars, strict)
            .await?)
    }
}

enum ConnectionType {
    Memory,
    File(String),
    #[cfg(feature = "tikv")]
    TiKV(String),
}

pub struct SurrealdbConnectionManager {
    connection_type: ConnectionType,
    session: Session,
}

impl SurrealdbConnectionManager {
    pub async fn memory(session: Session) -> Self {
        Self {
            session,
            connection_type: ConnectionType::Memory,
        }
    }

    pub async fn file(path: impl AsRef<str>, session: Session) -> Self {
        Self {
            session,
            connection_type: ConnectionType::File(format!("file://{}", path.as_ref())),
        }
    }

    #[cfg(feature = "tikv")]
    pub async fn tikv(uri: impl AsRef<str>, session: Session) -> Self {
        Self {
            session,
            connection_type: ConnectionType::TiKV(format!("tikv://{}", uri.as_ref())),
        }
    }
}

#[async_trait::async_trait]
impl bb8::ManageConnection for SurrealdbConnectionManager {
    type Connection = Connection;
    type Error = surrealdb::Error;

    async fn connect(&self) -> Result<Self::Connection, Self::Error> {
        Ok(Connection {
            ds: match &self.connection_type {
                ConnectionType::Memory => Datastore::new("memory").await?,
                ConnectionType::File(path) => Datastore::new(path.as_ref()).await?,
                #[cfg(feature = "tikv")]
                ConnectionType::TiKV(uri) => Datastore::new(uri.as_ref()).await?,
            },
            ses: self.session.clone(),
        })
    }

    async fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
        conn.execute("SELECT * FROM 1;", None, false).await?;
        Ok(())
    }

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