Skip to content

Commit

Permalink
update queue length query for postgresql
Browse files Browse the repository at this point in the history
  • Loading branch information
tmasternak committed Oct 22, 2024
1 parent 7d38d15 commit 7eaeed2
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/ServiceControl.Transports.PostgreSql/PostgreSqlTable.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#nullable enable
#nullable enable
namespace ServiceControl.Transports.PostgreSql;

class PostgreSqlTable
Expand All @@ -7,13 +7,14 @@ public PostgreSqlTable(string name, string schema)
{
//HINT: The query approximates queue length value based on max and min of the table sequence.
fullTableName = $"\"{schema}\".\"{name}\"";
//NOTE: Postgres doesn't have NOLOCK since it utilises snapshot isolation by default
// As a result, we want to skip rows locked by other transactions with SKIP LOCKED query hint.
LengthQuery = $$"""
SELECT CASE WHEN (EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{{schema}}' AND TABLE_NAME = '{{name}}')) THEN
COALESCE(cast(max(seq) - min(seq) + 1 AS int), 0)
COALESCE(cast((SELECT seq FROM {{schema}}."{{name}}" ORDER BY seq DESC LIMIT 1 FOR UPDATE SKIP LOCKED)
- (SELECT seq FROM {{schema}}."{{name}}" ORDER BY seq ASC LIMIT 1 FOR UPDATE SKIP LOCKED) + 1 AS int), 0)
ELSE
-1
END AS Id FROM {{fullTableName}};
END;
""";
}

Expand Down

0 comments on commit 7eaeed2

Please sign in to comment.