diff --git a/src/admin/route/mod.rs b/src/admin/route/mod.rs index 873c09a..28213e5 100644 --- a/src/admin/route/mod.rs +++ b/src/admin/route/mod.rs @@ -45,7 +45,11 @@ impl Route { .unwrap(); } - async fn add_station(&self, db: &SqlitePool, station: &Station) -> Result<(), String> { + pub(crate) async fn add_station( + &self, + db: &SqlitePool, + station: &Station, + ) -> Result<(), String> { sqlx::query!( r#" INSERT INTO route_station (route_id, station_id, pos) diff --git a/src/admin/station/mod.rs b/src/admin/station/mod.rs index acbbaca..37f4df5 100644 --- a/src/admin/station/mod.rs +++ b/src/admin/station/mod.rs @@ -80,10 +80,26 @@ impl Station { pub(crate) async fn create(db: &SqlitePool, name: &str) -> Result<(), String> { let code = generate_random_alphanumeric(8); - sqlx::query!("INSERT INTO station(name, pw) VALUES (?, ?)", name, code) - .execute(db) - .await - .map_err(|e| e.to_string())?; + let station_id = sqlx::query!( + "INSERT INTO station(name, pw) VALUES (?, ?) RETURNING id", + name, + code + ) + .fetch_one(db) + .await + .map_err(|e| e.to_string())?; + + let mut routes = Route::all(db).await.into_iter(); + if let Some(route) = routes.next() { + if routes.next().is_none() { + // Just one route exists -> use it for new station + let station = Station::find_by_id(db, station_id.id) + .await + .expect("just created"); + + route.add_station(db, &station).await?; + } + } Ok(()) }