Skip to content

Core\Db\Transaction::executeMany

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

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

Core\Db\Transaction::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\Transaction::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 difference from Core\Db\Connection::executeMany is what happens when a run in the middle fails. On the connection, the runs before it stay in the database. Here the transaction gives up, so the whole batch is removed again, together with everything else the transaction wrote.

The examples write three rows, show a batch that is removed again, and import a list of records under a row that describes the import.

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 inside a transaction

<?nvs
// Shows one statement running once for each set of values, inside a
// transaction. 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->runTransaction(fn(Core\Db\Transaction $tx): uint =>
$tx->executeMany('insert into notes (text) values (?)', $rows));
// This prints `3 rows written`.
echo $written, " rows written\n";
$db->close();
Output
3 rows written

All of the batch or none of it

<?nvs
// Shows a batch that is removed again. One run of the batch fails, so the
// transaction gives up. The rows the runs before it wrote are removed too.
var $db = Core\Db::connect('notes');
$db->execute('create table people (id integer primary key, name text not null unique)', []);
$db->execute('insert into people (name) values (?)', ['Ada']);
// The second set carries a name the table already has.
array<array<mixed>> $rows = [
['Bo'],
['Ada'],
['Chen'],
];
try {
$db->runTransaction(fn(Core\Db\Transaction $tx): uint =>
$tx->executeMany('insert into people (name) values (?)', $rows));
} catch (Core\Db\DbError $refused) {
// This prints `the batch stopped`.
echo "the batch stopped\n";
}
// `Bo` was written before the second run failed, and is gone again. Only the
// row from before the transaction is left, so this prints `1 person`.
echo $db->query('select id from people', [])->count(), " person\n";
$db->close();
Output
the batch stopped
1 person

Import a list of records under one row

<?nvs
// Shows the import a program does after it reads a file. The import gets a row
// of its own, and every record points at it. All of it is written together, so
// a half-finished import cannot be left behind.
var $db = Core\Db::connect('notes');
$db->execute('create table imports (id integer primary key, source text not null)', []);
$db->execute('create table people (id integer primary key, importId integer not null, name text not null)', []);
// In a real import these come from a file or an upload.
array<string> $names = ['Ada', 'Bo', 'Chen'];
uint $imported = $db->runTransaction(fn(Core\Db\Transaction $tx): uint => {
var $import = $tx->execute('insert into imports (source) values (?)', ['people.csv']);
var $importId = $import->lastId() ?? 0;
// One set per record. A `:name` in the statement takes its value from the
// key of the same name.
array<array<mixed>> $rows = [];
foreach ($names as string $name) {
$rows[] = ['importId' => $importId, 'name' => $name];
}
return $tx->executeMany('insert into people (importId, name) values (:importId, :name)', $rows);
});
// This prints `3 people imported`.
echo $imported, " people imported\n";
$db->close();
Output
3 people imported