     ON song
  USING gin(
     (
-        to_tsvector('english'::regconfig, ((((COALESCE(artist, ''::text) || ' '::text) || COALESCE(title, ''::text)) || ' '::text) || COALESCE(album, ''::text)))
-     || to_tsvector('simple'::regconfig,  ((((COALESCE(artist, ''::text) || ' '::text) || COALESCE(title, ''::text)) || ' '::text) || COALESCE(album, ''::text)))
+        TO_TSVECTOR('english'::REGCONFIG, ((((COALESCE(artist, ''::TEXT) || ' '::TEXT) || COALESCE(title, ''::TEXT)) || ' '::TEXT) || COALESCE(album, ''::TEXT)))
+     || TO_TSVECTOR('simple'::REGCONFIG,  ((((COALESCE(artist, ''::TEXT) || ' '::TEXT) || COALESCE(title, ''::TEXT)) || ' '::TEXT) || COALESCE(album, ''::TEXT)))
     )
 );

$$ LANGUAGE plpgsql;


CREATE OR REPLACE FUNCTION fn_get_songs_by_query( in_query tsquery )
    RETURNS SETOF integer
    AS $$
BEGIN
    RETURN QUERY
        SELECT song
          FROM song
         WHERE to_tsvector( 'english', coalesce( artist, '' ) || ' ' || coalesce( title, '' ) || ' ' || coalesce( album, '' ) )
            || to_tsvector( 'simple',  coalesce( artist, '' ) || ' ' || coalesce( title, '' ) || ' ' || 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;

