Bulk upsert to PostgreSQL table
Posted: Wed 17 Oct 2018 20:20
Following up on this post: viewtopic.php?t=27986.
I need to bulk upsert to a PostgreSQL table that has a SERIAL "id" column. I am trying to use PgSqlDataTable like this:
The problem is that after each newItem is added to the table, I have to call itemsToUpdate.Update() or when I add the next newItem it will throw an exception because the PK is not unique (i.e. the "id" of each new row is null). Calling Update() refreshes the "id" field so the next newItem has a unique "id".
But calling Update() after each added item defeats my whole purpose, which is to do a bulk upsert.
How do I do this? Update the PgSqlDataTable rows for items that already exist and use a Loader for new items?
I need to bulk upsert to a PostgreSQL table that has a SERIAL "id" column. I am trying to use PgSqlDataTable like this:
Code: Select all
PgSqlCommand select = new PgSqlCommand();
select.CommandText = "select * from table ...";
PgSqlDataTable itemsToUpdate = new PgSqlDataTable( select, conn );
itemsToUpdate .FetchAll = true;
itemsToUpdate .Active = true;
itemsToUpdate .RefreshMode = Devart.Common.RefreshRowMode.Both;
itemsToUpdate .RefreshingFields = "id";
itemsToUpdate .Columns[ "id" ].AllowDBNull = true;
foreach( newOrUpdatedItem )
{
if( item is in itemsToUpdate )
update the item;
else
{
newItem = itemsToUpdate.NewRow();
set all values of item except "id";
itemsToUpdate.Rows.Add( newItem );
}
}
But calling Update() after each added item defeats my whole purpose, which is to do a bulk upsert.
How do I do this? Update the PgSqlDataTable rows for items that already exist and use a Loader for new items?