Class NpgsqlConnection
- Namespace
- Npgsql
- Assembly
- Npgsql.dll
This class represents a connection to a PostgreSQL server.
public sealed class NpgsqlConnection : DbConnection, IComponent, IDbConnection, IDisposable, IAsyncDisposable, ICloneable
- Inheritance
-
NpgsqlConnection
- Implements
- Inherited Members
Constructors
NpgsqlConnection()
Initializes a new instance of the NpgsqlConnection class.
public NpgsqlConnection()
NpgsqlConnection(string)
Initializes a new instance of NpgsqlConnection with the given connection string.
public NpgsqlConnection(string connectionString)
Parameters
connectionStringstringThe connection used to open the PostgreSQL database.
Fields
DefaultPort
The default TCP/IP port for PostgreSQL.
public const int DefaultPort = 5432
Field Value
Properties
CommandTimeout
Gets the time to wait while trying to execute a command before terminating the attempt and generating an error.
public int CommandTimeout { get; }
Property Value
- int
The time (in seconds) to wait for a command to complete. The default value is 20 seconds.
ConnectionString
Gets or sets the string used to connect to a PostgreSQL database. See the manual for details.
public override string ConnectionString { get; set; }
Property Value
- string
The connection string that includes the server name, the database name, and other parameters needed to establish the initial connection. The default value is an empty string.
ConnectionTimeout
Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error.
public override int ConnectionTimeout { get; }
Property Value
- int
The time (in seconds) to wait for a connection to open. The default value is 15 seconds.
DataSource
Gets the string identifying the database server (host and port)
public override string DataSource { get; }
Property Value
Database
Gets the name of the current database or the database to be used after a connection is opened.
public override string Database { get; }
Property Value
- string
The name of the current database or the name of the database to be used after a connection is opened. The default value is the empty string.
DbProviderFactory
DB provider factory.
protected override DbProviderFactory DbProviderFactory { get; }
Property Value
FullState
Gets the current state of the connection.
[Browsable(false)]
public ConnectionState FullState { get; }
Property Value
- ConnectionState
A bitwise combination of the ConnectionState values. The default is Closed.
GlobalTypeMapper
The global type mapper, which contains defaults used by all new connections. Modify mappings on this mapper to affect your entire application.
public static INpgsqlTypeMapper GlobalTypeMapper { get; }
Property Value
HasIntegerDateTimes
Reports whether the backend uses the newer integer timestamp representation. Note that the old floating point representation is not supported. Meant for use by type plugins (e.g. Nodatime)
[Browsable(false)]
public bool HasIntegerDateTimes { get; }
Property Value
Host
Backend server host name.
[Browsable(true)]
public string Host { get; }
Property Value
IntegratedSecurity
Whether to use Windows integrated security to log in.
public bool IntegratedSecurity { get; }
Property Value
Port
Backend server port.
[Browsable(true)]
public int Port { get; }
Property Value
PostgreSqlVersion
Version of the PostgreSQL backend. This can only be called when there is an active connection.
[Browsable(false)]
public Version PostgreSqlVersion { get; }
Property Value
PostgresParameters
Holds all PostgreSQL parameters received for this connection. Is updated if the values change (e.g. as a result of a SET command).
[Browsable(false)]
public IReadOnlyDictionary<string, string> PostgresParameters { get; }
Property Value
ProcessID
Process id of backend server. This can only be called when there is an active connection.
[Browsable(false)]
public int ProcessID { get; }
Property Value
ProvideClientCertificatesCallback
Selects the local Secure Sockets Layer (SSL) certificate used for authentication.
public ProvideClientCertificatesCallback ProvideClientCertificatesCallback { get; set; }
Property Value
Remarks
ServerVersion
PostgreSQL server version.
public override string ServerVersion { get; }
Property Value
State
Gets whether the current state of the connection is Open or Closed
[Browsable(false)]
public override ConnectionState State { get; }
Property Value
- ConnectionState
ConnectionState.Open, ConnectionState.Closed or ConnectionState.Connecting
Timezone
The connection's timezone as reported by PostgreSQL, in the IANA/Olson database format.
[Browsable(false)]
public string Timezone { get; }
Property Value
TypeMapper
The connection-specific type mapper - all modifications affect this connection only, and are lost when it is closed.
public INpgsqlTypeMapper TypeMapper { get; }
Property Value
UserCertificateValidationCallback
Verifies the remote Secure Sockets Layer (SSL) certificate used for authentication. Ignored if TrustServerCertificate is set.
public RemoteCertificateValidationCallback UserCertificateValidationCallback { get; set; }
Property Value
Remarks
UserName
User name.
public string UserName { get; }
Property Value
Methods
BeginBinaryExport(string)
Begins a binary COPY TO STDOUT operation, a high-performance data export mechanism from a PostgreSQL table.
public NpgsqlBinaryExporter BeginBinaryExport(string copyToCommand)
Parameters
copyToCommandstringA COPY TO STDOUT SQL command
Returns
- NpgsqlBinaryExporter
A NpgsqlBinaryExporter which can be used to read rows and columns
Remarks
BeginBinaryImport(string)
Begins a binary COPY FROM STDIN operation, a high-performance data import mechanism to a PostgreSQL table.
public NpgsqlBinaryImporter BeginBinaryImport(string copyFromCommand)
Parameters
copyFromCommandstringA COPY FROM STDIN SQL command
Returns
- NpgsqlBinaryImporter
A NpgsqlBinaryImporter which can be used to write rows and columns
Remarks
BeginDbTransaction(IsolationLevel)
Begins a database transaction with the specified isolation level.
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
Parameters
isolationLevelIsolationLevelThe isolation level under which the transaction should run.
Returns
- DbTransaction
An DbTransaction object representing the new transaction.
Remarks
Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend. There's no support for nested transactions.
BeginRawBinaryCopy(string)
Begins a raw binary COPY operation (TO STDOUT or FROM STDIN), a high-performance data export/import mechanism to a PostgreSQL table. Note that unlike the other COPY API methods, BeginRawBinaryCopy(string) doesn't implement any encoding/decoding and is unsuitable for structured import/export operation. It is useful mainly for exporting a table as an opaque blob, for the purpose of importing it back later.
public NpgsqlRawCopyStream BeginRawBinaryCopy(string copyCommand)
Parameters
copyCommandstringA COPY TO STDOUT or COPY FROM STDIN SQL command
Returns
- NpgsqlRawCopyStream
A NpgsqlRawCopyStream that can be used to read or write raw binary data.
Remarks
BeginTextExport(string)
Begins a textual COPY TO STDOUT operation, a data export mechanism from a PostgreSQL table.
It is the user's responsibility to parse the textual input according to the format specified
in copyToCommand.
public TextReader BeginTextExport(string copyToCommand)
Parameters
copyToCommandstringA COPY TO STDOUT SQL command
Returns
- TextReader
A TextReader that can be used to read textual data.
Remarks
BeginTextImport(string)
Begins a textual COPY FROM STDIN operation, a data import mechanism to a PostgreSQL table.
It is the user's responsibility to send the textual input according to the format specified
in copyFromCommand.
public TextWriter BeginTextImport(string copyFromCommand)
Parameters
copyFromCommandstringA COPY FROM STDIN SQL command
Returns
- TextWriter
A TextWriter that can be used to send textual data.
Remarks
BeginTransaction()
Begins a database transaction.
public NpgsqlTransaction BeginTransaction()
Returns
- NpgsqlTransaction
A NpgsqlTransaction object representing the new transaction.
Remarks
Currently there's no support for nested transactions. Transactions created by this method will have Read Committed isolation level.
BeginTransaction(IsolationLevel)
Begins a database transaction with the specified isolation level.
public NpgsqlTransaction BeginTransaction(IsolationLevel level)
Parameters
levelIsolationLevelThe isolation level under which the transaction should run.
Returns
- NpgsqlTransaction
A NpgsqlTransaction object representing the new transaction.
Remarks
Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend. There's no support for nested transactions.
ChangeDatabase(string)
This method changes the current database by disconnecting from the actual database and connecting to the specified.
public override void ChangeDatabase(string dbName)
Parameters
dbNamestringThe name of the database to use in place of the current database.
ClearAllPools()
Clear all connection pools.
public static void ClearAllPools()
ClearPool(NpgsqlConnection)
Clear connection pool.
public static void ClearPool(NpgsqlConnection connection)
Parameters
connectionNpgsqlConnection
CloneWith(string)
Clones this connection, replacing its connection string with the given one. This allows creating a new connection with the same security information (password, SSL callbacks) while changing other connection parameters (e.g. database or pooling)
public NpgsqlConnection CloneWith(string connectionString)
Parameters
connectionStringstring
Returns
Close()
releases the connection to the database. If the connection is pooled, it will be made available for re-use. If it is non-pooled, the actual connection will be shutdown.
public override void Close()
CreateCommand()
Creates and returns a NpgsqlCommand object associated with the NpgsqlConnection.
public NpgsqlCommand CreateCommand()
Returns
- NpgsqlCommand
A NpgsqlCommand object.
CreateDbCommand()
Creates and returns a DbCommand object associated with the IDbConnection.
protected override DbCommand CreateDbCommand()
Returns
Dispose(bool)
Releases all resources used by the NpgsqlConnection.
protected override void Dispose(bool disposing)
Parameters
disposingbooltrue when called from Dispose(); false when being called from the finalizer.
EnlistTransaction(Transaction)
Enlist transation.
public override void EnlistTransaction(Transaction transaction)
Parameters
transactionTransaction
GetSchema()
Returns the supported collections
public override DataTable GetSchema()
Returns
GetSchema(string)
Returns the schema collection specified by the collection name.
public override DataTable GetSchema(string collectionName)
Parameters
collectionNamestringThe collection name.
Returns
- DataTable
The collection specified.
GetSchema(string, string[])
Returns the schema collection specified by the collection name filtered by the restrictions.
public override DataTable GetSchema(string collectionName, string[] restrictions)
Parameters
collectionNamestringThe collection name.
restrictionsstring[]The restriction values to filter the results. A description of the restrictions is contained in the Restrictions collection.
Returns
- DataTable
The collection specified.
MapCompositeGlobally<T>(string, INpgsqlNameTranslator)
Maps a CLR type to a PostgreSQL composite type for use with all connections created from now on. Existing connections aren't affected.
[Obsolete("Use NpgsqlConnection.GlobalTypeMapper.MapComposite() instead")]
public static void MapCompositeGlobally<T>(string pgName = null, INpgsqlNameTranslator nameTranslator = null) where T : new()
Parameters
pgNamestringA PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in
nameTranslatorwill be used.nameTranslatorINpgsqlNameTranslatorA component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to NpgsqlSnakeCaseNameTranslator
Type Parameters
TThe .NET type to be mapped
Remarks
CLR fields and properties by string 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 members to manually specify a PostgreSQL enum label.
If there is a discrepancy between the .NET and database labels while a composite is read or written,
an exception will be raised.
To map the type for a specific connection, use the MapEnum<TEnum>(string, INpgsqlNameTranslator) method.
MapComposite<T>(string, INpgsqlNameTranslator)
Maps a CLR type to a PostgreSQL composite type for use with this connection.
[Obsolete("Use NpgsqlConnection.TypeMapper.MapComposite() instead")]
public void MapComposite<T>(string pgName = null, INpgsqlNameTranslator nameTranslator = null) where T : new()
Parameters
pgNamestringA PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in
nameTranslatorwill be used.nameTranslatorINpgsqlNameTranslatorA component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to NpgsqlSnakeCaseNameTranslator
Type Parameters
TThe .NET type to be mapped
Remarks
CLR fields and properties by string 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 members to manually specify a PostgreSQL enum label.
If there is a discrepancy between the .NET and database labels while a composite is read or written,
an exception will be raised.
Can only be invoked on an open connection; if the connection is closed the mapping is lost.
To avoid mapping the type for each connection, use the MapCompositeGlobally<T>(string, INpgsqlNameTranslator) method.
MapEnumGlobally<TEnum>(string, INpgsqlNameTranslator)
Maps a CLR enum to a PostgreSQL enum type for use with all connections created from now on. Existing connections aren't affected.
[Obsolete("Use NpgsqlConnection.GlobalTypeMapper.MapEnum() instead")]
public static void MapEnumGlobally<TEnum>(string pgName = null, INpgsqlNameTranslator nameTranslator = null) where TEnum : struct
Parameters
pgNamestringA PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in
nameTranslatorwill be used.nameTranslatorINpgsqlNameTranslatorA component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to NpgsqlSnakeCaseNameTranslator
Type Parameters
TEnumThe .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.
To map the type for a specific connection, use the MapEnum<TEnum>(string, INpgsqlNameTranslator) method.
MapEnum<TEnum>(string, INpgsqlNameTranslator)
Maps a CLR enum to a PostgreSQL enum type for use with this connection.
[Obsolete("Use NpgsqlConnection.TypeMapper.MapEnum() instead")]
public void MapEnum<TEnum>(string pgName = null, INpgsqlNameTranslator nameTranslator = null) where TEnum : struct
Parameters
pgNamestringA PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in
nameTranslatorwill be used.nameTranslatorINpgsqlNameTranslatorA component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to NpgsqlSnakeCaseNameTranslator
Type Parameters
TEnumThe .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.
Can only be invoked on an open connection; if the connection is closed the mapping is lost.
To avoid mapping the type for each connection, use the MapEnumGlobally<TEnum>(string, INpgsqlNameTranslator) method.
Open()
Opens a database connection with the property settings specified by the ConnectionString.
public override void Open()
OpenAsync(CancellationToken)
This is the asynchronous version of Open().
public override Task OpenAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenThe cancellation instruction.
Returns
- Task
A task representing the asynchronous operation.
Remarks
Do not invoke other methods and properties of the NpgsqlConnection object until the returned Task is complete.
ReloadTypes()
Flushes the type cache for this connection's connection string and reloads the types for this connection only. Type changes will appear for other connections only after they are re-opened from the pool.
public void ReloadTypes()
UnmapCompositeGlobally<T>(string, INpgsqlNameTranslator)
Removes a previous global enum mapping.
[Obsolete("Use NpgsqlConnection.GlobalTypeMapper.UnmapComposite() instead")]
public static void UnmapCompositeGlobally<T>(string pgName, INpgsqlNameTranslator nameTranslator = null) where T : new()
Parameters
pgNamestringA PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in
nameTranslatorwill be used.nameTranslatorINpgsqlNameTranslatorA component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to NpgsqlSnakeCaseNameTranslator
Type Parameters
T
UnmapEnumGlobally<TEnum>(string, INpgsqlNameTranslator)
Removes a previous global enum mapping.
[Obsolete("Use NpgsqlConnection.GlobalTypeMapper.UnmapEnum() instead")]
public static void UnmapEnumGlobally<TEnum>(string pgName = null, INpgsqlNameTranslator nameTranslator = null) where TEnum : struct
Parameters
pgNamestringA PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in
nameTranslatorwill be used.nameTranslatorINpgsqlNameTranslatorA component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to NpgsqlSnakeCaseNameTranslator
Type Parameters
TEnum
UnprepareAll()
Unprepares all prepared statements on this connection.
public void UnprepareAll()
Wait()
Waits until an asynchronous PostgreSQL messages (e.g. a notification) arrives, and exits immediately. The asynchronous message is delivered via the normal events (Notification, Notice).
public void Wait()
Wait(int)
Waits until an asynchronous PostgreSQL messages (e.g. a notification) arrives, and exits immediately. The asynchronous message is delivered via the normal events (Notification, Notice).
public bool Wait(int timeout)
Parameters
timeoutintThe time-out value, in milliseconds, passed to ReceiveTimeout. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.
Returns
- bool
true if an asynchronous message was received, false if timed out.
Wait(TimeSpan)
Waits until an asynchronous PostgreSQL messages (e.g. a notification) arrives, and exits immediately. The asynchronous message is delivered via the normal events (Notification, Notice).
public bool Wait(TimeSpan timeout)
Parameters
timeoutTimeSpanThe time-out value is passed to ReceiveTimeout.
Returns
- bool
true if an asynchronous message was received, false if timed out.
WaitAsync()
Waits asynchronously until an asynchronous PostgreSQL messages (e.g. a notification) arrives, and exits immediately. The asynchronous message is delivered via the normal events (Notification, Notice).
public Task WaitAsync()
Returns
WaitAsync(CancellationToken)
Waits asynchronously until an asynchronous PostgreSQL messages (e.g. a notification) arrives, and exits immediately. The asynchronous message is delivered via the normal events (Notification, Notice). CancelationToken can not cancel wait operation if underlying NetworkStream does not support it (see https://stackoverflow.com/questions/12421989/networkstream-readasync-with-a-cancellation-token-never-cancels ).
public Task WaitAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationToken
Returns
Events
Notice
Fires when PostgreSQL notices are received from PostgreSQL.
public event NoticeEventHandler Notice
Event Type
Remarks
PostgreSQL notices are non-critical messages generated by PostgreSQL, either as a result of a user query (e.g. as a warning or informational notice), or due to outside activity (e.g. if the database administrator initiates a "fast" database shutdown).
Note that notices are very different from notifications (see the Notification event).
Notification
Fires when PostgreSQL notifications are received from PostgreSQL.
public event NotificationEventHandler Notification
Event Type
Remarks
PostgreSQL notifications are sent when your connection has registered for notifications on a specific channel via the LISTEN command. NOTIFY can be used to generate such notifications, allowing for an inter-connection communication channel.
Note that notifications are very different from notices (see the Notice event).