Add channels field to guild object.

This commit is contained in:
Paul Makles
2020-08-12 11:45:05 +02:00
parent a8eb403280
commit 74b4238f04
9 changed files with 106 additions and 58 deletions

View File

@@ -77,7 +77,7 @@ pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
}
}
pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String> {
pub fn fetch_channels(ids: &Vec<String>) -> Result<Vec<Channel>, String> {
let mut missing = vec![];
let mut channels = vec![];
@@ -98,7 +98,7 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String>
}
if missing.len() == 0 {
return Ok(Some(channels));
return Ok(channels);
}
let col = get_collection("channels");
@@ -117,7 +117,7 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String>
}
}
Ok(Some(channels))
Ok(channels)
} else {
Err("Failed to fetch channel from database.".to_string())
}

View File

@@ -42,7 +42,7 @@ pub struct Guild {
pub description: String,
pub owner: String,
// ? FIXME: ADD: pub channels: Vec<Channel>,
pub channels: Vec<String>,
pub invites: Vec<Invite>,
pub bans: Vec<Ban>,

View File

@@ -2,6 +2,7 @@ use super::super::get_collection;
use serde::{Serialize, Deserialize};
use mongodb::bson::{Bson, from_bson, doc};
use mongodb::options::FindOptions;
use log::info;
#[derive(Serialize, Deserialize)]
@@ -10,7 +11,7 @@ struct MigrationInfo {
revision: i32
}
pub const LATEST_REVISION: i32 = 1;
pub const LATEST_REVISION: i32 = 2;
pub fn migrate_database() {
let migrations = get_collection("migrations");
@@ -48,6 +49,60 @@ pub fn run_migrations(revision: i32) -> i32 {
info!("Running migration [revision 0]: Test migration system.");
}
if revision <= 1 {
info!("Running migration [revision 1]: Add channels to guild object.");
let col = get_collection("guilds");
let guilds = col.find(
None,
FindOptions::builder()
.projection(doc! { "_id": 1 })
.build()
)
.expect("Failed to fetch guilds.");
let result = get_collection("channels").find(
doc! {
"type": 2
},
FindOptions::builder()
.projection(doc! { "_id": 1, "guild": 1 })
.build()
).expect("Failed to fetch channels.");
let mut channels = vec![];
for doc in result {
let channel = doc.expect("Failed to fetch channel.");
let id = channel.get_str("_id").expect("Failed to get channel id.").to_string();
let gid = channel.get_str("guild").expect("Failed to get guild id.").to_string();
channels.push(( id, gid ));
}
for doc in guilds {
let guild = doc.expect("Failed to fetch guild.");
let id = guild.get_str("_id").expect("Failed to get guild id.");
let list: Vec<String> = channels
.iter()
.filter(|x| x.1 == id)
.map(|x| x.0.clone())
.collect();
col.update_one(
doc! {
"_id": id
},
doc! {
"$set": {
"channels": list
}
},
None
).expect("Failed to update guild.");
}
}
// Reminder to update LATEST_REVISION when adding new migrations.
LATEST_REVISION
}

View File

@@ -1,4 +1,3 @@
use mongodb::bson::doc;
use mongodb::sync::{Client, Collection, Database};
use std::env;