@@ -324,6 +324,60 @@ public function test_fetch( $query, $mode, $expected ): void {
324324 }
325325 }
326326
327+ public function test_fetch_column (): void {
328+ $ query = "
329+ SELECT 1, 'abc', true
330+ UNION ALL
331+ SELECT 2, 'xyz', false
332+ UNION ALL
333+ SELECT 3, null, null
334+ " ;
335+
336+ // Fetch first column (default).
337+ $ stmt = $ this ->driver ->query ( $ query );
338+ $ this ->assertSame ( '1 ' , $ stmt ->fetchColumn () );
339+ $ this ->assertSame ( '2 ' , $ stmt ->fetchColumn () );
340+ $ this ->assertSame ( '3 ' , $ stmt ->fetchColumn () );
341+ $ this ->assertFalse ( $ stmt ->fetchColumn () );
342+
343+ // Fetch second column.
344+ $ stmt = $ this ->driver ->query ( $ query );
345+ $ this ->assertSame ( 'abc ' , $ stmt ->fetchColumn ( 1 ) );
346+ $ this ->assertSame ( 'xyz ' , $ stmt ->fetchColumn ( 1 ) );
347+ $ this ->assertNull ( $ stmt ->fetchColumn ( 1 ) );
348+ $ this ->assertFalse ( $ stmt ->fetchColumn ( 1 ) );
349+
350+ // Fetch third column.
351+ $ stmt = $ this ->driver ->query ( $ query );
352+ $ this ->assertSame ( '1 ' , $ stmt ->fetchColumn ( 2 ) );
353+ $ this ->assertSame ( '0 ' , $ stmt ->fetchColumn ( 2 ) );
354+ $ this ->assertNull ( $ stmt ->fetchColumn ( 2 ) );
355+ $ this ->assertFalse ( $ stmt ->fetchColumn ( 2 ) );
356+
357+ // Fetch different columns across rows.
358+ $ stmt = $ this ->driver ->query ( $ query );
359+ $ this ->assertSame ( '1 ' , $ stmt ->fetchColumn ( 0 ) );
360+ $ this ->assertSame ( 'xyz ' , $ stmt ->fetchColumn ( 1 ) );
361+ $ this ->assertNull ( $ stmt ->fetchColumn ( 2 ) );
362+ $ this ->assertFalse ( $ stmt ->fetchColumn () );
363+ }
364+
365+ public function test_fetch_column_invalid_index (): void {
366+ $ stmt = $ this ->driver ->query ( "SELECT 1, 'abc', true " );
367+
368+ $ this ->expectException ( ValueError::class );
369+ $ this ->expectExceptionMessage ( 'Invalid column index ' );
370+ $ stmt ->fetchColumn ( 3 );
371+ }
372+
373+ public function test_fetch_column_negative_index (): void {
374+ $ stmt = $ this ->driver ->query ( "SELECT 1, 'abc', true " );
375+
376+ $ this ->expectException ( ValueError::class );
377+ $ this ->expectExceptionMessage ( 'Column index must be greater than or equal to 0 ' );
378+ $ stmt ->fetchColumn ( -1 );
379+ }
380+
327381 public function test_attr_default_fetch_mode (): void {
328382 $ this ->driver ->setAttribute ( PDO ::ATTR_DEFAULT_FETCH_MODE , PDO ::FETCH_NUM );
329383 $ result = $ this ->driver ->query ( "SELECT 'a', 'b', 'c' " );
0 commit comments