Lines
91.67 %
Functions
51.4 %
Branches
100 %
use crate::command::{admin_connection, connection};
use sqlx::Row;
use sqlx::types::Uuid;
use std::fmt::Debug;
use supp_macro::command;
use super::{CmdError, CmdResult};
use crate::{
config::{ConfigError, ConfigOption, config_on, list_config_on, set_config_on},
timezone,
user::User,
};
/// The config key as stored: trimmed, never blank.
fn config_key(name: &str) -> Result<&str, CmdError> {
match name.trim() {
"" => Err(CmdError::Args(
"The config name must not be blank".to_string(),
)),
key => Ok(key),
}
/// A timezone value must name a zone and is stored trimmed; every other key is stored as given.
fn stored_value(key: &str, value: String) -> Result<String, CmdError> {
if !timezone::is_key(key) {
return Ok(value);
let name = value.trim();
timezone::parse_zone(name).map_err(CmdError::Refused)?;
Ok(name.to_string())
command! {
GetConfig {
#[required]
user_id: Uuid,
name: String,
} => {
let user = User { id: user_id };
// An absent key is "not set" (Ok(None) → the native emits
// `(:config-value nil)`), not a hard error. This keeps absent
// (nil) distinct from a key holding the empty string ("") while
// letting genuine DB errors still propagate.
let mut conn = connection(&user).await?;
match config_on(&mut conn, config_key(&name)?).await {
Ok(opt) => Ok(opt.map(|v| match v {
ConfigOption::String(s) => CmdResult::String(s),
ConfigOption::Blob(b) => CmdResult::Data(b),
})),
Err(ConfigError::NoConfig(_)) => Ok(None),
Err(e) => Err(e.into()),
ListConfig {
let mut conn = connection(&User { id: user_id }).await?;
let entries = list_config_on(&mut conn).await?;
Ok(Some(CmdResult::ConfigEntries(entries)))
GetTimezone {
match timezone::zone_on(&mut conn).await {
Ok(zone) => Ok(Some(CmdResult::Timezone(zone))),
Err(ConfigError::InvalidTimezone(message)) => Err(CmdError::Refused(message)),
Err(err) => Err(err.into()),
GetVersion {
const HASH: &str = env!("GIT_HASH");
Ok(Some(CmdResult::String(HASH.to_string())))
GetBuildDate {
const BUILD: &str = env!("BUILD_DATE");
Ok(Some(CmdResult::String(BUILD.to_string())))
SetConfig {
value: String,
let key = config_key(&name)?;
let value = stored_value(key, value)?;
set_config_on(&mut conn, key, ConfigOption::String(value)).await?;
Ok(None)
SelectColumn {
field: String,
table: String,
let mut conn = admin_connection().await?;
// `field`/`table` are SQL identifiers (not bindable as `$n`), so they
// are interpolated. `AssertSqlSafe` is sound ONLY because select-column
// is a trusted-operator escape hatch: it is reachable from the CLI
// `sql selcol` / direct dispatch, never registered as an RPC/script
// native (see rpc::natives::config). Do not expose it to untrusted
// callers without validating/quoting the identifiers first.
let values: Vec<String> = sqlx::query(sqlx::AssertSqlSafe(format!(
"SELECT {field}::text FROM {table}"
)))
.fetch_all(&mut *conn)
.await?
.into_iter()
.map(|row| row.get::<Option<String>, _>(0).unwrap_or_default())
.collect();
Ok(Some(CmdResult::Lines(values)))
#[cfg(test)]
mod command_config_tests {
use super::*;
use crate::{db::install_test_pool, user::User};
use sqlx::{PgPool, types::Uuid};
use supp_macro::local_db_sqlx_test;
use tokio::sync::OnceCell;
/// Context for keeping environment intact
static CONTEXT: OnceCell<()> = OnceCell::const_new();
static USER: OnceCell<User> = OnceCell::const_new();
async fn setup() {
CONTEXT
.get_or_init(|| async {
crate::telemetry::init_test_logging();
})
.await;
USER.get_or_init(|| async { User { id: Uuid::new_v4() } })
#[local_db_sqlx_test]
async fn set_then_get_config_round_trips_per_user(pool: PgPool) -> anyhow::Result<()> {
let user_id = Uuid::new_v4();
SetConfig::new()
.user_id(user_id)
.name("testfield".to_string())
.value("testval".to_string())
.run()
.await?;
let val = GetConfig::new()
.unwrap();
assert_eq!(val.to_string(), "testval");
async fn set_config_refuses_a_blank_name(pool: PgPool) -> anyhow::Result<()> {
let result = SetConfig::new()
.user_id(Uuid::new_v4())
.name(" \t".to_string())
.value("v".to_string())
assert!(matches!(result, Err(CmdError::Args(_))), "{result:?}");
async fn list_config_returns_the_users_pairs_ordered_by_name(
pool: PgPool,
) -> anyhow::Result<()> {
for (name, value) in [("beta", "2"), ("Alpha", "1"), ("beta", "3")] {
.name(name.to_string())
.value(value.to_string())
let Some(CmdResult::ConfigEntries(listed)) =
ListConfig::new().user_id(user_id).run().await?
else {
anyhow::bail!("no config entries");
assert_eq!(
listed,
vec![
("Alpha".to_string(), "1".to_string()),
("beta".to_string(), "3".to_string()),
]
);