use crate::db::space::Space;
use crate::error::{Error, Result};
use crate::format::CollectionId;
#[derive(Clone, Debug)]
pub(crate) enum Field {
Text(Space),
Vector(Space),
}
#[derive(Clone, Debug, Default)]
pub(crate) struct Shape {
pub(crate) fields: Vec<(String, Field)>,
}
impl Shape {
pub(crate) fn text_field(&self) -> Option<(&str, &Space)> {
self.fields.iter().find_map(|(name, f)| match f {
Field::Text(s) => Some((name.as_str(), s)),
Field::Vector(_) => None,
})
}
pub(crate) fn vector_fields(&self) -> impl Iterator<Item = (&str, &Space)> {
self.fields.iter().filter_map(|(name, f)| match f {
Field::Vector(s) => Some((name.as_str(), s)),
Field::Text(_) => None,
})
}
pub(crate) fn field(&self, name: &str) -> Option<&Field> {
self.fields.iter().find(|(n, _)| n == name).map(|(_, f)| f)
}
pub(crate) fn validate(&self) -> Result<()> {
let mut text_fields = 0usize;
let mut seen_names: Vec<&str> = Vec::with_capacity(self.fields.len());
let mut seen_vec_spaces: Vec<&str> = Vec::new();
for (name, field) in &self.fields {
if seen_names.contains(&name.as_str()) {
return Err(Error::Format(format!(
"schema: duplicate field name '{name}'"
)));
}
seen_names.push(name);
match field {
Field::Text(space) => {
if !space.is_text() {
return Err(Error::Format(format!(
"schema: field '{name}' is declared text but bound to vector space '{}'",
space.name()
)));
}
text_fields += 1;
}
Field::Vector(space) => {
if !space.is_vector() {
return Err(Error::Format(format!(
"schema: field '{name}' is declared vector but bound to text space '{}'",
space.name()
)));
}
if seen_vec_spaces.contains(&space.name()) {
return Err(Error::Format(format!(
"schema: vector fields must use distinct spaces; '{}' is reused",
space.name()
)));
}
seen_vec_spaces.push(space.name());
}
}
}
if text_fields > 1 {
return Err(Error::Unsupported(
"schema: at most one text field per collection in v1 (use the doc→chunk pattern for multiple text fields)".into(),
));
}
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct Collection {
pub(crate) id: CollectionId,
pub(crate) name: String,
}
impl Collection {
#[must_use]
pub fn id(&self) -> CollectionId {
self.id
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
}
#[derive(Clone, Debug)]
pub struct CollectionInfo {
pub name: String,
pub id: CollectionId,
}