Include error detail postgre

To connect to a database, the application provides a connection string which specifies parameters such as the host, the username, the password, etc. Connection strings have the form keyword1=value; keyword2=value; and are case-insensitive. Values containing special characters (e.g. semicolons) can be double-quoted. For more information, see the official doc page on connection strings.

To connect to a database, the application provides a connection string which specifies parameters such as the host, the username, the password, etc. Connection strings have the form keyword1=value; keyword2=value; and are case-insensitive. Values containing special characters (e.g. semicolons) can be double-quoted. For more information, see the official doc page on connection strings.

Below are the connection string parameters which Npgsql understands, as well as some standard PostgreSQL environment variables.

Basic connection

Parameter Description Default
Host Specifies the host name — and optionally port — on which PostgreSQL is running. Multiple hosts may be specified, see the docs for more info. If the value begins with a slash, it is used as the directory for the Unix-domain socket (specifying a Port is still required). Required
Port The TCP port of the PostgreSQL server. 5432
Database The PostgreSQL database to connect to. Same as Username
Username The username to connect with. Not required if using IntegratedSecurity. PGUSER
Password The password to connect with. Not required if using IntegratedSecurity. PGPASSWORD
Passfile Path to a PostgreSQL password file (PGPASSFILE), from which the password is taken. PGPASSFILE

Security and encryption

Parameter Description Default
SSL Mode Controls whether SSL is used, depending on server support. See docs for possible values and more info. Prefer in 6.0, Disable previously
Trust Server Certificate Whether to trust the server certificate without validating it. See docs for more info. false
SSL Certificate Location of a client certificate to be sent to the server. Introduced in 6.0. See docs PGSSLCERT
SSL Key Location of a client key for a client certificate to be sent to the server. Introduced in 6.0. PGSSLKEY
SSL Password Password for a key for a client certificate. Introduced in 6.0.
Root Certificate Location of a CA certificate used to validate the server certificate. PGSSLROOTCERT
Check Certificate Revocation Whether to check the certificate revocation list during authentication. false
Integrated Security Whether to use integrated security to log in (GSS/SSPI). See docs for more info. false
Persist Security Info Gets or sets a Boolean value that indicates if security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Introduced in 3.1. false
Kerberos Service Name The Kerberos service name to be used for authentication. See docs for more info. postgres
Include Realm The Kerberos realm to be used for authentication. See docs for more info.
Include Error Detail When enabled, PostgreSQL error and notice details are included on PostgresException.Detail and PostgresNotice.Detail. These can contain sensitive data. false
Log Parameters When enabled, parameter values are logged when commands are executed. false

Pooling

Parameter Description Default
Pooling Whether connection pooling should be used. true
Minimum Pool Size The minimum connection pool size. 0
Maximum Pool Size The maximum connection pool size. 100 since 3.1, 20 previously
Connection Idle Lifetime The time (in seconds) to wait before closing idle connections in the pool if the count of all connections exceeds Minimum Pool Size. Introduced in 3.1. 300
Connection Pruning Interval How many seconds the pool waits before attempting to prune idle connections that are beyond idle lifetime (see Connection Idle Lifetime). Introduced in 3.1. 10
ConnectionLifetime The total maximum lifetime of connections (in seconds). Connections which have exceeded this value will be destroyed instead of returned from the pool. This is useful in clustered configurations to force load balancing between a running server and a server just brought online. 0 (disabled)

Timeouts and keepalive

Parameter Description Default
Timeout The time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error. 15
Command Timeout The time to wait (in seconds) while trying to execute a command before terminating the attempt and generating an error. Set to zero for infinity. 30
Internal Command Timeout The time to wait (in seconds) while trying to execute an internal command before terminating the attempt and generating an error. -1 uses CommandTimeout, 0 means no timeout. -1
Cancellation Timeout The time to wait (in milliseconds) while trying to read a response for a cancellation request for a timed out or cancelled query, before terminating the attempt and generating an error. -1 skips the wait, 0 means infinite wait. Introduced in 5.0. 2000
Keepalive The number of seconds of connection inactivity before Npgsql sends a keepalive query. 0 (disabled)
Tcp Keepalive Whether to use TCP keepalive with system defaults if overrides isn’t specified. false
Tcp Keepalive Time The number of milliseconds of connection inactivity before a TCP keepalive query is sent. Use of this option is discouraged, use KeepAlive instead if possible. Supported only on Windows. 0 (disabled)
Tcp Keepalive Interval The interval, in milliseconds, between when successive keep-alive packets are sent if no acknowledgement is received. Tcp KeepAlive Time must be non-zero as well. Supported only on Windows. value of Tcp Keepalive Time

Performance

Parameter Description Default
Max Auto Prepare The maximum number SQL statements that can be automatically prepared at any given point. Beyond this number the least-recently-used statement will be recycled. Zero disables automatic preparation. 0
Auto Prepare Min Usages The minimum number of usages an SQL statement is used before it’s automatically prepared. 5
Read Buffer Size Determines the size of the internal buffer Npgsql uses when reading. Increasing may improve performance if transferring large values from the database. 8192
Write Buffer Size Determines the size of the internal buffer Npgsql uses when writing. Increasing may improve performance if transferring large values to the database. 8192
Socket Receive Buffer Size Determines the size of socket receive buffer. System-dependent
Socket Send Buffer Size Determines the size of socket send buffer. System-dependent
No Reset On Close Improves performance in some cases by not resetting the connection state when it is returned to the pool, at the cost of leaking state. Use only if benchmarking shows a performance improvement false

Failover and load balancing

For more information, see the dedicated docs page.

Parameter Description Default
Target Session Attributes Determines the preferred PostgreSQL target server type. PGTARGETSESSIONATTRS, Any
Load Balance Hosts Enables balancing between multiple hosts by round-robin. false
Host Recheck Seconds Controls for how long the host’s cached state will be considered as valid. 10

Misc

Parameter Description Default
Options1 Specifies any valid PostgreSQL connection options (e.g. Options=-c synchronous_commit=local). Introduced in 5.0. PGOPTIONS
Application Name The optional application name parameter to be sent to the backend during connection initiation.
Enlist Whether to enlist in an ambient TransactionScope. true
Search Path Sets the schema search path.
Client Encoding Gets or sets the client_encoding parameter. PGCLIENTENCODING, UTF8
Encoding Gets or sets the .NET encoding that will be used to encode/decode PostgreSQL string data. UTF8
Timezone Gets or sets the session timezone. PGTZ
EF Template Database The database template to specify when creating a database in Entity Framework. template1
EF Admin Database The database admin to specify when creating and dropping a database in Entity Framework. template1
Load Table Composites Load table composite type definitions, and not just free-standing composite types. false
Array Nullability Mode Configure the way arrays of value types are returned when requested as object instances. Possible values are: Never (arrays of value types are always returned as non-nullable arrays), Always (arrays of value types are always returned as nullable arrays) and PerInstance (the type of array that gets returned is determined at runtime). Never

1The Options connection string parameter is essentially the string of command line options that get passed to the postgres program when the process is started.
It is most commonly used to set named run-time parameters via the -c option but other options can be used too (although not all of them make sense in that context).
Setting multiple options is possible by separating them with a space character. Space and backslash characters in option values need to be escaped by prefixing a backslash character.
Example: Options=-c default_transaction_isolation=serializable -c default_transaction_deferrable=on -c foo.bar=My\ Famous\\Thing

Compatibility

Parameter Description Default
Server Compatibility Mode A compatibility mode for special PostgreSQL server types. Currently «Redshift» is supported, as well as «NoTypeLoading», which will bypass the normal type loading mechanism from the PostgreSQL catalog tables and supports a hardcoded list of basic types. none

Obsolete

Parameter Description Default
Client Certificate Location of a client certificate to be sent to the server. Deprecated in 6.0. PGSSLCERT
Client Certificate Key Location of a client key for a client certificate to be sent to the server. Deprecated in 6.0. PGSSLKEY
Use Perf Counters Makes Npgsql write performance information about connection use to Windows Performance Counters. Removed in 5.0. false

Environment variables

In addition to the connection string parameters above, Npgsql also recognizes the standard PostgreSQL environment variables below. This helps Npgsql-based applications behave similar to other, non-.NET PostgreSQL client applications. The PostgreSQL doc page on environment variables recognized by libpq can be found here.

Environment variable Description
PGUSER Behaves the same as the user connection parameter.
PGPASSWORD Behaves the same as the password connection parameter. Use of this environment variable is not recommended for security reasons, as some operating systems allow non-root users to see process environment variables via ps; instead consider using a password file (see Section 33.15).
PGPASSFILE Behaves the same as the passfile connection parameter.
PGSSLCERT Behaves the same as the sslcert connection parameter.
PGSSLKEY Behaves the same as the sslkey connection parameter.
PGSSLROOTCERT Behaves the same as the sslrootcert connection parameter.
PGCLIENTENCODING Behaves the same as the client_encoding connection parameter.
PGTZ Sets the default time zone. (Equivalent to SET timezone TO ….)
PGOPTIONS Behaves the same as the options connection parameter.

Содержание

  1. Name already in use
  2. doc / conceptual / Npgsql / connection-string-parameters.md
  3. Include error detail postgre
  4. 43.9.2. Checking Assertions
  5. Submit correction

Name already in use

doc / conceptual / Npgsql / connection-string-parameters.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

Connection String Parameters

To connect to a database, the application provides a connection string which specifies parameters such as the host, the username, the password, etc. Connection strings have the form keyword1=value; keyword2=value; and are case-insensitive. Values containing special characters (e.g. semicolons) can be double-quoted. For more information, see the official doc page on connection strings.

Below are the connection string parameters which Npgsql understands, as well as some standard PostgreSQL environment variables.

Parameter Description Default
Host Specifies the host name — and optionally port — on which PostgreSQL is running. Multiple hosts may be specified, see the docs for more info. If the value begins with a slash, it is used as the directory for the Unix-domain socket (specifying a Port is still required). Required
Port The TCP port of the PostgreSQL server. 5432
Database The PostgreSQL database to connect to. Same as Username
Username The username to connect with. Not required if using IntegratedSecurity. PGUSER
Password The password to connect with. Not required if using IntegratedSecurity. PGPASSWORD
Passfile Path to a PostgreSQL password file (PGPASSFILE), from which the password is taken. PGPASSFILE

Security and encryption

Parameter Description Default
SSL Mode Controls whether SSL is used, depending on server support. See docs for possible values and more info. Prefer in 6.0, Disable previously
Trust Server Certificate Whether to trust the server certificate without validating it. See docs for more info. false
SSL Certificate Location of a client certificate to be sent to the server. Introduced in 6.0. See docs PGSSLCERT
SSL Key Location of a client key for a client certificate to be sent to the server. Introduced in 6.0. PGSSLKEY
SSL Password Password for a key for a client certificate. Introduced in 6.0.
Root Certificate Location of a CA certificate used to validate the server certificate. PGSSLROOTCERT
Check Certificate Revocation Whether to check the certificate revocation list during authentication. false
Integrated Security Whether to use integrated security to log in (GSS/SSPI). See docs for more info. false
Persist Security Info Gets or sets a Boolean value that indicates if security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Introduced in 3.1. false
Kerberos Service Name The Kerberos service name to be used for authentication. See docs for more info. postgres
Include Realm The Kerberos realm to be used for authentication. See docs for more info.
Include Error Detail When enabled, PostgreSQL error and notice details are included on xref:Npgsql.PostgresException.Detail?displayProperty=nameWithType and xref:Npgsql.PostgresNotice.Detail?displayProperty=nameWithType. These can contain sensitive data. false
Log Parameters When enabled, parameter values are logged when commands are executed. false
Parameter Description Default
Pooling Whether connection pooling should be used. true
Minimum Pool Size The minimum connection pool size.
Maximum Pool Size The maximum connection pool size. 100 since 3.1, 20 previously
Connection Idle Lifetime The time (in seconds) to wait before closing idle connections in the pool if the count of all connections exceeds Minimum Pool Size . Introduced in 3.1. 300
Connection Pruning Interval How many seconds the pool waits before attempting to prune idle connections that are beyond idle lifetime (see Connection Idle Lifetime ). Introduced in 3.1. 10
ConnectionLifetime The total maximum lifetime of connections (in seconds). Connections which have exceeded this value will be destroyed instead of returned from the pool. This is useful in clustered configurations to force load balancing between a running server and a server just brought online. 0 (disabled)

Timeouts and keepalive

Parameter Description Default
Timeout The time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error. 15
Command Timeout The time to wait (in seconds) while trying to execute a command before terminating the attempt and generating an error. Set to zero for infinity. 30
Internal Command Timeout The time to wait (in seconds) while trying to execute an internal command before terminating the attempt and generating an error. -1 uses CommandTimeout, 0 means no timeout. -1
Cancellation Timeout The time to wait (in milliseconds) while trying to read a response for a cancellation request for a timed out or cancelled query, before terminating the attempt and generating an error. -1 skips the wait, 0 means infinite wait. Introduced in 5.0. 2000
Keepalive The number of seconds of connection inactivity before Npgsql sends a keepalive query. 0 (disabled)
Tcp Keepalive Whether to use TCP keepalive with system defaults if overrides isn’t specified. false
Tcp Keepalive Time The number of milliseconds of connection inactivity before a TCP keepalive query is sent. Use of this option is discouraged, use KeepAlive instead if possible. Supported only on Windows. 0 (disabled)
Tcp Keepalive Interval The interval, in milliseconds, between when successive keep-alive packets are sent if no acknowledgement is received. Tcp KeepAlive Time must be non-zero as well. Supported only on Windows. value of Tcp Keepalive Time
Parameter Description Default
Max Auto Prepare The maximum number SQL statements that can be automatically prepared at any given point. Beyond this number the least-recently-used statement will be recycled. Zero disables automatic preparation.
Auto Prepare Min Usages The minimum number of usages an SQL statement is used before it’s automatically prepared. 5
Read Buffer Size Determines the size of the internal buffer Npgsql uses when reading. Increasing may improve performance if transferring large values from the database. 8192
Write Buffer Size Determines the size of the internal buffer Npgsql uses when writing. Increasing may improve performance if transferring large values to the database. 8192
Socket Receive Buffer Size Determines the size of socket receive buffer. System-dependent
Socket Send Buffer Size Determines the size of socket send buffer. System-dependent
No Reset On Close Improves performance in some cases by not resetting the connection state when it is returned to the pool, at the cost of leaking state. Use only if benchmarking shows a performance improvement false

Failover and load balancing

Parameter Description Default
Target Session Attributes Determines the preferred PostgreSQL target server type. PGTARGETSESSIONATTRS, Any
Load Balance Hosts Enables balancing between multiple hosts by round-robin. false
Host Recheck Seconds Controls for how long the host’s cached state will be considered as valid. 10
Parameter Description Default
Options 1 Specifies any valid PostgreSQL connection options (e.g. Options=-c synchronous_commit=local ). Introduced in 5.0. PGOPTIONS
Application Name The optional application name parameter to be sent to the backend during connection initiation.
Enlist Whether to enlist in an ambient TransactionScope. true
Search Path Sets the schema search path.
Client Encoding Gets or sets the client_encoding parameter. PGCLIENTENCODING, UTF8
Encoding Gets or sets the .NET encoding that will be used to encode/decode PostgreSQL string data. UTF8
Timezone Gets or sets the session timezone. PGTZ
EF Template Database The database template to specify when creating a database in Entity Framework. template1
EF Admin Database The database admin to specify when creating and dropping a database in Entity Framework. template1
Load Table Composites Load table composite type definitions, and not just free-standing composite types. false
Array Nullability Mode Configure the way arrays of value types are returned when requested as object instances. Possible values are: Never (arrays of value types are always returned as non-nullable arrays), Always (arrays of value types are always returned as nullable arrays) and PerInstance (the type of array that gets returned is determined at runtime). Never

1 The Options connection string parameter is essentially the string of command line options that get passed to the postgres program when the process is started. It is most commonly used to set named run-time parameters via the -c option but other options can be used too (although not all of them make sense in that context). Setting multiple options is possible by separating them with a space character. Space and backslash characters in option values need to be escaped by prefixing a backslash character. Example: Options=-c default_transaction_isolation=serializable -c default_transaction_deferrable=on -c foo.bar=My\ Famous\\Thing

Parameter Description Default
Server Compatibility Mode A compatibility mode for special PostgreSQL server types. Currently «Redshift» is supported, as well as «NoTypeLoading», which will bypass the normal type loading mechanism from the PostgreSQL catalog tables and supports a hardcoded list of basic types. none
Parameter Description Default
Client Certificate Location of a client certificate to be sent to the server. Deprecated in 6.0. PGSSLCERT
Client Certificate Key Location of a client key for a client certificate to be sent to the server. Deprecated in 6.0. PGSSLKEY
Use Perf Counters Makes Npgsql write performance information about connection use to Windows Performance Counters. Removed in 5.0. false

In addition to the connection string parameters above, Npgsql also recognizes the standard PostgreSQL environment variables below. This helps Npgsql-based applications behave similar to other, non-.NET PostgreSQL client applications. The PostgreSQL doc page on environment variables recognized by libpq can be found here.

Источник

Include error detail postgre

Use the RAISE statement to report messages and raise errors.

The level option specifies the error severity. Allowed levels are DEBUG , LOG , INFO , NOTICE , WARNING , and EXCEPTION , with EXCEPTION being the default. EXCEPTION raises an error (which normally aborts the current transaction); the other levels only generate messages of different priority levels. Whether messages of a particular priority are reported to the client, written to the server log, or both is controlled by the log_min_messages and client_min_messages configuration variables. See Chapter 20 for more information.

After level if any, you can specify a format string (which must be a simple string literal, not an expression). The format string specifies the error message text to be reported. The format string can be followed by optional argument expressions to be inserted into the message. Inside the format string, % is replaced by the string representation of the next optional argument’s value. Write %% to emit a literal % . The number of arguments must match the number of % placeholders in the format string, or an error is raised during the compilation of the function.

In this example, the value of v_job_id will replace the % in the string:

You can attach additional information to the error report by writing USING followed by option = expression items. Each expression can be any string-valued expression. The allowed option key words are:

Sets the error message text. This option can’t be used in the form of RAISE that includes a format string before USING .

Supplies an error detail message.

Supplies a hint message.

Specifies the error code (SQLSTATE) to report, either by condition name, as shown in Appendix A, or directly as a five-character SQLSTATE code.

COLUMN
CONSTRAINT
DATATYPE
TABLE
SCHEMA

Supplies the name of a related object.

This example will abort the transaction with the given error message and hint:

These two examples show equivalent ways of setting the SQLSTATE:

There is a second RAISE syntax in which the main argument is the condition name or SQLSTATE to be reported, for example:

In this syntax, USING can be used to supply a custom error message, detail, or hint. Another way to do the earlier example is

Still another variant is to write RAISE USING or RAISE level USING and put everything else into the USING list.

The last variant of RAISE has no parameters at all. This form can only be used inside a BEGIN block’s EXCEPTION clause; it causes the error currently being handled to be re-thrown.

Before PostgreSQL 9.1, RAISE without parameters was interpreted as re-throwing the error from the block containing the active exception handler. Thus an EXCEPTION clause nested within that handler could not catch it, even if the RAISE was within the nested EXCEPTION clause’s block. This was deemed surprising as well as being incompatible with Oracle’s PL/SQL.

If no condition name nor SQLSTATE is specified in a RAISE EXCEPTION command, the default is to use ERRCODE_RAISE_EXCEPTION ( P0001 ). If no message text is specified, the default is to use the condition name or SQLSTATE as message text.

When specifying an error code by SQLSTATE code, you are not limited to the predefined error codes, but can select any error code consisting of five digits and/or upper-case ASCII letters, other than 00000 . It is recommended that you avoid throwing error codes that end in three zeroes, because these are category codes and can only be trapped by trapping the whole category.

43.9.2. Checking Assertions

The ASSERT statement is a convenient shorthand for inserting debugging checks into PL/pgSQL functions.

The condition is a Boolean expression that is expected to always evaluate to true; if it does, the ASSERT statement does nothing further. If the result is false or null, then an ASSERT_FAILURE exception is raised. (If an error occurs while evaluating the condition , it is reported as a normal error.)

If the optional message is provided, it is an expression whose result (if not null) replaces the default error message text “ assertion failed ” , should the condition fail. The message expression is not evaluated in the normal case where the assertion succeeds.

Testing of assertions can be enabled or disabled via the configuration parameter plpgsql.check_asserts , which takes a Boolean value; the default is on . If this parameter is off then ASSERT statements do nothing.

Note that ASSERT is meant for detecting program bugs, not for reporting ordinary error conditions. Use the RAISE statement, described above, for that.

Prev Up Next
43.8. Transaction Management Home 43.10. Trigger Functions

Submit correction

If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.

Copyright © 1996-2023 The PostgreSQL Global Development Group

Источник

Connection String Parameters

To connect to a database, the application provides a connection string which specifies parameters such as the host, the username, the password, etc. Connection strings have the form keyword1=value; keyword2=value; and are case-insensitive. Values containing special characters (e.g. semicolons) can be double-quoted. For more information, see the official doc page on connection strings.

Below are the connection string parameters which Npgsql understands, as well as some standard PostgreSQL environment variables.

Basic connection

Parameter Description Default
Host Specifies the host name — and optionally port — on which PostgreSQL is running. Multiple hosts may be specified, see the docs for more info. If the value begins with a slash, it is used as the directory for the Unix-domain socket (specifying a Port is still required). Required
Port The TCP port of the PostgreSQL server. 5432
Database The PostgreSQL database to connect to. Same as Username
Username The username to connect with. Not required if using IntegratedSecurity. PGUSER
Password The password to connect with. Not required if using IntegratedSecurity. PGPASSWORD
Passfile Path to a PostgreSQL password file (PGPASSFILE), from which the password is taken. PGPASSFILE

Security and encryption

Parameter Description Default
SSL Mode Controls whether SSL is used, depending on server support. See docs for possible values and more info. Prefer in 6.0, Disable previously
Trust Server Certificate Whether to trust the server certificate without validating it. See docs for more info. false
SSL Certificate Location of a client certificate to be sent to the server. Introduced in 6.0. See docs PGSSLCERT
SSL Key Location of a client key for a client certificate to be sent to the server. Introduced in 6.0. PGSSLKEY
SSL Password Password for a key for a client certificate. Introduced in 6.0.
Root Certificate Location of a CA certificate used to validate the server certificate. PGSSLROOTCERT
Check Certificate Revocation Whether to check the certificate revocation list during authentication. false
Integrated Security Whether to use integrated security to log in (GSS/SSPI). See docs for more info. false
Persist Security Info Gets or sets a Boolean value that indicates if security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Introduced in 3.1. false
Kerberos Service Name The Kerberos service name to be used for authentication. See docs for more info. postgres
Include Realm The Kerberos realm to be used for authentication. See docs for more info.
Include Error Detail When enabled, PostgreSQL error and notice details are included on xref:Npgsql.PostgresException.Detail?displayProperty=nameWithType and xref:Npgsql.PostgresNotice.Detail?displayProperty=nameWithType. These can contain sensitive data. false
Log Parameters When enabled, parameter values are logged when commands are executed. false

Pooling

Parameter Description Default
Pooling Whether connection pooling should be used. true
Minimum Pool Size The minimum connection pool size. 0
Maximum Pool Size The maximum connection pool size. 100 since 3.1, 20 previously
Connection Idle Lifetime The time (in seconds) to wait before closing idle connections in the pool if the count of all connections exceeds Minimum Pool Size. Introduced in 3.1. 300
Connection Pruning Interval How many seconds the pool waits before attempting to prune idle connections that are beyond idle lifetime (see Connection Idle Lifetime). Introduced in 3.1. 10
ConnectionLifetime The total maximum lifetime of connections (in seconds). Connections which have exceeded this value will be destroyed instead of returned from the pool. This is useful in clustered configurations to force load balancing between a running server and a server just brought online. 0 (disabled)

Timeouts and keepalive

Parameter Description Default
Timeout The time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error. 15
Command Timeout The time to wait (in seconds) while trying to execute a command before terminating the attempt and generating an error. Set to zero for infinity. 30
Internal Command Timeout The time to wait (in seconds) while trying to execute an internal command before terminating the attempt and generating an error. -1 uses CommandTimeout, 0 means no timeout. -1
Cancellation Timeout The time to wait (in milliseconds) while trying to read a response for a cancellation request for a timed out or cancelled query, before terminating the attempt and generating an error. -1 skips the wait, 0 means infinite wait. Introduced in 5.0. 2000
Keepalive The number of seconds of connection inactivity before Npgsql sends a keepalive query. 0 (disabled)
Tcp Keepalive Whether to use TCP keepalive with system defaults if overrides isn’t specified. false
Tcp Keepalive Time The number of milliseconds of connection inactivity before a TCP keepalive query is sent. Use of this option is discouraged, use KeepAlive instead if possible. Supported only on Windows. 0 (disabled)
Tcp Keepalive Interval The interval, in milliseconds, between when successive keep-alive packets are sent if no acknowledgement is received. Tcp KeepAlive Time must be non-zero as well. Supported only on Windows. value of Tcp Keepalive Time

Performance

Parameter Description Default
Max Auto Prepare The maximum number SQL statements that can be automatically prepared at any given point. Beyond this number the least-recently-used statement will be recycled. Zero disables automatic preparation. 0
Auto Prepare Min Usages The minimum number of usages an SQL statement is used before it’s automatically prepared. 5
Read Buffer Size Determines the size of the internal buffer Npgsql uses when reading. Increasing may improve performance if transferring large values from the database. 8192
Write Buffer Size Determines the size of the internal buffer Npgsql uses when writing. Increasing may improve performance if transferring large values to the database. 8192
Socket Receive Buffer Size Determines the size of socket receive buffer. System-dependent
Socket Send Buffer Size Determines the size of socket send buffer. System-dependent
No Reset On Close Improves performance in some cases by not resetting the connection state when it is returned to the pool, at the cost of leaking state. Use only if benchmarking shows a performance improvement false

Failover and load balancing

For more information, see the dedicated docs page.

Parameter Description Default
Target Session Attributes Determines the preferred PostgreSQL target server type. PGTARGETSESSIONATTRS, Any
Load Balance Hosts Enables balancing between multiple hosts by round-robin. false
Host Recheck Seconds Controls for how long the host’s cached state will be considered as valid. 10

Misc

Parameter Description Default
Options1 Specifies any valid PostgreSQL connection options (e.g. Options=-c synchronous_commit=local). Introduced in 5.0. PGOPTIONS
Application Name The optional application name parameter to be sent to the backend during connection initiation.
Enlist Whether to enlist in an ambient TransactionScope. true
Search Path Sets the schema search path.
Client Encoding Gets or sets the client_encoding parameter. PGCLIENTENCODING, UTF8
Encoding Gets or sets the .NET encoding that will be used to encode/decode PostgreSQL string data. UTF8
Timezone Gets or sets the session timezone. PGTZ
EF Template Database The database template to specify when creating a database in Entity Framework. template1
EF Admin Database The database admin to specify when creating and dropping a database in Entity Framework. template1
Load Table Composites Load table composite type definitions, and not just free-standing composite types. false
Array Nullability Mode Configure the way arrays of value types are returned when requested as object instances. Possible values are: Never (arrays of value types are always returned as non-nullable arrays), Always (arrays of value types are always returned as nullable arrays) and PerInstance (the type of array that gets returned is determined at runtime). Never

1The Options connection string parameter is essentially the string of command line options that get passed to the postgres program when the process is started.
It is most commonly used to set named run-time parameters via the -c option but other options can be used too (although not all of them make sense in that context).
Setting multiple options is possible by separating them with a space character. Space and backslash characters in option values need to be escaped by prefixing a backslash character.
Example: Options=-c default_transaction_isolation=serializable -c default_transaction_deferrable=on -c foo.bar=My\ Famous\\Thing

Compatibility

Parameter Description Default
Server Compatibility Mode A compatibility mode for special PostgreSQL server types. Currently «Redshift» is supported, as well as «NoTypeLoading», which will bypass the normal type loading mechanism from the PostgreSQL catalog tables and supports a hardcoded list of basic types. none

Obsolete

Parameter Description Default
Client Certificate Location of a client certificate to be sent to the server. Deprecated in 6.0. PGSSLCERT
Client Certificate Key Location of a client key for a client certificate to be sent to the server. Deprecated in 6.0. PGSSLKEY
Use Perf Counters Makes Npgsql write performance information about connection use to Windows Performance Counters. Removed in 5.0. false

Environment variables

In addition to the connection string parameters above, Npgsql also recognizes the standard PostgreSQL environment variables below. This helps Npgsql-based applications behave similar to other, non-.NET PostgreSQL client applications. The PostgreSQL doc page on environment variables recognized by libpq can be found here.

Environment variable Description
PGUSER Behaves the same as the user connection parameter.
PGPASSWORD Behaves the same as the password connection parameter. Use of this environment variable is not recommended for security reasons, as some operating systems allow non-root users to see process environment variables via ps; instead consider using a password file (see Section 33.15).
PGPASSFILE Behaves the same as the passfile connection parameter.
PGSSLCERT Behaves the same as the sslcert connection parameter.
PGSSLKEY Behaves the same as the sslkey connection parameter.
PGSSLROOTCERT Behaves the same as the sslrootcert connection parameter.
PGCLIENTENCODING Behaves the same as the client_encoding connection parameter.
PGTZ Sets the default time zone. (Equivalent to SET timezone TO ….)
PGOPTIONS Behaves the same as the options connection parameter.

Содержание

  1. Postgresql include error detail
  2. Предупреждение
  3. Предупреждение
  4. Примечание
  5. 31.1.1. Строки параметров подключения
  6. 31.1.1.1. Строки параметров подключения вида «ключ/значение»
  7. 31.1.1.2. URI для подключения
  8. 31.1.2. Ключевые слова-параметры

Postgresql include error detail

Следующие функции имеют дело с созданием подключения к серверу Postgres Pro . Прикладная программа может иметь несколько подключений к серверу, открытых одновременно. (Одна из причин этого заключается в необходимости доступа к более чем одной базе данных.) Каждое соединение представляется объектом PGconn , который можно получить от функций PQconnectdb , PQconnectdbParams или PQsetdbLogin . Обратите внимание, что эти функции всегда возвратят ненулевой указатель на объект, если только, возможно, не осталось слишком мало памяти даже для того, чтобы выделить её для объекта PGconn . Прежде чем передавать запросы через объект подключения, следует вызвать функцию PQstatus для проверки возвращаемого значения в случае успешного подключения.

Предупреждение

Если к базе данных, которая не приведена в соответствие шаблону безопасного использования схем, имеют доступ недоверенные пользователи, начинайте сеанс с удаления доступных им для записи схем из пути поиска ( search_path ). Для этого можно присвоить параметру с ключом options значение -csearch_path= . Также можно выполнить PQexec( соединение , «SELECT pg_catalog.set_config(‘search_path’, », false)») после подключения. Это касается не только psql , но и любых других интерфейсов для выполнения произвольных SQL-команд.

Предупреждение

В системе Unix создание дочернего процесса на основе процесса, уже имеющего открытые подключения с помощью libpq, может привести к непредсказуемым результатам, потому что родительский и дочерний процессы совместно используют одни и те же сокеты и ресурсы операционной системы. По этой причине подобный подход не рекомендуется. Однако использование системного вызова exec из дочернего процесса для загрузки нового исполняемого файла является безопасным.

Примечание

В системе Windows существует способ повышения производительности, при котором единственное соединение с базой данных повторно стартует и останавливается. На внутреннем уровне libpq вызывает WSAStartup() и WSACleanup() для старта и остановки соединения соответственно. WSAStartup() увеличивает на единицу внутренний счётчик ссылок в библиотеке Windows, который уменьшается на единицу при вызове WSACleanup() . Когда счётчик ссылок равен единице, вызов WSACleanup() освобождает все ресурсы, и все библиотеки DLL выгружаются. Это дорогостоящая операция. Для её избежания приложение может «вручную» вызвать WSAStartup() , чтобы ресурсы не были освобождены, когда закрыто последнее соединение с базой данных.

Создаёт новое подключение к серверу баз данных.

Эта функция открывает новое соединение с базой данных, используя параметры, содержащиеся в двух массивах, завершающихся символом NULL . Первый из них, keywords , определяется как массив строк, каждая из которых представляет собой ключевое слово. Второй, values , даёт значение для каждого ключевого слова. В отличие от PQsetdbLogin , описываемой ниже, набор параметров может быть расширен без изменения сигнатуры функции, поэтому использование данной функции (или её неблокирующих аналогов PQconnectStartParams и PQconnectPoll ) является предпочтительным при разработке новых приложений.

Ключевые слова-параметры, распознаваемые в настоящее время, приведены в Подразделе 31.1.2.

Когда expand_dbname имеет ненулевое значение, тогда в качестве значения, соответствующего ключевому слову dbname , может быть указана строка подключения. Только первый экземпляр dbname расширяется таким образом, а все последующие значения dbname будут обработаны как обычные имена базы данных. Дополнительные сведения о возможных форматах строки подключения можно найти в Подразделе 31.1.1.

Передаваемые массивы могут быть пустыми. В этом случае используются все параметры по умолчанию. Массивы могут также содержать один или более элементов и должны быть согласованы по длине. Обработка прекращается, когда найден первый элемент со значением NULL в массиве keywords .

Если какой-либо параметр имеет значение NULL или содержит пустую строку, проверяется значение соответствующей переменной окружения (см. Раздел 31.14). Если и переменная окружения не установлена, используется встроенное значение по умолчанию.

В общем случае ключевые слова обрабатываются в индексном порядке, начиная с начала этих массивов. Вследствие такого подхода, когда ключевые слова повторяются, сохраняется последнее обработанное значение. Следовательно, за счёт соответствующего расположения ключевого слова dbname можно регулировать, что может быть переопределено строкой conninfo , а что не может. PQconnectdb

Создаёт новое подключение к серверу баз данных.

Эта функция открывает новое соединение с базой данных, используя параметры, полученные из строки conninfo .

Передаваемая строка может быть пустой. В этом случае используются все параметры по умолчанию. Она также может содержать одно или более значений параметров, разделённых пробелами, или URI . За подробностями обратитесь к Подразделу 31.1.1. PQsetdbLogin

Создаёт новое подключение к серверу баз данных.

Это предшественница функции PQconnectdb с фиксированным набором параметров. Она имеет такую же функциональность, за исключением того, что непереданные параметры всегда принимают значения по умолчанию. Подставьте NULL или пустую строку в качестве любого из фиксированных параметров, которые должны принять значения по умолчанию.

Создаёт новое подключение к серверу баз данных.

Это макрос, который вызывает PQsetdbLogin с нулевыми указателями в качестве значений параметров login и pwd . Обеспечивает обратную совместимость с очень старыми программами. PQconnectStartParams
PQconnectStart
PQconnectPoll

Создают подключение к серверу баз данных неблокирующим способом.

Три эти функции используются для того, чтобы открыть подключение к серверу баз данных таким образом, чтобы поток исполнения вашего приложения не был заблокирован при выполнении удалённой операции ввода/вывода в процессе подключения. Суть этого подхода в том, чтобы ожидание завершения операций ввода/вывода могло происходить в главном цикле приложения, а не в внутри функций PQconnectdbParams или PQconnectdb , с тем, чтобы приложение могло управлять этой операцией параллельно с другой работой.

С помощью функции PQconnectStartParams подключение к базе данных выполняется, используя параметры, взятые из массивов keywords и values , а управление осуществляется с помощью expand_dbname , как описано выше для PQconnectdbParams .

С помощью функции PQconnectStart подключение к базе данных выполняется, используя параметры, взятые из строки conninfo , как описано выше для PQconnectdb .

Ни PQconnectStartParams , ни PQconnectStart , ни PQconnectPoll не заблокируются до тех пор, пока выполняется ряд ограничений:

Параметры hostaddr и host используются так, чтобы прямой и обратный DNS-запросы не выполнялись. Подробнее эти параметры описаны в Подразделе 31.1.2.

Если вы вызываете PQtrace , обеспечьте, чтобы поток, в который выводится трассировочная информация, не заблокировался.

Перед вызовом PQconnectPoll вы должны перевести сокет в соответствующее состояние, как описано ниже.

Примечание: использование PQconnectStartParams аналогично использованию PQconnectStart , показанному ниже.

Чтобы начать неблокирующий запрос на подключение, вызовите conn = PQconnectStart(» connection_info_string «) . Если значение conn пустое, то, значит, libpq не смогла распределить память для новой структуры PGconn . В противном случае будет возвращён корректный указатель PGconn (хотя ещё и не представляющий действительного подключения к базе данных). После возврата из PQconnectStart вызовите status = PQstatus(conn) . Если status имеет значение CONNECTION_BAD , то, значит, вызов PQconnectStart завершился сбоем.

Если вызов PQconnectStart был успешным, теперь нужно опросить libpq , чтобы она могла продолжить процесс подключения. Используйте PQsocket(conn) для получения дескриптора сокета, лежащего в основе соединения с базой данных. Организуйте цикл таким образом: если PQconnectPoll(conn) в последний раз возвратила PGRES_POLLING_READING , то подождите, пока сокет не станет готовым к выполнению операции чтения (это покажет функция select() , poll() или подобная системная функция). Затем вызовите PQconnectPoll(conn) опять. И наоборот, если PQconnectPoll(conn) в последний раз возвратила PGRES_POLLING_WRITING , то подождите, пока сокет не станет готовым к выполнению операции записи, затем вызовите PQconnectPoll(conn) снова. Если вам всё же приходится вызвать PQconnectPoll , то есть сразу после вызова PQconnectStart , поступайте так, как будто она в последний раз возвратила PGRES_POLLING_WRITING . Продолжайте этот цикл до тех пор, пока PQconnectPoll(conn) не возвратит PGRES_POLLING_FAILED , показывая, что процедура подключения завершилась сбоем, или PGRES_POLLING_OK , показывая, что соединение было успешно установлено.

В любое время в процессе подключения его состояние можно проверить, вызвав PQstatus . Если этот вызов возвратит CONNECTION_BAD , значит, процедура подключения завершилась сбоем; если вызов возвратит CONNECTION_OK , значит, соединение готово. Оба эти состояния можно определить на основе возвращаемого значения функции PQconnectPoll , описанной выше. Другие состояния могут также иметь место в течение (и только в течение) асинхронной процедуры подключения. Они показывают текущую стадию процедуры подключения и могут быть полезны, например, для предоставления обратной связи пользователю. Вот эти состояния:

Ожидание, пока соединение будет установлено. CONNECTION_MADE

Соединение установлено; ожидание отправки. CONNECTION_AWAITING_RESPONSE

Ожидание ответа от сервера. CONNECTION_AUTH_OK

Аутентификация получена; ожидание завершения запуска серверной части. CONNECTION_SSL_STARTUP

Согласование SSL-шифрования. CONNECTION_SETENV

Согласование значений параметров, зависящих от программной среды.

Заметьте, что, хотя эти константы и сохранятся (для поддержания совместимости), приложение никогда не должно полагаться на то, что они появятся в каком-то конкретном порядке или вообще появятся, а также на то, что состояние всегда примет одно из этих документированных значений. Приложение может сделать что-то наподобие:

Параметр подключения connect_timeout игнорируется, когда используется PQconnectPoll ; именно приложение отвечает за принятие решения о том, является ли истекшее время чрезмерным. В противном случае вызов PQconnectStart с последующим вызовом PQconnectPoll в цикле будут эквивалентны вызову PQconnectdb .

Заметьте, что если функция PQconnectStart возвращает ненулевой указатель, то, закончив его использование, вы должны вызвать PQfinish , чтобы освободить полученную структуру и все связанные с ней блоки памяти. Это нужно сделать, даже если попытка подключения не последует или окажется неуспешной. PQconndefaults

Возвращает значения по умолчанию для параметров подключения.

Возвращает массив параметров подключения. Он может использоваться для определения всех возможных параметров PQconnectdb и их текущих значений по умолчанию. Возвращаемое значение указывает на массив структур PQconninfoOption , который завершается элементом, имеющим нулевой указатель keyword . Если выделить память не удалось, то возвращается нулевой указатель. Обратите внимание, что текущие значения по умолчанию (поля val ) будут зависеть от переменных среды и другого контекста. Отсутствующий или неверный сервисный файл будет молча проигнорирован. Вызывающие функции должны рассматривать данные параметров по умолчанию как «только для чтения».

После обработки массива параметров освободите память, передав его функции PQconninfoFree . Если этого не делать, то при каждом вызове функции PQconndefaults будут происходить небольшие «утечки» памяти. PQconninfo

Возвращает параметры подключения, используемые действующим соединением.

Возвращает массив параметров подключения. Он может использоваться для определения всех возможных параметров PQconnectdb и значений, которые были использованы для подключения к серверу. Возвращаемое значение указывает на массив структур PQconninfoOption , который завершается элементом, имеющим нулевой указатель keyword . Все замечания, приведённые выше для PQconndefaults , также справедливы и для результата PQconninfo . PQconninfoParse

Возвращает разобранные параметры подключения, переданные в строке подключения.

Разбирает строку подключения и возвращает результирующие параметры в виде массива; возвращает NULL , если возникают проблемы при разборе строки подключения. Эту функцию можно использовать для извлечения параметров функции PQconnectdb из предоставленной строки подключения. Возвращаемое значение указывает на массив структур PQconninfoOption , который завершается элементом, имеющим нулевой указатель keyword .

Все разрешённые параметры будут присутствовать в результирующем массиве, но PQconninfoOption для любого параметра, не присутствующего в строке подключения, будет иметь значение NULL в поле val ; значения по умолчанию не подставляются.

Если errmsg не равно NULL , тогда в случае успеха *errmsg присваивается NULL , а в противном случае — адрес строки сообщения об ошибке, объясняющего проблему. Память для этой строки выделяет функция malloc . (Также возможна ситуация, когда *errmsg будет установлено в NULL , и при этом функция возвращает NULL . Это указывает на нехватку памяти.)

После обработки массива параметров освободите память, передав его функции PQconninfoFree . Если этого не делать, тогда некоторое количество памяти будет утекать при каждом вызове PQconninfoParse . И наоборот, если произошла ошибка и errmsg не равно NULL , обязательно освободите память, занимаемую строкой сообщения об ошибке, используя PQfreemem . PQfinish

Закрывает соединение с сервером. Также освобождает память, используемую объектом PGconn .

Обратите внимание, что даже если попытка подключения к серверу потерпела неудачу (как показывает PQstatus ), приложение все равно должно вызвать PQfinish , чтобы освободить память, используемую объектом PGconn . Указатель PGconn не должен использоваться повторно после того, как была вызвана функция PQfinish . PQreset

Переустанавливает канал связи с сервером.

Эта функция закроет подключение к серверу, а потом попытается восстановить подключение к тому же серверу, используя все те же параметры, которые использовались прежде. Это может быть полезным для восстановления после ошибки, если работающее соединение оказалось потерянным. PQresetStart
PQresetPoll

Переустанавливает канал связи с сервером неблокирующим способом.

Эти функции закроют подключение к серверу, а потом попытаются восстановить подключение к тому же серверу, используя все те же параметры, которые использовались прежде. Это может быть полезным для восстановления после ошибки, если работающее соединение оказалось потерянным. Они отличаются от PQreset (см. выше) тем, что действуют неблокирующим способом. На эти функции налагаются те же ограничения, что и на PQconnectStartParams , PQconnectStart и PQconnectPoll .

Чтобы приступить к переустановке подключения, вызовите PQresetStart . Если она возвратит 0, переустановка завершилась неудачно. Если она возвратит 1, опросите результат переустановки, используя PQresetPoll , точно таким же образом, как если бы вы создавали подключение, используя PQconnectPoll . PQpingParams

PQpingParams сообщает состояние сервера. Она принимает параметры подключения, идентичные тем, что получает функция PQconnectdbParams , описанная выше. Нет необходимости предоставлять корректные имя пользователя, пароль или имя базы данных, чтобы получить состояние сервера. Однако, если предоставлены некорректные значения, сервер занесёт в журнал неудачную попытку подключения.

Функция возвращает одно из следующих значений:

Сервер работает и, по-видимому, принимает подключения. PQPING_REJECT

Сервер работает, но находится в состоянии, которое запрещает подключения (запуск, завершение работы или восстановление после аварийного отказа). PQPING_NO_RESPONSE

Контакт с сервером не удался. Это может указывать на то, что сервер не запущен или что-то не в порядке с параметрами данного подключения (например, неверный номер порта), или имеет место проблема с возможностью соединения по сети (например, брандмауэр блокирует запрос на подключение). PQPING_NO_ATTEMPT

Никакой попытки установить контакт с сервером сделано не было, поскольку предоставленные параметры были явно некорректными, или имела место какая-то проблема на стороне клиента (например, нехватка памяти).

PQping сообщает состояние сервера. Она принимает параметры подключения, идентичные тем, что получает функция PQconnectdb , описанная выше. Нет необходимости предоставлять корректные имя пользователя, пароль или имя базы данных, чтобы получить состояние сервера. Однако, если предоставлены некорректные значения, сервер занесёт в журнал неудачную попытку подключения.

Возвращаемые значения такие же, как и для PQpingParams .

31.1.1. Строки параметров подключения

Ряд функций libpq получают параметры подключения, разбирая строки, заданные пользователем. Эти строки воспринимаются в двух форматах: простые строки ключ = значение и URI, соответствующие RFC 3986.

31.1.1.1. Строки параметров подключения вида «ключ/значение»

Согласно первому формату, установка каждого параметра выполняется в форме keyword = value . Пробелы вокруг знака равенства не являются обязательными. Для записи пустого значения или значения, содержащего пробелы, заключите его в одинарные кавычки, например, keyword = ‘a value’ . Одинарные кавычки и символы обратной косой черты внутри значения нужно обязательно экранировать с помощью символа обратной косой черты, т. е., ’ и \ .

Ключевые слова-параметры, распознаваемые в настоящее время, приведены в Подразделе 31.1.2.

31.1.1.2. URI для подключения

Для включения символов, имеющих специальное значение, в любой части URI можно применять URL-кодирование (с использованием символа %).

Любые параметры соединения, не соответствующие ключевым словам, приведённым в Подразделе 31.1.2, игнорируются, а предупреждающее сообщение об этом направляется на stderr .

Сервер можно представить либо доменным именем, либо IP-адресом. При использовании протокола IPv6 нужно заключить адрес в квадратные скобки:

Компонент «host» интерпретируется в соответствии с описанием параметра host. В частности, если этот компонент пуст или начинается с символа косой черты, выбирается соединение через Unix-сокеты, а в противном случае инициируется соединение по TCP/IP. Обратите внимание, однако, что символ косой черты в иерархической части URI является зарезервированным. Поэтому, чтобы указать нестандартный каталог Unix-сокета, нужно поступить одним из двух способов: не задавать сервер в URI и указать сервер в качестве параметра, либо закодировать путь в компоненте «host» с процентами:

31.1.2. Ключевые слова-параметры

Ключевые слова-параметры, распознаваемые в настоящее время, следующие:

Имя компьютера для подключения. Если оно начинается с косой черты, соединение будет установлено через Unix-сокет, а не по протоколу TCP/IP; значение задаёт имя каталога, содержащего файл сокета. По умолчанию, когда host не указан, подключение производится через Unix-сокет в каталоге /tmp (или в том каталоге, который был назначен при сборке Postgres Pro ). В системах, не поддерживающих Unix-сокеты, подключение по умолчанию производится к localhost . hostaddr

Числовой IP-адрес компьютера для подключения. Он должен быть представлен в стандартном формате адресов IPv4, например, 172.28.40.9 . Если ваша машина поддерживает IPv6, вы можете использовать и эти адреса. Связь по протоколу TCP/IP используется всегда, когда в качестве этого параметра передана непустая строка.

Использование hostaddr вместо host позволяет приложению избежать поиска на сервере имён, что может быть важно для приложений, имеющих временные ограничения. Однако, имя компьютера требуется для методов аутентификации GSSAPI или SSPI, а также для проверки полномочий на основе SSL-сертификатов в режиме verify-full . Используются следующие правила:

Если host указан, а hostaddr не указан, тогда выполняется поиск на сервере имён.

Если указан hostaddr , а host не указан, тогда значение hostaddr даёт сетевой адрес сервера. Попытка подключения завершится неудачей, если метод аутентификации требует наличия имени компьютера.

Если указаны как host , так и hostaddr , тогда значение hostaddr даёт сетевой адрес сервера, а значение host игнорируется, если только метод аутентификации его не потребует. В таком случае оно будет использоваться в качестве имени компьютера.

Заметьте, что аутентификация может завершится неудачей, если host не является именем сервера, имеющего сетевой адрес hostaddr . Заметьте также, что host , а не hostaddr используется для того, чтобы идентифицировать соединение в

Если не указаны ни имя компьютера, ни его адрес, libpq будет производить подключение, используя локальный Unix-сокет; в системах, не поддерживающих Unix-сокеты, она будет пытаться подключиться к localhost . port

Номер порта для подключения к серверу или расширение имени файла-сокета для подключений в домене Unix. dbname

Имя базы данных. По умолчанию оно совпадает с именем пользователя. В определённых контекстах это значение проверяется на соответствие расширенным форматам; см. Подраздел 31.1.1 для получения подробной информации. user

Имя пользователя Postgres Pro , используемое для подключения. По умолчанию используется то же имя, которое имеет в операционной системе пользователь, от лица которого выполняется приложение. password

Пароль, используемый в случае, когда сервер требует аутентификации по паролю. connect_timeout

Максимальный период ожидания подключения, в секундах (записывается в виде строки, представляющей десятичное целое число). client_encoding

Этим устанавливается конфигурационный параметр client_encoding для данного подключения. В дополнение к значениям, которые принимает соответствующий параметр сервера, вы можете использовать значение auto . В этом случае правильная кодировка определяется на основе текущей локали на стороне клиента (в системах Unix это переменная системного окружения LC_CTYPE ). options

Задаёт параметры командной строки, которые будут отправлены серверу при установлении соединения. Например, значение -c geqo=off установит для параметра сеанса geqo значение off . Пробелы в этой строке считаются разделяющими аргументы командной строки, если только перед ними не стоит обратная косая черта ( ); чтобы записать собственно обратную косую черту, её нужно продублировать ( \ ). Подробное описание возможных параметров можно найти в Главе 18. application_name

Устанавливает значение для конфигурационного параметра application_name. fallback_application_name

Устанавливает альтернативное значение для конфигурационного параметра application_name. Это значение будет использоваться, если для параметра application_name не было передано никакого значения с помощью параметров подключения или переменной системного окружения PGAPPNAME . Задание альтернативного имени полезно для универсальных программ-утилит, которые желают установить имя приложения по умолчанию, но позволяют пользователю изменить его. keepalives

Управляет использованием сообщений keepalive протокола TCP на стороне клиента. Значение по умолчанию равно 1, что означает использование сообщений. Вы можете изменить его на 0, если эти сообщения не нужны. Для соединений, установленных через Unix-сокеты, этот параметр игнорируется. keepalives_idle

Управляет длительностью периода отсутствия активности, выраженного числом секунд, по истечении которого TCP должен отправить сообщение keepalive серверу. При значении 0 действует системная величина. Этот параметр игнорируется для соединений, установленных через Unix-сокеты, или если сообщения keepalive отключены. Он поддерживается только в системах, воспринимающих параметр сокета TCP_KEEPIDLE или равнозначный, и в Windows; в других системах он не оказывает влияния. keepalives_interval

Управляет количеством секунд, по прошествии которых сообщение keepalive протокола TCP, получение которого не подтверждено сервером, должно быть отправлено повторно. При значении 0 действует системная величина. Этот параметр игнорируется для соединений, установленных через Unix-сокеты, или если сообщения keepalive отключены. Он поддерживается только в системах, воспринимающих параметр сокета TCP_KEEPINTVL или равнозначный, и в Windows; в других системах он не оказывает влияния. keepalives_count

Управляет количеством сообщений keepalive протокола TCP, которые могут быть потеряны, прежде чем соединение клиента с сервером будет признано неработающим. Нулевое значение этого параметра указывает, что будет использоваться системное значение по умолчанию. Этот параметр игнорируется для соединений, установленных через Unix-сокеты, или если сообщения keepalive отключены. Он поддерживается только в системах, воспринимающих параметр сокета TCP_KEEPCNT или равнозначный; в других системах он не оказывает влияния. tty

Игнорируется (прежде он указывал, куда направить вывод отладочных сообщений сервера). sslmode

следует пытаться установить только соединение без использования SSL allow

В Разделе 31.18 приведено подробное описание работы этих режимов.

sslmode игнорируется при использовании Unix-сокетов. Если Postgres Pro скомпилирован без поддержки SSL, использование параметров require , verify-ca или verify-full приведёт к ошибке, в то время как параметры allow и prefer будут приняты, но libpq в действительности не будет пытаться установить SSL -соединение. requiressl

Использовать этот параметр не рекомендуется, в качестве замены предлагается установить sslmode .

Если установлено значение 1 (по умолчанию), данные, пересылаемые через SSL-соединения, будут сжиматься (это требует OpenSSL версии 0.9.8 или более поздней). Если установлено значение 0, сжатие будет отключено (это требует OpenSSL версии 1.0.0 или более поздней). Этот параметр игнорируется, если выполнено подключение без SSL, или если используемая версия OpenSSL не поддерживает его.

Сжатие требует процессорного времени, но может улучшить пропускную способность, если узким местом является сеть. Отключение сжатия может улучшить время отклика и пропускную способность, если ограничивающим фактором является производительность CPU. sslcert

Этот параметр предписывает имя файла для SSL-сертификата клиента, заменяющего файл по умолчанию

/.postgresql/postgresql.crt . Этот параметр игнорируется, если SSL-подключение не выполнено. sslkey

Этот параметр предписывает местоположение секретного ключа, используемого для сертификата клиента. Он может либо указывать имя файла, которое будет использоваться вместо имени по умолчанию

/.postgresql/postgresql.key , либо он может указывать ключ, полученный от внешнего « криптомодуля » (криптомодули — это загружаемые модули OpenSSL ). Спецификация внешнего криптомодуля должна состоять из имени модуля и ключевого идентификатора, зависящего от конкретного модуля, разделённых двоеточием. Этот параметр игнорируется, если SSL-подключение не выполнено. sslrootcert

Этот параметр указывает имя файла, содержащего список отозванных SSL-сертификатов (CRL). Сертификаты, перечисленные в этом файле, если он существует, будут отвергаться при попытке установить подлинность сертификата сервера. Имя по умолчанию такое

Этот параметр указывает имя пользователя операционной системы, предназначенное для сервера, например, requirepeer=postgres . При создании подключения через Unix-сокет, если этот параметр установлен, клиент проверяет в самом начале процедуры подключения, что серверный процесс запущен от имени указанного пользователя; если это не так, соединение аварийно прерывается с ошибкой. Этот параметр можно использовать, чтобы обеспечить аутентификацию сервера, подобную той, которая доступна с помощью SSL-сертификатов при соединениях по протоколу TCP/IP. (Заметьте, что если Unix-сокет находится в каталоге /tmp или в другом каталоге, запись в который разрешена всем пользователям, тогда любой пользователь сможет запустить сервер, прослушивающий сокет в том каталоге. Используйте этот параметр, чтобы гарантировать, что вы подключены к серверу, запущенному доверенным пользователем.) Он поддерживается только на платформах, для которых реализован метод аутентификации peer ; см. Подраздел 19.3.6. krbsrvname

Имя сервиса Kerberos, предназначенное для использования при аутентификации на основе GSSAPI. Оно должно соответствовать имени сервиса, указанному в конфигурации сервера, чтобы аутентификация на основе Kerberos прошла успешно. (См. также Подраздел 19.3.3.) gsslib

Библиотека GSS, предназначенная для использования при аутентификации на основе GSSAPI. Используется только в системе Windows. Назначьте значение gssapi , чтобы заставить libpq использовать для аутентификации библиотеку GSSAPI вместо SSPI, применяемого по умолчанию. service

Источник

tyler-boyd

Steps to reproduce

I’m sorry but I don’t have a repro as this issue happens very intermittently in our production workloads.

The issue

Very rarely, when saving changes to the database, we get a DbUpdateException:

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
 ---> System.ArgumentException: The output byte buffer is too small to contain the encoded data, encoding codepage '20127' and fallback 'System.Text.EncoderReplacementFallback'. (Parameter 'bytes')
   at System.Text.Encoding.ThrowBytesOverflow()
   at System.Text.Encoding.ThrowBytesOverflow(EncoderNLS encoder, Boolean nothingEncoded)
   at System.Text.Encoding.GetBytesWithFallback(ReadOnlySpan`1 chars, Int32 originalCharsLength, Span`1 bytes, Int32 originalBytesLength, EncoderNLS encoder)
   at System.Text.ASCIIEncoding.GetBytesWithFallback(ReadOnlySpan`1 chars, Int32 originalCharsLength, Span`1 bytes, Int32 originalBytesLength, EncoderNLS encoder)
   at System.Text.Encoding.GetBytesWithFallback(Char* pOriginalChars, Int32 originalCharCount, Byte* pOriginalBytes, Int32 originalByteCount, Int32 charsConsumedSoFar, Int32 bytesWrittenSoFar)
   at System.Text.ASCIIEncoding.GetBytes(String chars, Int32 charIndex, Int32 charCount, Byte[] bytes, Int32 byteIndex)
   at Npgsql.NpgsqlCommand.<Write>g__WriteExecute|105_0(NpgsqlConnector connector, Boolean async, Boolean flush, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Infrastructure.Domain.Purchases.PurchaseEventRepository.Add(String purchaseId, BasePurchaseEvent data) in /src/src/Infrastructure/Domain/Purchases/PurchaseEventRepository.cs:line 121

Searching this error did not yield any open issues, but there seem to have been some similar issues in the past in npgsql.

Unfortunately, after this error happens, it seems to leave the connection «poisoned» and around 100 other requests on the same pod fail due to an error PostgresException: 42P05: prepared statement "_auto0" already exists.

I understand this isn’t much to go on, but would strongly appreciate advise on either how to investigate this buffer error further, or how to mitigate the effects and avoid the poisoned connection failing so many other requests.

Further technical details

Npgsql version: 7.0.0
PostgreSQL version: Aurora Postgres, I believe engine 11.9 compat
Operating system: Amazon EKS (Linux), running a Docker image based off mcr.microsoft.com/dotnet/sdk:7.0-bullseye-slim

Other details about my project setup:

  • Autoprepare is enabled
  • We do query/save binary blobs up to a few KB to postgres

arunsaho

Before submitting

This repo is for Npgsql ADO.NET issues only. My code is working fine while debugging. We are deploying the code in PCF.
It throws an exception while trying open the connection to PostgreSQL Server in Linux.

Steps to reproduce

The code is having issues while trying to open the connection.

The issue

Describe what is not working as expected.

Exception message: Exception while reading from stream

Npgsql.NpgsqlException (0x80004005): Exception while reading from stream
—> System.TimeoutException: Timeout during reading attempt
Npgsql.Internal.NpgsqlReadBuffer.g__EnsureLong|41_0(NpgsqlReadBuffer buffer, Int32 count, Boolean async, Boolean readingNotifications)
Npgsql.Internal.NpgsqlConnector.RawOpen(SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
Npgsql.Internal.NpgsqlConnector.g__OpenCore|191_1(NpgsqlConnector conn, SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
Npgsql.Internal.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
Npgsql.ConnectorPool.OpenNewConnector(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
Npgsql.ConnectorPool.g__RentAsync|28_0(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
Npgsql.NpgsqlConnection.g__OpenAsync|45_0(Boolean async, CancellationToken cancellationToken)

Further technical details

Npgsql version: 6.0.4
PostgreSQL version: 13.3
Operating system: Linux 8.x

Other details about my project setup:

zhujoel

Hello,

Is there a reason why the function WriteRowAsync doesn’t acccept null as values? The document states that it is equivalent to calling StartRow with multiple Write. Write does allow null values through the [AllowNull] attribute.

Currently, we must force the null through a bang operator !, which is not ideal.

Would be nice if it was supported! Thanks. 🙂

Npgsql version: 7.0.1.0

Other details about my project setup: We get the warning CS8604 — Possible null reference argument for parameter.

datguyvladik

Hello,

After migrating to version 7.0.1 missing metrics npgsql_busy_connections and npgsql_idle_connections. The implementation of getting metrics has not changed. On Npgsq version 4.1.9 and Npgsql.EntityFrameworkCore.PostgreSQL version 3.1.4 everything worked.

Here is my code how i get metrics options. Also i use app.metrics.aspnetcore version 4.3.0

    internal sealed class MetricsCollectionService : EventListener, IHostedService
    {
        private readonly IMetrics _metrics;
        private readonly List<MetricValueOptionsBase> _metricsOptions;
        private readonly string[] _sources = new[] { "Npgsql", "System.Runtime", "Microsoft.AspNetCore.Hosting" };

        public MetricsCollectionService(IMetrics metrics)
        {
            _metrics = metrics;
            var sourceName = nameof(IExternalMetrics.SourceName);
            _metricsOptions = Assembly.GetExecutingAssembly()
                .GetTypes()
                .Where(t => t.GetInterfaces().Contains(typeof(IExternalMetrics)))
                .Where(t => _sources.Contains(t.GetProperty(sourceName).GetValue(null, null) as string))
                .SelectMany(t => t.GetProperties()
                    .Where(p => p.PropertyType.IsSubclassOf(typeof(MetricValueOptionsBase)))
                    .Select(p => p.GetValue(null, null) as MetricValueOptionsBase))
                .ToList();
        }

        public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;

        protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            if (_metrics is null || _metricsOptions is null)
                return;

            if (eventData.EventName != "EventCounters"
                || eventData.Payload.Count <= 0
                || !(eventData.Payload[0] is IDictionary<string, object> data))
                return;

            WriteCounters(data);
        }

        private void WriteCounters(IDictionary<string, object> eventPayload)
        {
            var name = (string) eventPayload["Name"];
            var metricOptions = _metricsOptions.FirstOrDefault(x => x.Name == name);

            if (metricOptions == null)
            {
                return;
            }

            if (metricOptions is GaugeOptions)
            {
                _metrics.Measure.Gauge.SetValue((GaugeOptions) metricOptions, Convert.ToSingle(eventPayload["Mean"]));

            }
            else if (metricOptions is CounterOptions)
            {
                _metrics.Measure.Counter.Increment((CounterOptions) metricOptions, Convert.ToInt64(eventPayload["Increment"]));
            }
        }

        protected override void OnEventSourceCreated(EventSource eventSource)
        {
            foreach (var allowedSource in _sources)
            {
                if (eventSource.Name.Equals(allowedSource, StringComparison.OrdinalIgnoreCase))
                {
                    EnableEvents(eventSource, EventLevel.Verbose, EventKeywords.None, new Dictionary<string, string>
                    {
                        {"EventCounterIntervalSec", "1"}
                    });
                }
            }
        }
    }

Have these metrics been removed or am I doing something wrong?

Further technical details

Npgsql version: 7.0.1
Npgsql.EntityFrameworkCore.PostgreSQL version: 7.0.1
PostgreSQL version: 13.9.0
Operating system: docker

Anioz

Steps to reproduce

Create Xamarin Forms project with Xamarin Android tree branch
Implement connection method and surround it with try catch under the Xamarin Android tree branch
make sure local lan wifi is available WITHOUT internet access
try to use the method

The issue

try catches are ignored and method crashes the complete app

It should never ignore the catch, using the method on a seperate thread makes no difference at the moment

Less than ideal workaround

I now ping a time server and surround that with a try catch before trying to connect to the cluster however pinging the clusters directly is disabled by default and there could be a situation where the cluster isnt available and the time server (route) is

Further technical details

Npgsql version: 7.0.1
Operating system: Windows 21H1

Other details about my project setup:
Visual Studio Enterprise 2022
PCL uses Netstandard 2.0

steveoh

Steps to reproduce

Try to UseNetTopologySuite(); as the readme states on this project

NpgsqlConnection.GlobalTypeMapper.UseNetTopologySuite();

The issue

Describe what is not working as expected.

warning CS0618: 'NpgsqlConnection.GlobalTypeMapper' is obsolete: 'Global-level type mapping has been replaced with data source mapping, see the 7.0 release notes.

What is the correct way to use the topology suite now that the global type mapper is deprecated?

I’m happy to pr this to the readme so others can benefit from it also.

jeet137

Steps to reproduce

I am running a select query (using linq) which is fetching some records from the postgres database. Then I upgraded the npgsql 2.0 to npgsql 6.0.3. Then the below issue starts coming.

 ### Query in code as linq:

SELECT
system_update_time
FROM Company com WHERE
(com.system_update_time > :p1) // here I am doing one comparison.

I am passing :p1 = DateTime.UtcNow in code.

The issue

An exception was caught during the execution of a retrieval query: Cannot write DateTime with Kind=UTC to PostgreSQL type ‘timestamp without time zone’, consider using ‘timestamp with time zone’. Note that it’s not possible to mix DateTimes with different Kinds in an array/range. See the Npgsql.EnableLegacyTimestampBehavior AppContext switch to enable legacy behavior.

This column called StartDate which is present in database is of type «timestamp with time zone».

Further technical details

Npgsql version: 6.0.3
PostgreSQL version: 14
Operating system: windows 2022

cwsheng

Steps to reproduce

  1. use npgsql 7.0.1 packages
  2. Create a connection using the following code
    var conn = new NpgsqlConnection(BaseString); if (conn.State != ConnectionState.Open) conn.Open();

The issue

Describe what is not working as expected.

If you are seeing an exception, include the full exceptions details (message and stack trace).

Exception message:There is not enough space left in the buffer.
Stack trace:
   at Npgsql.Internal.NpgsqlReadBuffer.ThrowNotSpaceLeft()
   at Npgsql.PostgresDatabaseInfo.LoadBackendTypes(NpgsqlConnector conn, NpgsqlTimeout timeout, Boolean async)
   at Npgsql.PostgresDatabaseInfo.LoadPostgresInfo(NpgsqlConnector conn, NpgsqlTimeout timeout, Boolean async)
   at Npgsql.PostgresDatabaseInfoFactory.Load(NpgsqlConnector conn, NpgsqlTimeout timeout, Boolean async)
   at Npgsql.Internal.NpgsqlDatabaseInfo.Load(NpgsqlConnector conn, NpgsqlTimeout timeout, Boolean async)
   at Npgsql.Internal.NpgsqlConnector.LoadDatabaseInfo(Boolean forceReload, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Internal.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.ConnectorPool.OpenNewConnector(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.ConnectorPool.<Get>g__RentAsync|31_0(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<Open>g__OpenAsync|45_0(Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.Open()

Further technical details

Npgsql version: 7.0.1
PostgreSQL version: PostgreSQL 16devel on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44), 64-bit
Operating system: win 10

Other details about my project setup:

roji

Npgsql provides NpgsqlDate, NpgsqlDateTime and NpgsqlTimeSpan for reading and writing date/time values that cannot be represented with the standard BCL DateTime/TimeSpan (which are more limited in range). However, now that we support NodaTime, it may be a good idea to obsolete these provider-specific types.

These types are probably pretty inefficient and contain bugs (e.g. this, they’re seldom-used and a bit untested), and it just doesn’t seem right for a database driver to come with its own date/time types. One possible compromise is to keep the types but remove all calculations on them; this would at least allow access to out-of-range values.

Changes done for 6.0:

  • NpgsqlDateTime, NpgsqlDate and NpgsqlTimeSpan are now obsolete. They will be removed in Npgsql 7.0.
  • NodaTime can be used to interact with values which are out-of-range for the BCL types.
  • To support values which are out-of-range for NodaTime, PostgreSQL timestamps can now be read/written as long, and dates can be read/written as int. These are the raw PostgreSQL representations, with no operations — they simply provide an «escape hatch» in case users need to interact with out-of-range values.
  • For interval, a new NpgsqlInterval type has been introduced, which again contains the raw PostgreSQL data (months, days, time); no conversions, no methods — just pure raw data.

Moved from npgsql/efcore.pg#468

mibiio

Hello,

I am trying to upgrade a large app from Npgsql 5.x to Npgsql 6.x.
Its not possible to upgrade everything at once to the new Timestamp behaviour. Is there a way to set AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); as default but also have the option to opt-in to the new behavior for the already checked/rewritten parts of the application?

thanks,

rogerfar

According to the docs from Microsoft the ExecuteDeleteAsync should run within a transaction context:
https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-7.0/whatsnew#executeupdate-and-executedelete-bulk-updates

Multiple ExecuteDelete and ExecuteUpdate commands will not be contained in a single transaction by default. However, the [DbContext transaction APIs](https://learn.microsoft.com/en-us/ef/core/saving/transactions) can be used in the normal way to wrap these commands in a transaction.

But when running this code:

var builder = new DbContextOptionsBuilder<DataContextTransactionLogs>();
builder.UseNpgsql(connectionString);
await using var dataContextTransactionLogs = new DataContextTransactionLogs(builder.Options);

await using var dbContextTransaction = await dataContext.Database.BeginTransactionAsync();

try
{
	foreach (var messageId in messageIds)
	{
		var message = await dataContext.Messages.FirstAsync(m => m.MessageId == messageId);
		dataContext.Remove(message);
	}

	// This works
	await dataContext.SaveChangesAsync();

	// Will give foreign key exceptions
	await dataContext.Messages.Where(m => messageIds.Contains(m.MessageId)).ExecuteDeleteAsync();

	await dbContextTransaction.CommitAsync();
}
catch
{
	await dbContextTransaction.RollbackAsync();
}

The manual removing record by record and SaveChangesAsync uses the transaction, but ExecuteDeleteAsync does not.

vonzshik

In some cases instead of sending a query immediately, we prepend it, so we can send it with a next query. We do this for BEGIN TRANSACTION and whenever a connection is reset as it’s returned to the pool.
#4907 made it so we shouldn’t even send a cancellation request until we’ve read all of the responses for the prepended query. Instead, we can make it so the prepended query runs in the same transaction as an actual query.
This is going to require:

  • Make prepended queries use extended query protocol
  • Automatically prepare all of prepended queries on opening a connection
  • We should restore the write buffer with prepended query whenever there is an error while executing a query
  • Benchmark the change

cc @roji

biodevc

Steps to reproduce

Open a connection using SSPI authentication from a Windows Server 2012 R2 client (or Windows 8.1) using version 7.0.1 of Npgsql.

The issue

Getting an ‘Exception while reading from stream’ when opening a connection using SSPI authentication and version 7.0.1 of Npgsql from a Windows Server 2012 R2 client (or Windows 8.1).

Non-SSPI, ie standard username/password, authentication works fine.

Npgsql version 6.0.8 is unaffected.

Windows 10 clients are unaffected.

Exception message: 
   Exception while reading from stream
Stack trace:
   at Npgsql.Internal.NpgsqlReadBuffer.<Ensure>g__EnsureLong|42_0(NpgsqlReadBuffer buffer, Int32 count, Boolean async, Boolean readingNotifications)
   at Npgsql.Internal.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|226_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
   at Npgsql.Internal.NpgsqlConnector.AuthenticateGSS(Boolean async)
   at Npgsql.Internal.NpgsqlConnector.Authenticate(String username, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Internal.NpgsqlConnector.<Open>g__OpenCore|208_1(NpgsqlConnector conn, SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
   at Npgsql.Internal.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.PoolingDataSource.OpenNewConnector(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.PoolingDataSource.<Get>g__RentAsync|28_0(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<Open>g__OpenAsync|45_0(Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.Open()

Further technical details

Npgsql version: 7.0.1
.NET version: 7.0.101
PostgreSQL version: 15.1
Operating system: Windows Server 2012 R2 (and also Windows 8.1)

Other details about my project setup:
Works fine when not using SSPI.
Works fine when connecting from Windows 10 clients.
Works fine when using Npgsql version 6.0.8.
Also affects Windows 8.1 which I realise is EOL however Windows Server 2012 R2 is supposedly still in support.

mgkeen

Steps to reproduce

There’s no obvious steps. We have a reasonably high level of traffic on this DB instance and we see a message like this every few weeks. It’s not having an impact on us, but it says please file a bug 😄

Let me know if there’s any other information I can provide!

The issue

A couple of times now we’ve seen error messages along these lines:

On 26/1/23:

Exception message: Received backend message CommandComplete while expecting BindCompleteMessage. Please file a bug.
Stack trace:
async Task<bool> NpgsqlDataReader.NextResult(bool async, bool isConsuming, CancellationToken cancellationToken)
async ValueTask<NpgsqlDataReader> NpgsqlCommand.ExecuteReader(CommandBehavior behavior, bool async, CancellationToken cancellationToken) x 2
async Task<TResult> TaskContinuationGenerator<TIntegration, TTarget, TReturn, TResult>.ContinuationAction(Task<TResult> previousTask, TTarget target, CallTargetState state)

On 5/1/23:

Exception message: Received backend message CommandComplete while expecting ParseCompleteMessage. Please file a bug.
Stack trace:
async Task<bool> NpgsqlDataReader.NextResult(bool async, bool isConsuming, CancellationToken cancellationToken)
async ValueTask<NpgsqlDataReader> NpgsqlCommand.ExecuteReader(CommandBehavior behavior, bool async, CancellationToken cancellationToken) x 2
async Task<TResult> TaskContinuationGenerator<TIntegration, TTarget, TReturn, TResult>.ContinuationAction(Task<TResult> previousTask, TTarget target, CallTargetState state)

For the one that happened today, these are the potentially relevant log lines from our postgres error logs:

2023-01-26 02:36:15 UTC:10.11.1.205(49184):<user>@<database>:[30821]:ERROR: canceling statement due to user request
2023-01-26 02:36:15 UTC:10.11.1.205(49184):<user>@<database>:[30821]:STATEMENT: SET SESSION AUTHORIZATION DEFAULT;RESET ALL;CLOSE ALL;UNLISTEN *;SELECT pg_advisory_unlock_all();DISCARD SEQUENCES;DISCARD TEMP
2023-01-26 02:36:15 UTC:10.11.1.205(49184):<user>@<database>:[30821]:LOG: could not receive data from client: Connection reset by peer

Further technical details

Npgsql version: 6.0.7
PostgreSQL version: 14.4 and 11.16 (we upgraded between occurrences)
Operating system: Alpine linux

Other details about my project setup:

satishviswanathan

Overview

Framework : Dotnet core 5.0
Ngpsql version : 6.0.4
Pooling : false. Pooling is disable in connection string.

Question

I’m using Pgbouncer for the connection pooling. Basically I’m looking for a recommendation if it would be a good practice to enable pooling in the connection string while using it with Pgbouncer ? If it’s not a good practice then what is the impact it creates when it is enabled.

Thanks in advance !

roji

The total size of the binary is 29.80MB (compared to 14.83MB trimmed, 11.28MB trimmed compressed). Npgsql code accounts for 4.2MB. Inspect actual size within Npgsql to understand what’s going on, e.g. where do we have generic explosion.

A lot of this most probably comes from our type handlers, see what can be done there.

Dumps produced by @eerhardt (thank you ❤️):

Npgsql.Internal.TypeHandlers.txt
npgsql-aot-size.txt

Work:

  • #4846
  • #4892
  • #4898
  • #4896
  • #4897
  • TLS?
  • ICU?

roji

A NativeAOT size analysis of Npgsql shows 276k of System.Text.RegularExpressions. These come from the geometry types (NpgsqlPoint, NpgsqlLine…), which parse their PG text representation via regex, and a trivial usage in PgPassFile.

We should remove these. In general, we shouldn’t be in the business of reimplementing PG text representations (no other type does this any more), and the geometry types are very rarely used.

roji

We’re concentrating efforts into reducing Npgsql’s size when using NativeAOT. We should generate a report in CI which shows the overall size + breakdown, to make it easier to locate regressions etc.

roji

roji

And probably remove CreateTempPool.

Понравилась статья? Поделить с друзьями:
  • Inaccessible boot device windows 10 как исправить через биос на ноутбуке
  • Inaccessible boot device windows 10 как исправить lenovo
  • In the context of data services an unknown internal server error occurred перевод
  • In silence ошибка голосового чата пожалуйста проверьте
  • In passing steam error