Init Git
This commit is contained in:
35
AMREZ.EOP.Infrastructures/Tenancy/SearchPathInterceptor.cs
Normal file
35
AMREZ.EOP.Infrastructures/Tenancy/SearchPathInterceptor.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using System.Data.Common;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
|
||||
namespace AMREZ.EOP.Infrastructures.Tenancy;
|
||||
|
||||
public sealed class SearchPathInterceptor : DbConnectionInterceptor
|
||||
{
|
||||
private string _schema = "public";
|
||||
private bool _enabled;
|
||||
|
||||
public void Configure(string? schema, bool enabled)
|
||||
{
|
||||
_enabled = enabled;
|
||||
_schema = string.IsNullOrWhiteSpace(schema) ? "public" : schema.Trim();
|
||||
}
|
||||
|
||||
public override async Task ConnectionOpenedAsync(DbConnection connection, ConnectionEndEventData eventData, CancellationToken ct = default)
|
||||
{
|
||||
if (_enabled)
|
||||
{
|
||||
var schema = string.IsNullOrWhiteSpace(_schema) ? "public" : _schema.Replace("\"", "\"\"");
|
||||
await using (var cmd = connection.CreateCommand())
|
||||
{
|
||||
cmd.CommandText = $"CREATE SCHEMA IF NOT EXISTS \"{schema}\";";
|
||||
await cmd.ExecuteNonQueryAsync(ct);
|
||||
}
|
||||
await using (var cmd = connection.CreateCommand())
|
||||
{
|
||||
cmd.CommandText = $"SET LOCAL search_path TO \"{schema}\", pg_catalog;";
|
||||
await cmd.ExecuteNonQueryAsync(ct);
|
||||
}
|
||||
}
|
||||
await base.ConnectionOpenedAsync(connection, eventData, ct);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user