1

I have the following table in PostgreSQL:

+------------+----------+                   
|   Column   |   Type   |
+------------+----------+
| name       | text     |
| keywords   | text[]   |
+------------+----------+

I'd like to insert a whole lot of rows in it, but I can't figure out how to insert data into an array field. Using BeginTextImport does not work since the TextWriter doesn't accept arrays:

using (var writer = connection.BeginTextImport(
  "COPY table (name, keywords) FROM STDIN DELIMITER ';'"
))
{     
    foreach (var item in items)
    {
        writer.Write(item.Name + ";");
        // How to do this?
        writer.Write(item.Keywords.ToArray(), NpgsqlDbType.Array | NpgsqlDbType.Text);
    }
}

Using BeginBinaryImport gives an error: "Can't close writer, a row is still in progress, end it first NpgSql".

using (var writer = connection.BeginBinaryImport(
  "COPY table (name, keywords) FROM STDIN (FORMAT BINARY)"
))
{     
    foreach (var item in items)
    {
        writer.StartRow();
        writer.Write(item.Name, NpgsqlDbType.Text);
        writer.Write(item.Keywords.ToArray(), NpgsqlDbType.Array | NpgsqlDbType.Text);
    }
}// Exception thrown here

How can we bulk copy data into an array field?

2
  • Text import is inappropriate for this case - it means you're responsible for formatting everything in PostgreSQL's text format (delimiters and all). Commented May 11, 2016 at 16:47
  • I just tried your binary code example and it works just fine - what version of Npgsql are you using exactly? What type exactly is your items list? Can you submit the full source code which reproduces the issue? Commented May 11, 2016 at 16:48

2 Answers 2

2

What about this? It references this library, which you could use (haven't used it myself so I can't comment on it).

If you don't want to take an additional dependency, you could at least look at what it does under the hood.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! The extra dependency is an issue indeed but based on how this library is implemented I noticed that I can better use BinairyImport. It is still not working (see my update) but i'm sure is a step towards a solution.
0

The error "Can't close writer, a row is still in progress, end it first NpgSql", is likely because the number of writer.Write items you use is less than the number of columns expected.

Comments

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.