|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +use Phenix\Database\Constants\Connection; |
| 6 | +use Phenix\Database\Constants\Driver; |
| 7 | +use Phenix\Database\Models\QueryBuilders\DatabaseQueryBuilder; |
| 8 | +use Phenix\Facades\Config; |
| 9 | +use Tests\Feature\Database\Models\User; |
| 10 | +use Tests\Mocks\Database\PostgresqlConnectionPool; |
| 11 | +use Tests\Mocks\Database\Result; |
| 12 | +use Tests\Mocks\Database\Statement; |
| 13 | + |
| 14 | +use function Pest\Faker\faker; |
| 15 | + |
| 16 | +it('saves a new model on postgresql using its mapped key column', function (): void { |
| 17 | + Config::set('database.default', Driver::POSTGRESQL->value); |
| 18 | + |
| 19 | + $capturedSql = ''; |
| 20 | + $connection = $this->getMockBuilder(PostgresqlConnectionPool::class)->getMock(); |
| 21 | + |
| 22 | + $connection->expects($this->once()) |
| 23 | + ->method('prepare') |
| 24 | + ->willReturnCallback(function (string $sql) use (&$capturedSql): Statement { |
| 25 | + $capturedSql = $sql; |
| 26 | + |
| 27 | + $result = new Result([['user_id' => 77]]); |
| 28 | + $result->setLastInsertedId(77); |
| 29 | + |
| 30 | + return new Statement($result); |
| 31 | + }); |
| 32 | + |
| 33 | + $this->app->swap(Connection::name(Driver::POSTGRESQL->value), $connection); |
| 34 | + |
| 35 | + $model = new User(); |
| 36 | + $model->setConnection(Driver::POSTGRESQL->value); |
| 37 | + $model->name = 'John Doe'; |
| 38 | + $model->email = faker()->email(); |
| 39 | + |
| 40 | + expect($model->save())->toBeTrue(); |
| 41 | + expect($model->id)->toBe(77); |
| 42 | + expect($model->isExisting())->toBeTrue(); |
| 43 | + expect($capturedSql)->toContain('RETURNING id'); |
| 44 | +}); |
| 45 | + |
| 46 | +it('creates a new model on postgresql using its mapped key column', function (): void { |
| 47 | + Config::set('database.default', Driver::POSTGRESQL->value); |
| 48 | + |
| 49 | + $capturedSql = ''; |
| 50 | + $connection = $this->getMockBuilder(PostgresqlConnectionPool::class)->getMock(); |
| 51 | + |
| 52 | + $connection->expects($this->once()) |
| 53 | + ->method('prepare') |
| 54 | + ->willReturnCallback(function (string $sql) use (&$capturedSql): Statement { |
| 55 | + $capturedSql = $sql; |
| 56 | + |
| 57 | + return new Statement(new Result([['user_id' => 88]])); |
| 58 | + }); |
| 59 | + |
| 60 | + $queryBuilder = new DatabaseQueryBuilder(); |
| 61 | + $queryBuilder->connection($connection); |
| 62 | + $queryBuilder->setModel(new User()); |
| 63 | + |
| 64 | + $model = $queryBuilder->create([ |
| 65 | + 'name' => 'Jane Doe', |
| 66 | + 'email' => faker()->email(), |
| 67 | + ]); |
| 68 | + |
| 69 | + expect($model->id)->toBe(88); |
| 70 | + expect($model->isExisting())->toBeTrue(); |
| 71 | + expect($capturedSql)->toContain('RETURNING id'); |
| 72 | +}); |
0 commit comments