The geometric problem is similar to this other one, that can be described as "small extrapolation of the line ends".
The correct solution must to expand/extrapolate d meters (ex. 2 meters) of line ends, of lines of any length.
Illustrating by a real life example
Here we need a small expansion into line ends to glue lines of a road network. The magic function not exists, but in some cases we can use ST_Scale to illustrate in the context.
I am testing this algorithm with no changes, except to include ST_Scale:
CREATE VIEW v AS SELECT city_id, (st_dump).path as poly_id, (st_dump).geom FROM ( SELECT city_id, ST_Dump(ST_Polygonize(geom)) FROM ( SELECT city_id, -- this works only for some straight lines ST_Union( ST_Scale(geom,1.01,1.01) ) as geom FROM road_network -- suppose all LINESTRINGs GROUP BY city_id ) mergedlines GROUP BY city_id ) polys ;
This wrong use of ST_Scale() funciton expanded in 1% the length (average ~2m) of the lines... Seems that works with straight lines, but, of course, curved lines will be distorted. And also I not need "proportional expansion" but only "constant line ends expansion" (the small 2 meters extrapolation of line ends).
I not see how to use the @SzieberthAdam's function of his solution, replacing ST_Scale of the example. The @Jayden and @EoghanM solutions must be transformed into a generic function to be applied into LINESTRINGs.
PS: on this problem the ST_SnapToGrid is valid but only for very small correction. Not a good solution, because cause geometric distortions, and the ST_SnapToGrid(geom,w) not solves all cases with
w=2m (need bigger), and it not shows convergence with w (destroys/collapses the network).