I'm trying to alter a bytea
column to have type oid
and still retain the values.
I have tried using queries like:
ALTER TABLE mytable ADD COLUMN mycol_tmp oid;
UPDATE mytable SET mycol_tmp = CAST(mycol as oid);
ALTER TABLE mytable DROP COLUMN mycol;
ALTER TABLE mytable RENAME mycol_tmp TO mycol;
But that just gives me the error:
ERROR: cannot cast type bytea to oid
Is there any way to achieve what I want?
To solve the problem, I successfully used blob_write procedure from Grace Batumbya's Blog: http://gbatumbya.wordpress.com/2011/06/.
A column of type Oid is just a reference to the binary contents which are actually stored in the system's pg_largeobject table. In terms of storage, an Oid a 4 byte integer. On the other hand, a column of type bytea is the actual contents.
To transfer a bytea into a large object, a new large object should be created with the file-like API of large objects: lo_create() to get a new OID, then lo_open() in write mode, then writes with lo_write() or lowrite(), and then lo_close().
This can't reasonably be done with just a cast.
Basically, you would need to write a ~10 lines piece of code in the language of your choice (at least one that supports the large object API, including plpgsql) to do this conversion.
I am sure its late, but for anybody having the same problem in future.
I also faced a similar issue where I had old data in the columns of text directly in the columns not as OIDs. And when I was trying to use that data with upgraded application I too was getting
I used the knowledge of this thread to solve this issue. I strongly feel that whoever stumbles upon this question would surely like to have a look at this here
I think the best answer can be found at Grace Batumbya's Blog, in verbis:
I've tried it and works like a charm.
Postgres 9.4 adds a built-in function for this:
From the release notes:
For older versions, this is more efficient than what has been posted before:
The
STRICT
modifier is smarter than handling NULL manually.SQL Fiddle.
More in this related answer: