database persistence in progress
This commit is contained in:
1287
Cargo.lock
generated
1287
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -14,3 +14,4 @@ actix-web = "4.12.1"
|
||||
paperclip = { version = "0.9.5", features = ["actix4"] }
|
||||
apistos = { version = "0.6.0", features = ["swagger-ui"] }
|
||||
schemars = { package = "apistos-schemars", version = "0.8" }
|
||||
sea-orm = { version = "1.1.19", features = ["macros", "runtime-tokio", "sqlx-sqlite"] }
|
||||
|
||||
2
migration/.gitignore
vendored
Normal file
2
migration/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/target
|
||||
result
|
||||
2129
migration/Cargo.lock
generated
Normal file
2129
migration/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
23
migration/Cargo.toml
Normal file
23
migration/Cargo.toml
Normal file
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "migration"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
name = "migration"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
tokio = {version = "1.49.0", features = ["macros", "rt-multi-thread"]}
|
||||
|
||||
[dependencies.sea-orm-migration]
|
||||
version = "1.1.0"
|
||||
features = [
|
||||
# Enable at least one `ASYNC_RUNTIME` and `DATABASE_DRIVER` feature if you want to run migration via CLI.
|
||||
# View the list of supported features at https://www.sea-ql.org/SeaORM/docs/install-and-config/database-and-async-runtime.
|
||||
# e.g.
|
||||
"runtime-tokio-rustls", # `ASYNC_RUNTIME` feature
|
||||
# "sqlx-postgres", # `DATABASE_DRIVER` feature
|
||||
"sqlx-sqlite"
|
||||
]
|
||||
41
migration/README.md
Normal file
41
migration/README.md
Normal file
@@ -0,0 +1,41 @@
|
||||
# Running Migrator CLI
|
||||
|
||||
- Generate a new migration file
|
||||
```sh
|
||||
cargo run -- generate MIGRATION_NAME
|
||||
```
|
||||
- Apply all pending migrations
|
||||
```sh
|
||||
cargo run
|
||||
```
|
||||
```sh
|
||||
cargo run -- up
|
||||
```
|
||||
- Apply first 10 pending migrations
|
||||
```sh
|
||||
cargo run -- up -n 10
|
||||
```
|
||||
- Rollback last applied migrations
|
||||
```sh
|
||||
cargo run -- down
|
||||
```
|
||||
- Rollback last 10 applied migrations
|
||||
```sh
|
||||
cargo run -- down -n 10
|
||||
```
|
||||
- Drop all tables from the database, then reapply all migrations
|
||||
```sh
|
||||
cargo run -- fresh
|
||||
```
|
||||
- Rollback all applied migrations, then reapply all migrations
|
||||
```sh
|
||||
cargo run -- refresh
|
||||
```
|
||||
- Rollback all applied migrations
|
||||
```sh
|
||||
cargo run -- reset
|
||||
```
|
||||
- Check the status of all migrations
|
||||
```sh
|
||||
cargo run -- status
|
||||
```
|
||||
12
migration/src/lib.rs
Normal file
12
migration/src/lib.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
pub use sea_orm_migration::prelude::*;
|
||||
|
||||
mod m20220101_000001_create_table;
|
||||
|
||||
pub struct Migrator;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigratorTrait for Migrator {
|
||||
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
|
||||
vec![Box::new(m20220101_000001_create_table::Migration)]
|
||||
}
|
||||
}
|
||||
36
migration/src/m20220101_000001_create_table.rs
Normal file
36
migration/src/m20220101_000001_create_table.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
use sea_orm_migration::{prelude::*, schema::*};
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
// Replace the sample below with your own migration scripts
|
||||
|
||||
manager.create_table(
|
||||
Table::create()
|
||||
.table(Alarm::Table)
|
||||
.if_not_exists()
|
||||
.col(pk_auto(Alarm::Id))
|
||||
.col(date_time(Alarm::Time))
|
||||
.col(boolean(Alarm::Enabled))
|
||||
.col(string(Alarm::Title))
|
||||
.to_owned(),
|
||||
).await
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
// Replace the sample below with your own migration scripts
|
||||
manager.drop_table(Table::drop().table(Alarm::Table).to_owned()).await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Alarm {
|
||||
Table,
|
||||
Id,
|
||||
Time,
|
||||
Enabled,
|
||||
Title
|
||||
}
|
||||
6
migration/src/main.rs
Normal file
6
migration/src/main.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
use sea_orm_migration::prelude::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
cli::run_cli(migration::Migrator).await;
|
||||
}
|
||||
BIN
snooze-pal.db
Normal file
BIN
snooze-pal.db
Normal file
Binary file not shown.
22
src/dao/alarm.rs
Normal file
22
src/dao/alarm.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use chrono::{DateTime, Local};
|
||||
use sea_orm::{
|
||||
ActiveModelTrait, ActiveValue::Set, ConnectionTrait, DbErr
|
||||
};
|
||||
|
||||
use crate::model::{self, alarm};
|
||||
|
||||
pub async fn create_alarm<C: ConnectionTrait>(
|
||||
db: &C,
|
||||
title: &str,
|
||||
time: DateTime<Local>,
|
||||
) -> Result<alarm::Model, DbErr> {
|
||||
let alarm_to_create = model::alarm::ActiveModel {
|
||||
title: Set(title.to_string()),
|
||||
time: Set(time.naive_utc()),
|
||||
enabled: Set(true),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
Ok(alarm_to_create.insert(db).await?)
|
||||
}
|
||||
|
||||
2
src/dao/mod.rs
Normal file
2
src/dao/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod alarm;
|
||||
|
||||
11
src/main.rs
11
src/main.rs
@@ -4,6 +4,7 @@ use actix_web::{App, HttpServer, web};
|
||||
use apistos::{SwaggerUIConfig, app::{BuildConfig, OpenApiWrapper}, info::Info, spec::Spec};
|
||||
use cron_tab::Cron;
|
||||
use gpio_cdev::Chip;
|
||||
use sea_orm::Database;
|
||||
|
||||
use crate::{ringer::BeepRinger, scheduler::Scheduler};
|
||||
|
||||
@@ -11,6 +12,8 @@ mod scheduler;
|
||||
mod ringer;
|
||||
mod types;
|
||||
mod resources;
|
||||
mod dao;
|
||||
mod model;
|
||||
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -18,20 +21,22 @@ struct AppState {
|
||||
scheduler: Arc<Scheduler<BeepRinger>>
|
||||
}
|
||||
|
||||
fn app_state() -> AppState {
|
||||
async fn app_state() -> AppState {
|
||||
let chip: Arc<Mutex<Chip>> = Arc::new(Mutex::new(Chip::new("/dev/gpiochip0").unwrap()));
|
||||
let cron = Arc::new(Mutex::new(Cron::new(chrono::Local)));
|
||||
let db = Database::connect("sqlite://snooze-pal.db").await.unwrap();
|
||||
AppState {
|
||||
scheduler: Arc::new(Scheduler::new(
|
||||
Arc::new(Mutex::new(BeepRinger::new(chip.clone()))),
|
||||
cron.clone()
|
||||
cron.clone(),
|
||||
Arc::new(db)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let app_state = app_state();
|
||||
let app_state = app_state().await;
|
||||
|
||||
app_state.scheduler.start();
|
||||
|
||||
|
||||
18
src/model/alarm.rs
Normal file
18
src/model/alarm.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.19
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
|
||||
#[sea_orm(table_name = "alarm")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub time: DateTime,
|
||||
pub enabled: bool,
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
5
src/model/mod.rs
Normal file
5
src/model/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.19
|
||||
|
||||
pub mod prelude;
|
||||
|
||||
pub mod alarm;
|
||||
3
src/model/prelude.rs
Normal file
3
src/model/prelude.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.19
|
||||
|
||||
pub use super::alarm::Entity as Alarm;
|
||||
@@ -2,24 +2,31 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use chrono::{DateTime, Local, Timelike};
|
||||
use cron_tab::Cron;
|
||||
use sea_orm::DatabaseConnection;
|
||||
|
||||
use crate::dao::alarm::create_alarm;
|
||||
use crate::ringer::Ringer;
|
||||
use crate::types::Alarm;
|
||||
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Scheduler<T: Ringer + 'static> {
|
||||
ringer: Arc<Mutex<T>>,
|
||||
cron: Arc<Mutex<Cron<Local>>>,
|
||||
alarms: Arc<Mutex<Vec<Alarm>>>,
|
||||
db: Arc<DatabaseConnection>,
|
||||
}
|
||||
|
||||
impl<T: Ringer> Scheduler<T> {
|
||||
pub fn new(ringer: Arc<Mutex<T>>, cron: Arc<Mutex<Cron<Local>>>) -> Self {
|
||||
pub fn new(
|
||||
ringer: Arc<Mutex<T>>,
|
||||
cron: Arc<Mutex<Cron<Local>>>,
|
||||
db: Arc<DatabaseConnection>,
|
||||
) -> Self {
|
||||
Self {
|
||||
ringer,
|
||||
cron,
|
||||
alarms: Arc::new(Mutex::new(Vec::new())),
|
||||
db,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,12 +48,15 @@ impl<T: Ringer> Scheduler<T> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
pub fn add_alarm(&self, time: DateTime<Local>) -> Result<Alarm, String> {
|
||||
let mut alarms = self.alarms.lock().map_err(|e| e.to_string())?;
|
||||
pub async fn add_alarm(&self, time: DateTime<Local>) -> Result<Alarm, String> {
|
||||
let cron_schedule = format!("{} {} {} * * *", "*", time.minute(), time.hour());
|
||||
let alarm = Alarm::new(true, time);
|
||||
alarms.push(alarm.clone());
|
||||
self.schedule(&cron_schedule).map_err(|e| e.to_string())?;
|
||||
let alarm = Alarm::new(true, time);
|
||||
|
||||
create_alarm(&*self.db, "something", time)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
self.schedule(&cron_schedule).map_err(|e| e.to_string())?;
|
||||
println!("Added alarm {}", cron_schedule);
|
||||
|
||||
Ok(alarm)
|
||||
|
||||
Reference in New Issue
Block a user