Skip to content

Core\Db\Connection::executeMany

$connection->executeMany(
    string $sql,
    array<array<mixed>> $sets,
    {timeout?: Core\Time\Duration},
): uint

Runs one statement once for every set of values, and says how many rows the whole batch wrote.

Core\Db\Connection::executeMany is the method for writing a group of rows with a single call. The first argument is the statement, written once. The second is an array of arrays: one inner array per run, each holding that run's values in the form Core\Db\Connection::execute takes. The result is a whole number, the sum of what every run changed. An empty second argument writes nothing and the result is 0.

Every set must bind the same number of values, because there is only one statement. Two sets that need a statement of a different length are two calls. The result has no id of a new row, and no rows. A batch has many runs, so no single run's id or rows can be returned.

A batch is not a transaction. Each run is separate, so a failure in the middle leaves the earlier writes in place. Wrap the call in Core\Db\Connection::runTransaction when you need all of it or none of it.

The examples write three rows, give each row its own new value, and import a list of records.

Parameters

  • $sqlstringThe statement, written once and bound once for each set. A tainted string does not compile here, as in execute. All sets use this one text.
  • $setsarray<array<mixed>>One $params array for each run, each with keys as execute needs them. All sets must bind the same number of values. A set whose inList has a different length is a different statement.

Options

  • timeoutCore\Time\DurationoptionalHow long this statement may take. The limit covers the whole statement: the prepare, the execution and every row of the result. When the time passes, the statement stops with an IOError. The connection cannot be used again, because it stopped in the middle of a message. Without it, the statement waits as long as the server takes.

Return value

Returns uint. The sum of the counts each run reported. A command that reports no count adds nothing. An empty $sets writes nothing and returns 0. Rows from a RETURNING clause are discarded. There is no lastId, because no single run owns it.

Errors

  • LogicErrorThe call is wrong, not the database. A set uses both list keys and string keys, two sets bind different numbers of values, or an element cannot be bound. A statement already streaming on this connection throws it too.
  • Core\Db\DbErrorThe server rejected one run, for example for a syntax error, a constraint or a permission. Each run is its own transaction, so the writes before the failed run stay. Use runTransaction to save all or nothing.
  • IOErrorThe connection failed while the batch was running, or timeout passed before it finished. The connection cannot be used for the rest of the request.

Examples

The examples below run with this configuration file.

nvs.toml
# The `notes` database is kept in memory. It is deleted when the program ends.
[db.notes]
driver = "sqlite"
path = ":memory:"
# The program may open the `notes` database.
[capabilities.db]
connect = ["notes"]

Write many rows with one statement

<?nvs
// Shows one statement running once for each set of values. The result is the
// number of rows the whole batch wrote.
var $db = Core\Db::connect('notes');
$db->execute('create table notes (id integer primary key, text text not null)', []);
// One array per row. Each inner array holds the values of one `?` in order.
array<array<mixed>> $rows = [
['buy milk'],
['call Ana'],
['book train'],
];
uint $written = $db->executeMany('insert into notes (text) values (?)', $rows);
// This prints `3 rows written`.
echo $written, " rows written\n";
$db->close();
Output
3 rows written

Give each row its own new value

<?nvs
// Shows a batch that changes rows. Each set gives one row its own new value,
// and the result adds up what all of the runs changed.
var $db = Core\Db::connect('notes');
$db->execute('create table prices (sku text primary key, cents int not null)', []);
$db->execute('insert into prices (sku, cents) values (?, ?)', ['apple', 100]);
$db->execute('insert into prices (sku, cents) values (?, ?)', ['bread', 250]);
$db->execute('insert into prices (sku, cents) values (?, ?)', ['cocoa', 480]);
// The first value of each set is the new price and the second is the row.
array<array<mixed>> $changes = [
[120, 'apple'],
[260, 'bread'],
];
uint $changed = $db->executeMany('update prices set cents = ? where sku = ?', $changes);
// This prints `2 prices changed`. The third row was in no set, so it is
// unchanged.
echo $changed, " prices changed\n";
$db->close();
Output
2 prices changed

Import a list of records

<?nvs
// Shows the import a program does after it reads a file: build one set per
// record, then write them all with a single call. A `:name` in the statement
// takes its value from the key of the same name. The order of the keys in a
// set does not matter.
var $db = Core\Db::connect('notes');
$db->execute('create table people (id integer primary key, name text not null, city text not null)', []);
// In a real import these come from a file or an upload.
array<array<mixed>> $records = [];
$records[] = ['name' => 'Ada', 'city' => 'Bremen'];
$records[] = ['city' => 'Porto', 'name' => 'Bo'];
$records[] = ['name' => 'Chen', 'city' => 'Aarhus'];
uint $imported = $db->executeMany(
'insert into people (name, city) values (:name, :city)',
$records,
);
// This prints `3 people imported`.
echo $imported, " people imported\n";
$db->close();
Output
3 people imported