swiftpostgresqlsupabasesupabase-database

Supabase Swift SELECT from table with geography data from postgis, cant find the function


I have tried lots of different variations of the same code trying to get the supabase client to get data from the route_cache table, using the fetch_route function and not.

drop function public.fetch_route;
CREATE OR REPLACE FUNCTION public.fetch_route(destinationWKT text, sourceWKT text)
RETURNS SETOF route_cache AS $$
BEGIN
    RETURN QUERY SELECT * FROM route_cache
    WHERE ST_Equals(source::geometry, ST_GeomFromText(sourceWKT, 4326)::geometry)
    AND ST_Equals(destination::geometry, ST_GeomFromText(destinationWKT, 4326)::geometry);
END;
$$ LANGUAGE plpgsql;

This is the function.

let sourceWKT = "POINT(\(source.longitude) \(source.latitude))"
let destinationWKT = "POINT(\(destination.longitude) \(destination.latitude))"
let data = RouteCacheResponse(sourceWKT: sourceWKT, destinationWKT: destinationWKT)
do {
    print(sourceWKT)
    print(destinationWKT)
    let response = try await supabase.database.rpc("fetch_route", params: data).execute()

And this is my implementation in swift.

drop table route_cache;

create table
  route_cache (
    id uuid primary key,
    source geography (point),
    destination geography (point),
    route geography (LINESTRING),
    travelTime float,
    created_at timestamp with time zone default current_timestamp
  );

And this is my SQL query to create the table.

When I run the function in the supabase dashboard directly through an SQL query it works fine.

SELECT * FROM public.fetch_route(
    'POINT(-73.935242 40.730610)', -- Example WKT for New York City
    'POINT(-122.431297 37.773972)' -- Example WKT for San Francisco
);

Just not in Xcode, it gives off this error.

POINT(-2.5872552394866943 51.45983123779297)
POINT(-2.590308666229248 51.45743942260742)
Error fetching route: Could not find the function public.fetch_route(destinationWKT, sourceWKT) in the schema cache

Im confused, please help


Solution

  • I tried your code and if you change the RouteCacheResponse struct definition to use lowercase field names, it works.

    Example:

    struct RouteCacheResponse: Codable {
      let sourcewkt: String
      let destinationwkt: String
    }
    

    That happens because when you create the function Postgres converts the arguments to lowercase.

    So you have 2 ways to overcome this:

    1. Define the struct fields as lowercase as I mentioned above.
    2. Quote the argument names when creating the function, that way Postgres doesn't auto-lowercase them. Example:
    CREATE OR REPLACE FUNCTION public.fetch_route("destinationWKT" text, "sourceWKT" text)
    

    Hope that clarifies it for you, let me know if you still have issues.