Skip to content

Instantly share code, notes, and snippets.

@giansalex
Created January 13, 2018 18:59
Show Gist options
  • Save giansalex/ec626727c0112380c4c23e3b7f296272 to your computer and use it in GitHub Desktop.
Save giansalex/ec626727c0112380c4c23e3b7f296272 to your computer and use it in GitHub Desktop.
Read file and insert data to field - PostgreSQL

First

Create function

create or replace function bytea_import(p_path text, p_result out bytea) 
                   language plpgsql as $$
declare
  l_oid oid;
  r record;
begin
  p_result := '';
  select lo_import(p_path) into l_oid;
  for r in ( select data 
             from pg_largeobject 
             where loid = l_oid 
             order by pageno ) loop
    p_result = p_result || r.data;
  end loop;
  perform lo_unlink(l_oid);
end;$$;

Second

Execute any queries. Example 1

insert into my_table(bytea_data) select bytea_import('/my/file.name');

Example 2

UPDATE "VentaStatus" SET "XmlContent"=bytea_import('D://App//f001-1.xml') WHERE "VentaId"=54 ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment