5

I know it's possible to insert into a large object from a PostgreSQL script using a lo_import():

INSERT INTO image (name, raster)
VALUES ('beautiful image', lo_import('/etc/motd'));

Te problem is, I'm trying to execute a script on a tightly locked up server, so I can't upload a file to it. Is it possible to insert a constant string into a large object without relying on an external file?

4
  • As long as the text in the file will fit inside of the field I don't think it will be an issue. Commented Mar 7, 2016 at 14:20
  • It's a large object, so the size won't be a problem; the question is: how do I store a string into a large object from inside a SQL script without pulling the contents from an external file? All examples I've found so far rely on an external file. Commented Mar 7, 2016 at 14:24
  • You can store up to 1 GB of text in a simple text or varchar field. Why do you need a actual large object (or bytea)? Commented Mar 7, 2016 at 15:43
  • It's a legacy issue... Commented Mar 7, 2016 at 16:08

1 Answer 1

7

If the value is less than a 1GB, you can do this:

INSERT INTO image (name, raster)
    VALUES ('beautiful image', lo_from_bytea(0,$1));

The bytea type is a bit annoying. You may have to resort to driver-specific shenanigans to make the driver/client library understand that $1 is of type bytea. For example in with Perl's DBD::Pg, you have to prepare the statement and then do something like:

$insert->bind_param(1, $blob, { pg_type => PG_BYTEA });
Sign up to request clarification or add additional context in comments.

3 Comments

Mmm... interesting... so if I wanted to store some large text into a large object, maybe I could do something like: INSERT INTO something (name, raster) VALUES ('some name', lo_from_bytea(0,'some really long text'::bytea))
Yes. I think it will even do the cast to bytea for you if you omit it.
@jjanes Yes, it does. Just tested it on PostgreSQL 9.6.5 and it works without the cast.

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.