diff --git a/src/Database/Table/Selection.php b/src/Database/Table/Selection.php index fb252ee30..fa8e68956 100644 --- a/src/Database/Table/Selection.php +++ b/src/Database/Table/Selection.php @@ -739,6 +739,10 @@ protected function refreshData(): void */ public function insert(iterable $data) { + //should be called before query for not to spoil PDO::lastInsertId + $primarySequenceName = $this->getPrimarySequence(); + $primaryAutoincrementKey = $this->context->getStructure()->getPrimaryAutoincrementKey($this->name); + if ($data instanceof self) { $return = $this->context->queryArgs($this->sqlBuilder->buildInsertQuery() . ' ' . $data->getSql(), $data->getSqlBuilder()->getParameters()); @@ -756,9 +760,6 @@ public function insert(iterable $data) return $return->getRowCount(); } - $primarySequenceName = $this->getPrimarySequence(); - $primaryAutoincrementKey = $this->context->getStructure()->getPrimaryAutoincrementKey($this->name); - $primaryKey = []; foreach ((array) $this->primary as $key) { if (isset($data[$key])) { diff --git a/tests/Database/Table/bugs/bug216.phpt b/tests/Database/Table/bugs/bug216.phpt new file mode 100644 index 000000000..69eb6e1fa --- /dev/null +++ b/tests/Database/Table/bugs/bug216.phpt @@ -0,0 +1,46 @@ + null, 'password' => null]; + +try { + $connection = new Nette\Database\Connection($options['dsn'], $options['user'], $options['password']); +} catch (PDOException $e) { + Tester\Environment::skip("Connection to '$options[dsn]' failed. Reason: " . $e->getMessage()); +} + +if (strpos($options['dsn'], 'sqlite::memory:') === false) { + Tester\Environment::lock($options['dsn'], TEMP_DIR); +} + +$driverName = $connection->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME); +$cacheMemoryStorage = new Nette\Caching\Storages\MemoryStorage; + +$structure = new Nette\Database\Structure($connection, $cacheMemoryStorage); +$conventions = new Nette\Database\Conventions\StaticConventions(); +$context = new Nette\Database\Context($connection, $structure, $conventions, $cacheMemoryStorage); + +//Testing +Nette\Database\Helpers::loadFromFile($connection, __DIR__ . "/../files/{$driverName}-nette_test1.sql"); + +$book = $context->table('author')->insert([ + 'name' => $context->literal('LOWER(?)', 'Eddard Stark'), + 'web' => 'http://example.com', + 'born' => new \DateTime('2011-11-11'), +]); // INSERT INTO `author` (`name`, `web`) VALUES (LOWER('Eddard Stark'), 'http://example.com', '2011-11-11 00:00:00') +// id = 14 + +Assert::type(Nette\Database\Table\ActiveRow::class, $book); +Assert::equal('eddard stark', $book->name); +Assert::equal(new Nette\Utils\DateTime('2011-11-11'), $book->born);