Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PostGIS support and/or custom types tutorial #592

Open
tysonzero opened this issue May 12, 2024 · 1 comment
Open

PostGIS support and/or custom types tutorial #592

tysonzero opened this issue May 12, 2024 · 1 comment

Comments

@tysonzero
Copy link

I'm currently getting Opaleye working with PostGIS and it'd be awesome if that was supported out of the box, but even if not it'd be a lot easier with a good tutorial for defining custom sql types with custom serializers (in my case using geos readHex/writeHex functions).

@tysonzero
Copy link
Author

This is the code I currently have for some basic PostGIS stuff for those that are curious:

data SqlGeographyPoint

instance Default ToFields (V2 Double) (Field SqlGeographyPoint) where
    def = toToFields $ \(V2 x y) -> let
        geo = Geos.PointGeometry (Geos.Point $ Geos.Coordinate2 x y) (Just 4326)
        in unsafeCast "geography(POINT, 4326)" . toFieldsI . T.decodeUtf8Lenient $ Geos.writeHex geo

instance DefaultFromField SqlGeographyPoint (V2 Double) where
    defaultFromField = fromPGSFieldParser $ \f mv -> do
        nm <- PGS.typename f
        when (nm /= "geography") $ PGS.returnError PGS.Incompatible f ""
        v <- maybe (PGS.returnError PGS.UnexpectedNull f "") pure mv
        case Geos.readHex v of
            Just (Geos.Some (PointGeometry (Geos.Point (Coordinate2 x y)) (Just 4326))) -> do
                pure $ V2 x y
            _ -> PGS.returnError PGS.ConversionFailed f ""

stDistance :: Field SqlGeographyPoint -> Field SqlGeographyPoint -> Field SqlFloat8
stDistance (Column a) (Column b) = Column $ HPQ.FunExpr "ST_Distance" [a, b]

The stDistance function does seem to require importing from Internal modules which is not totally ideal, but it does seem to work at least.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant