Skip to content

Commit

Permalink
Optimizations to SQL queue length provider (#4327)
Browse files Browse the repository at this point in the history
* dont query star (#4317)

* avoid array alloc in sql UpdateChunk (#4318)

---------

Co-authored-by: Simon Cropp <simon.cropp@gmail.com>
  • Loading branch information
DavidBoike and SimonCropp authored Jul 22, 2024
1 parent 53dedaa commit 3caca15
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions src/ServiceControl.Transports.SqlServer/QueueLengthProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ async Task QueryTableSizes(CancellationToken cancellationToken)

async Task UpdateChunk(SqlConnection connection, KeyValuePair<SqlTable, int>[] chunk, CancellationToken cancellationToken)
{
var query = string.Join(Environment.NewLine, chunk.Select(c => BuildQueueLengthQuery(c.Key)).ToArray());
var query = string.Join(Environment.NewLine, chunk.Select(c => BuildQueueLengthQuery(c.Key)));

await using var command = new SqlCommand(query, connection);
await using var reader = await command.ExecuteReaderAsync(cancellationToken);
Expand Down Expand Up @@ -132,16 +132,20 @@ static string BuildQueueLengthQuery(SqlTable t)
// Min and Max values return NULL when no rows are found.
if (t.QuotedCatalog == null)
{
return $@"IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{t.UnquotedSchema}' AND TABLE_NAME = '{t.UnquotedName}'))
SELECT isnull(cast(max([RowVersion]) - min([RowVersion]) + 1 AS int), 0) FROM {t.QuotedSchema}.{t.QuotedName} WITH (nolock)
ELSE
SELECT -1;";
return $"""
IF (EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{t.UnquotedSchema}' AND TABLE_NAME = '{t.UnquotedName}'))
SELECT isnull(cast(max([RowVersion]) - min([RowVersion]) + 1 AS int), 0) FROM {t.QuotedSchema}.{t.QuotedName} WITH (nolock)
ELSE
SELECT -1;
""";
}

return $@"IF (EXISTS (SELECT * FROM {t.QuotedCatalog}.INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{t.UnquotedSchema}' AND TABLE_NAME = '{t.UnquotedName}'))
SELECT isnull(cast(max([RowVersion]) - min([RowVersion]) + 1 AS int), 0) FROM {t.QuotedCatalog}.{t.QuotedSchema}.{t.QuotedName} WITH (nolock)
ELSE
SELECT -1;";
return $"""
IF (EXISTS (SELECT TABLE_NAME FROM {t.QuotedCatalog}.INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{t.UnquotedSchema}' AND TABLE_NAME = '{t.UnquotedName}'))
SELECT isnull(cast(max([RowVersion]) - min([RowVersion]) + 1 AS int), 0) FROM {t.QuotedCatalog}.{t.QuotedSchema}.{t.QuotedName} WITH (nolock)
ELSE
SELECT -1;
""";
}

readonly ConcurrentDictionary<EndpointToQueueMapping, SqlTable> tableNames = new ConcurrentDictionary<EndpointToQueueMapping, SqlTable>();
Expand Down

0 comments on commit 3caca15

Please sign in to comment.