This is not an easy problem.
Finding pipes affected by the defect is easy, you can do this with a short query:
SELECT * FROM Pipes WHERE EXISTS
(SELECT * FROM Defect WHERE Distance(Pipes.ID, Defect.ID) < 1)
Finding pipes connected to specified pipes and finding valves on specified pipes is similarly easy.
But you want to figure out which valves you have to close to fix the problem. In general, this calls for an iterative process and this can only be done using a script.
Here's the gist of the issue: let's say we find the pipe that the defect is on and that pipe contains a valve. Obviously we should close the valve, but this fixes half of the issue and we have to figure out which one and proceed closing valves further in one direction but not in the other. Even simpler, let's say we assume the valves on the pipe with the defect are going to be broken and we have to ignore them. Good, so we find all pipes connected to the pipe with the defect and we find all valves on those pipes. But what if some pipes have no valves? Is it guaranteed that each pipe always has a valve? If so, we solved it. But if not, we have to close the valves that we did find, then identify the pipes without the valves and repeat the search from them. This is a fairly laborious script, particularly because we have to make sure we don't create an infinite loop. If it is a one-off for you, say so and maybe someone will help write it, but if things like that are a recurring task, it would be better for you to start writing the script with the thread helping get through the difficult places.