Skip to content

Commit

Permalink
+ class UseCurrentXactIdAsConcurrencyTokenCommandInterceptor to fix…
Browse files Browse the repository at this point in the history
… `cannot retrieve a system column in this context` with partitioned table: npgsql/efcore.pg#1035 (comment) @ TbmDbContext.cs

$ mv Db/Entit{ies,y}WithImageId.cs
@ c#/shared
  • Loading branch information
n0099 committed May 18, 2024
1 parent 65c6bc7 commit 6870be0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
File renamed without changes.
34 changes: 34 additions & 0 deletions c#/shared/src/Db/TbmDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,39 @@ private sealed class NoSavePointTransaction(IRelationalConnection connection,
public override bool SupportsSavepoints => false;
}
}

/// <see>https://www.postgresql.org/message-id/flat/141051591267657%40mail.yandex.ru</see>
/// <see>https://dba.stackexchange.com/questions/123145/how-to-view-tuples-changed-in-a-postgresql-transaction/123183#123183</see>
/// <see>https://stackoverflow.com/questions/49214219/what-is-the-meaning-of-epoch-in-txid-current-in-postgresql</see>
/// <see>https://github.com/npgsql/efcore.pg/issues/1035#issuecomment-2118584744</see>
protected class UseCurrentXactIdAsConcurrencyTokenCommandInterceptor : DbCommandInterceptor
{
public static UseCurrentXactIdAsConcurrencyTokenCommandInterceptor Instance => new();

public override InterceptionResult<DbDataReader> ReaderExecuting(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result)
{
ManipulateCommand(command);
return result;
}

public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = default)
{
ManipulateCommand(command);
return new(result);
}

private static void ManipulateCommand(DbCommand command) =>
command.CommandText = command.CommandText.Replace(
"RETURNING xmin",
"RETURNING pg_current_xact_id()::xid");
}
}
public class TbmDbContext<TModelCacheKeyFactory>(ILogger<TbmDbContext<TModelCacheKeyFactory>> logger)
: TbmDbContext(logger)
Expand All @@ -113,6 +146,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder options)
options.UseNpgsql(GetNpgsqlDataSource(Config.GetConnectionString("Main")).Value, OnConfiguringNpgsql)
.ReplaceService<IModelCacheKeyFactory, TModelCacheKeyFactory>()
.ReplaceService<IRelationalTransactionFactory, NoSavePointTransactionFactory>()
.AddInterceptors(UseCurrentXactIdAsConcurrencyTokenCommandInterceptor.Instance)
.UseCamelCaseNamingConvention();

var dbSettings = Config.GetSection("DbSettings");
Expand Down

0 comments on commit 6870be0

Please sign in to comment.