nilportugues / sql-repository

[PHP 7] SQL Repository implementation
http://nilportugues.com
MIT License
36 stars 3 forks source link

Avoid calling lastInsertId on entity updates #23

Closed flavioheleno closed 7 years ago

flavioheleno commented 7 years ago

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;');
    }
}