nilportugues / sql-repository

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

Invalid SQL generation on addAll() #21

Closed flavioheleno closed 7 years ago

flavioheleno commented 7 years ago

When calling addAll() with an array of new entities (i.e. no entity has an id set yet), addAll calls fetchExistingRows() with an empty id list, generating something like: SELECT id FROM table WHERE id IN () which is an invalid query on PostgreSQL, but works fine on SQLite - meaning that it cannot be caught by current unit tests.

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\CustomerRepository;
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 customers (
              customer_id SERIAL PRIMARY KEY,
              customer_name TEXT,
              total_orders INT,
              total_earnings FLOAT,
              created_at TIMESTAMP
            );
        ');
        $this->repository = new CustomerRepository($this->pdo, new SqliteCustomerMappingWithGeneratedId());
    }

    public function testAddAll()
    {
        $customers = [
            new Customer(
                null,
                'Customer 1',
                4,
                69158.687,
                new DateTime('2010-12-10')
            ),
            new Customer(
                null,
                'Customer 2',
                1,
                7123.88,
                new DateTime('2011-01-02')
            )
        ];
        $values = $this->repository->addAll($customers);

        $this->assertNotNull($this->repository->find(new CustomerId($values[0]->id())));
        $this->assertNotNull($this->repository->find(new CustomerId($values[1]->id())));
    }

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