Struct MySqlSessionStore

Source
pub struct MySqlSessionStore { /* private fields */ }
Expand description

sqlx mysql session store for async-sessions

use async_sqlx_session::MySqlSessionStore;
use async_session::{Session, SessionStore};
use std::time::Duration;

let store = MySqlSessionStore::new(&std::env::var("MYSQL_TEST_DB_URL").unwrap()).await?;
store.migrate().await?;
store.spawn_cleanup_task(Duration::from_secs(60 * 60));

let mut session = Session::new();
session.insert("key", vec![1,2,3]);

let cookie_value = store.store_session(session).await?.unwrap();
let session = store.load_session(cookie_value).await?.unwrap();
assert_eq!(session.get::<Vec<i8>>("key").unwrap(), vec![1,2,3]);

Implementations§

Source§

impl MySqlSessionStore

Source

pub fn from_client(client: MySqlPool) -> Self

constructs a new MySqlSessionStore from an existing sqlx::MySqlPool. the default table name for this session store will be “async_sessions”. To override this, chain this with with_table_name.

let pool = sqlx::MySqlPool::connect(&std::env::var("MYSQL_TEST_DB_URL").unwrap()).await.unwrap();
let store = MySqlSessionStore::from_client(pool)
    .with_table_name("custom_table_name");
store.migrate().await;
Source

pub async fn new(database_url: &str) -> Result<Self>

Constructs a new MySqlSessionStore from a mysql:// database url. The default table name for this session store will be “async_sessions”. To override this, either chain with with_table_name or use new_with_table_name

let store = MySqlSessionStore::new(&std::env::var("MYSQL_TEST_DB_URL").unwrap()).await?;
store.migrate().await;
Source

pub async fn new_with_table_name( database_url: &str, table_name: &str, ) -> Result<Self>

constructs a new MySqlSessionStore from a mysql:// url. the default table name for this session store will be “async_sessions”. To override this, either chain with with_table_name or use new_with_table_name

let store = MySqlSessionStore::new_with_table_name(&std::env::var("MYSQL_TEST_DB_URL").unwrap(), "custom_table_name").await?;
store.migrate().await;
Source

pub fn with_table_name(self, table_name: impl AsRef<str>) -> Self

Chainable method to add a custom table name. This will panic if the table name is not [a-zA-Z0-9_-].

let store = MySqlSessionStore::new(&std::env::var("MYSQL_TEST_DB_URL").unwrap()).await?
    .with_table_name("custom_name");
store.migrate().await;
let store = MySqlSessionStore::new(&std::env::var("MYSQL_TEST_DB_URL").unwrap()).await?
    .with_table_name("johnny (); drop users;");
Source

pub async fn migrate(&self) -> Result<()>

Creates a session table if it does not already exist. If it does, this will noop, making it safe to call repeatedly on store initialization. In the future, this may make exactly-once modifications to the schema of the session table on breaking releases.

let store = MySqlSessionStore::new(&std::env::var("MYSQL_TEST_DB_URL").unwrap()).await?;
store.migrate().await?;
store.store_session(Session::new()).await?;
store.migrate().await?; // calling it a second time is safe
assert_eq!(store.count().await?, 1);
Source

pub fn spawn_cleanup_task(&self, period: Duration) -> JoinHandle<()>

Spawns an async_std::task that clears out stale (expired) sessions on a periodic basis. Only available with the async_std feature enabled.

let store = MySqlSessionStore::new(&std::env::var("MYSQL_TEST_DB_URL").unwrap()).await?;
store.migrate().await?;
store.spawn_cleanup_task(Duration::from_secs(1));
let mut session = Session::new();
session.expire_in(Duration::from_secs(0));
store.store_session(session).await?;
assert_eq!(store.count().await?, 1);
async_std::task::sleep(Duration::from_secs(2)).await;
assert_eq!(store.count().await?, 0);
Source

pub async fn cleanup(&self) -> Result<()>

Performs a one-time cleanup task that clears out stale (expired) sessions. You may want to call this from cron.

let store = MySqlSessionStore::new(&std::env::var("MYSQL_TEST_DB_URL").unwrap()).await?;
store.migrate().await?;
let mut session = Session::new();
session.set_expiry(Utc::now() - Duration::seconds(5));
store.store_session(session).await?;
assert_eq!(store.count().await?, 1);
store.cleanup().await?;
assert_eq!(store.count().await?, 0);
Source

pub async fn count(&self) -> Result<i64>

retrieves the number of sessions currently stored, including expired sessions

let store = MySqlSessionStore::new(&std::env::var("MYSQL_TEST_DB_URL").unwrap()).await?;
store.migrate().await?;
assert_eq!(store.count().await?, 0);
store.store_session(Session::new()).await?;
assert_eq!(store.count().await?, 1);

Trait Implementations§

Source§

impl Clone for MySqlSessionStore

Source§

fn clone(&self) -> MySqlSessionStore

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for MySqlSessionStore

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl SessionStore for MySqlSessionStore

Source§

fn load_session<'life0, 'async_trait>( &'life0 self, cookie_value: String, ) -> Pin<Box<dyn Future<Output = Result<Option<Session>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Get a session from the storage backend. Read more
Source§

fn store_session<'life0, 'async_trait>( &'life0 self, session: Session, ) -> Pin<Box<dyn Future<Output = Result<Option<String>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Store a session on the storage backend. Read more
Source§

fn destroy_session<'life0, 'async_trait>( &'life0 self, session: Session, ) -> Pin<Box<dyn Future<Output = Result> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Remove a session from the session store
Source§

fn clear_store<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Empties the entire store, destroying all sessions

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,