Skip to content

Negative TimeSpan result when hours are 0 is converted to positive #518

@euantorano

Description

@euantorano

When running a query that returns a TimeSpan value, if the value is a negative value less than 1 hour, the timespan is converted into a positive.

For example, take the following query:

SELECT TIMEDIFF(DATE_SUB(NOW(), INTERVAL 5 MINUTE), NOW()) AS span;

The expected result would be: -00:05:00

Now, when running that query with the following code, the value is actually 00:05:00:

using (MySqlConnection connection = new MySqlConnection(connectionString))
{
    connection.Open();

    const string query = @"SELECT TIMEDIFF(DATE_SUB(NOW(), INTERVAL 5 MINUTE), NOW()) AS span;";

    using (MySqlCommand cmd = new MySqlCommand(query, connection))
    {
        object result = cmd.ExecuteScalar();

        if (result is TimeSpan ts)
        {
            Console.WriteLine($"Got timespan result: {ts}");
        }
        else
        {
            Console.WriteLine($"Got result of invalid type '{result.GetType().Name}': {result}");
        }
    }
}

I've tracked this issue down to the following line of code:

if (!Utf8Parser.TryParse(value, out int hours, out var bytesConsumed))

Looking at the source for Utf8Parser.TryParse, it looks like if the value is 0, the sign in front will be lost (eg: -0 becomes 0): https://github.com/dotnet/corefx/blob/master/src/System.Memory/src/System/Buffers/Text/Utf8Parser/Utf8Parser.Number.cs#L17

Looking at Utf8Parser.TryParse(ReadOnlySpan<byte> source, out TimeSpan value, out int bytesConsumed, char standardFormat = default)), they handle any sign at the start before parsing any further: https://github.com/dotnet/corefx/blob/master/src/System.Memory/src/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.BigG.cs#L28

I wonder if it's possible for MySqlConnector to simple use Utf8Parser.TryParse(ReadOnlySpan<byte> source, out TimeSpan value, out int bytesConsumed, char standardFormat = default))?

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions