bb8_skytable/
lib.rs

1//! Skytable support for the `bb8` connection pool.
2//!
3//! # Basic Example
4//!
5//! ```
6//! use bb8_skytable::{
7//!     bb8,
8//!     skytable::{actions::Actions},
9//!     SkytableConnectionManager
10//! };
11//!
12//! #[tokio::main]
13//! async fn main() {
14//! 	let manager = SkytableConnectionManager::new("127.0.0.1", 2003);
15//!		let pool = bb8::Pool::builder().build(manager).await.unwrap();
16
17//!   	let mut conn = pool.get().await.unwrap();
18//!     conn.set("x", "100").await.unwrap();
19//! }
20//! ```
21#![allow(clippy::needless_doctest_main)]
22#![deny(missing_docs, missing_debug_implementations)]
23
24pub use bb8;
25pub use skytable;
26
27use async_trait::async_trait;
28
29use skytable::aio::Connection;
30use skytable::query;
31use skytable::Element;
32
33/// A `bb8::ManageConnection` for `skytable::aio::Connection`.
34
35#[derive(Clone, Debug)]
36pub struct SkytableConnectionManager {
37	host: String,
38	port: u16,
39}
40
41impl SkytableConnectionManager {
42	/// Create a new `SkytableConnectionManager`.
43	/// See `skytable::aio::Connection::new` for a description of the parameter types.
44	pub fn new(host: &str, port: u16) -> SkytableConnectionManager {
45		SkytableConnectionManager {
46			host: host.to_string(),
47			port,
48		}
49	}
50}
51
52#[async_trait]
53impl bb8::ManageConnection for SkytableConnectionManager {
54	type Connection = Connection;
55	type Error = std::io::Error;
56
57	async fn connect(&self) -> Result<Self::Connection, Self::Error> {
58		Connection::new(&self.host, self.port).await
59	}
60
61	async fn is_valid(
62		&self,
63		conn: &mut bb8::PooledConnection<'_, Self>,
64	) -> Result<(), Self::Error> {
65		let query = query!("HEYA");
66		let result = conn.run_simple_query(&query).await;
67		let response = match result {
68			Ok(response) => response,
69			Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::NotConnected, e.to_string())),
70		};
71
72		match response {
73			Element::String(s) => {
74				if s == "HEY!" {
75					Ok(())
76				} else {
77					Err(std::io::Error::new(
78						std::io::ErrorKind::InvalidData,
79						"Did not receive HEY!",
80					))
81				}
82			}
83			_ => Err(std::io::Error::new(
84				std::io::ErrorKind::InvalidData,
85				"Did not receive a String!",
86			)),
87		}
88	}
89
90	fn has_broken(&self, _: &mut Self::Connection) -> bool {
91		false
92	}
93}