Skip to content

Commit 2fe3e71

Browse files
committed
Fix return value of ExecuteScalar.
It must return the first column of the first row of the first result set.
1 parent b0436e6 commit 2fe3e71

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

src/MySqlConnector/Core/TextCommandExecutor.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,19 @@ public virtual async Task<int> ExecuteNonQueryAsync(string commandText, MySqlPar
3737
public virtual async Task<object> ExecuteScalarAsync(string commandText, MySqlParameterCollection parameterCollection,
3838
IOBehavior ioBehavior, CancellationToken cancellationToken)
3939
{
40+
var hasSetResult = false;
4041
object result = null;
4142
using (var reader = (MySqlDataReader) await ExecuteReaderAsync(commandText, parameterCollection, CommandBehavior.SingleResult | CommandBehavior.SingleRow, ioBehavior, cancellationToken).ConfigureAwait(false))
4243
{
4344
do
4445
{
45-
if (await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false))
46-
result = reader.GetValue(0);
46+
var hasResult = await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
47+
if (!hasSetResult)
48+
{
49+
if (hasResult)
50+
result = reader.GetValue(0);
51+
hasSetResult = true;
52+
}
4753
} while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false));
4854
}
4955
return result;

tests/SideBySide/QueryTests.cs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,40 @@ id bigint(20) not null primary key
498498
}
499499
}
500500

501+
[Fact]
502+
public void ExecuteScalarReturnsFirstValue()
503+
{
504+
var result = m_database.Connection.ExecuteScalar("select 1; select 2;");
505+
Assert.Equal(1L, result);
506+
}
507+
508+
[Fact]
509+
public async Task ExecuteScalarAsyncReturnsFirstValue()
510+
{
511+
var result = await m_database.Connection.ExecuteScalarAsync("select 1; select 2;");
512+
Assert.Equal(1L, result);
513+
}
514+
515+
[Fact]
516+
public void ExecuteScalarReturnsNull()
517+
{
518+
m_database.Connection.Execute(@"drop table if exists empty_table;
519+
create table empty_table(id bigint not null primary key);");
520+
var result = m_database.Connection.ExecuteScalar("select * from empty_table; select 2;");
521+
Assert.Null(result);
522+
}
523+
524+
[Fact]
525+
public void ExecuteScalarReturnsDBNull()
526+
{
527+
using (var command = m_database.Connection.CreateCommand())
528+
{
529+
command.CommandText = "select null; select 2;";
530+
var result = command.ExecuteScalar();
531+
Assert.Equal(DBNull.Value, result);
532+
}
533+
}
534+
501535
[Fact]
502536
public void SumBytes()
503537
{

0 commit comments

Comments
 (0)