 $$ LANGUAGE plpgsql;
 
 
-CREATE OR REPLACE FUNCTION fn_fuzzy_search_song( in_query tsquery )
-    RETURNS TABLE( match text, match_type text )
+CREATE OR REPLACE FUNCTION fn_fuzzy_search_song( in_query TSQUERY )
+    RETURNS TABLE( match TEXT, match_type TEXT )
     AS $$
 BEGIN
     RETURN QUERY

$$ LANGUAGE plpgsql;


CREATE OR REPLACE FUNCTION fn_get_tsquery_from_text( in_query text )
    RETURNS SETOF tsquery
    AS $$
BEGIN
    RETURN QUERY
        SELECT song
          FROM song
         WHERE to_tsvector( 'english', coalesce( artist, '' ) ) || to_tsvector( 'simple', coalesce( artist, '' ) )
            || to_tsvector( 'english', coalesce( title,  '' ) ) || to_tsvector( 'simple', coalesce( title,  '' ) )
            || to_tsvector( 'english', coalesce( album,  '' ) ) || to_tsvector( 'simple', coalesce( album,  '' ) )
            @@ in_query;

    RETURN;

        SELECT artist AS match,
               'artist' AS match_type,
               ts_rank(
                   TO_TSVECTOR( 'english', COALESCE( artist, '' ) ),
                   in_query
               ) AS match_rank
          FROM song
         WHERE TO_TSVECTOR( 'english', COALESCE( artist, '' ) ) @@ in_query
         GROUP BY artist
        UNION ALL
        SELECT album AS match,
               'album' AS match_type,
               ts_rank(
                   TO_TSVECTOR( 'english', COALESCE( album, '' ) ),
                   in_query
               ) AS match_rank
          FROM song
         WHERE TO_TSVECTOR( 'english', COALESCE( album, '' ) ) @@ in_query
         GROUP BY album
        UNION ALL
        SELECT title AS match,
               'title' AS match_type,
               ts_rank(
                   TO_TSVECTOR( 'english', COALESCE( title, '' ) ),
                   in_query
               ) AS match_rank
          FROM song
         WHERE TO_TSVECTOR( 'english', COALESCE( title, '' ) ) @@ in_query
         GROUP BY title
    )
    SELECT m.match::TEXT, m.match_type
      FROM matches m
     ORDER BY m.match_rank DESC;

