使用deadpool_postgres/tokio_postgres搭配cornucopia时遇到GenericClient trait绑定错误
deadpool_postgres/tokio_postgres搭配cornucopia时遇到GenericClient trait绑定错误
看起来你遇到了cornucopia和deadpool_postgres之间的Trait适配问题,我之前也碰到过类似的坑,下面是具体的解决思路和步骤:
问题原因
deadpool返回的Object<Manager>是连接池封装后的连接对象,而cornucopia的GenericClient Trait默认只给tokio_postgres::Client、Transaction这类原生客户端类型实现了适配,并没有直接支持deadpool的包装对象,所以编译器会抛出trait bound不满足的错误。
解决方法:手动实现GenericClient Trait
我们可以为deadpool的Object类型手动实现cornucopia_async::GenericClient Trait,把方法调用转发给内部的原生Postgres客户端:
use cornucopia_async::GenericClient; use deadpool_postgres::Object; // 为deadpool的连接对象实现cornucopia的GenericClient trait impl GenericClient for Object { type Error = deadpool_postgres::PoolError; async fn query<'a, 'b>( &'a self, query: &'b str, params: &'b [tokio_postgres::types::ToSql], ) -> Result<tokio_postgres::RowStream, Self::Error> { // 转发调用到内部的postgres客户端 Ok(self.query(query, params).await?) } async fn query_one<'a, 'b>( &'a self, query: &'b str, params: &'b [tokio_postgres::types::ToSql], ) -> Result<tokio_postgres::Row, Self::Error> { Ok(self.query_one(query, params).await?) } async fn query_opt<'a, 'b>( &'a self, query: &'b str, params: &'b [tokio_postgres::types::ToSql], ) -> Result<Option<tokio_postgres::Row>, Self::Error> { Ok(self.query_opt(query, params).await?) } async fn execute<'a, 'b>( &'a self, query: &'b str, params: &'b [tokio_postgres::types::ToSql], ) -> Result<u64, Self::Error> { Ok(self.execute(query, params).await?) } }
额外检查点
确保cornucopia生成异步代码:
你需要确认cornucopia是在异步模式下生成的代码,比如生成命令加上--async参数,或者在cornucopia配置中启用async选项,否则生成的同步查询函数无法和deadpool的异步客户端配合使用。依赖版本兼容性:
不同版本的cornucopia和deadpool_postgres可能存在方法签名差异,建议检查你的Cargo.toml依赖版本是否匹配,比如可以参考以下兼容版本:cornucopia_async = "0.15" deadpool_postgres = "0.12" tokio_postgres = "0.7"
测试验证
添加完Trait实现后,你原来的代码应该就能正常编译运行了,比如:
// 从连接池获取连接 let client = pool.get().await?; // 调用cornucopia生成的查询函数 let result = my_generated_queries::get_some_data(&client).await?;
备注:内容来源于stack exchange,提问作者Anshul Raman
相关产品推荐
相关产品推荐

