Include error detail in the connection string

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.

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. Повторяющееся значение ключа нарушает уникальное ограничение «PK_Users». Ошибка в EntityFramework при попытке вставить объект с отношением 1: N.
  2. Name already in use
  3. doc / conceptual / Npgsql / connection-string-parameters.md
  4. newly created Oracle connection fails, visual studio code #137
  5. Comments

Повторяющееся значение ключа нарушает уникальное ограничение «PK_Users». Ошибка в EntityFramework при попытке вставить объект с отношением 1: N.

Я создаю приложение веб-API ASP.NET, и у меня есть две сущности: пользователь и устройство. У пользователя есть отношения «один ко многим» с устройствами (у пользователя несколько устройств). Проблема в том, что когда я вставляю новое устройство с определенным идентификатором пользователя, я получаю неприятную ошибку из базы данных Posgres, которую я использую. Я начну с показа своих сущностей:

Нет необходимости показывать метод контроллера, который перехватывает почтовый запрос для вставки устройства, этот метод просто вызывает следующую служебную функцию:

Я использую шаблон репозитория с единицей работы. Общий метод Insert в репозитории очень прост и хорошо работает с другими объектами:

Позвольте мне теперь объяснить детали моей проблемы. Например, у меня в базе данных есть пользователь с идентификатором 1. В Swagger я хочу вставить следующее устройство, например:

Я говорю, что это устройство принадлежит пользователю с идентификатором 1. Код ответа на запрос, который я получаю, — это внутренняя ошибка сервера 500 и следующая ошибка:

Когда я вставляю устройство с идентификатором пользователя, которого еще нет в базе данных, например, например, 10, оно создает нового пользователя с идентификатором 10 со всеми пустыми полями. Эта ошибка возникает при вызове _context.SaveChangesAsync (). Если мне нужно вставить устройство в базу данных с данными, представленными выше, с использованием простого SQL непосредственно в Postgres, оно будет работать нормально. EntityFramework делает что-то не так, или я что-то делаю не так. В чем может быть причина моей проблемы? Если вам потребуется дополнительная информация, я с радостью ее предложу, мне срочно нужно решить эту проблему. Спасибо!

Изменить: Моя первая миграция выглядит так:

Я добавил свойство навигации, как сказал @Thyselius, и это не решило проблему. Это миграция после добавления:

Источник

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.

Источник

newly created Oracle connection fails, visual studio code #137

Describe the bug
When trying to connect to oracle database with new connection, notification continues to say «You need «oracledb@3.1.1″ to connect to database.» When I click install i get no response with no connection or a «Request DependencyInstaller/install failed unexpectadly without providing any details» Error with no connection. FYI I have already installed node js and node-oracledb was already installed. I also set the node runtime variable in vscode settings.json. Is there another step I am missing?

To Reproduce
Steps to reproduce the behavior:

  1. Create a new connection with Oracle
  2. Enter necessary db details to connection page
  3. click create
  4. See Notification then bug

Expected behavior
Connect to database to begin writing queries

Desktop (please complete the following information):

Additional context
first time user of sqltools

The text was updated successfully, but these errors were encountered:

Hey @diggerydoo68 .
Please post output from «Output» view (Ctrl + Shift +U) — channel «SQLTools Language Server» (right corner dropdown) just after the error happens, And also from channell «SQLTools».
That would be really helpful. Thanks

@mickeypearce I’m assigning this one to you, so you can verify and work on it.

If confirmed, let me in case we need to publish it.

I realized after looking at the output(thanks for that info) why it was having trouble installing the oracledb extension. Now the extension is installed but I am getting a «ORA-12154: TNS: could not resolve the connect identifier specified» error. Does SQLtools use a ODBC driver? How does sqltools locate the tsnames.ora file?

SQLTools uses node-oracledb driver that uses Oracle native client (Instant Client, for ex.) for connecting to Oracle DB.

Service name should be specified in «database» property of connections setting:

For example if you have tnsnames.ora file with service name defined or any other alternative connection strings:

<
«dialect»: «OracleDB»,
«name»: «oracledb2»,
«username»: «hr»,
«password»: «welcome»,
«askForPassword»: false,
«connectionTimeout»: 15,
«database»: «oraclpdb»
>

If that wouldn’t work you can include the whole connection string directly in «database» property:
«database: «hostname:port/service_name» , including alternative types, etc

Property «port» and «server should be excluded! in this case.

@diggerydoo68 did you get it running?

Let us know so we could close this issue.

Still working on it. Where is it writing the connections details to? I don’t see it in the settings.json file nor my oracle files (tnsnames.ora or oracle instant client folder). I created a connection through the regular «Setup a new connection» interface and I added the whole connection string to the the «database field» and excluded the port field and it still gave me the above Oracle error after trying to connect.

a follow up question does sqltools work with LDAP?

In the workspace settings. Try manually adding connection to settings.json. maybe there is a problem if ./.vscode/settings.json doesn’t exist already.

Maybe we should print actual connection string to output for easier debugging or even leave out port and server option completely.

I’m having the same problem as first described. In my case, the installation fails because of the proxy authentication settings.
It seems that the installation command does not use the .npmrc settings on my user profile nor the «http.proxy» from vscode?.
Do I need to add those settings somewhere else?

Hmmm. I’ll take a look. I haven’t tested with a proxy. Should work seamlessly, but I better to take a second look at this.

@rogenaro if you have JS skills and wants to try, take a shot please.

There is a link in the comment with proxy instructions.

@mtxr, where libs get installed to try this first manually? In the ext folder or somewhere else?

@rogenaro can you provide some information about your setup?
Which OS, npm/node version are you using? Where is you npmrc file? Workspace dir or home dir?

no dice. I manually added the connection details to the settings.json file. I ran it and it still gave me the TNS error. How do I know that it is using that settings file? If I go and create the connection through the extension interface it does not change my settings.json file. Should it? I also tried leaving out the server and port option. It still gives me the TNS oracle error. I’m a little fuzzy on how I can print the connection string to the output interface. How would that work with this extension?

@mtxr , do you perhaps have any idea why it wouldn’t add/create settings file? I tried with no folder open, but it prints an error about not opened workspace. 👍

@diggerydoo68 , yes, it should be added to your workspace setting file. Do you see your connection in connection explorer? Can you please check your user settings if it was added there for some reason. (%USERPROFILE%AppDataRoamingCodeUsersettings.json or «Preferences: Open User Settings» command.

ok so whenever I create a new connection it shows up in the connection explorer and the connection details are written to the settings.json from the workspace directory and nothing gets written to the settings.json for the user settings (%USERPROFILE%AppDataRoamingCodeUsersettings.json ). I need to keep my settings.json files straight. So usually I am connecting via sqldeveloper to the database using an LDAP connection.

About LDAP connection: oracle/node-oracledb#287 (comment)
There is a link in the comment that could be helpful. Unfortunately you need some extra steps.

@mickeypearce it’s a bug. We should be able to create connections for workspaces, or just in user settings.

I’ll fix this tonight. Thanks!

I’ve fixed the add connection issue. I’m keeping the default behavior but I added an option to always save to globalSettings.

I’ll close this issue since @mickeypearce comment seems to resolve the LDAP connection.

@mickeypearce or @diggerydoo68 would be great if you could write a guide to get LDAP running with the extension.

@diggerydoo68 if it doesn’t solve your problem, feel free to reopen this issue for further investigation.

I tried to use this plugin to connect to my work database but no luck.
Still using Datagrip with no problem.

Источник

Когда я хочу сохранить много данных в базе данных (PostgreSQL 12 и Entity Framework Core (C #)), я получаю следующие исключения:

fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (197ms) [Parameters=[@p0='?', @p1='?', @p2='?' (DbType = DateTimeOffset), @p3='?'], CommandType='Text', CommandTimeout='30']
      INSERT INTO "FileInfos" ("FileId", "FileName", "LastModifiedDateTime", "Path")
      VALUES (@p0, @p1, @p2, @p3);
fail: Microsoft.EntityFrameworkCore.Update[10000]
  An exception occurred in the database while saving changes for context type 'PostgreSQLConnect.ContextModels.WebhookContext'.
  Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
   ---> Npgsql.PostgresException (0x80004005): 23505: duplicate key value violates unique constraint "PK_FileInfos 
    Severity: FEHLER
      SqlState: 23505
      MessageText: double key value violates unique constraint »PK_FileInfos«
      Detail: Detail redacted as it may contain sensitive data. Specify 'Include Error Detail' in the connection string to include this information.
      SchemaName: public
      TableName: FileInfos
      ConstraintName: PK_FileInfos
      File: d:pginstaller_12.autopostgres.windows-x64srcbackendaccessnbtreenbtinsert.c
      Line: 570
      Routine: _bt_check_unique

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

    private async Task SaveFileInfos(FileInfo fileInfo)
    {
        var foundFileInfo = _context.FileInfos.
        Where(f => f.FileId == fileInfo.FileId).FirstOrDefault();

        if (foundFileInfo == null)
        {
            await _context.FileInfos.AddAsync(fileInfo);
        }
        else
        {
            foundFileInfo.FileName = fileInfo.FileName;
            foundFileInfo.LastModifiedDateTime = fileInfo.LastModifiedDateTime;
            foundFileInfo.Path = fileInfo.Path;
        }

        await _context.SaveChangesAsync();
    }
     

Класс сущности:

    public class FileInfo : IFileInfo
    {

    [Key]
    public string FileId {get; set;}

    public string FileName {get; set;}

    public DateTimeOffset? LastModifiedDateTime {get; set;}

    public string Path {get; set;}
    }

Класс контекста:

   public class WebhookContext : DbContext
   {
    public WebhookContext(DbContextOptions<WebhookContext> options) : base(options) { }

    public DbSet<FileInfo> FileInfos { get; set; }
    }

Цикл, вызывающий метод сохранения:

 private async Task ConvertAndSaveFiles(IDriveItemDeltaCollectionPage files)
  { 

    foreach (var file in files)
    {
         await SaveFileInfos(file.Name, file.Id, file.LastModifiedDateTime,
                    file.ParentReference.Path);
    }
           
  }

Кстати: идентификатор уже был сгенерирован другим приложением и состоит из 34 символов.

Какую ошибку я сделал новичком? :-)

2 ответа

Лучший ответ

  • Используйте FirstOrDefaultAsync
  • Если предложение является избыточным, его также можно удалить
    private async Task SaveFileInfos(FileInfo fileInfo)
    {
        //update your code to use FirstOrDefaultAsync
        var foundFileInfo = await _context.FileInfos
        .FirstOrDefaultAsync(f => f.FileId == fileInfo.FileId);

        if (foundFileInfo == null)
        {
            await _context.FileInfos.AddAsync(fileInfo);
        }
        else
        {
            foundFileInfo.FileName = fileInfo.FileName;
            foundFileInfo.LastModifiedDateTime = fileInfo.LastModifiedDateTime;
            foundFileInfo.Path = fileInfo.Path;
        }

       // move this outside the for loop.
       // this will round trip to Db in EVERY fileInfo, not an optimal solution.
        await _context.SaveChangesAsync(); 
    }
  • Рассмотрите возможность вызова await _context.SaveChangesAsync (); вне цикла for
 private async Task ConvertAndSaveFiles(IDriveItemDeltaCollectionPage files)
  { 

    foreach (var file in files)
    {
         await SaveFileInfos(file.Name, file.Id, file.LastModifiedDateTime,
                    file.ParentReference.Path);
    }

    // this will save everything to Db in just 1 round trip
    await _context.SaveChangesAsync(); 
}


2

Edd
23 Сен 2021 в 06:44

Поскольку вы упомянули, что эта проблема возникает, когда вы много пишете в базу данных, проблема может заключаться в том, как вы вызываете метод SaveFileInfos (FileInfo fileInfo) (вызов из параллельного цикла?), Если в этом случае ваш вызов foundFileInfo не будет обнаруживать дубликаты.

Также подумайте о том, чтобы избегать SaveChangesAsync внутри цикла.


1

Lemanas
22 Сен 2021 в 22:59

Понравилась статья? Поделить с друзьями:
  • 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