我正在连接到数据库。插入凭据后,连接器会返回一个(client, connection)
元组。之后,程序宏必须访问某个“全局位置”,从那里检索凭据并将数据连接到生成的代码中。
我试过这样的事情:
pub static RUNTIME_DATA: RuntimeData<'static> = RuntimeData::new().await;
struct RuntimeData<'a> {
db_credentials: DatabaseConnection<'static>,
phantom: PhantomData<&'a RuntimeData<'a>>
}
unsafe impl Send for RuntimeData<'_> {}
unsafe impl Sync for RuntimeData<'_> {}
impl<'a> RuntimeData<'a> {
pub async fn new() -> RuntimeData<'a> {
Self {
db_credentials: DatabaseConnection::new().await.unwrap(),
phantom: PhantomData,
}
}
}
我不能.await
在静态上下文中。是否有解决方法来保存RuntimeData
on的数据RUNTIME_DATA
?
我试图避免调用 DatabaseConnection::new()
每个 proc-macro 使用,因为它会解析配置文件中的凭据并将它们连接到实例中。我看到 Rust 做得非常快,即使我认为它的效率很低。如果我可以在静态上下文中存储一次凭据,我可以避免为每个 proc-macro 使用分配多个实例。
我的数据库处理程序是:
pub struct DatabaseConnection<'a> {
pub client: Client,
pub connection: Connection<Socket, NoTlsStream>,
pub phantom: &'a PhantomData<DatabaseConnection<'a>>
}
unsafe impl Send for DatabaseConnection<'_> {}
unsafe impl Sync for DatabaseConnection<'_> {}
impl<'a> DatabaseConnection<'a> {
pub async fn new() -> Result<DatabaseConnection<'a>, Error> {
let credentials = DatabaseCredentials::new();
let (new_client, new_connection) =
tokio_postgres::connect(
&format!(
"postgres://{user}:{pswd}@localhost/{db}",
user = credentials.username,
pswd = credentials.password,
db = credentials.db_name
)[..],
NoTls)
.await?;
Ok(Self {
client: new_client,
connection: new_connection,
phantom: &PhantomData
})
}
}
编辑 clarifiyinPitaJ
方法:
pub static lazy: Lazy<RuntimeData<'static>> = Lazy::new(|| async {
block_on(RuntimeData::new()).await.unwrap()
});