2

I know you can run a copy command like this from a file:

"COPY zip_codes FROM '/path/to/csv/ZIP_CODES.txt' DELIMITER ',' CSV;"

I'd like to copy csv data from a ruby variable so I can do like so

"COPY zip_codes FROM '#{csv_data}' DELIMITER ',' CSV;"
2
  • I believe nobody understood your question, if it is a question.
    – MurifoX
    Commented Jun 7, 2013 at 19:19
  • I edited it to make it clearer
    – bobarillo
    Commented Jun 7, 2013 at 19:27

1 Answer 1

4

That's not possible with the SQL COPY command. COPY only copies from a file or STDIN.

You can either write the content of the variable to a file or pipe it via STDIN. Only makes sense for more than a couple of rows.


I think I misunderstood your question before the update, you probably don't need this:

The file path can not be exchanged like other data items, and you can't use a prepared statement for that. Build the whole statement before executing or resort to dynamic SQL with a server-side function like:

CREATE OR REPLACE FUNCTION f_cp(_file text)
  RETURNS void AS
$BODY$
BEGIN
EXECUTE format($$COPY zip_codes FROM %L DELIMITER ',' CSV$$, $1);
END
$BODY$
  LANGUAGE plpgsql;

Call:

SELECT f_cp('/var/lib/postgres/sync/myfile.csv')

format() requires Postgres 9.1 or later.

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.