use crate::DbError;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Identifier(String);
impl Identifier {
pub(crate) fn parse(value: &str) -> Result<Self, DbError> {
let mut chars = value.chars();
match chars.next() {
Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
_ => return Err(invalid_identifier(value)),
}
if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
return Err(invalid_identifier(value));
}
Ok(Self(value.to_string()))
}
#[cfg(any(feature = "mysql", feature = "postgres"))]
pub(crate) fn as_str(&self) -> &str {
&self.0
}
}
#[cfg(feature = "postgres")]
pub(crate) const POSTGRES_MAX_IDENTIFIER_BYTES: usize = 63;
#[cfg(feature = "postgres")]
impl Identifier {
pub(crate) fn parse_postgres(value: &str) -> Result<Self, DbError> {
if value.len() > POSTGRES_MAX_IDENTIFIER_BYTES {
return Err(invalid_identifier(value));
}
let mut chars = value.chars();
match chars.next() {
Some(c) if c.is_alphabetic() || c == '_' => {}
_ => return Err(invalid_identifier(value)),
}
if !chars.all(is_postgres_identifier_continuation) {
return Err(invalid_identifier(value));
}
Ok(Self(value.to_string()))
}
}
#[cfg(feature = "postgres")]
fn is_postgres_identifier_continuation(c: char) -> bool {
!c.is_control() && (c.is_alphanumeric() || matches!(c, '_' | '$' | '"'))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct QualifiedIdentifier(Vec<Identifier>);
impl QualifiedIdentifier {
pub(crate) fn parse(value: &str) -> Result<Self, DbError> {
Self::parse_with_max_parts(value, 3)
}
pub(crate) fn parse_with_max_parts(value: &str, max_parts: usize) -> Result<Self, DbError> {
let parts = value
.split('.')
.map(Identifier::parse)
.collect::<Result<Vec<_>, _>>()?;
if parts.is_empty() || parts.len() > max_parts {
return Err(invalid_identifier(value));
}
Ok(Self(parts))
}
#[cfg(any(feature = "mysql", feature = "postgres"))]
pub(crate) fn render(&self, quote: char) -> String {
self.0
.iter()
.map(|identifier| quote_part(identifier, quote))
.collect::<Vec<_>>()
.join(".")
}
}
#[cfg(feature = "postgres")]
impl QualifiedIdentifier {
pub(crate) fn parse_postgres(value: &str) -> Result<Self, DbError> {
Self::parse_postgres_with_max_parts(value, 3)
}
pub(crate) fn parse_postgres_with_max_parts(
value: &str,
max_parts: usize,
) -> Result<Self, DbError> {
let parts = value
.split('.')
.map(Identifier::parse_postgres)
.collect::<Result<Vec<_>, _>>()?;
if parts.is_empty() || parts.len() > max_parts {
return Err(invalid_identifier(value));
}
Ok(Self(parts))
}
pub(crate) fn render_postgres(&self) -> String {
self.0
.iter()
.map(|identifier| format!("\"{}\"", identifier.as_str().replace('"', "\"\"")))
.collect::<Vec<_>>()
.join(".")
}
}
#[cfg(any(feature = "mysql", feature = "postgres"))]
#[derive(Debug)]
pub(crate) struct RenderedCondition<T> {
pub(crate) sql: String,
pub(crate) params: Vec<T>,
}
#[cfg(any(feature = "mysql", feature = "postgres"))]
fn quote_part(identifier: &Identifier, quote: char) -> String {
format!("{quote}{}{quote}", identifier.as_str())
}
fn invalid_identifier(value: &str) -> DbError {
DbError::InvalidArgument(format!("非法 SQL 标识符: {value:?}"))
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn identifier_types_reject_adversarial_boundaries() {
for invalid in [
"",
".id",
"users.",
"a.b.c.d",
"users.id--",
"用户",
"a\0b",
"a b",
"a\"b",
"a`b",
] {
assert!(QualifiedIdentifier::parse(invalid).is_err(), "{invalid:?}");
}
assert!(Identifier::parse("users_1").is_ok());
assert!(QualifiedIdentifier::parse("users.id").is_ok());
assert!(QualifiedIdentifier::parse("public.users.id").is_ok());
assert!(QualifiedIdentifier::parse_with_max_parts("public.users", 2).is_ok());
assert!(QualifiedIdentifier::parse_with_max_parts("a.b.c", 2).is_err());
}
#[cfg(any(feature = "mysql", feature = "postgres"))]
#[test]
fn qualified_identifier_renders_both_dialects() {
let identifier = match QualifiedIdentifier::parse("users.id") {
Ok(identifier) => identifier,
Err(error) => panic!("合法限定标识符不应失败: {error}"),
};
assert_eq!(identifier.render('`'), "`users`.`id`");
assert_eq!(identifier.render('"'), "\"users\".\"id\"");
}
#[cfg(feature = "postgres")]
#[test]
fn postgres_identifiers_accept_unicode_dollar_and_embedded_quotes() {
assert!(Identifier::parse_postgres("用户").is_ok());
assert!(Identifier::parse_postgres("名前_1").is_ok());
assert!(Identifier::parse_postgres("a$b").is_ok());
assert!(Identifier::parse_postgres("col$").is_ok());
assert!(Identifier::parse_postgres("a\"b").is_ok());
assert!(Identifier::parse_postgres("_x$1").is_ok());
for invalid in ["$leading", "1abc", "\"lead", " a"] {
assert!(
Identifier::parse_postgres(invalid).is_err(),
"{invalid:?} 应被拒绝"
);
}
for invalid in ["a\0b", "a\nb", "a\tb", "\u{7f}"] {
assert!(
Identifier::parse_postgres(invalid).is_err(),
"{invalid:?} 应被拒绝"
);
}
for invalid in ["a;b", "a b", "a`b", "a'b", "a-b"] {
assert!(
Identifier::parse_postgres(invalid).is_err(),
"{invalid:?} 应被拒绝"
);
}
}
#[cfg(feature = "postgres")]
#[test]
fn postgres_identifier_63_byte_limit_is_rejected_not_truncated() {
assert!(Identifier::parse_postgres(&"a".repeat(63)).is_ok());
assert!(Identifier::parse_postgres(&"a".repeat(64)).is_err());
assert!(Identifier::parse_postgres(&"用".repeat(21)).is_ok());
assert!(Identifier::parse_postgres(&"用".repeat(22)).is_err());
}
#[cfg(feature = "postgres")]
#[test]
#[allow(clippy::expect_used)]
fn postgres_identifiers_render_with_doubled_quotes() {
let unicode =
QualifiedIdentifier::parse_postgres("模式.用户").expect("Unicode 限定标识符应合法");
assert_eq!(unicode.render_postgres(), "\"模式\".\"用户\"");
let quoted = QualifiedIdentifier::parse_postgres("a\"b").expect("内嵌双引号应合法");
assert_eq!(quoted.render_postgres(), "\"a\"\"b\"");
let qualified_quoted =
QualifiedIdentifier::parse_postgres("t.a\"b").expect("限定名每段都允许内嵌双引号");
assert_eq!(qualified_quoted.render_postgres(), "\"t\".\"a\"\"b\"");
assert!(QualifiedIdentifier::parse_postgres("a.b.c.d").is_err());
assert!(QualifiedIdentifier::parse_postgres_with_max_parts("a.b", 1).is_err());
assert!(QualifiedIdentifier::parse_postgres_with_max_parts("a.b", 2).is_ok());
}
proptest! {
#[test]
fn accepted_identifiers_always_match_the_strict_grammar(value in any::<String>()) {
if QualifiedIdentifier::parse(&value).is_ok() {
let parts: Vec<_> = value.split('.').collect();
prop_assert!(parts.len() <= 3);
for part in parts {
let mut chars = part.chars();
prop_assert!(matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_'));
prop_assert!(chars.all(|c| c.is_ascii_alphanumeric() || c == '_'));
}
}
}
}
}