sqlpostgresqlsupabasecreate-function

rpc function tell me to reload the schema cache


I am creating an rpc function to get the number of likes for each post for a user, so I have created a function that takes userId as an argument, which is the uuid of the user that is in the session. But when I call the function on the front it returns me.

If a new function was created in the database with this name and parameters, try reloading the schema cache.

The function:

create function get_number_of_posts_by_user(userId uuid)
returns integer
as $$
  SELECT 
  count(pl.id)
  FROM 
  auth.users au
  join posts p on p.user_id = au.id
  join post_likes pl on pl.post_id = p.id
  where au.id = userId
$$ language sql;

Solution

  • get the number of likes for each post for a user

    You need to group by post to get there.

    CREATE OR REPLACE FUNCTION get_likes_per_post_for_user(_userid uuid)
      RETURNS TABLE (post_id uuid, likes bigint)  -- use actual type of post_id
      LANGUAGE sql AS
    $func$
    SELECT p.id, count(*)
    FROM   posts      p 
    JOIN   post_likes pl ON pl.post_id = p.id
    WHERE  p.user_id = _userid
    GROUP  BY 1
    ORDER  BY 1;  -- or some other order?
    $func$;
    

    Call:

    SELECT * FROM get_likes_per_post_for_user(<some_uuid>);
    

    Major points:

    Your original issue may have been a XY problem that goes away with a proper function definition.

    Addressing the title

    If you actually need to reload the schema cache, use:

    SELECT pg_stat_clear_snapshot();
    

    The manual:

    You can invoke pg_stat_clear_snapshot() to discard the current transaction's statistics snapshot or cached values (if any). The next use of statistical information will (when in snapshot mode) cause a new snapshot to be built or (when in cache mode) accessed statistics to be cached.

    I have never had a need for this myself, yet. Typically, the problem lies elsewhere.