Table of Contents

Class NpgsqlSlimDataSourceBuilder

Namespace
Npgsql
Assembly
Npgsql.dll

Provides a simple API for configuring and creating an NpgsqlDataSource, from which database connections can be obtained.

public sealed class NpgsqlSlimDataSourceBuilder : INpgsqlTypeMapper
Inheritance
NpgsqlSlimDataSourceBuilder
Implements
Inherited Members

Remarks

On this builder, various features are disabled by default; unless you're looking to save on code size (e.g. when publishing with NativeAOT), use NpgsqlDataSourceBuilder instead.

Constructors

NpgsqlSlimDataSourceBuilder(string?)

Constructs a new NpgsqlSlimDataSourceBuilder, optionally starting out from the given connectionString.

public NpgsqlSlimDataSourceBuilder(string? connectionString = null)

Parameters

connectionString string

Properties

ConnectionString

Returns the connection string, as currently configured on the builder.

public string ConnectionString { get; }

Property Value

string

ConnectionStringBuilder

A connection string builder that can be used to configured the connection string on the builder.

public NpgsqlConnectionStringBuilder ConnectionStringBuilder { get; }

Property Value

NpgsqlConnectionStringBuilder

DefaultNameTranslator

The default name translator to convert CLR type names and member names. Defaults to NpgsqlSnakeCaseNameTranslator.

public INpgsqlNameTranslator DefaultNameTranslator { get; set; }

Property Value

INpgsqlNameTranslator

Name

A diagnostics name used by Npgsql when generating tracing, logging and metrics.

public string? Name { get; set; }

Property Value

string

Methods

AddTypeInfoResolverFactory(PgTypeInfoResolverFactory)

Adds a type info resolver factory which can add or modify support for PostgreSQL types. Typically used by plugins.

public void AddTypeInfoResolverFactory(PgTypeInfoResolverFactory factory)

Parameters

factory PgTypeInfoResolverFactory

The type resolver factory to be added.

Build()

Builds and returns an NpgsqlDataSource which is ready for use.

public NpgsqlDataSource Build()

Returns

NpgsqlDataSource

BuildMultiHost()

Builds and returns a NpgsqlMultiHostDataSource which is ready for use for load-balancing and failover scenarios.

public NpgsqlMultiHostDataSource BuildMultiHost()

Returns

NpgsqlMultiHostDataSource

ConfigureJsonOptions(JsonSerializerOptions)

Configures the JSON serializer options used when reading and writing all System.Text.Json data.

public NpgsqlSlimDataSourceBuilder ConfigureJsonOptions(JsonSerializerOptions serializerOptions)

Parameters

serializerOptions JsonSerializerOptions

Options to customize JSON serialization and deserialization.

Returns

NpgsqlSlimDataSourceBuilder

EnableArrays()

Sets up mappings for the PostgreSQL array types.

public NpgsqlSlimDataSourceBuilder EnableArrays()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableDynamicJson(Type[]?, Type[]?)

Sets up dynamic System.Text.Json mappings. This allows mapping arbitrary .NET types to PostgreSQL json and jsonb types, as well as JsonNode and its derived types.

public NpgsqlSlimDataSourceBuilder EnableDynamicJson(Type[]? jsonbClrTypes = null, Type[]? jsonClrTypes = null)

Parameters

jsonbClrTypes Type[]

A list of CLR types to map to PostgreSQL jsonb (no need to specify Jsonb).

jsonClrTypes Type[]

A list of CLR types to map to PostgreSQL json (no need to specify Json).

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

Remarks

Due to the dynamic nature of these mappings, they are not compatible with NativeAOT or trimming.

EnableExtraConversions()

Sets up mappings for extra conversions from PostgreSQL to .NET types.

public NpgsqlSlimDataSourceBuilder EnableExtraConversions()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableFullTextSearch()

Sets up mappings for the PostgreSQL tsquery and tsvector types.

public NpgsqlSlimDataSourceBuilder EnableFullTextSearch()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableGeometricTypes()

Sets up network mappings. This allows mapping types like NpgsqlPoint and NpgsqlPath to PostgreSQL point, path and so on types.

public NpgsqlSlimDataSourceBuilder EnableGeometricTypes()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableIntegratedSecurity()

Enables the possibility to use GSS/SSPI authentication for connections to PostgreSQL. This does not guarantee that it will actually be used; see https://www.npgsql.org/doc/security.html for more details.

public NpgsqlSlimDataSourceBuilder EnableIntegratedSecurity()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableJsonTypes()

Sets up System.Text.Json mappings. This allows mapping JsonDocument and JsonElement types to PostgreSQL json and jsonb types.

public NpgsqlSlimDataSourceBuilder EnableJsonTypes()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableLTree()

Sets up mappings for the PostgreSQL ltree extension types.

public NpgsqlSlimDataSourceBuilder EnableLTree()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableMultiranges()

Sets up mappings for the PostgreSQL multirange types.

public NpgsqlSlimDataSourceBuilder EnableMultiranges()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableNetworkTypes()

Sets up network mappings. This allows mapping PhysicalAddress, IPAddress, NpgsqlInet and NpgsqlCidr types to PostgreSQL macaddr, macaddr8, inet and cidr types.

public NpgsqlSlimDataSourceBuilder EnableNetworkTypes()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableParameterLogging(bool)

Enables parameters to be included in logging. This includes potentially sensitive information from data sent to PostgreSQL. You should only enable this flag in development, or if you have the appropriate security measures in place based on the sensitivity of this data.

public NpgsqlSlimDataSourceBuilder EnableParameterLogging(bool parameterLoggingEnabled = true)

Parameters

parameterLoggingEnabled bool

If true, then sensitive data is logged.

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableRanges()

Sets up mappings for the PostgreSQL range types.

public NpgsqlSlimDataSourceBuilder EnableRanges()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableRecords()

Sets up mappings for the PostgreSQL record type as a .NET object[].

public NpgsqlSlimDataSourceBuilder EnableRecords()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableRecordsAsTuples()

Sets up mappings for the PostgreSQL record type as a .NET ValueTuple or Tuple.

public NpgsqlSlimDataSourceBuilder EnableRecordsAsTuples()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableTransportSecurity()

Enables the possibility to use TLS/SSl encryption for connections to PostgreSQL. This does not guarantee that encryption will actually be used; see https://www.npgsql.org/doc/security.html for more details.

public NpgsqlSlimDataSourceBuilder EnableTransportSecurity()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

EnableUnmappedTypes()

Sets up mappings allowing the use of unmapped enum, range and multirange types.

public NpgsqlSlimDataSourceBuilder EnableUnmappedTypes()

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

MapComposite(Type, string?, INpgsqlNameTranslator?)

Maps a CLR type to a composite type.

public INpgsqlTypeMapper MapComposite(Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)

Parameters

clrType Type

The .NET type to be mapped.

pgName string

A PostgreSQL type name for the corresponding composite type in the database. If null, the name translator given in nameTranslator will be used.

nameTranslator INpgsqlNameTranslator

A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

Returns

INpgsqlTypeMapper

Remarks

Maps CLR fields and properties by string to PostgreSQL names. The translation strategy can be controlled by the nameTranslator parameter, which defaults to DefaultNameTranslator. If there is a discrepancy between the .NET type and database type while a composite is read or written, an exception will be raised.

MapComposite<T>(string?, INpgsqlNameTranslator?)

Maps a CLR type to a PostgreSQL composite type.

public INpgsqlTypeMapper MapComposite<T>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)

Parameters

pgName string

A PostgreSQL type name for the corresponding composite type in the database. If null, the name translator given in nameTranslator will be used.

nameTranslator INpgsqlNameTranslator

A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

Returns

INpgsqlTypeMapper

Type Parameters

T

The .NET type to be mapped

Remarks

CLR fields and properties by string to PostgreSQL names. The translation strategy can be controlled by the nameTranslator parameter, which defaults to NpgsqlSnakeCaseNameTranslator. You can also use the PgNameAttribute on your members to manually specify a PostgreSQL name. If there is a discrepancy between the .NET type and database type while a composite is read or written, an exception will be raised.

MapEnum(Type, string?, INpgsqlNameTranslator?)

Maps a CLR enum to a PostgreSQL enum type.

public INpgsqlTypeMapper MapEnum(Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)

Parameters

clrType Type

The .NET enum type to be mapped

pgName string

A PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in nameTranslator will be used.

nameTranslator INpgsqlNameTranslator

A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

Returns

INpgsqlTypeMapper

Remarks

CLR enum labels are mapped by name to PostgreSQL enum labels. The translation strategy can be controlled by the nameTranslator parameter, which defaults to NpgsqlSnakeCaseNameTranslator. You can also use the PgNameAttribute on your enum fields to manually specify a PostgreSQL enum label. If there is a discrepancy between the .NET and database labels while an enum is read or written, an exception will be raised.

MapEnum<TEnum>(string?, INpgsqlNameTranslator?)

Maps a CLR enum to a PostgreSQL enum type.

public INpgsqlTypeMapper MapEnum<TEnum>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null) where TEnum : struct, Enum

Parameters

pgName string

A PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in nameTranslator will be used.

nameTranslator INpgsqlNameTranslator

A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

Returns

INpgsqlTypeMapper

Type Parameters

TEnum

The .NET enum type to be mapped

Remarks

CLR enum labels are mapped by name to PostgreSQL enum labels. The translation strategy can be controlled by the nameTranslator parameter, which defaults to NpgsqlSnakeCaseNameTranslator. You can also use the PgNameAttribute on your enum fields to manually specify a PostgreSQL enum label. If there is a discrepancy between the .NET and database labels while an enum is read or written, an exception will be raised.

UnmapComposite(Type, string?, INpgsqlNameTranslator?)

Removes an existing composite mapping.

public bool UnmapComposite(Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)

Parameters

clrType Type

The .NET type to be unmapped.

pgName string

A PostgreSQL type name for the corresponding composite type in the database. If null, the name translator given in nameTranslator will be used.

nameTranslator INpgsqlNameTranslator

A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

Returns

bool

UnmapComposite<T>(string?, INpgsqlNameTranslator?)

Removes an existing composite mapping.

public bool UnmapComposite<T>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)

Parameters

pgName string

A PostgreSQL type name for the corresponding composite type in the database. If null, the name translator given in nameTranslator will be used.

nameTranslator INpgsqlNameTranslator

A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to NpgsqlSnakeCaseNameTranslator

Returns

bool

Type Parameters

T

UnmapEnum(Type, string?, INpgsqlNameTranslator?)

Removes an existing enum mapping.

public bool UnmapEnum(Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)

Parameters

clrType Type

The .NET enum type to be mapped

pgName string

A PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in nameTranslator will be used.

nameTranslator INpgsqlNameTranslator

A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

Returns

bool

UnmapEnum<TEnum>(string?, INpgsqlNameTranslator?)

Removes an existing enum mapping.

public bool UnmapEnum<TEnum>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null) where TEnum : struct, Enum

Parameters

pgName string

A PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in nameTranslator will be used.

nameTranslator INpgsqlNameTranslator

A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

Returns

bool

Type Parameters

TEnum

UseClientCertificate(X509Certificate?)

Specifies an SSL/TLS certificate which Npgsql will send to PostgreSQL for certificate-based authentication.

public NpgsqlSlimDataSourceBuilder UseClientCertificate(X509Certificate? clientCertificate)

Parameters

clientCertificate X509Certificate

The client certificate to be sent to PostgreSQL when opening a connection.

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

UseClientCertificates(X509CertificateCollection?)

Specifies a collection of SSL/TLS certificates which Npgsql will send to PostgreSQL for certificate-based authentication.

public NpgsqlSlimDataSourceBuilder UseClientCertificates(X509CertificateCollection? clientCertificates)

Parameters

clientCertificates X509CertificateCollection

The client certificate collection to be sent to PostgreSQL when opening a connection.

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

UseClientCertificatesCallback(Action<X509CertificateCollection>?)

Specifies a callback to modify the collection of SSL/TLS client certificates which Npgsql will send to PostgreSQL for certificate-based authentication. This is an advanced API, consider using UseClientCertificate(X509Certificate?) or UseClientCertificates(X509CertificateCollection?) instead.

public NpgsqlSlimDataSourceBuilder UseClientCertificatesCallback(Action<X509CertificateCollection>? clientCertificatesCallback)

Parameters

clientCertificatesCallback Action<X509CertificateCollection>

The callback to modify the client certificate collection.

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

Remarks

The callback is invoked every time a physical connection is opened, and is therefore suitable for rotating short-lived client certificates. Simply make sure the certificate collection argument has the up-to-date certificate(s).

The callback's collection argument already includes any client certificates specified via the connection string or environment variables.

UseLoggerFactory(ILoggerFactory?)

Sets the ILoggerFactory that will be used for logging.

public NpgsqlSlimDataSourceBuilder UseLoggerFactory(ILoggerFactory? loggerFactory)

Parameters

loggerFactory ILoggerFactory

The logger factory to be used.

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

UsePasswordProvider(Func<NpgsqlConnectionStringBuilder, string>?, Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>?)

Configures a password provider, which is called by the data source when opening connections.

public NpgsqlSlimDataSourceBuilder UsePasswordProvider(Func<NpgsqlConnectionStringBuilder, string>? passwordProvider, Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>? passwordProviderAsync)

Parameters

passwordProvider Func<NpgsqlConnectionStringBuilder, string>

A callback that may be invoked during Open() which returns the password to be sent to PostgreSQL.

passwordProviderAsync Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>

A callback that may be invoked during OpenAsync(CancellationToken) which returns the password to be sent to PostgreSQL.

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

Remarks

The provided callback is invoked when opening connections. Therefore its important the callback internally depends on cached data or returns quickly otherwise. Any unnecessary delay will affect connection opening time.

UsePeriodicPasswordProvider(Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>?, TimeSpan, TimeSpan)

Configures a periodic password provider, which is automatically called by the data source at some regular interval. This is the recommended way to fetch a rotating access token.

public NpgsqlSlimDataSourceBuilder UsePeriodicPasswordProvider(Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>? passwordProvider, TimeSpan successRefreshInterval, TimeSpan failureRefreshInterval)

Parameters

passwordProvider Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>

A callback which returns the password to be sent to PostgreSQL.

successRefreshInterval TimeSpan

How long to cache the password before re-invoking the callback.

failureRefreshInterval TimeSpan

If a password refresh attempt fails, it will be re-attempted with this interval. This should typically be much lower than successRefreshInterval.

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

Remarks

The provided callback is invoked in a timer, and not when opening connections. It therefore doesn't affect opening time.

The provided cancellation token is only triggered when the entire data source is disposed. If you'd like to apply a timeout to the token fetching, do so within the provided callback.

UsePhysicalConnectionInitializer(Action<NpgsqlConnection>?, Func<NpgsqlConnection, Task>?)

Register a connection initializer, which allows executing arbitrary commands when a physical database connection is first opened.

public NpgsqlSlimDataSourceBuilder UsePhysicalConnectionInitializer(Action<NpgsqlConnection>? connectionInitializer, Func<NpgsqlConnection, Task>? connectionInitializerAsync)

Parameters

connectionInitializer Action<NpgsqlConnection>

A synchronous connection initialization lambda, which will be called from Open() when a new physical connection is opened.

connectionInitializerAsync Func<NpgsqlConnection, Task>

An asynchronous connection initialization lambda, which will be called from OpenAsync(CancellationToken) when a new physical connection is opened.

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

Remarks

If an initializer is registered, both sync and async versions must be provided. If you do not use sync APIs in your code, simply throw NotSupportedException, which would also catch accidental cases of sync opening.

UseRootCertificate(X509Certificate2?)

Sets the X509Certificate2 that will be used validate SSL certificate, received from the server.

public NpgsqlSlimDataSourceBuilder UseRootCertificate(X509Certificate2? rootCertificate)

Parameters

rootCertificate X509Certificate2

The CA certificate.

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

UseRootCertificateCallback(Func<X509Certificate2>?)

Specifies a callback that will be used to validate SSL certificate, received from the server.

public NpgsqlSlimDataSourceBuilder UseRootCertificateCallback(Func<X509Certificate2>? rootCertificateCallback)

Parameters

rootCertificateCallback Func<X509Certificate2>

The callback to get CA certificate.

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

Remarks

This overload, which accepts a callback, is suitable for scenarios where the certificate rotates and might change during the lifetime of the application. When that's not the case, use the overload which directly accepts the certificate.

UseUserCertificateValidationCallback(RemoteCertificateValidationCallback)

When using SSL/TLS, this is a callback that allows customizing how the PostgreSQL-provided certificate is verified. This is an advanced API, consider using VerifyFull or VerifyCA instead.

public NpgsqlSlimDataSourceBuilder UseUserCertificateValidationCallback(RemoteCertificateValidationCallback userCertificateValidationCallback)

Parameters

userCertificateValidationCallback RemoteCertificateValidationCallback

The callback containing custom callback verification logic.

Returns

NpgsqlSlimDataSourceBuilder

The same builder instance so that multiple calls can be chained.

Remarks