|
- # Graph relationships between entries (native tables + recursive queries).
-
- function Add-FoundryRelationship {
- <#
- .SYNOPSIS Connect two entries: (SourceId)-[Type]->(TargetId).
- .DESCRIPTION Type is an UPPER_SNAKE label such as RELATED_TO, DEPENDS_ON, SOLVES, CAUSES, SUPERSEDES.
- Adding an edge that already exists is not an error; 'created' says whether it was new.
- #>
- [CmdletBinding()]
- param(
- [Parameter(Mandatory)][long]$SourceId, [Parameter(Mandatory)][long]$TargetId,
- [Parameter(Mandatory)][string]$Type, [hashtable]$Metadata = @{}, [switch]$AsJson
- )
- if ($SourceId -eq $TargetId) { throw 'An entry cannot be related to itself.' }
- if ($Type -notmatch '^[A-Za-z][A-Za-z0-9_]{0,59}$') { throw "Invalid relationship type '$Type'. Use letters, digits and underscores (for example RELATED_TO)." }
- foreach ($id in $SourceId, $TargetId) { $null = Get-FoundryKnowledge -Id $id }
- $row = Invoke-FkeSql -Payload @{ s = $SourceId; t = $TargetId; type = $Type.ToUpperInvariant(); metadata = $Metadata } -Sql @'
- WITH p AS (SELECT current_setting('fke.p')::jsonb AS j),
- ins AS (
- INSERT INTO knowledge.relationships (source_id, target_id, relationship_type, metadata)
- SELECT (j->>'s')::bigint, (j->>'t')::bigint, j->>'type', COALESCE(j->'metadata', '{}'::jsonb) FROM p
- ON CONFLICT (source_id, target_id, relationship_type) DO NOTHING
- RETURNING id, source_id, target_id, relationship_type)
- SELECT to_jsonb(x) FROM (
- SELECT id, source_id, target_id, relationship_type, true AS created FROM ins
- UNION ALL
- SELECT r.id, r.source_id, r.target_id, r.relationship_type, false
- FROM knowledge.relationships r, p
- WHERE NOT EXISTS (SELECT 1 FROM ins)
- AND r.source_id = (p.j->>'s')::bigint AND r.target_id = (p.j->>'t')::bigint AND r.relationship_type = p.j->>'type') x;
- '@
- Out-FkeResult $row -AsJson:$AsJson
- }
-
- function Get-FoundryRelationships {
- <#
- .SYNOPSIS Walk the graph from an entry, up to -Depth hops (cycle-safe).
- .DESCRIPTION Each reachable entry is returned once, at its shortest depth, with the edge that
- reached it. -Direction Out follows source->target, In follows target->source, Both (default) either.
- #>
- [CmdletBinding()]
- param(
- [Parameter(Mandatory)][long]$Id,
- [ValidateRange(1, 6)][int]$Depth = 1,
- [ValidateSet('Both', 'Out', 'In')][string]$Direction = 'Both',
- [string]$Type, [switch]$IncludeSuperseded, [switch]$AsJson
- )
- $null = Get-FoundryKnowledge -Id $Id
- # $join is chosen from a closed set above, never from caller text.
- $join = switch ($Direction) {
- 'Out' { 'r.source_id = w.node' }
- 'In' { 'r.target_id = w.node' }
- default { '(r.source_id = w.node OR r.target_id = w.node)' }
- }
- $first = $join -replace 'w\.node', 'c.start'
- $rows = @(Invoke-FkeSql -Payload @{ id = $Id; depth = $Depth; type = $Type; includeSuperseded = [bool]$IncludeSuperseded } -Sql @"
- WITH RECURSIVE p AS (SELECT current_setting('fke.p')::jsonb AS j),
- c AS (SELECT (j->>'id')::bigint AS start, (j->>'depth')::int AS maxd, NULLIF(j->>'type', '') AS rtype FROM p),
- walk AS (
- SELECT 1 AS depth, c.start AS from_id,
- CASE WHEN r.source_id = c.start THEN r.target_id ELSE r.source_id END AS node,
- r.relationship_type, CASE WHEN r.source_id = c.start THEN 'out' ELSE 'in' END AS direction,
- ARRAY[c.start, CASE WHEN r.source_id = c.start THEN r.target_id ELSE r.source_id END] AS path
- FROM c JOIN knowledge.relationships r ON $first
- WHERE c.rtype IS NULL OR r.relationship_type = c.rtype
- UNION ALL
- SELECT w.depth + 1, w.node,
- CASE WHEN r.source_id = w.node THEN r.target_id ELSE r.source_id END,
- r.relationship_type, CASE WHEN r.source_id = w.node THEN 'out' ELSE 'in' END,
- w.path || CASE WHEN r.source_id = w.node THEN r.target_id ELSE r.source_id END
- FROM walk w CROSS JOIN c JOIN knowledge.relationships r ON $join
- WHERE w.depth < c.maxd AND (c.rtype IS NULL OR r.relationship_type = c.rtype)
- AND NOT (CASE WHEN r.source_id = w.node THEN r.target_id ELSE r.source_id END) = ANY(w.path))
- SELECT COALESCE(jsonb_agg(x ORDER BY x.depth, x.id), '[]'::jsonb) FROM (
- SELECT DISTINCT ON (n.id) w.depth, n.id, n.title, n.knowledge_type AS type, n.status, n.confidence,
- w.relationship_type AS relationship, w.direction, w.from_id AS "from"
- FROM walk w JOIN knowledge.entries n ON n.id = w.node, p
- WHERE (p.j->>'includeSuperseded')::boolean OR n.status <> 'superseded'
- ORDER BY n.id, w.depth) x;
- "@)
- Out-FkeResult ([pscustomobject]@{ id = $Id; depth = $Depth; direction = $Direction; related = @($rows) }) -AsJson:$AsJson
- }
|