Rust中DieselConnectionManager<PgConnection>未实现ManageConnection问题求助
在Rust项目中使用bb8-diesel crate的DieselConnectionManager<PgConnection>类型时遇到错误,具体错误提示:
the trait
ManageConnectionis not implemented forDieselConnectionManager<PgConnection>
使用的版本为Diesel 2.0.3和bb8-diesel 0.2.1,项目的Cargo.toml相关配置如下:
[package] name = "uchat_query" version = "0.1.0" edition = "2021" [dependencies] bb8 = "0.8.0" bb8-diesel = { version = "0.2.1" } chrono = { version = "0.4.23", features = ["serde"] } diesel-derive-newtype = "2.0.0-rc.0" diesel_migrations = { version = "2.0.0", features = ["postgres"] } password-hash = { version = "0.5.0", features = ["std"] } r2d2 = "0.8.10" serde = { version = "1.0.152", features = ["derive"] } serde_json = "1.0.93" thiserror = "1.0.38" tokio = { version = "1.25.0", features = ["full"] } tracing = { version = "0.1.37", features = ["attributes"] } url = { version = "2.2.2" } uuid = { version = "1.3.0", features = ["v4", "serde"] } [dependencies.diesel] features = [ "postgres", "uuid", "chrono", "serde_json", "i-implement-a-third-party-backend-and-opt-into-breaking-changes", "postgres_backend", ] version = "2.0.3" default-features = false [dev-dependencies] dotenvy = "0.15.7" uchat_crypto = { path = "../crypto" }
错误相关的代码定义:
type AsyncConnectionManager = bb8_diesel::DieselConnectionManager;
已尝试更新bb8-diesel到最新版本、将Diesel降级到1.4.5,但问题仍未解决,希望了解这两个crate的交互逻辑是否存在遗漏或兼容性问题,并获取解决建议。
相关完整代码如下:
use diesel::{ConnectionError, PgConnection}; use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness}; use std::{error::Error, time::Duration}; use bb8::ManageConnection; use crate::error::QueryError; pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("../migrations"); type AsyncConnectionManager = bb8_diesel::DieselConnectionManager<PgConnection>; pub type AsyncConnection<'a> = bb8::PooledConnection<'a, AsyncConnectionManager>; pub type OwnedAsyncConnection = bb8::PooledConnection<'static, AsyncConnectionManager>; #[derive(Clone, Debug)] pub struct AsyncConnectionPool(bb8::Pool<AsyncConnectionManager>); impl AsyncConnectionPool { pub async fn new<S: AsRef<str>>(url: S) -> Result<Self, QueryError> { let pool = new_async_pool(url).await?; { // check connection let _ = pool .0 .get() .await .map_err(|e| QueryError::Connection(e.to_string()))?; } Ok(pool) } pub async fn get(&self) -> Result<AsyncConnection, QueryError> { self.0 .get() .await .map_err(|e| QueryError::Connection(e.to_string())) } pub async fn get_owned(&self) -> Result<OwnedAsyncConnection, QueryError> { self.0 .get_owned() .await .map_err(|e| QueryError::Connection(e.to_string())) } pub fn state(&self) -> bb8::State { self.0.state() } } /// Run database migrations pub fn run_migrations( connection: &mut impl MigrationHarness<diesel::pg::Pg>, ) -> Result<(), Box<dyn Error + Send + Sync + 'static>> { connection.run_pending_migrations(MIGRATIONS)?; Ok(()) } /// Connect to the database pub fn connect<S: AsRef<str>>(url: S) -> Result<PgConnection, ConnectionError> { use diesel::Connection; let url = url.as_ref(); PgConnection::establish(url) } /// Usage: /// ``` /// let async_pool = new_async_pool("postgres://login@localhost/sample").await; /// let conn = &mut async_pool.get().await?; /// ``` pub async fn new_async_pool<S: AsRef<str>>(url: S) -> Result<AsyncConnectionPool, QueryError> { let url = url.as_ref(); let manager = bb8_diesel::DieselConnectionManager::<PgConnection>::new(url); bb8::Pool::builder() .test_on_check_out(true) .connection_timeout(Duration::from_secs(10)) .build(manager) .await .map(AsyncConnectionPool) .map_err(|e| QueryError::Pool(e.to_string())) }
核心问题是bb8-diesel 0.2.1基于Diesel 1.x开发,与Diesel 2.x存在兼容性断层;降级Diesel到1.4.5仍出错大概率是依赖树版本冲突导致的。具体解决步骤如下:
切换兼容版本
使用bb8-diesel 0.3.x版本,它专门适配Diesel 2.x。修改Cargo.toml中的bb8-diesel依赖:bb8-diesel = { version = "0.3.0" }当前使用的Diesel 2.0.3可保持不变,两者兼容。
排查依赖冲突
运行cargo tree -p diesel查看是否有其他依赖强制引入不兼容的Diesel版本。如果存在,通过patch字段统一版本:[patch.crates-io] diesel = { version = "2.0.3", features = ["postgres", "uuid", "chrono", "serde_json", "i-implement-a-third-party-backend-and-opt-into-breaking-changes", "postgres_backend"] }调整特征导入
bb8-diesel 0.3.x实现的是异步特征AsyncManageConnection,而非bb8的同步ManageConnection。在代码顶部添加正确的导入:use bb8_diesel::AsyncManageConnection;验证连接池逻辑
bb8-diesel 0.3.x的DieselConnectionManager已正确实现AsyncManageConnection,因此原代码中bb8::Pool::builder().build(manager)的调用可正常工作,无需额外修改。
内容的提问来源于stack exchange,提问作者Mr Coder

