35 lines
1.2 KiB
C#
35 lines
1.2 KiB
C#
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);
|
|
}
|
|
} |