我正在尝试为每个池连接准备语句。
我基本上想做的是:
const SQL_1: &str = "SELECT foo FROM bar WHERE baz = $1";
在池连接创建期间,为每个新连接运行:
let stmt = conn.prepare(SQL_1);
__some_magic_to_store_at_connection__(SQL_1, stmt);
在处理程序中时:
let conn = my_pool.get().unwrap();
let stmt = __some_magic_to_get_the_stmt__(conn, SQL_1);
现在怎么办?到目前为止,我想出了这个:
const SQL_1: &str = "SELECT foo FROM bar WHERE baz = $1";
// Customized connection which will run all required PREPARE
#[derive(Debug)]
pub struct PreparedConnection {}
// Trait implementation for customized connection
impl r2d2::CustomizeConnection<r2d2_postgres::postgres::Client, r2d2_postgres::postgres::Error> for PreparedConnection {
// Run all statement preparators
fn on_acquire(&self, p_conn: &mut r2d2_postgres::postgres::Client) -> Result<(), r2d2_postgres::postgres::Error> {
// Prepare it
let stmt = p_conn.prepare(SQL_1);
// Now ... what?
// Done
Ok(())
}
// Noting to do on release
fn on_release(&self, _: r2d2_postgres::postgres::Client) {}
}
所以我需要以某种方式将语句存储在连接中。稍后再取回。我看到有一个可用于池连接的 extensions() 东西,但我正在努力让它工作。