relateby-pattern 0.4.2

Core pattern data structures
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! StandardGraph: ergonomic wrapper around PatternGraph<(), Subject>.
//!
//! Provides zero-configuration graph construction and querying for the common
//! case of building graph structures from atomic patterns (nodes, relationships,
//! walks, annotations).

use std::collections::HashMap;

use crate::graph::graph_classifier::{canonical_classifier, GraphValue};
use crate::graph::graph_query::GraphQuery;
use crate::graph::graph_view::GraphView;
use crate::pattern::Pattern;
use crate::pattern_graph::PatternGraph;
use crate::subject::{Subject, Symbol};

/// A concrete, ergonomic graph type wrapping `PatternGraph<(), Subject>`.
///
/// StandardGraph eliminates the type parameters and classifier/policy boilerplate
/// needed when working with `PatternGraph` directly. It provides fluent construction
/// methods and graph-native queries.
///
/// # Examples
///
/// ```rust
/// use pattern_core::graph::StandardGraph;
/// use pattern_core::subject::Subject;
///
/// let mut g = StandardGraph::new();
/// let alice = Subject::build("alice").label("Person").done();
/// let bob   = Subject::build("bob").label("Person").done();
/// g.add_node(alice.clone());
/// g.add_node(bob.clone());
/// g.add_relationship(Subject::build("r1").label("KNOWS").done(), &alice, &bob);
/// assert_eq!(g.node_count(), 2);
/// assert_eq!(g.relationship_count(), 1);
/// ```
pub struct StandardGraph {
    inner: PatternGraph<(), Subject>,
}

impl StandardGraph {
    /// Creates an empty StandardGraph.
    pub fn new() -> Self {
        StandardGraph {
            inner: PatternGraph::empty(),
        }
    }

    // ========================================================================
    // Atomic element addition (Phase 3: US1)
    // ========================================================================

    /// Adds a node to the graph.
    ///
    /// The subject becomes an atomic pattern (no elements). If a node with the
    /// same identity already exists, it is replaced (last-write-wins).
    pub fn add_node(&mut self, subject: Subject) -> &mut Self {
        let id = subject.identity.clone();
        let pattern = Pattern::point(subject);
        self.inner.pg_nodes.insert(id, pattern);
        self
    }

    /// Adds a relationship to the graph.
    ///
    /// Creates a 2-element pattern with the source and target nodes as elements.
    /// If the source or target nodes don't exist yet, minimal placeholder nodes
    /// are created automatically.
    ///
    /// Pass the actual `Subject` objects for source and target when you have them;
    /// use `Subject::from_id("id")` as a lightweight reference when you only have
    /// an identity string.
    pub fn add_relationship(
        &mut self,
        subject: Subject,
        source: &Subject,
        target: &Subject,
    ) -> &mut Self {
        let source_pattern = self.get_or_create_placeholder_node(&source.identity);
        let target_pattern = self.get_or_create_placeholder_node(&target.identity);

        let id = subject.identity.clone();
        let pattern = Pattern::pattern(subject, vec![source_pattern, target_pattern]);
        self.inner.pg_relationships.insert(id, pattern);
        self
    }

    /// Adds a walk to the graph.
    ///
    /// Creates an N-element pattern where each element is a relationship pattern.
    /// If referenced relationships don't exist, minimal placeholders are created.
    ///
    /// Pass the actual `Subject` objects for relationships when you have them;
    /// use `Subject::from_id("id")` as a lightweight reference when you only have
    /// an identity string.
    pub fn add_walk(&mut self, subject: Subject, relationships: &[Subject]) -> &mut Self {
        let rel_patterns: Vec<Pattern<Subject>> = relationships
            .iter()
            .map(|rel| self.get_or_create_placeholder_relationship(&rel.identity))
            .collect();

        let id = subject.identity.clone();
        let pattern = Pattern::pattern(subject, rel_patterns);
        self.inner.pg_walks.insert(id, pattern);
        self
    }

    /// Adds an annotation to the graph.
    ///
    /// Creates a 1-element pattern wrapping the referenced element.
    /// If the referenced element doesn't exist, a minimal placeholder node is created.
    ///
    /// Pass the actual `Subject` when you have it; use `Subject::from_id("id")` as
    /// a lightweight reference when you only have an identity string.
    pub fn add_annotation(&mut self, subject: Subject, element: &Subject) -> &mut Self {
        let element_id = &element.identity;
        let element_pattern = if let Some(existing) = self.find_element(element_id) {
            existing
        } else {
            // Insert placeholder into pg_nodes for consistency with add_relationship
            let placeholder = Self::make_placeholder_node(element_id);
            self.inner
                .pg_nodes
                .insert(element_id.clone(), placeholder.clone());
            placeholder
        };

        let id = subject.identity.clone();
        let pattern = Pattern::pattern(subject, vec![element_pattern]);
        self.inner.pg_annotations.insert(id, pattern);
        self
    }

    // ========================================================================
    // Pattern ingestion (Phase 4: US3)
    // ========================================================================

    /// Adds a single pattern, classifying it by shape and inserting into the
    /// appropriate bucket.
    ///
    /// When a node with the same identity already exists, labels and properties
    /// are merged using union semantics rather than overwriting. This preserves
    /// labels declared in earlier patterns when a later back-reference omits them.
    pub fn add_pattern(&mut self, pattern: Pattern<Subject>) -> &mut Self {
        let classifier = canonical_classifier();
        let policy = pattern_merge_policy();
        self.inner = crate::pattern_graph::merge_with_policy(
            &classifier,
            &policy,
            pattern,
            std::mem::replace(&mut self.inner, PatternGraph::empty()),
        );
        self
    }

    /// Adds multiple patterns, classifying each by shape.
    ///
    /// When a node with the same identity already exists, labels and properties
    /// are merged using union semantics rather than overwriting. This preserves
    /// labels declared in earlier patterns when a later back-reference omits them.
    pub fn add_patterns(
        &mut self,
        patterns: impl IntoIterator<Item = Pattern<Subject>>,
    ) -> &mut Self {
        let classifier = canonical_classifier();
        let policy = pattern_merge_policy();
        let mut graph = std::mem::replace(&mut self.inner, PatternGraph::empty());
        for pattern in patterns {
            graph = crate::pattern_graph::merge_with_policy(&classifier, &policy, pattern, graph);
        }
        self.inner = graph;
        self
    }

    /// Creates a StandardGraph from an iterator of patterns.
    ///
    /// When the same identity appears multiple times (back-references), labels and
    /// properties are merged using union semantics so that labels declared in an
    /// earlier pattern are preserved even when a later occurrence omits them.
    pub fn from_patterns(patterns: impl IntoIterator<Item = Pattern<Subject>>) -> Self {
        let classifier = canonical_classifier();
        let policy = pattern_merge_policy();
        let inner = crate::pattern_graph::from_patterns_with_policy(&classifier, &policy, patterns);
        StandardGraph { inner }
    }

    /// Creates a StandardGraph by wrapping an existing PatternGraph directly.
    pub fn from_pattern_graph(graph: PatternGraph<(), Subject>) -> Self {
        StandardGraph { inner: graph }
    }

    // ========================================================================
    // Element access (Phase 3: US1)
    // ========================================================================

    /// Returns the node with the given identity.
    pub fn node(&self, id: &Symbol) -> Option<&Pattern<Subject>> {
        self.inner.pg_nodes.get(id)
    }

    /// Returns the relationship with the given identity.
    pub fn relationship(&self, id: &Symbol) -> Option<&Pattern<Subject>> {
        self.inner.pg_relationships.get(id)
    }

    /// Returns the walk with the given identity.
    pub fn walk(&self, id: &Symbol) -> Option<&Pattern<Subject>> {
        self.inner.pg_walks.get(id)
    }

    /// Returns the annotation with the given identity.
    pub fn annotation(&self, id: &Symbol) -> Option<&Pattern<Subject>> {
        self.inner.pg_annotations.get(id)
    }

    // ========================================================================
    // Counts and health (Phase 3: US1)
    // ========================================================================

    /// Returns the number of nodes.
    pub fn node_count(&self) -> usize {
        self.inner.pg_nodes.len()
    }

    /// Returns the number of relationships.
    pub fn relationship_count(&self) -> usize {
        self.inner.pg_relationships.len()
    }

    /// Returns the number of walks.
    pub fn walk_count(&self) -> usize {
        self.inner.pg_walks.len()
    }

    /// Returns the number of annotations.
    pub fn annotation_count(&self) -> usize {
        self.inner.pg_annotations.len()
    }

    /// Returns true if the graph has no elements in any bucket.
    pub fn is_empty(&self) -> bool {
        self.inner.pg_nodes.is_empty()
            && self.inner.pg_relationships.is_empty()
            && self.inner.pg_walks.is_empty()
            && self.inner.pg_annotations.is_empty()
            && self.inner.pg_other.is_empty()
            && self.inner.pg_conflicts.is_empty()
    }

    /// Returns true if any reconciliation conflicts have been recorded.
    pub fn has_conflicts(&self) -> bool {
        !self.inner.pg_conflicts.is_empty()
    }

    /// Returns the conflict map (identity → conflicting patterns).
    pub fn conflicts(&self) -> &HashMap<Symbol, Vec<Pattern<Subject>>> {
        &self.inner.pg_conflicts
    }

    /// Returns the "other" bucket (unclassifiable patterns).
    pub fn other(&self) -> &HashMap<Symbol, ((), Pattern<Subject>)> {
        &self.inner.pg_other
    }

    // ========================================================================
    // Iterators (Phase 5: US4)
    // ========================================================================

    /// Iterates over all nodes.
    pub fn nodes(&self) -> impl Iterator<Item = (&Symbol, &Pattern<Subject>)> {
        self.inner.pg_nodes.iter()
    }

    /// Iterates over all relationships.
    pub fn relationships(&self) -> impl Iterator<Item = (&Symbol, &Pattern<Subject>)> {
        self.inner.pg_relationships.iter()
    }

    /// Iterates over all walks.
    pub fn walks(&self) -> impl Iterator<Item = (&Symbol, &Pattern<Subject>)> {
        self.inner.pg_walks.iter()
    }

    /// Iterates over all annotations.
    pub fn annotations(&self) -> impl Iterator<Item = (&Symbol, &Pattern<Subject>)> {
        self.inner.pg_annotations.iter()
    }

    // ========================================================================
    // Graph-native queries (Phase 5: US4)
    // ========================================================================

    /// Returns the source node of a relationship.
    pub fn source(&self, rel_id: &Symbol) -> Option<&Pattern<Subject>> {
        self.inner
            .pg_relationships
            .get(rel_id)
            .and_then(|rel| rel.elements.first())
    }

    /// Returns the target node of a relationship.
    pub fn target(&self, rel_id: &Symbol) -> Option<&Pattern<Subject>> {
        self.inner
            .pg_relationships
            .get(rel_id)
            .and_then(|rel| rel.elements.get(1))
    }

    /// Returns all neighbor nodes of the given node (both directions).
    pub fn neighbors(&self, node_id: &Symbol) -> Vec<&Pattern<Subject>> {
        let mut result = Vec::new();
        for rel in self.inner.pg_relationships.values() {
            if rel.elements.len() == 2 {
                let src_id = rel.elements[0].value.identify();
                let tgt_id = rel.elements[1].value.identify();
                if src_id == node_id {
                    result.push(&rel.elements[1]);
                } else if tgt_id == node_id {
                    result.push(&rel.elements[0]);
                }
            }
        }
        result
    }

    /// Returns the degree of a node (number of incident relationships, both directions).
    pub fn degree(&self, node_id: &Symbol) -> usize {
        self.inner
            .pg_relationships
            .values()
            .filter(|rel| {
                rel.elements.len() == 2
                    && (rel.elements[0].value.identify() == node_id
                        || rel.elements[1].value.identify() == node_id)
            })
            .count()
    }

    // ========================================================================
    // Escape hatches (Phase 6: US5)
    // ========================================================================

    /// Returns a reference to the inner PatternGraph.
    pub fn as_pattern_graph(&self) -> &PatternGraph<(), Subject> {
        &self.inner
    }

    /// Consumes the StandardGraph and returns the inner PatternGraph.
    pub fn into_pattern_graph(self) -> PatternGraph<(), Subject> {
        self.inner
    }

    /// Creates a GraphQuery from this graph.
    #[cfg(not(feature = "thread-safe"))]
    pub fn as_query(&self) -> GraphQuery<Subject> {
        use std::rc::Rc;
        let graph = Rc::new(PatternGraph {
            pg_nodes: self.inner.pg_nodes.clone(),
            pg_relationships: self.inner.pg_relationships.clone(),
            pg_walks: self.inner.pg_walks.clone(),
            pg_annotations: self.inner.pg_annotations.clone(),
            pg_other: self.inner.pg_other.clone(),
            pg_conflicts: self.inner.pg_conflicts.clone(),
        });
        crate::pattern_graph::from_pattern_graph(graph)
    }

    /// Creates a GraphQuery from this graph.
    #[cfg(feature = "thread-safe")]
    pub fn as_query(&self) -> GraphQuery<Subject> {
        use std::sync::Arc;
        let graph = Arc::new(PatternGraph {
            pg_nodes: self.inner.pg_nodes.clone(),
            pg_relationships: self.inner.pg_relationships.clone(),
            pg_walks: self.inner.pg_walks.clone(),
            pg_annotations: self.inner.pg_annotations.clone(),
            pg_other: self.inner.pg_other.clone(),
            pg_conflicts: self.inner.pg_conflicts.clone(),
        });
        crate::pattern_graph::from_pattern_graph(graph)
    }

    /// Creates a GraphView snapshot from this graph.
    pub fn as_snapshot(&self) -> GraphView<(), Subject> {
        let classifier = canonical_classifier();
        crate::graph::graph_view::from_pattern_graph(&classifier, &self.inner)
    }

    // ========================================================================
    // Private helpers
    // ========================================================================

    fn make_placeholder_node(id: &Symbol) -> Pattern<Subject> {
        Pattern::point(Subject {
            identity: id.clone(),
            labels: std::collections::HashSet::new(),
            properties: HashMap::new(),
        })
    }

    fn get_or_create_placeholder_node(&mut self, id: &Symbol) -> Pattern<Subject> {
        if let Some(node) = self.inner.pg_nodes.get(id) {
            node.clone()
        } else {
            let placeholder = Self::make_placeholder_node(id);
            self.inner.pg_nodes.insert(id.clone(), placeholder.clone());
            placeholder
        }
    }

    fn get_or_create_placeholder_relationship(&self, id: &Symbol) -> Pattern<Subject> {
        if let Some(rel) = self.inner.pg_relationships.get(id) {
            rel.clone()
        } else {
            // Create a minimal placeholder relationship (just a point with the id)
            Pattern::point(Subject {
                identity: id.clone(),
                labels: std::collections::HashSet::new(),
                properties: HashMap::new(),
            })
        }
    }

    fn find_element(&self, id: &Symbol) -> Option<Pattern<Subject>> {
        self.inner
            .pg_nodes
            .get(id)
            .or_else(|| self.inner.pg_relationships.get(id))
            .or_else(|| self.inner.pg_walks.get(id))
            .or_else(|| self.inner.pg_annotations.get(id))
            .cloned()
    }
}

impl Default for StandardGraph {
    fn default() -> Self {
        Self::new()
    }
}

/// Returns the reconciliation policy used by `add_pattern`, `add_patterns`, and
/// `from_patterns`.
///
/// Union label semantics ensure that back-references (node occurrences without
/// labels that refer to an earlier labelled declaration) do not silently discard
/// the labels established by the first declaration.
fn pattern_merge_policy(
) -> crate::reconcile::ReconciliationPolicy<crate::reconcile::SubjectMergeStrategy> {
    crate::reconcile::ReconciliationPolicy::Merge(
        crate::reconcile::ElementMergeStrategy::UnionElements,
        crate::reconcile::default_subject_merge_strategy(),
    )
}