1#![doc(html_favicon_url = "https://spring-rs.github.io/favicon.ico")]
3#![doc(html_logo_url = "https://spring-rs.github.io/logo.svg")]
4
5pub mod config;
6pub extern crate tokio_postgres as postgres;
7
8use config::PgConfig;
9use spring::app::AppBuilder;
10use spring::async_trait;
11use spring::config::ConfigRegistry;
12use spring::plugin::{MutableComponentRegistry, Plugin};
13use std::ops::Deref;
14use std::sync::Arc;
15use tokio_postgres::NoTls;
16
17#[derive(Clone)]
18pub struct Postgres(Arc<tokio_postgres::Client>);
19
20impl Postgres {
21 fn new(client: tokio_postgres::Client) -> Self {
22 Self(Arc::new(client))
23 }
24}
25
26impl Deref for Postgres {
27 type Target = tokio_postgres::Client;
28
29 fn deref(&self) -> &Self::Target {
30 &self.0
31 }
32}
33
34pub struct PgPlugin;
35
36#[async_trait]
37impl Plugin for PgPlugin {
38 async fn build(&self, app: &mut AppBuilder) {
39 let config = app
40 .get_config::<PgConfig>()
41 .expect("postgres plugin config load failed");
42
43 let (client, connection) = tokio_postgres::connect(&config.connect, NoTls)
44 .await
45 .expect("connect postgresql failed");
46
47 tokio::spawn(async move {
48 if let Err(e) = connection.await {
49 tracing::error!("postgresql connection error: {}", e);
50 }
51 });
52
53 app.add_component(Postgres::new(client));
54 }
55}