Search code examples
npgsql

Batching separate prepared npgsql commands


Say you have three prepared NpgsqlCommands. Because they must be executed separatedly. But sometimes two or all three must be executed at once (well, one after the other).

Is there a way to batch and reuse these previously prepared commands using a single roundtrip to the server? (goal is to minimize latency)

Now I use a fourth command and semicolon separate a copy of the original three commands, and prepare this -- but I assume this will use more resources at the server, and more SQL parsing at the npgsql client.


Solution

  • Npgsql supports batching through including several statements in your CommandText, separated by semicolons. These are executed in a single network roundtrip, and can also be prepared:

    cmd.CommandText = "SELECT ...; UPDATE ...";
    cmd.Prepare();
    

    Internally, Npgsql splits such commands on semicolons and prepares each statement separately (PostgreSQL does not actually recognize batches, only individual statements). In addition, Npgsql manages prepared statements on a statement-by-statement level, and knows to reuse already-existing statements. This means that if you prepare two commands which contain the same statements, those statements will share the same server-side prepared statement resource.