You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
How do you do multiple inserts with npgsql (batch not serial) #2779
Which to me looks like its just doing a bunch of singular inserts collecting the results and returning (maybe I am wrong - if so my fault).
But yes I need to basically insert blocks of data which would be roughly equal to 500 rows per second (which is not a vast amount - but it creates significant overhead doing it in a singular loop), the postgresql peeps have told me to use batch inserts, I just cannot seem to see how to get them to work. Any help availible?
As an oddity I do not actually even care about the result as long as the query succeeds
@roji I spotted that but thought if you used the COPY api things like BIGSERIAL and such fields would not be triggered and auto incremented so I went down the path of doing:
NpgsqlConnectiondbh=newNpgsqlConnection(databaseDSN);// Connect to the correct databasesdbh.Open();// How many inserts should be bundled?intsqlBundleAmount=500;// Create buffers for bundling inserts togetherhttps://dpaste.org/peZGList<string>sqlBuffer=newList<string>();stringsqlCommand="INSERT INTO public.market_data(type, product, market, side, price, size) VALUES ";for(intiterator=0;iterator<sqlBundleAmount;iterator++){stringiteratorStr=iterator.ToString();sqlCommand+=string.Format("({0},{1},{2},{3},{4},{5})","@a"+iteratorStr,"@b"+iteratorStr,"@c"+iteratorStr,"@d"+iteratorStr,"@f"+iteratorStr,"@g"+iteratorStr);if(iterator+1!=sqlBundleAmount){sqlCommand+=",";}}
#pragma warning disable CA2100// Review SQL queries for security vulnerabilitiesNpgsqlCommandinsertBatch=newNpgsqlCommand(sqlCommand,dbh);
#pragma warning restore CA2100// Review SQL queries for security vulnerabilitiesfor(intiterator=0;iterator<sqlBundleAmount;iterator++){stringiteratorStr=iterator.ToString();insertBatch.Parameters.Add("a"+iteratorStr,NpgsqlDbType.Text);insertBatch.Parameters.Add("b"+iteratorStr,NpgsqlDbType.Text);insertBatch.Parameters.Add("c"+iteratorStr,NpgsqlDbType.Text);insertBatch.Parameters.Add("d"+iteratorStr,NpgsqlDbType.Text);insertBatch.Parameters.Add("f"+iteratorStr,NpgsqlDbType.Bigint);insertBatch.Parameters.Add("g"+iteratorStr,NpgsqlDbType.Bigint);}insertBatch.Prepare();for(intiterator=0;iterator<sqlBundleAmount;iterator++){stringiteratorStr=iterator.ToString();insertBatch.Parameters["a"+iteratorStr].Value="OPEN";insertBatch.Parameters["b"+iteratorStr].Value="BTC-USD";insertBatch.Parameters["c"+iteratorStr].Value="GDAX";insertBatch.Parameters["d"+iteratorStr].Value="MARKETSALE";insertBatch.Parameters["f"+iteratorStr].Value=27300000;insertBatch.Parameters["g"+iteratorStr].Value=10000000;}insertBatch.ExecuteNonQuery();
@roji I spotted that but thought if you used the COPY api things like BIGSERIAL and such fields would not be triggered and auto incremented so I went down the path of doing:
I'm almost 100% sure that COPY will properly handle SERIAL/IDENTITY columns - this is really a better way to do things than to batch insert statements. Did you try this out and run into an issue?
Did comparison of different insertion methods supported by PostgreSQL. As expected COPY wins. The second place holds INSERT INTO ... FROM unnest(...) which is fast enough to insert one or a few thousand rows. The third fastest way is batched INSERT used by Entity Framework, but it's limited by 32767 parameters or by a row count equals to 32767 divided by number of inserting columns.
A nice feature of unnest inserts is that you can do populate two tables, or update another, or get back values of some columns (for example identity) at the same time using a CTE, or do upsert:
Simple UPSERT
INSERT INTO data_table (id, name)
SELECT*FROM unnest(@i, @n)
ON CONFLICT ON data_table_pkey
DO UPDATESET name =EXCLUDED.name
UPSERT with INSERTion into a log table
WITH upd AS (
INSERT INTO data_table (id, name)
SELECT*FROM unnest(@i, @n)
ON CONFLICT ON data_table_pkey
DO UPDATESET name =EXCLUDED.name
RETURNING *
)
INSERT INTO data_table_log
SELECT*, current_timestampFROM upd
Benchmarks
[Config(typeof(Config))]publicclassInsert{protectedclassConfig:ManualConfig{publicConfig(){Add(StatisticColumn.OperationsPerSecond);Add(MemoryDiagnoser.Default);}}NpgsqlConnection_connection=default!;(intId,stringName)[]_records=default!;[Params(1,10,100,1_000,10_000,100_000)]publicintRecords{get;set;}=default!;[GlobalSetup]publicvoidGlobalSetup(){_connection=newNpgsqlConnection(newNpgsqlConnectionStringBuilder(BenchmarkEnvironment.ConnectionString){Pooling=false}.ToString());_connection.Open();using(varcommand=newNpgsqlCommand(connection:_connection,cmdText:"CREATE TEMP TABLE data_table (id INTEGER NOT NULL, name TEXT NOT NULL) ON COMMIT DELETE ROWS"))command.ExecuteNonQuery();_records=Enumerable.Range(0,Records).Select(i =>(i,$"My identifier is {i}")).ToArray();}[GlobalCleanup]publicvoidGlobalCleanup()=>_connection.Close();[Benchmark(Baseline=true)]publicasyncTaskInsertPlain(){vartransaction=_connection.BeginTransaction();usingvarcommand=newNpgsqlCommand(connection:_connection,cmdText:"INSERT INTO data_table (id, name) VALUES (@i, @n)");varid=newNpgsqlParameter<int>("i",default(int));varname=newNpgsqlParameter<string>("n",string.Empty);command.Parameters.Add(id);command.Parameters.Add(name);foreach(varelementin_records){id.TypedValue=element.Id;name.TypedValue=element.Name;awaitcommand.ExecuteNonQueryAsync();}awaittransaction.CommitAsync();}[Benchmark]publicasyncTaskInsertPrepared(){vartransaction=_connection.BeginTransaction();usingvarcommand=newNpgsqlCommand(connection:_connection,cmdText:"INSERT INTO data_table (id, name) VALUES (@i, @n)");varid=newNpgsqlParameter<int>("i",default(int));varname=newNpgsqlParameter<string>("n",string.Empty);command.Parameters.Add(id);command.Parameters.Add(name);awaitcommand.PrepareAsync();foreach(varelementin_records){id.TypedValue=element.Id;name.TypedValue=element.Name;awaitcommand.ExecuteNonQueryAsync();}awaittransaction.CommitAsync();}[Benchmark]publicasyncTaskInsertBatched(){usingvarcommand=newNpgsqlCommand(connection:_connection,cmdText:null);varsb=newStringBuilder("INSERT INTO data_table (id, name) VALUES ");for(vari=0;i<_records.Length;i++){if(i!=0)sb.Append(',');variName=(i*2+1).ToString();varnName=(i*2+2).ToString();sb.Append("(@").Append(iName).Append(", @").Append(nName).Append(')');command.Parameters.Add(newNpgsqlParameter<int>(iName,_records[i].Id));command.Parameters.Add(newNpgsqlParameter<string>(nName,_records[i].Name));}command.CommandText=sb.ToString();awaitcommand.ExecuteNonQueryAsync();}[Benchmark]publicasyncTaskInsertUnnest(){usingvarcommand=newNpgsqlCommand(connection:_connection,cmdText:"INSERT INTO data_table (id, name) SELECT * FROM unnest(@i, @n) AS d");command.Parameters.Add(newNpgsqlParameter<int[]>("i",_records.Select(e =>e.Id).ToArray()));command.Parameters.Add(newNpgsqlParameter<string[]>("n",_records.Select(e =>e.Name).ToArray()));awaitcommand.ExecuteNonQueryAsync();}[Benchmark]publicasyncTaskCopy(){usingvarimporter=_connection.BeginBinaryImport("COPY data_table (id, name) FROM STDIN (FORMAT binary)");foreach(varelementin_records){awaitimporter.StartRowAsync();awaitimporter.WriteAsync(element.Id);awaitimporter.WriteAsync(element.Name);}awaitimporter.CompleteAsync();}}
Reacted by Salih Hajlakovic, Bobby Driggs, Maxime Chambonnet, Alex Gausman, Brad Gardner, Valentas, caxepok, wenchin77, Greg Lindstrom, Ankurkh1 and 30 more
Reacted by Bobby Driggs, Maxime Chambonnet, Alex Gausman, Ezequiel Perez, caxepok, Julien Debache, Vladimir Aralin, Martin Dimitrov, Evgeny Morozov, kristianmo and 12 more
I wanted to use @YohDeadfall's benchmarks to justify moving from COPY to INSERT INTO ... FROM unnest ... but it was correctly pointed out to me that the performance characteristics of Postgres might have changed in more recent version.
Using Testcontainers to run the database locally with Docker, I got these results with the a few recent version:
The Postgres 16 Beta 1 notes mention the following about COPY: PostgreSQL 16 can also improve the performance of concurrent bulk loading of data using COPY up to 300%. It's a bit more complicated though, helpfully described on pganalyse (emphasis copied):
If you want to know whether there is a chance that you will benefit from this once Postgres 16 comes out: when you're doing these types of bulk loads with COPY watch out for the wait event of wait event type "lock" and then the lock wait event "extend".
I might do a bit more testing and I'll update accordingly.
Reacted by Shay Rojansky, Colin Aygalinc and Alexei
Activity
PaulGWebster commentedon Jan 6, 2020
oh I am using .NET Framework (as needs to be compatible with mono) not sure if it makes any difference
YohDeadfall commentedon Jan 6, 2020
Answered in #2511 (comment). You should pass values using an array and change the query to:
roji commentedon Jan 6, 2020
For inserting large amounts of rows it's generally best to use the bulk COPY API.
PaulGWebster commentedon Jan 6, 2020
@roji I spotted that but thought if you used the COPY api things like BIGSERIAL and such fields would not be triggered and auto incremented so I went down the path of doing:
PaulGWebster commentedon Jan 6, 2020
oh as an aside it might be nice adding: insertBatch.Parameters["c" + iteratorStr].Value = "GDAX"; in my case to the 'simple preperatio' example on:
http://www.npgsql.org/doc/prepare.html
roji commentedon Jan 6, 2020
I'm almost 100% sure that COPY will properly handle SERIAL/IDENTITY columns - this is really a better way to do things than to batch insert statements. Did you try this out and run into an issue?
YohDeadfall commentedon Jan 12, 2020
Did comparison of different insertion methods supported by PostgreSQL. As expected
COPYwins. The second place holdsINSERT INTO ... FROM unnest(...)which is fast enough to insert one or a few thousand rows. The third fastest way is batchedINSERTused by Entity Framework, but it's limited by 32767 parameters or by a row count equals to 32767 divided by number of inserting columns.A nice feature of
unnestinserts is that you can do populate two tables, or update another, or get back values of some columns (for example identity) at the same time using a CTE, or do upsert:Simple UPSERT
UPSERT with INSERTion into a log table
Benchmarks
Summary
kojo12228 commentedon Sep 30, 2023
I wanted to use @YohDeadfall's benchmarks to justify moving from
COPYtoINSERT INTO ... FROM unnest ...but it was correctly pointed out to me that the performance characteristics of Postgres might have changed in more recent version.Using Testcontainers to run the database locally with Docker, I got these results with the a few recent version:
Code in https://github.com/kojo12228/PostgresPerf.Net (mostly copy of @YohDeadfall but in F# and not using a temp table due to an issue I encountered).
The Postgres 16 Beta 1 notes mention the following about COPY: PostgreSQL 16 can also improve the performance of concurrent bulk loading of data using COPY up to 300%. It's a bit more complicated though, helpfully described on pganalyse (emphasis copied):
I might do a bit more testing and I'll update accordingly.