Skip to content

Commit 1cd0e61

Browse files
committed
Set MySqlCommand.CommandText to empty string by default. Fixes #743
1 parent 973f4bc commit 1cd0e61

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

src/MySqlConnector/MySql.Data.MySqlClient/MySqlCommand.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public MySqlCommand(string? commandText, MySqlConnection? connection, MySqlTrans
4040
{
4141
GC.SuppressFinalize(this);
4242
m_commandId = ICancellableCommandExtensions.GetNextId();
43-
CommandText = commandText;
43+
m_commandText = commandText ?? "";
4444
Connection = connection;
4545
Transaction = transaction;
4646
CommandType = CommandType.Text;
@@ -144,14 +144,15 @@ private bool NeedsPrepare(out Exception? exception)
144144
return Connection.Session.TryGetPreparedStatement(CommandText!) is null;
145145
}
146146

147-
public override string? CommandText
147+
[AllowNull]
148+
public override string CommandText
148149
{
149150
get => m_commandText;
150151
set
151152
{
152153
if (m_connection?.HasActiveReader ?? false)
153154
throw new InvalidOperationException("Cannot set MySqlCommand.CommandText when there is an open DataReader for this command; it must be closed first.");
154-
m_commandText = value;
155+
m_commandText = value ?? "";
155156
}
156157
}
157158

@@ -360,7 +361,7 @@ private bool IsValid([NotNullWhen(false)] out Exception? exception)
360361
readonly int m_commandId;
361362
bool m_isDisposed;
362363
MySqlConnection? m_connection;
363-
string? m_commandText;
364+
string m_commandText;
364365
MySqlParameterCollection? m_parameterCollection;
365366
int? m_commandTimeout;
366367
CommandType m_commandType;

tests/SideBySide/CommandTests.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,36 @@ public CommandTests(DatabaseFixture database)
1414
m_database = database;
1515
}
1616

17+
[Fact]
18+
public void CommandTextIsEmptyStringByDefault()
19+
{
20+
using var command = new MySqlCommand();
21+
Assert.Equal("", command.CommandText);
22+
}
23+
24+
[Fact]
25+
public void InitializeWithNullCommandText()
26+
{
27+
using var command = new MySqlCommand(default(string));
28+
Assert.Equal("", command.CommandText);
29+
}
30+
31+
[Fact]
32+
public void SetCommandTextToNull()
33+
{
34+
using var command = new MySqlCommand();
35+
command.CommandText = null;
36+
Assert.Equal("", command.CommandText);
37+
}
38+
39+
[Fact]
40+
public void SetCommandTextToEmptyString()
41+
{
42+
using var command = new MySqlCommand();
43+
command.CommandText = "";
44+
Assert.Equal("", command.CommandText);
45+
}
46+
1747
[Fact]
1848
public void CreateCommandSetsConnection()
1949
{

0 commit comments

Comments
 (0)