Skip to content

Avoid calling lastInsertId on entity updates - #23

Merged
nilportugues merged 2 commits into
nilportugues:masterfrom
flavioheleno:master
Mar 13, 2017
Merged

Avoid calling lastInsertId on entity updates#23
nilportugues merged 2 commits into
nilportugues:masterfrom
flavioheleno:master

Conversation

@flavioheleno

Copy link
Copy Markdown
Contributor

Calling add() with a previously existent entity (i.e. with an id set), leads to a call to updateQuery() and a subsequent call to lastInsertId() that fails on PostgreSQL as no id has been created by the update.

The test passes on SQLite with or without the changes.

Test script:

<?php

namespace NilPortugues\Tests\Foundation\Infrastructure\Model\Repository\Sql;

use PDO;
use DateTime;
use NilPortugues\Tests\Foundation\Customer;
use NilPortugues\Tests\Foundation\CustomerId;
use NilPortugues\Tests\Foundation\SqliteCustomerMappingWithCustomId;
use NilPortugues\Tests\Foundation\CustomerRepository;
use NilPortugues\Tests\Foundation\PDOProvider;
use NilPortugues\Tests\Foundation\SqliteCustomerMappingWithGeneratedId;

class SqlRepositoryTestAutoGeneratedId extends \PHPUnit_Framework_TestCase
{
    /** @var \PDO */
    private $pdo;
    /** @var CustomerRepository */
    private $repository;

    public function setUp()
    {
        $this->pdo = new PDO('pgsql:host=localhost;port=5432;dbname=testdb', 'test', 'test');
        $this->pdo->exec('
            CREATE TABLE IF NOT EXISTS customers (
              customer_id SERIAL PRIMARY KEY,
              customer_name TEXT,
              total_orders INT,
              total_earnings FLOAT,
              created_at TIMESTAMP
            );
        ');
        $this->pdo->exec('INSERT INTO customers ("customer_name", "created_at", "total_orders", "total_earnings") VALUES(\'John Doe\', \'2014-12-11\', 3, 25.125);');
        unset($this->pdo); // forces a new connection/session to be established
        $this->pdo = new PDO('pgsql:host=localhost;port=5432;dbname=testdb', 'test', 'test');
        $this->repository = new CustomerRepository($this->pdo, new SqliteCustomerMappingWithGeneratedId());
    }

    public function testAddAll()
    {
        $customer = new Customer(
            1,
            'John Doe',
            4,
            35.125,
            new DateTime('2014-12-11')
        );

        $value = $this->repository->add($customer);

        $this->assertNotNull($this->repository->find(new CustomerId($value->id())));
    }

    public function tearDown()
    {
        $this->pdo->exec('DROP TABLE customers;');
    }
}

@nilportugues
nilportugues merged commit 7ddddbc into nilportugues:master Mar 13, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants