#[cfg(any(
feature = "edition-lite",
feature = "edition-document",
feature = "edition-graph",
feature = "edition-vector"
))]
use crate::{Connection, Result};
#[cfg(any(
feature = "edition-lite",
feature = "edition-document",
feature = "edition-graph",
feature = "edition-vector"
))]
use std::path::Path;
#[cfg(feature = "edition-lite")]
pub struct LiteDatabase {
connection: Connection,
}
#[cfg(feature = "edition-lite")]
impl LiteDatabase {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
Ok(Self {
connection: Connection::open(path)?,
})
}
pub fn open_in_memory() -> Result<Self> {
Ok(Self {
connection: Connection::open_in_memory()?,
})
}
pub fn execute(&self, sql: &str) -> Result<usize> {
check_lite_sql(sql, &[])?;
self.connection.execute(sql)
}
pub fn query(&self, sql: &str) -> Result<Vec<crate::Row>> {
check_lite_sql(sql, &[])?;
self.connection.query(sql)
}
pub fn execute_with_params(&self, sql: &str, params: &[crate::Value]) -> Result<usize> {
check_lite_sql(sql, params)?;
self.connection.execute_with_params(sql, params)
}
pub fn query_with_params(&self, sql: &str, params: &[crate::Value]) -> Result<Vec<crate::Row>> {
check_lite_sql(sql, params)?;
self.connection.query_with_params(sql, params)
}
pub fn close(&self) -> Result<()> {
self.connection.close()
}
}
#[cfg(feature = "edition-lite")]
fn check_lite_sql(sql: &str, params: &[crate::Value]) -> Result<()> {
use crate::sql::lexer::{Token, tokenize};
use crate::sql::parser::{bind_parameters, parse_tokens};
let tokens = tokenize(sql)?;
let tokens = bind_parameters(&tokens, params)?;
let denied = tokens.iter().enumerate().any(|(index, token)| match token {
Token::Vector | Token::VectorLit(_) | Token::Graph | Token::Match => true,
Token::Ident(name) => {
let upper = name.to_ascii_uppercase();
let model_function = (upper.starts_with("TAP_")
|| matches!(upper.as_str(), "VECTOR_COSINE" | "VECTOR_L2"))
&& tokens.get(index + 1) == Some(&Token::OpenParen);
name.starts_with("__") || model_function
}
_ => false,
});
if denied {
return Err(crate::Error::SqlSyntax(
"This statement requires a non-Lite TapirusDB edition".into(),
));
}
let statement = parse_tokens(&tokens)?;
if matches!(
statement,
crate::Statement::VectorSearch { .. }
| crate::Statement::GraphInsertNode { .. }
| crate::Statement::GraphInsertEdge { .. }
| crate::Statement::GraphTraverse { .. }
| crate::Statement::GraphShortestPath { .. }
| crate::Statement::GraphMatch { .. }
| crate::Statement::GraphAlgorithm { .. }
) {
return Err(crate::Error::SqlSyntax(
"This statement requires a non-Lite TapirusDB edition".into(),
));
}
Ok(())
}
#[cfg(feature = "edition-document")]
pub struct DocumentDatabase {
connection: Connection,
}
#[cfg(feature = "edition-document")]
impl DocumentDatabase {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
Ok(Self {
connection: Connection::open(path)?,
})
}
pub fn open_in_memory() -> Result<Self> {
Ok(Self {
connection: Connection::open_in_memory()?,
})
}
pub fn collection(&self, name: &str) -> Result<crate::Collection<'_>> {
self.connection.collection(name)
}
pub fn close(&self) -> Result<()> {
self.connection.close()
}
}
#[cfg(feature = "edition-graph")]
pub struct GraphDatabase {
connection: Connection,
}
#[cfg(feature = "edition-graph")]
impl GraphDatabase {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
Ok(Self {
connection: Connection::open(path)?,
})
}
pub fn open_in_memory() -> Result<Self> {
Ok(Self {
connection: Connection::open_in_memory()?,
})
}
pub fn add_node(&self, id: u64, label: &str, properties: &str) -> Result<()> {
self.connection.graph_add_node(id, label, properties)
}
pub fn add_edge(
&self,
from_id: u64,
to_id: u64,
label: &str,
weight: f32,
properties: &str,
) -> Result<u64> {
self.connection
.graph_add_edge(from_id, to_id, label, weight, properties)
}
pub fn neighbors(
&self,
id: u64,
direction: crate::Direction,
label: Option<&str>,
) -> Vec<(crate::Node, crate::Edge)> {
self.connection.graph_neighbors(id, direction, label)
}
pub fn close(&self) -> Result<()> {
self.connection.close()
}
}
#[cfg(feature = "edition-vector")]
pub struct VectorDatabase {
connection: Connection,
}
#[cfg(feature = "edition-vector")]
impl VectorDatabase {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
Ok(Self {
connection: Connection::open(path)?,
})
}
pub fn open_in_memory() -> Result<Self> {
Ok(Self {
connection: Connection::open_in_memory()?,
})
}
pub fn collection(&self, name: &str, dimension: usize) -> Result<VectorCollection<'_>> {
if name.is_empty()
|| !name
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
|| dimension == 0
{
return Err(crate::Error::ConstraintViolation(
"Vector collection requires a simple name and positive dimension".into(),
));
}
let table = format!("__vec_{name}");
self.connection.execute(&format!(
"CREATE TABLE IF NOT EXISTS {table} (id INTEGER PRIMARY KEY, embedding VECTOR({dimension}), metadata TEXT)"
))?;
let definition = self
.connection
.table(&table)
.ok_or_else(|| crate::Error::TableNotFound(table.clone()))?;
if !definition.columns.iter().any(|column| {
column.name.eq_ignore_ascii_case("embedding")
&& column.data_type == crate::sql::catalog::DataType::Vector(dimension)
}) {
return Err(crate::Error::ConstraintViolation(format!(
"Collection {name} has a different vector dimension or schema"
)));
}
Ok(VectorCollection {
connection: &self.connection,
table,
dimension,
})
}
pub fn close(&self) -> Result<()> {
self.connection.close()
}
}
#[cfg(feature = "edition-vector")]
pub struct VectorCollection<'a> {
connection: &'a Connection,
table: String,
dimension: usize,
}
#[cfg(feature = "edition-vector")]
impl VectorCollection<'_> {
pub fn insert(&self, id: u64, embedding: &[f32], metadata: &serde_json::Value) -> Result<()> {
self.validate_embedding(embedding)?;
let id = i64::try_from(id).map_err(|_| {
crate::Error::ConstraintViolation("Vector ID exceeds signed 64-bit range".into())
})?;
self.connection.execute_with_params(
&format!(
"INSERT INTO {} (id, embedding, metadata) VALUES (?, ?, ?)",
self.table
),
&[
crate::Value::Integer(id),
crate::Value::Vector(embedding.to_vec()),
crate::Value::Text(metadata.to_string()),
],
)?;
Ok(())
}
pub fn search(&self, embedding: &[f32], limit: usize) -> Result<Vec<crate::Row>> {
self.validate_embedding(embedding)?;
if limit == 0 {
return Ok(Vec::new());
}
let vector = embedding
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ");
self.connection.query(&format!(
"SELECT id, metadata FROM {} VECTOR NEAR embedding = [{vector}] TOP {limit}",
self.table
))
}
fn validate_embedding(&self, embedding: &[f32]) -> Result<()> {
if embedding.len() != self.dimension {
return Err(crate::Error::DimensionMismatch(
self.dimension,
embedding.len(),
));
}
if !embedding.iter().all(|value| value.is_finite()) {
return Err(crate::Error::ConstraintViolation(
"Vector components must be finite".into(),
));
}
Ok(())
}
}