mcp_postgres/
validation.rs1use crate::errors::MCPError;
2
3const MAX_IDENTIFIER_LEN: usize = 255;
4
5pub fn validate_identifier(name: &str, label: &str) -> Result<(), MCPError> {
6 if name.is_empty() {
7 return Err(MCPError::InvalidParams(format!("'{label}' must not be empty")));
8 }
9 if name.len() > MAX_IDENTIFIER_LEN {
10 return Err(MCPError::InvalidParams(
11 format!("'{label}' exceeds maximum length of {MAX_IDENTIFIER_LEN} characters (got {})", name.len())
12 ));
13 }
14 for ch in name.chars() {
15 if !ch.is_alphanumeric() && ch != '_' {
16 return Err(MCPError::InvalidParams(
17 format!("'{label}' contains invalid character '{ch}' — only alphanumeric and underscore allowed")
18 ));
19 }
20 }
21 if name.starts_with(|c: char| c.is_ascii_digit()) {
22 return Err(MCPError::InvalidParams(
23 format!("'{label}' must not start with a digit")
24 ));
25 }
26 Ok(())
27}
28
29pub fn quote_identifier(name: &str) -> String {
30 format!("\"{}\"", name)
31}
32
33#[cfg(test)]
34mod tests {
35 use super::*;
36
37 #[test]
38 fn test_valid_identifier() {
39 assert!(validate_identifier("users", "table").is_ok());
40 assert!(validate_identifier("user_orders_2024", "table").is_ok());
41 }
42
43 #[test]
44 fn test_empty_identifier() {
45 let err = validate_identifier("", "table").unwrap_err();
46 assert!(err.to_string().contains("must not be empty"));
47 }
48
49 #[test]
50 fn test_too_long_identifier() {
51 let long = "a".repeat(256);
52 let err = validate_identifier(&long, "table").unwrap_err();
53 assert!(err.to_string().contains("exceeds maximum length"));
54 }
55
56 #[test]
57 fn test_invalid_char_identifier() {
58 let err = validate_identifier("users; DROP TABLE", "table").unwrap_err();
59 assert!(err.to_string().contains("invalid character"));
60 }
61
62 #[test]
63 fn test_digit_start_identifier() {
64 let err = validate_identifier("1users", "table").unwrap_err();
65 assert!(err.to_string().contains("must not start with a digit"));
66 }
67
68 #[test]
69 fn test_quote_identifier() {
70 assert_eq!(quote_identifier("users"), "\"users\"");
71 assert_eq!(quote_identifier("order_items"), "\"order_items\"");
72 }
73}