mysqladm/server/
common.rs

1use crate::core::common::UnixUser;
2use sqlx::prelude::*;
3
4/// This function creates a regex that matches items (users, databases)
5/// that belong to the user or any of the user's groups.
6pub fn create_user_group_matching_regex(user: &UnixUser) -> String {
7    if user.groups.is_empty() {
8        format!("{}_.+", user.username)
9    } else {
10        format!("({}|{})_.+", user.username, user.groups.join("|"))
11    }
12}
13
14/// Some mysql versions with some collations mark some columns as binary fields,
15/// which in the current version of sqlx is not parsable as string.
16/// See: https://github.com/launchbadge/sqlx/issues/3387
17#[inline]
18pub fn try_get_with_binary_fallback(
19    row: &sqlx::mysql::MySqlRow,
20    column: &str,
21) -> Result<String, sqlx::Error> {
22    row.try_get(column).or_else(|_| {
23        row.try_get::<Vec<u8>, _>(column)
24            .map(|v| String::from_utf8_lossy(&v).to_string())
25    })
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31    use regex::Regex;
32
33    #[test]
34    fn test_create_user_group_matching_regex() {
35        let user = UnixUser {
36            username: "user".to_owned(),
37            groups: vec!["group1".to_owned(), "group2".to_owned()],
38        };
39
40        let regex = create_user_group_matching_regex(&user);
41        let re = Regex::new(&regex).unwrap();
42
43        assert!(re.is_match("user_something"));
44        assert!(re.is_match("group1_something"));
45        assert!(re.is_match("group2_something"));
46
47        assert!(!re.is_match("other_something"));
48        assert!(!re.is_match("user"));
49        assert!(!re.is_match("usersomething"));
50    }
51}