stablekernel / postgresql-dart

Dart PostgreSQL driver: supports extended query format, binary protocol and statement reuse.
https://www.dartdocs.org/documentation/postgres/latest
BSD 3-Clause "New" or "Revised" License
129 stars 32 forks source link

execute.many #128

Closed agavrel closed 4 years ago

agavrel commented 4 years ago

Is there an equivalent of this python function in order to perform multiple insert at once in the database?

isoos commented 4 years ago

Option 1

You can insert more rows in a single insert:

await conn.execute(
    'INSERT INTO tbl VALUES (@a1, @b1, @c1), (@a2, @b2, @c2)',
    substituteValues: {[... map with a1, b1, c1, a2, b2, c2 ...] });

Option 2

You can send commands without awaiting them separately, but probably should wait for them eventually:

final futures = <Future>[];
futures.add(conn.execute(query, {[... values ...]}));
futures.add(conn.execute(query, {[... values ...]}));
futures.add(conn.execute(query, {[... values ...]}));
await Future.wait(futures);

Option 3

You can use the above in a different way:

final query = 'INSERT INTO ...';
final values = [{[... first row data ...]}, {... second row data...}];
await Future.wait(values.map((v) => conn.execute(query, substititeValues: v)));

Note: using package:postgres_pool with configurable concurrency may be a better choice for this. It may use different connections for the inserts, and you can still control the overall connections being used.

agavrel commented 4 years ago

Thank you very much, I will go for option2 as I don't want more connections.

To understand a bit better, what is the difference between execute and query methods :

connection.execute(sqlQuery, substitutionValues: substitutionValues)

and

connection.query(sqlQuery, substitutionValues: substitutionValues);
isoos commented 4 years ago

execute is for modifications (DDL, insert, update, delete), while query is for selects.

agavrel commented 4 years ago

Thank you and sorry for the rookie question!