Permalink
Browse files

Selection: fixed insert spoiling PDO:lastInsertId (#217)

  • Loading branch information...
Stopka authored and dg committed Feb 8, 2019
1 parent 6af5cbf commit 2eb679f7f2e0fc1b7b186a02d29b29c631212b6e
Showing with 50 additions and 3 deletions.
  1. +4 −3 src/Database/Table/Selection.php
  2. +46 −0 tests/Database/Table/bugs/bug216.phpt
@@ -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])) {
@@ -0,0 +1,46 @@
<?php
/**
* Test: bug #216
* @dataProvider? ../databases.ini
*/
declare(strict_types=1);
use Tester\Assert;
require __DIR__ . '/../../../bootstrap.php';
//Prepare connection
$options = Tester\Environment::loadData() + ['user' => 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);

0 comments on commit 2eb679f

Please sign in to comment.