rocket_flex_session/storage/
sqlx.rs

1//! Session storage via sqlx
2
3mod base;
4use base::*;
5
6#[cfg(feature = "sqlx_postgres")]
7mod postgres;
8#[cfg(feature = "sqlx_postgres")]
9pub use postgres::SqlxPostgresStorage;
10
11#[cfg(feature = "sqlx_sqlite")]
12mod sqlite;
13#[cfg(feature = "sqlx_sqlite")]
14pub use sqlite::SqlxSqliteStorage;
15
16use crate::SessionIdentifier;
17
18/**
19Trait for session data types that can be stored using sqlx.
20The generic parameter `Database` represents the sqlx database type.
21# Example
22
23```
24use rocket_flex_session::error::SessionError;
25use rocket_flex_session::storage::sqlx::SessionSqlx;
26use rocket_flex_session::SessionIdentifier;
27
28#[derive(Clone)]
29struct SessionData {
30    user_id: i32,
31    data: String,
32}
33
34// Implement SessionIdentifier to define how to group/index sessions
35impl SessionIdentifier for SessionData {
36    type Id = i32; // must be a type supported by sqlx
37    fn identifier(&self) -> Option<Self::Id> {
38        Some(self.user_id) // this will typically be the user ID
39    }
40}
41
42impl SessionSqlx<sqlx::Postgres> for SessionData {
43    type Error = SessionError; // or a custom error
44    type Data = String; // the data type passed to sqlx
45
46    fn into_sql(self) -> Result<Self::Data, Self::Error> {
47        Ok(format!("{}:{}", self.user_id, self.data))
48    }
49
50    fn from_sql(value: Self::Data) -> Result<Self, Self::Error> {
51        let (user_id, data) = value.split_once(':').ok_or(SessionError::InvalidData)?;
52        Ok(SessionData {
53            user_id: user_id.parse().map_err(|e| SessionError::Parsing(Box::new(e)))?,
54            data: data.to_owned(),
55        })
56    }
57}
58```
59*/
60pub trait SessionSqlx<Database>
61where
62    Self: SessionIdentifier + 'static,
63    <Self as SessionIdentifier>::Id: for<'q> sqlx::Encode<'q, Database> + sqlx::Type<Database>,
64    Database: sqlx::Database,
65{
66    /// The error that can occur when converting to/from the SQL value.
67    type Error: std::error::Error + Send + Sync;
68
69    /// The data type passed to sqlx to be stored in the SQL database. Must be a type supported by sqlx.
70    type Data: for<'q> sqlx::Encode<'q, Database>
71        + for<'q> sqlx::Decode<'q, Database>
72        + sqlx::Type<Database>
73        + Send
74        + Sync;
75
76    /// Convert this session into a SQL value.
77    fn into_sql(self) -> Result<Self::Data, Self::Error>;
78
79    /// Convert a SQL value into the session data type.
80    fn from_sql(value: Self::Data) -> Result<Self, Self::Error>;
81}