You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 line
4.6KB

  1. # Graph relationships between entries (native tables + recursive queries).
  2. function Add-FoundryRelationship {
  3. <#
  4. .SYNOPSIS Connect two entries: (SourceId)-[Type]->(TargetId).
  5. .DESCRIPTION Type is an UPPER_SNAKE label such as RELATED_TO, DEPENDS_ON, SOLVES, CAUSES, SUPERSEDES.
  6. Adding an edge that already exists is not an error; 'created' says whether it was new.
  7. #>
  8. [CmdletBinding()]
  9. param(
  10. [Parameter(Mandatory)][long]$SourceId, [Parameter(Mandatory)][long]$TargetId,
  11. [Parameter(Mandatory)][string]$Type, [hashtable]$Metadata = @{}, [switch]$AsJson
  12. )
  13. if ($SourceId -eq $TargetId) { throw 'An entry cannot be related to itself.' }
  14. 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)." }
  15. foreach ($id in $SourceId, $TargetId) { $null = Get-FoundryKnowledge -Id $id }
  16. $row = Invoke-FkeSql -Payload @{ s = $SourceId; t = $TargetId; type = $Type.ToUpperInvariant(); metadata = $Metadata } -Sql @'
  17. WITH p AS (SELECT current_setting('fke.p')::jsonb AS j),
  18. ins AS (
  19. INSERT INTO knowledge.relationships (source_id, target_id, relationship_type, metadata)
  20. SELECT (j->>'s')::bigint, (j->>'t')::bigint, j->>'type', COALESCE(j->'metadata', '{}'::jsonb) FROM p
  21. ON CONFLICT (source_id, target_id, relationship_type) DO NOTHING
  22. RETURNING id, source_id, target_id, relationship_type)
  23. SELECT to_jsonb(x) FROM (
  24. SELECT id, source_id, target_id, relationship_type, true AS created FROM ins
  25. UNION ALL
  26. SELECT r.id, r.source_id, r.target_id, r.relationship_type, false
  27. FROM knowledge.relationships r, p
  28. WHERE NOT EXISTS (SELECT 1 FROM ins)
  29. AND r.source_id = (p.j->>'s')::bigint AND r.target_id = (p.j->>'t')::bigint AND r.relationship_type = p.j->>'type') x;
  30. '@
  31. Out-FkeResult $row -AsJson:$AsJson
  32. }
  33. function Get-FoundryRelationships {
  34. <#
  35. .SYNOPSIS Walk the graph from an entry, up to -Depth hops (cycle-safe).
  36. .DESCRIPTION Each reachable entry is returned once, at its shortest depth, with the edge that
  37. reached it. -Direction Out follows source->target, In follows target->source, Both (default) either.
  38. #>
  39. [CmdletBinding()]
  40. param(
  41. [Parameter(Mandatory)][long]$Id,
  42. [ValidateRange(1, 6)][int]$Depth = 1,
  43. [ValidateSet('Both', 'Out', 'In')][string]$Direction = 'Both',
  44. [string]$Type, [switch]$IncludeSuperseded, [switch]$AsJson
  45. )
  46. $null = Get-FoundryKnowledge -Id $Id
  47. # $join is chosen from a closed set above, never from caller text.
  48. $join = switch ($Direction) {
  49. 'Out' { 'r.source_id = w.node' }
  50. 'In' { 'r.target_id = w.node' }
  51. default { '(r.source_id = w.node OR r.target_id = w.node)' }
  52. }
  53. $first = $join -replace 'w\.node', 'c.start'
  54. $rows = @(Invoke-FkeSql -Payload @{ id = $Id; depth = $Depth; type = $Type; includeSuperseded = [bool]$IncludeSuperseded } -Sql @"
  55. WITH RECURSIVE p AS (SELECT current_setting('fke.p')::jsonb AS j),
  56. c AS (SELECT (j->>'id')::bigint AS start, (j->>'depth')::int AS maxd, NULLIF(j->>'type', '') AS rtype FROM p),
  57. walk AS (
  58. SELECT 1 AS depth, c.start AS from_id,
  59. CASE WHEN r.source_id = c.start THEN r.target_id ELSE r.source_id END AS node,
  60. r.relationship_type, CASE WHEN r.source_id = c.start THEN 'out' ELSE 'in' END AS direction,
  61. ARRAY[c.start, CASE WHEN r.source_id = c.start THEN r.target_id ELSE r.source_id END] AS path
  62. FROM c JOIN knowledge.relationships r ON $first
  63. WHERE c.rtype IS NULL OR r.relationship_type = c.rtype
  64. UNION ALL
  65. SELECT w.depth + 1, w.node,
  66. CASE WHEN r.source_id = w.node THEN r.target_id ELSE r.source_id END,
  67. r.relationship_type, CASE WHEN r.source_id = w.node THEN 'out' ELSE 'in' END,
  68. w.path || CASE WHEN r.source_id = w.node THEN r.target_id ELSE r.source_id END
  69. FROM walk w CROSS JOIN c JOIN knowledge.relationships r ON $join
  70. WHERE w.depth < c.maxd AND (c.rtype IS NULL OR r.relationship_type = c.rtype)
  71. AND NOT (CASE WHEN r.source_id = w.node THEN r.target_id ELSE r.source_id END) = ANY(w.path))
  72. SELECT COALESCE(jsonb_agg(x ORDER BY x.depth, x.id), '[]'::jsonb) FROM (
  73. SELECT DISTINCT ON (n.id) w.depth, n.id, n.title, n.knowledge_type AS type, n.status, n.confidence,
  74. w.relationship_type AS relationship, w.direction, w.from_id AS "from"
  75. FROM walk w JOIN knowledge.entries n ON n.id = w.node, p
  76. WHERE (p.j->>'includeSuperseded')::boolean OR n.status <> 'superseded'
  77. ORDER BY n.id, w.depth) x;
  78. "@)
  79. Out-FkeResult ([pscustomobject]@{ id = $Id; depth = $Depth; direction = $Direction; related = @($rows) }) -AsJson:$AsJson
  80. }

Powered by TurnKey Linux.