Path: redb/redb.Postgres/Data/NpgsqlDataSourceFactory.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Postgres/Data/NpgsqlDataSourceFactory.cs
----
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Npgsql;
using redb.Core.Query;
namespace redb.Postgres.Data
{
///
/// Builds the every registration path uses, so the
/// redb.string_collation and redb.lazy_refs session settings are installed in one
/// place instead of six.
///
///
/// Why a GUC at all. The Free query path builds its SQL inside the database:
/// pvt_build_query_sql and the functions below it generate the text, and they take twelve
/// positional parameters with nowhere to put an option. Threading a thirteenth through five
/// layers would change every one of those signatures. A run-time setting reaches them without
/// touching a single signature, and pvt_fold_case() reads it with
/// current_setting('redb.string_collation', true), which yields NULL when unset. Unset
/// therefore means byte-for-byte the SQL that was generated before this feature existed. The
/// lazy-reference flag (V4, Л2) rides the same mechanism into the JSON builders.
///
///
///
/// Why on every hand-out, not in the physical-connection initializer. A session GUC set
/// with set_config(..., false) lives for the session - but Npgsql sends DISCARD ALL
/// when a connection returns to the pool, and RESET ALL inside it puts every session
/// setting back to its default. The physical-connection initializer runs once per backend, so
/// only the first scope on each pooled connection saw the settings; every later scope got a
/// connection with both GUCs empty (review, V4). The settings are therefore registered per data
/// source here and re-applied by each time it opens its
/// connection: one round trip per context, the same shape MSSQL and SQLite use.
///
///
public static class NpgsqlDataSourceFactory
{
private sealed record SessionSettings(string? Collation, bool LazyReferences);
// Weak by design: the data source owns its lifetime, the registry never keeps it alive.
private static readonly ConditionalWeakTable Registry = new();
///
/// The session settings registered for as text: part of the signature under which a
/// connection an ambient transaction holds is shared.
///
internal static string SessionSettingsText(NpgsqlDataSource dataSource)
=> Registry.TryGetValue(dataSource, out var settings)
? $"collation={settings.Collation};lazy_refs={(settings.LazyReferences ? 1 : 0)}"
: "collation=;lazy_refs=0";
///
/// Creates a data source. With null and
/// false this is
/// and nothing else.
///
public static NpgsqlDataSource Create(string connectionString, string? stringCollation, bool lazyReferences = false)
{
connectionString = WithJitOff(connectionString);
if (string.IsNullOrWhiteSpace(stringCollation) && !lazyReferences)
return NpgsqlDataSource.Create(connectionString);
// Validated before it can reach any SQL. It is also never interpolated: set_config
// takes the value as a bound parameter, so there is no text to escape here at all.
// (The in-database side does have to build an identifier, and quotes it there.)
if (stringCollation != null) CollationNameValidator.Validate(stringCollation);
var dataSource = NpgsqlDataSource.Create(connectionString);
Registry.Add(dataSource, new SessionSettings(stringCollation, lazyReferences));
return dataSource;
}
///
/// The connection string with -c jit=off added to its Options, unless the Options already
/// name jit, in which case the caller's choice stands.
///
/// PostgreSQL compiles a plan with JIT once its estimated cost passes jit_above_cost
/// (100 000 by default), and the estimate of a REDB query over a large scheme passes it easily,
/// also for a branch that never runs. The compilation costs tens of milliseconds on a query that
/// itself takes two: a page of 100 employees sorted by salary, 82 ms with JIT and 2.5 ms
/// without. The server takes the option when the connection opens, so it costs no round trip.
///
internal static string WithJitOff(string connectionString)
{
var builder = new NpgsqlConnectionStringBuilder(connectionString);
var options = builder.Options ?? string.Empty;
if (options.Contains("jit", StringComparison.OrdinalIgnoreCase))
return connectionString;
builder.Options = (options + " -c jit=off").Trim();
return builder.ConnectionString;
}
///
/// Re-applies the session settings registered for on a
/// connection it has just handed out. No-op for a data source created without settings.
///
public static Task ApplySessionSettingsAsync(NpgsqlDataSource dataSource, NpgsqlConnection connection)
{
if (!Registry.TryGetValue(dataSource, out var settings))
return Task.CompletedTask;
return ApplySettingsAsync(connection, settings.Collation, settings.LazyReferences);
}
private static async Task ApplySettingsAsync(NpgsqlConnection connection, string? collation, bool lazyReferences)
{
if (collation != null) await ApplyCollationAsync(connection, collation).ConfigureAwait(false);
if (lazyReferences) await ApplyLazyRefsAsync(connection).ConfigureAwait(false);
}
///
/// Synchronous for the thread-pool-free lazy path:
/// same settings, executed on the calling thread.
///
public static void ApplySessionSettings(NpgsqlDataSource dataSource, NpgsqlConnection connection)
{
if (!Registry.TryGetValue(dataSource, out var settings))
return;
if (settings.Collation != null)
{
using var cmd = CreateCommand(connection, settings.Collation);
cmd.ExecuteNonQuery();
}
if (settings.LazyReferences)
{
using var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT set_config('redb.lazy_refs', '1', false)";
cmd.ExecuteNonQuery();
}
}
private static async Task ApplyLazyRefsAsync(NpgsqlConnection connection)
{
await using var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT set_config('redb.lazy_refs', '1', false)";
await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
}
private static async Task ApplyCollationAsync(NpgsqlConnection connection, string collation)
{
await using var cmd = CreateCommand(connection, collation);
await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
}
///
/// set_config rather than SET: it is an ordinary function, so the value binds
/// as a parameter. SET takes a literal and would have to be built by concatenation.
/// The third argument false makes the setting session-wide rather than transaction-local.
///
private static NpgsqlCommand CreateCommand(NpgsqlConnection connection, string collation)
{
var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT set_config('redb.string_collation', $1, false)";
cmd.Parameters.Add(new NpgsqlParameter { Value = collation });
return cmd;
}
}
}