Convert a bytea column to OID while retaining values

前端 未结 5 973
情话喂你
情话喂你 2021-01-18 16:20

I\'m trying to alter a bytea column to have type oid and still retain the values.

I have tried using queries like:

ALTER TA         


        
5条回答
  •  轮回少年
    2021-01-18 16:45

    I think the best answer can be found at Grace Batumbya's Blog, in verbis:

    The algorithm is pretty simple, get the binary data, if it is null, return null. Else create a large object and in the lowrite function, pass it the binary value, instead of a path to a file.

    The code for the procedure is below. Note that the lo_manage package should be installed for this to work.

    create or replace function blob_write(lbytea bytea)
       returns oid
       volatile
       language plpgsql as
    $f$
       declare
          loid oid;
          lfd integer;
          lsize integer;
    begin
       if(lbytea is null) then
          return null;
       end if;
    
       loid := lo_create(0);
       lfd := lo_open(loid,131072);
       lsize := lowrite(lfd,lbytea);
       perform lo_close(lfd);
       return loid;
    end;
    $f$;
    CREATE CAST (bytea AS oid) WITH FUNCTION blob_write(bytea) AS ASSIGNMENT;
    

    So now the following code works: CREATE TABLE bytea_to_lo ( lo largeObj );

    INSERT INTO bytea_to_lo VALUES ( DECODE('00AB','hex'));
    

    I've tried it and works like a charm.

提交回复
热议问题