After a specific demand in my work that needed to create a single line from two untouched geometries (lines), I needed to develop a function and follow for contribution:
Passing as a parameter two separate non-touching geometries (lines), a single complete line is returned filling the empty space between the nearest ends.
Code:
CREATE OR REPLACE FUNCTION public.st_mergecloselines(
geometry, geometry)
RETURNS geometry
LANGUAGE 'sql'
-- This function merge two lines that don't within (dont touching) returing a single multiline. By Emilson Ribeiro Neto - emilsonribeiro@hotmail.com
AS $BODY$
select ST_LineMerge(st_union(st_union($1,
(case
WHEN (st_distanceSphere(ST_StartPoint($1),ST_StartPoint($2)) < st_distanceSphere(ST_StartPoint($1),ST_EndPoint($2))
and (st_distanceSphere(ST_StartPoint($1),ST_StartPoint($2)) < st_distanceSphere(ST_EndPoint($1),ST_StartPoint($2)))
and (st_distanceSphere(ST_StartPoint($1),ST_StartPoint($2)) < st_distanceSphere(ST_EndPoint($1),ST_EndPoint($2)))
) THEN st_makeLine(ST_StartPoint($1),ST_StartPoint($2))
WHEN (st_distanceSphere(ST_EndPoint($1),ST_StartPoint($2)) < st_distanceSphere(ST_StartPoint($1),ST_EndPoint($2))
and (st_distanceSphere(ST_EndPoint($1),ST_StartPoint($2)) < st_distanceSphere(ST_StartPoint($1),ST_StartPoint($2)))
and (st_distanceSphere(ST_EndPoint($1),ST_StartPoint($2)) < st_distanceSphere(ST_EndPoint($1),ST_EndPoint($2)))
) THEN st_makeLine(ST_EndPoint($1),ST_StartPoint($2))
WHEN (st_distanceSphere(ST_StartPoint($1),ST_EndPoint($2)) < st_distanceSphere(ST_StartPoint($1),ST_StartPoint($2))
and (st_distanceSphere(ST_StartPoint($1),ST_EndPoint($2)) < st_distanceSphere(ST_EndPoint($1),ST_StartPoint($2)))
and (st_distanceSphere(ST_StartPoint($1),ST_EndPoint($2)) < st_distanceSphere(ST_EndPoint($1),ST_EndPoint($2)))
) THEN st_makeLine(ST_StartPoint($1),ST_EndPoint($2))
else st_makeLine(ST_EndPoint($1),ST_EndPoint($2))
end)),$2))
$BODY$