1use serde::{Deserialize, Serialize};
10
11use relate_catalog::ConstraintDef;
12use relate_core::{NodeId, RelId, Result, Value};
13
14use crate::graph_type::GraphTypeSpec;
15
16mod index;
21pub use index::*;
22pub mod wal_format_json;
23pub use wal_format_json::{props_from_json, props_json};
24
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26#[serde(tag = "op")]
27pub enum RedoOp {
28 CreateNode {
29 id: NodeId,
30 labels: std::sync::Arc<Vec<String>>,
31 properties: std::sync::Arc<relate_core::PropertyMap>,
32 },
33 CreateRel {
34 id: RelId,
35 start: NodeId,
36 end: NodeId,
37 rel_type: String,
38 properties: std::sync::Arc<relate_core::PropertyMap>,
39 },
40 DeleteNode {
41 id: NodeId,
42 },
43 DeleteRel {
44 id: RelId,
45 },
46 SetNodeProp {
47 id: NodeId,
48 key: String,
49 value: Value,
50 },
51 RemoveNodeProp {
52 id: NodeId,
53 key: String,
54 },
55 SetRelProp {
56 id: RelId,
57 key: String,
58 value: Value,
59 },
60 RemoveRelProp {
61 id: RelId,
62 key: String,
63 },
64 AddLabels {
65 id: NodeId,
66 labels: Vec<String>,
67 },
68 RemoveLabels {
69 id: NodeId,
70 labels: Vec<String>,
71 },
72 CreateIndex {
73 name: String,
74 label: String,
75 property: String,
76 },
77 DropIndex {
78 name: String,
79 },
80 CreateConstraint {
81 name: String,
82 #[serde(default)]
83 relationship: bool,
84 label: String,
85 properties: Vec<String>,
86 kind: String,
87 #[serde(default)]
88 property_type: Option<String>,
89 #[serde(default, skip_serializing_if = "Option::is_none")]
94 enforced_label: Option<String>,
95 },
96 DropConstraint {
97 name: String,
98 },
99 CatalogIndexDetail {
100 name: String,
101 detail: IndexDetailSpec,
102 options: serde_json::Value,
105 },
106 CatalogDerivedConstraint {
108 constraint: relate_model::Constraint,
109 },
110 PutDatabase {
111 name: String,
112 language: u32,
113 composite: bool,
114 },
115 DropDatabase {
123 name: String,
124 },
125 PutGraphType {
126 name: String,
127 body: GraphTypeSpec,
128 },
129 SetCurrentGraphType {
130 body: GraphTypeSpec,
131 },
132 PullIdentityPut {
134 source: String,
135 kind: PullKind,
136 remote_id: String,
137 local_id: i64,
138 },
139 OntologySet {
146 database: String,
147 spec: String,
148 },
149 OntologyDrop {
150 database: String,
151 },
152}
153
154pub const MAX_ONTOLOGY_SPEC_BYTES: usize = 16 * 1024 * 1024;
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub enum OntologyOp<'a> {
164 Set(&'a str),
166 Drop,
168}
169
170impl RedoOp {
171 pub fn create_constraint(def: ConstraintDef) -> Self {
175 Self::CreateConstraint {
176 name: def.name,
177 relationship: def.relationship,
178 label: def.label,
179 properties: def.properties,
180 kind: def.kind,
181 property_type: def.property_type,
182 enforced_label: def.enforced_label,
183 }
184 }
185
186 pub fn constraint_def(&self) -> Option<ConstraintDef> {
189 match self {
190 Self::CreateConstraint {
191 name,
192 relationship,
193 label,
194 properties,
195 kind,
196 property_type,
197 enforced_label,
198 } => Some(ConstraintDef {
199 name: name.clone(),
200 relationship: *relationship,
201 label: label.clone(),
202 properties: properties.clone(),
203 kind: kind.clone(),
204 property_type: property_type.clone(),
205 enforced_label: enforced_label.clone(),
206 }),
207 _ => None,
208 }
209 }
210
211 pub fn create_node(
212 id: NodeId,
213 labels: impl Into<std::sync::Arc<Vec<String>>>,
214 properties: impl Into<relate_core::PropertyMap>,
215 ) -> Self {
216 Self::CreateNode {
217 id,
218 labels: labels.into(),
219 properties: std::sync::Arc::new(properties.into()),
220 }
221 }
222
223 pub fn create_rel(
224 id: RelId,
225 start: NodeId,
226 end: NodeId,
227 rel_type: String,
228 properties: impl Into<relate_core::PropertyMap>,
229 ) -> Self {
230 Self::CreateRel {
231 id,
232 start,
233 end,
234 rel_type,
235 properties: std::sync::Arc::new(properties.into()),
236 }
237 }
238
239 pub fn delete_node(id: NodeId) -> Self {
240 Self::DeleteNode { id }
241 }
242
243 pub fn delete_rel(id: RelId) -> Self {
244 Self::DeleteRel { id }
245 }
246
247 pub fn add_labels(id: NodeId, labels: Vec<String>) -> Self {
248 Self::AddLabels { id, labels }
249 }
250
251 pub fn remove_labels(id: NodeId, labels: Vec<String>) -> Self {
252 Self::RemoveLabels { id, labels }
253 }
254
255 pub fn set_node_prop(id: NodeId, key: String, value: Value) -> Self {
256 Self::SetNodeProp { id, key, value }
257 }
258
259 pub fn remove_node_prop(id: NodeId, key: String) -> Self {
260 Self::RemoveNodeProp { id, key }
261 }
262
263 pub fn set_rel_prop(id: RelId, key: String, value: Value) -> Self {
264 Self::SetRelProp { id, key, value }
265 }
266
267 pub fn remove_rel_prop(id: RelId, key: String) -> Self {
268 Self::RemoveRelProp { id, key }
269 }
270
271 pub fn ontology_op(&self) -> Option<OntologyOp<'_>> {
277 match self {
278 Self::OntologySet { spec, .. } => Some(OntologyOp::Set(spec)),
279 Self::OntologyDrop { .. } => Some(OntologyOp::Drop),
280 _ => None,
281 }
282 }
283
284 pub fn is_ontology_op(&self) -> bool {
289 self.ontology_op().is_some()
290 }
291
292 pub fn validate_ids(&self) -> Result<()> {
298 fn check(id: i64, what: &str) -> Result<()> {
299 relate_core::validate_persisted_id(id, what)
300 }
301 match self {
302 Self::CreateNode { id, .. }
303 | Self::DeleteNode { id }
304 | Self::SetNodeProp { id, .. }
305 | Self::RemoveNodeProp { id, .. }
306 | Self::AddLabels { id, .. }
307 | Self::RemoveLabels { id, .. } => check(*id, "WAL node"),
308 Self::CreateRel { id, start, end, .. } => {
309 check(*id, "WAL relationship")?;
310 check(*start, "WAL relationship start")?;
311 check(*end, "WAL relationship end")
312 }
313 Self::DeleteRel { id }
314 | Self::SetRelProp { id, .. }
315 | Self::RemoveRelProp { id, .. } => check(*id, "WAL relationship"),
316 Self::PullIdentityPut { local_id, .. } => check(*local_id, "WAL pull identity local"),
317 Self::OntologySet { spec, .. } => {
321 if spec.len() > MAX_ONTOLOGY_SPEC_BYTES {
322 return Err(relate_core::Error::storage(format!(
323 "ontology document of {} bytes exceeds the 16 MiB limit",
324 spec.len()
325 )));
326 }
327 Ok(())
328 }
329 Self::CreateIndex { .. }
330 | Self::DropIndex { .. }
331 | Self::CreateConstraint { .. }
332 | Self::DropConstraint { .. }
333 | Self::CatalogIndexDetail { .. }
334 | Self::CatalogDerivedConstraint { .. }
335 | Self::PutDatabase { .. }
336 | Self::DropDatabase { .. }
337 | Self::PutGraphType { .. }
338 | Self::SetCurrentGraphType { .. }
339 | Self::OntologyDrop { .. } => Ok(()),
340 }
341 }
342
343 pub fn is_catalog(&self) -> bool {
349 self.write_target().is_catalog()
350 }
351
352 pub fn write_target(&self) -> WriteTarget<'_> {
358 match self {
359 Self::CreateNode { id, .. } => WriteTarget::CreatedNode(*id),
360 Self::CreateRel { id, start, end, .. } => WriteTarget::CreatedRel {
361 id: *id,
362 start: *start,
363 end: *end,
364 },
365 Self::DeleteNode { id } => WriteTarget::DeletedNode(*id),
366 Self::DeleteRel { id } => WriteTarget::DeletedRel(*id),
367 Self::SetNodeProp { id, .. }
368 | Self::RemoveNodeProp { id, .. }
369 | Self::AddLabels { id, .. }
370 | Self::RemoveLabels { id, .. } => WriteTarget::MutatedNode(*id),
371 Self::SetRelProp { id, .. } | Self::RemoveRelProp { id, .. } => {
372 WriteTarget::MutatedRel(*id)
373 }
374 Self::CreateIndex {
375 name,
376 label,
377 property,
378 } => WriteTarget::CreateIndex {
379 name,
380 label,
381 property,
382 },
383 Self::DropIndex { name } => WriteTarget::DropIndex { name },
384 Self::CreateConstraint { name, .. } => WriteTarget::CreateConstraint { name },
385 Self::DropConstraint { name } => WriteTarget::DropConstraint { name },
386 Self::CatalogIndexDetail { .. }
387 | Self::CatalogDerivedConstraint { .. }
388 | Self::PutDatabase { .. }
389 | Self::DropDatabase { .. }
390 | Self::PutGraphType { .. }
391 | Self::SetCurrentGraphType { .. } => WriteTarget::CatalogMeta,
392 Self::PullIdentityPut { .. } => WriteTarget::PullIdentity,
393 Self::OntologySet { .. } | Self::OntologyDrop { .. } => WriteTarget::Ontology,
394 }
395 }
396
397 pub fn catalog_names(&self) -> Vec<CatalogName<'_>> {
421 fn push<'a>(
423 out: &mut Vec<CatalogName<'a>>,
424 names: impl IntoIterator<Item = &'a String>,
425 mention: fn(&'a str) -> CatalogName<'a>,
426 ) {
427 out.extend(names.into_iter().map(|name| mention(name)));
428 }
429
430 match self {
431 Self::CreateNode {
432 labels, properties, ..
433 } => {
434 let mut names = Vec::with_capacity(labels.len() + properties.len());
435 push(&mut names, labels.iter(), CatalogName::Label);
436 push(&mut names, properties.keys(), CatalogName::PropertyKey);
437 names
438 }
439 Self::CreateRel {
440 rel_type,
441 properties,
442 ..
443 } => {
444 let mut names = Vec::with_capacity(1 + properties.len());
445 names.push(CatalogName::RelType(rel_type));
446 push(&mut names, properties.keys(), CatalogName::PropertyKey);
447 names
448 }
449 Self::SetNodeProp { key, .. }
450 | Self::RemoveNodeProp { key, .. }
451 | Self::SetRelProp { key, .. }
452 | Self::RemoveRelProp { key, .. } => vec![CatalogName::PropertyKey(key)],
453 Self::AddLabels { labels, .. } | Self::RemoveLabels { labels, .. } => {
454 let mut names = Vec::with_capacity(labels.len());
455 push(&mut names, labels.iter(), CatalogName::Label);
456 names
457 }
458 Self::CreateIndex {
459 label, property, ..
460 } => vec![
461 CatalogName::Label(label),
462 CatalogName::PropertyKey(split_legacy_property_encoding(property).0),
463 ],
464 Self::CreateConstraint {
465 relationship,
466 label,
467 properties,
468 ..
469 } => {
470 let mut names = Vec::with_capacity(1 + properties.len());
471 names.push(if *relationship {
472 CatalogName::RelType(label)
473 } else {
474 CatalogName::Label(label)
475 });
476 push(&mut names, properties.iter(), CatalogName::PropertyKey);
477 names
478 }
479 Self::CatalogIndexDetail { detail, .. } => {
480 let mut names = Vec::with_capacity(
481 detail.labels.len() + detail.properties.len() + detail.with_properties.len(),
482 );
483 if detail.relationship {
484 push(&mut names, detail.labels.iter(), CatalogName::RelType);
485 } else {
486 push(&mut names, detail.labels.iter(), CatalogName::Label);
487 }
488 push(
489 &mut names,
490 detail.properties.iter(),
491 CatalogName::PropertyKey,
492 );
493 push(
494 &mut names,
495 detail.with_properties.iter(),
496 CatalogName::PropertyKey,
497 );
498 names
499 }
500 Self::CatalogDerivedConstraint { constraint } => {
501 let relationship =
506 relate_model::EntityKind::from_display_name(&constraint.entity_type)
507 == Some(relate_model::EntityKind::Relationship);
508 let mut names = Vec::with_capacity(2 + constraint.properties.len());
509 names.push(if relationship {
510 CatalogName::RelType(&constraint.label)
511 } else {
512 CatalogName::Label(&constraint.label)
513 });
514 if let Some(enforced) = &constraint.enforced_label {
518 names.push(CatalogName::Label(enforced));
519 }
520 push(
521 &mut names,
522 constraint.properties.iter(),
523 CatalogName::PropertyKey,
524 );
525 names
526 }
527 Self::DeleteNode { .. }
530 | Self::DeleteRel { .. }
531 | Self::DropIndex { .. }
532 | Self::DropConstraint { .. } => Vec::new(),
533 Self::PutDatabase { .. }
536 | Self::DropDatabase { .. }
537 | Self::PutGraphType { .. }
538 | Self::SetCurrentGraphType { .. }
539 | Self::PullIdentityPut { .. }
540 | Self::OntologySet { .. }
541 | Self::OntologyDrop { .. } => Vec::new(),
542 }
543 }
544}
545
546#[derive(Debug, Clone, Copy, PartialEq, Eq)]
552pub enum WriteTarget<'a> {
553 CreatedNode(NodeId),
554 CreatedRel {
555 id: RelId,
556 start: NodeId,
557 end: NodeId,
558 },
559 DeletedNode(NodeId),
560 DeletedRel(RelId),
561 MutatedNode(NodeId),
562 MutatedRel(RelId),
563 CreateIndex {
564 name: &'a str,
565 label: &'a str,
566 property: &'a str,
567 },
568 DropIndex {
569 name: &'a str,
570 },
571 CreateConstraint {
572 name: &'a str,
573 },
574 DropConstraint {
575 name: &'a str,
576 },
577 CatalogMeta,
580 PullIdentity,
582 Ontology,
585}
586
587impl WriteTarget<'_> {
588 pub fn is_catalog(&self) -> bool {
592 match self {
593 WriteTarget::CreatedNode(_)
594 | WriteTarget::CreatedRel { .. }
595 | WriteTarget::DeletedNode(_)
596 | WriteTarget::DeletedRel(_)
597 | WriteTarget::MutatedNode(_)
598 | WriteTarget::MutatedRel(_)
599 | WriteTarget::PullIdentity
600 | WriteTarget::Ontology => false,
601 WriteTarget::CreateIndex { .. }
602 | WriteTarget::DropIndex { .. }
603 | WriteTarget::CreateConstraint { .. }
604 | WriteTarget::DropConstraint { .. }
605 | WriteTarget::CatalogMeta => true,
606 }
607 }
608}
609
610#[derive(Debug, Clone, Copy, PartialEq, Eq)]
614pub enum CatalogName<'a> {
615 Label(&'a str),
616 RelType(&'a str),
617 PropertyKey(&'a str),
618}
619
620#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
622#[serde(rename_all = "lowercase")]
623pub enum PullKind {
624 Node,
625 Rel,
626}
627
628#[cfg(test)]
629mod tests;