use serde::{Deserialize, Serialize};
use relate_catalog::ConstraintDef;
use relate_core::{NodeId, RelId, Result, Value};
use crate::graph_type::GraphTypeSpec;
mod index;
pub use index::*;
pub mod wal_format_json;
pub use wal_format_json::{props_from_json, props_json};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op")]
pub enum RedoOp {
CreateNode {
id: NodeId,
labels: std::sync::Arc<Vec<String>>,
properties: std::sync::Arc<relate_core::PropertyMap>,
},
CreateRel {
id: RelId,
start: NodeId,
end: NodeId,
rel_type: String,
properties: std::sync::Arc<relate_core::PropertyMap>,
},
DeleteNode {
id: NodeId,
},
DeleteRel {
id: RelId,
},
SetNodeProp {
id: NodeId,
key: String,
value: Value,
},
RemoveNodeProp {
id: NodeId,
key: String,
},
SetRelProp {
id: RelId,
key: String,
value: Value,
},
RemoveRelProp {
id: RelId,
key: String,
},
AddLabels {
id: NodeId,
labels: Vec<String>,
},
RemoveLabels {
id: NodeId,
labels: Vec<String>,
},
CreateIndex {
name: String,
label: String,
property: String,
},
DropIndex {
name: String,
},
CreateConstraint {
name: String,
#[serde(default)]
relationship: bool,
label: String,
properties: Vec<String>,
kind: String,
#[serde(default)]
property_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
enforced_label: Option<String>,
},
DropConstraint {
name: String,
},
CatalogIndexDetail {
name: String,
detail: IndexDetailSpec,
options: serde_json::Value,
},
CatalogDerivedConstraint {
constraint: relate_model::Constraint,
},
PutDatabase {
name: String,
language: u32,
composite: bool,
},
DropDatabase {
name: String,
},
PutGraphType {
name: String,
body: GraphTypeSpec,
},
SetCurrentGraphType {
body: GraphTypeSpec,
},
PullIdentityPut {
source: String,
kind: PullKind,
remote_id: String,
local_id: i64,
},
OntologySet {
database: String,
spec: String,
},
OntologyDrop {
database: String,
},
}
pub const MAX_ONTOLOGY_SPEC_BYTES: usize = 16 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OntologyOp<'a> {
Set(&'a str),
Drop,
}
impl RedoOp {
pub fn create_constraint(def: ConstraintDef) -> Self {
Self::CreateConstraint {
name: def.name,
relationship: def.relationship,
label: def.label,
properties: def.properties,
kind: def.kind,
property_type: def.property_type,
enforced_label: def.enforced_label,
}
}
pub fn constraint_def(&self) -> Option<ConstraintDef> {
match self {
Self::CreateConstraint {
name,
relationship,
label,
properties,
kind,
property_type,
enforced_label,
} => Some(ConstraintDef {
name: name.clone(),
relationship: *relationship,
label: label.clone(),
properties: properties.clone(),
kind: kind.clone(),
property_type: property_type.clone(),
enforced_label: enforced_label.clone(),
}),
_ => None,
}
}
pub fn create_node(
id: NodeId,
labels: impl Into<std::sync::Arc<Vec<String>>>,
properties: impl Into<relate_core::PropertyMap>,
) -> Self {
Self::CreateNode {
id,
labels: labels.into(),
properties: std::sync::Arc::new(properties.into()),
}
}
pub fn create_rel(
id: RelId,
start: NodeId,
end: NodeId,
rel_type: String,
properties: impl Into<relate_core::PropertyMap>,
) -> Self {
Self::CreateRel {
id,
start,
end,
rel_type,
properties: std::sync::Arc::new(properties.into()),
}
}
pub fn delete_node(id: NodeId) -> Self {
Self::DeleteNode { id }
}
pub fn delete_rel(id: RelId) -> Self {
Self::DeleteRel { id }
}
pub fn add_labels(id: NodeId, labels: Vec<String>) -> Self {
Self::AddLabels { id, labels }
}
pub fn remove_labels(id: NodeId, labels: Vec<String>) -> Self {
Self::RemoveLabels { id, labels }
}
pub fn set_node_prop(id: NodeId, key: String, value: Value) -> Self {
Self::SetNodeProp { id, key, value }
}
pub fn remove_node_prop(id: NodeId, key: String) -> Self {
Self::RemoveNodeProp { id, key }
}
pub fn set_rel_prop(id: RelId, key: String, value: Value) -> Self {
Self::SetRelProp { id, key, value }
}
pub fn remove_rel_prop(id: RelId, key: String) -> Self {
Self::RemoveRelProp { id, key }
}
pub fn ontology_op(&self) -> Option<OntologyOp<'_>> {
match self {
Self::OntologySet { spec, .. } => Some(OntologyOp::Set(spec)),
Self::OntologyDrop { .. } => Some(OntologyOp::Drop),
_ => None,
}
}
pub fn is_ontology_op(&self) -> bool {
self.ontology_op().is_some()
}
pub fn validate_ids(&self) -> Result<()> {
fn check(id: i64, what: &str) -> Result<()> {
relate_core::validate_persisted_id(id, what)
}
match self {
Self::CreateNode { id, .. }
| Self::DeleteNode { id }
| Self::SetNodeProp { id, .. }
| Self::RemoveNodeProp { id, .. }
| Self::AddLabels { id, .. }
| Self::RemoveLabels { id, .. } => check(*id, "WAL node"),
Self::CreateRel { id, start, end, .. } => {
check(*id, "WAL relationship")?;
check(*start, "WAL relationship start")?;
check(*end, "WAL relationship end")
}
Self::DeleteRel { id }
| Self::SetRelProp { id, .. }
| Self::RemoveRelProp { id, .. } => check(*id, "WAL relationship"),
Self::PullIdentityPut { local_id, .. } => check(*local_id, "WAL pull identity local"),
Self::OntologySet { spec, .. } => {
if spec.len() > MAX_ONTOLOGY_SPEC_BYTES {
return Err(relate_core::Error::storage(format!(
"ontology document of {} bytes exceeds the 16 MiB limit",
spec.len()
)));
}
Ok(())
}
Self::CreateIndex { .. }
| Self::DropIndex { .. }
| Self::CreateConstraint { .. }
| Self::DropConstraint { .. }
| Self::CatalogIndexDetail { .. }
| Self::CatalogDerivedConstraint { .. }
| Self::PutDatabase { .. }
| Self::DropDatabase { .. }
| Self::PutGraphType { .. }
| Self::SetCurrentGraphType { .. }
| Self::OntologyDrop { .. } => Ok(()),
}
}
pub fn is_catalog(&self) -> bool {
self.write_target().is_catalog()
}
pub fn write_target(&self) -> WriteTarget<'_> {
match self {
Self::CreateNode { id, .. } => WriteTarget::CreatedNode(*id),
Self::CreateRel { id, start, end, .. } => WriteTarget::CreatedRel {
id: *id,
start: *start,
end: *end,
},
Self::DeleteNode { id } => WriteTarget::DeletedNode(*id),
Self::DeleteRel { id } => WriteTarget::DeletedRel(*id),
Self::SetNodeProp { id, .. }
| Self::RemoveNodeProp { id, .. }
| Self::AddLabels { id, .. }
| Self::RemoveLabels { id, .. } => WriteTarget::MutatedNode(*id),
Self::SetRelProp { id, .. } | Self::RemoveRelProp { id, .. } => {
WriteTarget::MutatedRel(*id)
}
Self::CreateIndex {
name,
label,
property,
} => WriteTarget::CreateIndex {
name,
label,
property,
},
Self::DropIndex { name } => WriteTarget::DropIndex { name },
Self::CreateConstraint { name, .. } => WriteTarget::CreateConstraint { name },
Self::DropConstraint { name } => WriteTarget::DropConstraint { name },
Self::CatalogIndexDetail { .. }
| Self::CatalogDerivedConstraint { .. }
| Self::PutDatabase { .. }
| Self::DropDatabase { .. }
| Self::PutGraphType { .. }
| Self::SetCurrentGraphType { .. } => WriteTarget::CatalogMeta,
Self::PullIdentityPut { .. } => WriteTarget::PullIdentity,
Self::OntologySet { .. } | Self::OntologyDrop { .. } => WriteTarget::Ontology,
}
}
pub fn catalog_names(&self) -> Vec<CatalogName<'_>> {
fn push<'a>(
out: &mut Vec<CatalogName<'a>>,
names: impl IntoIterator<Item = &'a String>,
mention: fn(&'a str) -> CatalogName<'a>,
) {
out.extend(names.into_iter().map(|name| mention(name)));
}
match self {
Self::CreateNode {
labels, properties, ..
} => {
let mut names = Vec::with_capacity(labels.len() + properties.len());
push(&mut names, labels.iter(), CatalogName::Label);
push(&mut names, properties.keys(), CatalogName::PropertyKey);
names
}
Self::CreateRel {
rel_type,
properties,
..
} => {
let mut names = Vec::with_capacity(1 + properties.len());
names.push(CatalogName::RelType(rel_type));
push(&mut names, properties.keys(), CatalogName::PropertyKey);
names
}
Self::SetNodeProp { key, .. }
| Self::RemoveNodeProp { key, .. }
| Self::SetRelProp { key, .. }
| Self::RemoveRelProp { key, .. } => vec![CatalogName::PropertyKey(key)],
Self::AddLabels { labels, .. } | Self::RemoveLabels { labels, .. } => {
let mut names = Vec::with_capacity(labels.len());
push(&mut names, labels.iter(), CatalogName::Label);
names
}
Self::CreateIndex {
label, property, ..
} => vec![
CatalogName::Label(label),
CatalogName::PropertyKey(split_legacy_property_encoding(property).0),
],
Self::CreateConstraint {
relationship,
label,
properties,
..
} => {
let mut names = Vec::with_capacity(1 + properties.len());
names.push(if *relationship {
CatalogName::RelType(label)
} else {
CatalogName::Label(label)
});
push(&mut names, properties.iter(), CatalogName::PropertyKey);
names
}
Self::CatalogIndexDetail { detail, .. } => {
let mut names = Vec::with_capacity(
detail.labels.len() + detail.properties.len() + detail.with_properties.len(),
);
if detail.relationship {
push(&mut names, detail.labels.iter(), CatalogName::RelType);
} else {
push(&mut names, detail.labels.iter(), CatalogName::Label);
}
push(
&mut names,
detail.properties.iter(),
CatalogName::PropertyKey,
);
push(
&mut names,
detail.with_properties.iter(),
CatalogName::PropertyKey,
);
names
}
Self::CatalogDerivedConstraint { constraint } => {
let relationship =
relate_model::EntityKind::from_display_name(&constraint.entity_type)
== Some(relate_model::EntityKind::Relationship);
let mut names = Vec::with_capacity(2 + constraint.properties.len());
names.push(if relationship {
CatalogName::RelType(&constraint.label)
} else {
CatalogName::Label(&constraint.label)
});
if let Some(enforced) = &constraint.enforced_label {
names.push(CatalogName::Label(enforced));
}
push(
&mut names,
constraint.properties.iter(),
CatalogName::PropertyKey,
);
names
}
Self::DeleteNode { .. }
| Self::DeleteRel { .. }
| Self::DropIndex { .. }
| Self::DropConstraint { .. } => Vec::new(),
Self::PutDatabase { .. }
| Self::DropDatabase { .. }
| Self::PutGraphType { .. }
| Self::SetCurrentGraphType { .. }
| Self::PullIdentityPut { .. }
| Self::OntologySet { .. }
| Self::OntologyDrop { .. } => Vec::new(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WriteTarget<'a> {
CreatedNode(NodeId),
CreatedRel {
id: RelId,
start: NodeId,
end: NodeId,
},
DeletedNode(NodeId),
DeletedRel(RelId),
MutatedNode(NodeId),
MutatedRel(RelId),
CreateIndex {
name: &'a str,
label: &'a str,
property: &'a str,
},
DropIndex {
name: &'a str,
},
CreateConstraint {
name: &'a str,
},
DropConstraint {
name: &'a str,
},
CatalogMeta,
PullIdentity,
Ontology,
}
impl WriteTarget<'_> {
pub fn is_catalog(&self) -> bool {
match self {
WriteTarget::CreatedNode(_)
| WriteTarget::CreatedRel { .. }
| WriteTarget::DeletedNode(_)
| WriteTarget::DeletedRel(_)
| WriteTarget::MutatedNode(_)
| WriteTarget::MutatedRel(_)
| WriteTarget::PullIdentity
| WriteTarget::Ontology => false,
WriteTarget::CreateIndex { .. }
| WriteTarget::DropIndex { .. }
| WriteTarget::CreateConstraint { .. }
| WriteTarget::DropConstraint { .. }
| WriteTarget::CatalogMeta => true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CatalogName<'a> {
Label(&'a str),
RelType(&'a str),
PropertyKey(&'a str),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PullKind {
Node,
Rel,
}
#[cfg(test)]
mod tests;