|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace ipl\Tests\Sql; |
| 4 | + |
| 5 | +use ipl\Sql\Connection; |
| 6 | +use ipl\Sql\Cursor; |
| 7 | +use ipl\Sql\Select; |
| 8 | +use PDO; |
| 9 | + |
| 10 | +class CursorTest extends \PHPUnit\Framework\TestCase |
| 11 | +{ |
| 12 | + public function testGetFetchMode() |
| 13 | + { |
| 14 | + $this->assertSame([], (new Cursor($this->getFixturesDb(), new Select()))->getFetchMode()); |
| 15 | + } |
| 16 | + |
| 17 | + public function testSetFetchMode() |
| 18 | + { |
| 19 | + $cursor = (new Cursor($this->getFixturesDb(), new Select())) |
| 20 | + ->setFetchMode(PDO::FETCH_COLUMN, 1); |
| 21 | + |
| 22 | + $this->assertSame([PDO::FETCH_COLUMN, 1], $cursor->getFetchMode()); |
| 23 | + } |
| 24 | + |
| 25 | + public function testWithoutSpecificFetchMode() |
| 26 | + { |
| 27 | + $db = $this->getFixturesDb(); |
| 28 | + |
| 29 | + $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); |
| 30 | + |
| 31 | + $cursor = new Cursor( |
| 32 | + $db, |
| 33 | + (new Select()) |
| 34 | + ->from('user') |
| 35 | + ->columns(['username', 'id']) |
| 36 | + ); |
| 37 | + |
| 38 | + $this->assertSame( |
| 39 | + [ |
| 40 | + [ |
| 41 | + 'username' => 'admin', |
| 42 | + 'id' => '1' |
| 43 | + ], |
| 44 | + [ |
| 45 | + 'username' => 'guest', |
| 46 | + 'id' => '2' |
| 47 | + ] |
| 48 | + ], |
| 49 | + iterator_to_array($cursor) |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + public function testFetchModeColumn() |
| 54 | + { |
| 55 | + $cursor = new Cursor( |
| 56 | + $this->getFixturesDb(), |
| 57 | + (new Select()) |
| 58 | + ->from('user') |
| 59 | + ->columns(['username', 'id']) |
| 60 | + ); |
| 61 | + |
| 62 | + $cursor->setFetchMode(PDO::FETCH_COLUMN); |
| 63 | + |
| 64 | + $this->assertSame(['admin', 'guest'], iterator_to_array($cursor)); |
| 65 | + } |
| 66 | + |
| 67 | + public function testFetchModeKeyPair() |
| 68 | + { |
| 69 | + $cursor = new Cursor( |
| 70 | + $this->getFixturesDb(), |
| 71 | + (new Select()) |
| 72 | + ->from('user') |
| 73 | + ->columns(['username', 'id', 'password']) |
| 74 | + ); |
| 75 | + |
| 76 | + $cursor->setFetchMode(PDO::FETCH_KEY_PAIR); |
| 77 | + |
| 78 | + $this->assertSame(['admin' => '1', 'guest' => '2'], iterator_to_array($cursor)); |
| 79 | + } |
| 80 | + |
| 81 | + protected function getFixturesDb() |
| 82 | + { |
| 83 | + $db = new Connection([ |
| 84 | + 'db' => 'sqlite', |
| 85 | + 'dbname' => ':memory:' |
| 86 | + ]); |
| 87 | + |
| 88 | + $fixtures = file_get_contents(__DIR__ . '/fixtures.sql'); |
| 89 | + |
| 90 | + $db->exec($fixtures); |
| 91 | + |
| 92 | + return $db; |
| 93 | + } |
| 94 | +} |
0 commit comments