From 4a582e8079178a7ac11f2a492e7988fcdaa210cd Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sat, 23 Jul 2022 23:40:25 +0200 Subject: store active version id in bots table --- planetwars-server/src/db/bots.rs | 48 ++++++++++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 7 deletions(-) (limited to 'planetwars-server/src/db') diff --git a/planetwars-server/src/db/bots.rs b/planetwars-server/src/db/bots.rs index a112a9a..a0a31b0 100644 --- a/planetwars-server/src/db/bots.rs +++ b/planetwars-server/src/db/bots.rs @@ -16,6 +16,7 @@ pub struct Bot { pub id: i32, pub owner_id: Option, pub name: String, + pub active_version: Option, } pub fn create_bot(new_bot: &NewBot, conn: &PgConnection) -> QueryResult { @@ -38,11 +39,34 @@ pub fn find_bot_by_name(name: &str, conn: &PgConnection) -> QueryResult { bots::table.filter(bots::name.eq(name)).first(conn) } +pub fn find_bot_with_version_by_name( + bot_name: &str, + conn: &PgConnection, +) -> QueryResult<(Bot, BotVersion)> { + bots::table + .inner_join(bot_versions::table.on(bots::active_version.eq(bot_versions::id.nullable()))) + .filter(bots::name.eq(bot_name)) + .first(conn) +} + +pub fn all_active_bots_with_version(conn: &PgConnection) -> QueryResult> { + bots::table + .inner_join(bot_versions::table.on(bots::active_version.eq(bot_versions::id.nullable()))) + .get_results(conn) +} + pub fn find_all_bots(conn: &PgConnection) -> QueryResult> { - // TODO: filter out bots that cannot be run (have no valid code bundle associated with them) bots::table.get_results(conn) } +/// Find all bots that have an associated active version. +/// These are the bots that can be run. +pub fn find_active_bots(conn: &PgConnection) -> QueryResult> { + bots::table + .filter(bots::active_version.is_not_null()) + .get_results(conn) +} + #[derive(Insertable)] #[table_name = "bot_versions"] pub struct NewBotVersion<'a> { @@ -69,15 +93,25 @@ pub fn create_bot_version( .get_result(conn) } -pub fn find_bot_versions(bot_id: i32, conn: &PgConnection) -> QueryResult> { +pub fn set_active_version( + bot_id: i32, + version_id: Option, + conn: &PgConnection, +) -> QueryResult<()> { + diesel::update(bots::table.filter(bots::id.eq(bot_id))) + .set(bots::active_version.eq(version_id)) + .execute(conn)?; + Ok(()) +} + +pub fn find_bot_version(version_id: i32, conn: &PgConnection) -> QueryResult { bot_versions::table - .filter(bot_versions::bot_id.eq(bot_id)) - .get_results(conn) + .filter(bot_versions::id.eq(version_id)) + .first(conn) } -pub fn active_bot_version(bot_id: i32, conn: &PgConnection) -> QueryResult { +pub fn find_bot_versions(bot_id: i32, conn: &PgConnection) -> QueryResult> { bot_versions::table .filter(bot_versions::bot_id.eq(bot_id)) - .order(bot_versions::created_at.desc()) - .first(conn) + .get_results(conn) } -- cgit v1.2.3