0

Hello I am having trouble querying when I have apostrophe in my where clause in postgresql using pgpsql function, I know that manually I could do something like:

select 'author''s'

however my word is stored in a variable, here is my function:

CREATE OR REPLACE FUNCTION public.fn_inserir_doc(caminho_arqv text, conteudo text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
    declare
        conteudo_array text array;
        palavra text;
    begin
        execute 'insert into documento(caminho)
                    select ''' || caminho_arqv || '''
                    where not exists(select id 
                                    from documento
                                    where caminho='''||caminho_arqv||''')';
        conteudo_array := regexp_split_to_array(conteudo, E'\\s+');
        FOREACH palavra in array conteudo_array
        loop
              if length(palavra) >=3 then
                raise notice 'palavra: %', palavra;
                execute 'insert into termo(descricao)
                            select ''' || palavra || '''
                            where not exists(
                                            select id from termo
                                            where descricao='''||palavra||''')';
                execute 'insert into documento_termo(id_termo, id_documento, frequencia)
                            select t.id, d.id, 1
                            from termo t
                            cross join documento d
                            where t.descricao = '''|| palavra ||'''
                            and d.caminho = '''|| caminho_arqv ||'''
                            on conflict (id_termo, id_documento) do update set frequencia = documento_termo.frequencia + 1;';
                 end if;
        end loop;
    end;
$function$

The following sample is the one that has the problem:

select id from termo
where descricao='''||palavra||'''

because palavra contains single quote

1 Answer 1

1

Use dollar quoting and the function format(). Example:

create or replace function test(str text)
returns setof text language plpgsql as $$
begin
-- instead of this:
--  return query execute 'select '''||str||'''::text';
-- use:
    return query execute format(
        $fmt$
            select %L::text
        $fmt$, str);
end $$;

select * from test('O''Brian');

  test   
---------
 O'Brian
(1 row) 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.