Convert a bytea column to OID while retaining values

前端 未结 5 984
情话喂你
情话喂你 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 17:09

    Postgres 9.4 adds a built-in function for this:

    lo_from_bytea(loid oid, string bytea)
    

    From the release notes:

    • Add SQL functions to allow [large object reads/writes][12] at arbitrary offsets (Pavel Stehule)

    For older versions, this is more efficient than what has been posted before:

    CREATE OR REPLACE FUNCTION blob_write(bytea)
      RETURNS oid AS
    $func$
    DECLARE
       loid oid := lo_create(0);
       lfd   int := lo_open(loid, 131072);  -- = 2^17 = x2000
       -- symbolic constant defined in the header file libpq/libpq-fs.h
       -- #define   INV_WRITE   0x00020000
    BEGIN
       PERFORM lowrite(lfd, $1);
       PERFORM lo_close(lfd);
       RETURN loid;
    END
    $func$  LANGUAGE plpgsql VOLATILE STRICT;
    

    The STRICT modifier is smarter than handling NULL manually.

    SQL Fiddle.

    More in this related answer:

    • Understanding cast from bytea to oid

提交回复
热议问题