use std::fmt::{self, Display, Formatter};
use common::fmt::{EscapeIdent, Fmt};
use surrealdb_strand::Strand;
use surrealdb_types::{SqlFormat, ToSql, write_sql};
use crate::expr::Kind;
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct KeyNames(Box<[Strand]>);
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum KeyNamesError {
#[error("a record id with named components needs at least one component")]
Empty,
#[error("the record id component `{0}` is named twice")]
Duplicate(String),
#[error("the record id component name `{0}` is reserved")]
Reserved(String),
#[error("{names} component names were given for a record id of {kinds} components")]
Arity {
names: usize,
kinds: usize,
},
}
const RESERVED: [&str; 3] = ["id", "in", "out"];
impl KeyNames {
pub fn new(names: Vec<Strand>, arity: usize) -> Result<Self, KeyNamesError> {
if names.is_empty() {
return Err(KeyNamesError::Empty);
}
for (i, name) in names.iter().enumerate() {
if RESERVED.contains(&name.as_str()) {
return Err(KeyNamesError::Reserved(name.as_str().to_owned()));
}
if names[..i].iter().any(|earlier| earlier == name) {
return Err(KeyNamesError::Duplicate(name.as_str().to_owned()));
}
}
if names.len() != arity {
return Err(KeyNamesError::Arity {
names: names.len(),
kinds: arity,
});
}
Ok(Self(names.into_boxed_slice()))
}
pub fn is_reserved(name: &str) -> bool {
RESERVED.contains(&name)
}
pub fn position(&self, name: &str) -> Option<u32> {
self.0.iter().position(|n| n.as_str() == name).map(|i| i as u32)
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = &str> {
self.0.iter().map(Strand::as_str)
}
pub fn as_slice(&self) -> &[Strand] {
&self.0
}
pub fn fmt_keyed<'a>(&'a self, kinds: &'a [Kind]) -> KeyedKinds<'a> {
KeyedKinds {
names: self,
kinds,
}
}
}
pub struct KeyedKinds<'a> {
names: &'a KeyNames,
kinds: &'a [Kind],
}
impl ToSql for KeyedKinds<'_> {
fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
f.push('[');
let fmt = fmt.increment();
write_sql!(
f,
fmt,
"{}",
Fmt::pretty_comma_separated(self.names.0.iter().zip(self.kinds.iter()).map(|pair| {
Fmt::new(pair, |(name, kind), f, fmt| {
write_sql!(f, fmt, "{}: {}", EscapeIdent(name.as_str()), kind)
})
}))
);
f.push(']');
}
}
impl Display for KeyedKinds<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_sql())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn names(list: &[&str]) -> Vec<Strand> {
list.iter().map(Strand::new).collect()
}
#[test]
fn new_accepts_distinct_names_matching_the_arity() {
let n = KeyNames::new(names(&["city", "time"]), 2).unwrap();
assert_eq!(n.len(), 2);
assert_eq!(n.position("city"), Some(0));
assert_eq!(n.position("time"), Some(1));
assert_eq!(n.position("value"), None);
assert_eq!(n.iter().collect::<Vec<_>>(), ["city", "time"]);
}
#[test]
fn new_refuses_each_invalid_list() {
assert_eq!(KeyNames::new(vec![], 0), Err(KeyNamesError::Empty));
assert_eq!(
KeyNames::new(names(&["a", "a"]), 2),
Err(KeyNamesError::Duplicate("a".to_owned()))
);
for reserved in ["id", "in", "out"] {
assert_eq!(
KeyNames::new(names(&["a", reserved]), 2),
Err(KeyNamesError::Reserved(reserved.to_owned()))
);
}
assert_eq!(
KeyNames::new(names(&["a", "b"]), 3),
Err(KeyNamesError::Arity {
names: 2,
kinds: 3
})
);
}
#[test]
fn fmt_keyed_escapes_keywords_and_spaces() {
let n = KeyNames::new(names(&["my city", "value", "plain"]), 3).unwrap();
let kinds = [Kind::String, Kind::Int, Kind::Datetime];
assert_eq!(
n.fmt_keyed(&kinds).to_string(),
"[`my city`: string, `value`: int, plain: datetime]"
);
}
}