       ref_field_id := OLD.record_id ; 
     ELSIF OLD.people_type = 'identifier' THEN
       SELECT record_id,referenced_relation INTO ref_field_id, ref_relation FROM identifications where id=OLD.record_id ;
-      /* 'IF ref_field_id is Null, so the identification associated must have been deleted, we have nothing to do because an other trigger have done the job' */
       IF ref_field_id is NULL THEN
         RETURN OLD ;
       END IF ;      

              'WHERE ' || quote_ident(ref_field) || ' = ' || quote_literal(ref_field_id) ;
    END IF;
  END IF;  
  RETURN NEW;
END;
$$ language plpgsql;

CREATE OR REPLACE FUNCTION fct_filter_encodable_row(ids varchar, col_name varchar, user_id integer) RETURNS SETOF integer
AS $$
DECLARE
  rec_id integer;
BEGIN
    IF col_name = 'spec_ref' THEN    
      FOR rec_id IN SELECT id FROM specimens WHERE id in (select X::int from regexp_split_to_table(ids, '','' ) as X)
            AND collection_ref in (select X FROM fct_search_authorized_encoding_collections(user_id) as X)
      LOOP
        return next rec_id;
      END LOOP;

    ELSIF col_name = 'individual_ref' THEN
      FOR rec_id IN SELECT i.id FROM specimens s INNER JOIN specimen_individuals i ON s.id = i.specimen_ref
            WHERE i.id in (select X::int from regexp_split_to_table(ids, '','' ) as X)
            AND collection_ref in (select X FROM fct_search_authorized_encoding_collections(user_id) as X)
      LOOP
        return next rec_id;
      END LOOP;

    ELSIF col_name = 'part_ref' THEN
      FOR rec_id IN SELECT p.id FROM specimens s INNER JOIN specimen_individuals i ON s.id = i.specimen_ref
            INNER JOIN specimen_parts p ON i.id = p.specimen_individual_ref
            WHERE p.id in (select X::int from regexp_split_to_table(ids, '','' ) as X)
            AND collection_ref in (select X FROM fct_search_authorized_encoding_collections(user_id) as X)
      LOOP
        return next rec_id;
      END LOOP;
    END IF;

END;
$$ LANGUAGE plpgsql;
