News in Nette Database 3.1

3 years ago by David Grudl  

With an elegant way of working with a transaction comes a new method transaction(). You pass in a callback that runs in the transaction. If any exception is thrown, the transaction is rolled back. If everything goes well, the transaction will be committed.

Method Connection::transaction() returns the value returned by the callback, so you can pass the insert id for example:

$id = $db->transaction(function ($db) {
	$db->query('DELETE FROM ...');
	$db->query('INSERT INTO ...');
	$id = $db->getInsertId();
	// ...
	return $id;

The transaction() can also be nested, which simplifies the implementation of independent entities. So the mentioned savePerson() method can look like this:

public function savePerson($data)
    $this->db->transaction(function () {


Because the name Database Explorer has been used for the part of library allowing easy object access to the database, the base class Nette\Database\Context changes its name to Nette\Database\Explorer. Furthermore, Nette gradually leaves the prefix I in the interface names, which also applies to the Database library.

Of course, the original names still work as aliases.

Other Changes

  • The SQL statement translator, which is the heart of the whole library, is a bit more careful and checks the inputs more.
  • MySqlDriver driver uses subqueries.
  • The minimum required version of PHP is 7.2.