async_sea_orm_session/migration.rs
1//! This module contains migrations to help adding the sessions table required for this crate.
2//!
3//! # Example - Single migration
4//! If you don't need to run any other migrations the [`Migrator`] struct can be used directly
5//!
6//! ```rust
7//! use async_sea_orm_session::migration::Migrator;
8//! use async_sea_orm_session::DatabaseSessionStore;
9//! use sea_orm::{Database, DatabaseConnection};
10//! use sea_orm_migration::MigratorTrait;
11//!
12//! # async fn doctest() -> Result<(), Box<dyn std::error::Error>> {
13//!
14//! let db: DatabaseConnection =
15//! Database::connect("protocol://username:password@host/database").await?;
16//!
17//! // Run the async-sea-orm-session migration, if it hasn't already been run.
18//! Migrator::up(&db, None).await?;
19//! let store = DatabaseSessionStore::new(db);
20//! # Ok(())
21//! # }
22//! ```
23//!
24//! # Example - Multiple migrations
25//! The previous example isn't super useful because it doesn't allow you to run other migrations.
26//! To resolve this you should include [`SessionTableMigration`] directly in your own
27//! [`MigratorTrait`] implementation, as in the example below:
28//!
29//! ```rust,ignore
30//! // In migrations/src/lib.rs
31//! pub use sea_orm_migration::prelude::*;
32//! use async_sea_orm_session::migration::SessionTableMigration;
33//!
34//! mod m20220101_000001_sample_migration;
35//! mod m20220102_000002_some_other_migration;
36//!
37//! pub struct Migrator;
38//!
39//! #[async_trait::async_trait]
40//! impl MigratorTrait for Migrator {
41//! fn migrations() -> Vec<Box<dyn MigrationTrait>> {
42//! vec![
43//! Box::new(m20220101_000001_sample_migration::Migration),
44//! Box::new(m20220102_000002_some_other_migration::Migration),
45//! Box::new(SessionTableMigration),
46//! ]
47//! }
48//! }
49//! ```
50use crate::sessions;
51use async_session::async_trait;
52use sea_orm_migration::prelude::*;
53
54pub struct Migrator;
55
56#[async_trait]
57impl MigratorTrait for Migrator {
58 fn migrations() -> Vec<Box<dyn MigrationTrait>> {
59 vec![Box::new(SessionTableMigration)]
60 }
61}
62
63pub struct SessionTableMigration;
64impl MigrationName for SessionTableMigration {
65 fn name(&self) -> &str {
66 "create_session_table"
67 }
68}
69
70#[async_trait]
71impl MigrationTrait for SessionTableMigration {
72 async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
73 manager
74 .create_table(
75 sea_query::Table::create()
76 .table(sessions::Entity)
77 .if_not_exists()
78 .col(
79 ColumnDef::new(sessions::Column::Id)
80 .text()
81 .not_null()
82 .primary_key(),
83 )
84 .col(
85 ColumnDef::new(sessions::Column::Session)
86 .json_binary()
87 .not_null(),
88 )
89 .to_owned(),
90 )
91 .await?;
92
93 Ok(())
94 }
95
96 async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
97 manager
98 .drop_table(sea_query::Table::drop().table(sessions::Entity).to_owned())
99 .await?;
100 Ok(())
101 }
102}