Skip to main content

teloxide/dispatching/dialogue/storage/
postgres_storage.rs

1use std::{
2    collections::HashSet,
3    convert::Infallible,
4    fmt::{Debug, Display},
5    str,
6    sync::Arc,
7};
8
9use futures::future::BoxFuture;
10use serde::{de::DeserializeOwned, Serialize};
11use sqlx::postgres::{PgPool, PgPoolOptions};
12use thiserror::Error;
13
14use super::{from_sql_key, initialize, sql_key, DialogueKey, Serializer, Storage, StorageKeys};
15
16/// An error returned from [`PostgresStorage`].
17#[derive(Debug, Error)]
18pub enum PostgresStorageError<SE>
19where
20    SE: Debug + Display,
21{
22    #[error("dialogue serialization error: {0}")]
23    SerdeError(SE),
24
25    #[error("postgres error: {0}")]
26    PostgresError(#[from] sqlx::Error),
27
28    // TODO maybe add chat_id for the sake of completeness?
29    #[error("row not found")]
30    DialogueNotFound,
31}
32
33/// A persistent dialogue storage based on [PostgreSQL](https://www.postgresql.org/)
34pub struct PostgresStorage<S> {
35    pool: PgPool,
36    serializer: S,
37}
38
39impl<S> PostgresStorage<S> {
40    /// Opens a connection pool to the [Postgres](https://www.postgresql.org/) database and creates the table
41    /// for storing dialogues.
42    ///
43    /// Parameters:
44    /// - database_url: full url to the postgres database, for example
45    ///   `"postgres://postgres:password@localhost/test")`
46    /// - max_connections: number of connections in creating connection pool. Be
47    ///   mindful of the connection limits for your database, each connection
48    ///   established with the Postgres creates a new process on the server side
49    /// - serializer: what [`Serializer`] will be used to encode the dialogue
50    ///   data. Available ones are: [`Json`], [`Bincode`], [`Cbor`]
51    ///
52    /// [`Json`]: crate::dispatching::dialogue::serializer::Json
53    /// [`Bincode`]: crate::dispatching::dialogue::serializer::Bincode
54    /// [`Cbor`]: crate::dispatching::dialogue::serializer::Cbor
55    pub async fn open(
56        database_url: &str,
57        max_connections: u32,
58        serializer: S,
59    ) -> Result<Arc<Self>, PostgresStorageError<Infallible>> {
60        let pool =
61            PgPoolOptions::new().max_connections(max_connections).connect(database_url).await?;
62        let mut tx = pool.begin().await?;
63        // Serialize schema creation/migration across concurrent opens.
64        sqlx::query("SELECT pg_advisory_xact_lock(1598376190, 1)").execute(&mut *tx).await?;
65        sqlx::query(include_str!("postgres_storage/queries/create_teloxide_dialogues.sql"))
66            .execute(&mut *tx)
67            .await?;
68        let scoped: bool = sqlx::query_scalar(
69            "SELECT EXISTS(SELECT 1 FROM pg_attribute WHERE attrelid = \
70             'teloxide_dialogues'::regclass AND attname = 'business_scope' AND NOT attisdropped)",
71        )
72        .fetch_one(&mut *tx)
73        .await?;
74        if !scoped {
75            sqlx::query(
76                "ALTER TABLE teloxide_dialogues ADD COLUMN business_scope TEXT NOT NULL DEFAULT \
77                 '', DROP CONSTRAINT teloxide_dialogues_pkey, ADD PRIMARY KEY (chat_id, \
78                 business_scope)",
79            )
80            .execute(&mut *tx)
81            .await?;
82        }
83        tx.commit().await?;
84
85        Ok(Arc::new(Self { pool, serializer }))
86    }
87}
88
89// FIXME: these methods' bodies are almostly the same as SqliteStorage ones
90// (except actual queries) Maybe combine them somehow?
91
92impl<S, D> Storage<D> for PostgresStorage<S>
93where
94    S: Send + Sync + Serializer<D> + 'static,
95    D: Send + Serialize + DeserializeOwned + 'static,
96    <S as Serializer<D>>::Error: Debug + Display,
97{
98    type Error = PostgresStorageError<<S as Serializer<D>>::Error>;
99
100    fn remove_dialogue(
101        self: Arc<Self>,
102        key: DialogueKey,
103    ) -> BoxFuture<'static, Result<(), Self::Error>>
104    where
105        D: Send + 'static,
106    {
107        Box::pin(async move {
108            let (chat_id, scope) = sql_key(key);
109            let deleted_rows_count =
110                sqlx::query(include_str!("postgres_storage/queries/remove_dialogue.sql"))
111                    .bind(chat_id)
112                    .bind(scope)
113                    .execute(&self.pool)
114                    .await?
115                    .rows_affected();
116
117            if deleted_rows_count == 0 {
118                return Err(PostgresStorageError::DialogueNotFound);
119            }
120
121            Ok(())
122        })
123    }
124
125    fn update_dialogue(
126        self: Arc<Self>,
127        key: DialogueKey,
128        dialogue: D,
129    ) -> BoxFuture<'static, Result<(), Self::Error>>
130    where
131        D: Send + 'static,
132    {
133        Box::pin(async move {
134            let (chat_id, scope) = sql_key(key);
135            let d =
136                self.serializer.serialize(&dialogue).map_err(PostgresStorageError::SerdeError)?;
137            sqlx::query(include_str!("postgres_storage/queries/update_dialogue.sql"))
138                .bind(chat_id)
139                .bind(scope)
140                .bind(d)
141                .execute(&self.pool)
142                .await?;
143            Ok(())
144        })
145    }
146
147    fn get_dialogue(
148        self: Arc<Self>,
149        key: DialogueKey,
150    ) -> BoxFuture<'static, Result<Option<D>, Self::Error>> {
151        Box::pin(async move {
152            let (chat_id, scope) = sql_key(key);
153            read(&self.pool, chat_id, &scope)
154                .await?
155                .map(|d| self.serializer.deserialize(&d).map_err(PostgresStorageError::SerdeError))
156                .transpose()
157        })
158    }
159
160    fn get_or_insert_dialogue(
161        self: Arc<Self>,
162        key: DialogueKey,
163        default: fn() -> D,
164        reset_incompatible: bool,
165    ) -> BoxFuture<'static, Result<D, Self::Error>> {
166        Box::pin(async move {
167            let (chat_id, scope) = sql_key(key);
168            let scope = scope.as_str();
169            let pool = &self.pool;
170            initialize(
171                &self.serializer,
172                PostgresStorageError::SerdeError,
173                default,
174                reset_incompatible,
175                || async { Ok(read(pool, chat_id, scope).await?) },
176                |expected, bytes| async move {
177                    Ok(compare_exchange(pool, chat_id, scope, expected, bytes).await?)
178                },
179            )
180            .await
181        })
182    }
183}
184
185impl<S: Send + Sync + 'static> StorageKeys for PostgresStorage<S> {
186    type Error = sqlx::Error;
187
188    fn keys(self: Arc<Self>) -> BoxFuture<'static, Result<HashSet<DialogueKey>, Self::Error>> {
189        Box::pin(async move {
190            let keys = sqlx::query_as(include_str!("postgres_storage/queries/keys.sql"))
191                .fetch_all(&self.pool)
192                .await?;
193            Ok(keys.into_iter().map(from_sql_key).collect())
194        })
195    }
196}
197
198async fn read(pool: &PgPool, chat_id: i64, scope: &str) -> Result<Option<Vec<u8>>, sqlx::Error> {
199    sqlx::query_scalar(include_str!("postgres_storage/queries/get_dialogue.sql"))
200        .bind(chat_id)
201        .bind(scope)
202        .fetch_optional(pool)
203        .await
204}
205
206async fn compare_exchange(
207    pool: &PgPool,
208    chat_id: i64,
209    scope: &str,
210    expected: Option<Vec<u8>>,
211    bytes: Vec<u8>,
212) -> Result<bool, sqlx::Error> {
213    let result = if let Some(expected) = expected {
214        sqlx::query(
215            "UPDATE teloxide_dialogues SET dialogue = $1 WHERE chat_id = $2 AND business_scope = \
216             $3 AND dialogue = $4",
217        )
218        .bind(bytes)
219        .bind(chat_id)
220        .bind(scope)
221        .bind(expected)
222        .execute(pool)
223        .await?
224    } else {
225        sqlx::query(
226            "INSERT INTO teloxide_dialogues (chat_id, business_scope, dialogue) VALUES ($1, $2, \
227             $3) ON CONFLICT (chat_id, business_scope) DO NOTHING",
228        )
229        .bind(chat_id)
230        .bind(scope)
231        .bind(bytes)
232        .execute(pool)
233        .await?
234    };
235    Ok(result.rows_affected() == 1)
236}