Skip to content

support connection URI - #2733

Closed
y-code wants to merge 2 commits into
npgsql:mainfrom
y-code:support-connection-uri
Closed

y-code wants to merge 2 commits into
npgsql:mainfrom
y-code:support-connection-uri

Conversation

@y-code

@y-code y-code commented Nov 10, 2019

Copy link
Copy Markdown

resolves #2090

Based on the comments in #2090, I assumed the following requirements and designed the specification as follows.

However, a couple of questions remained. Please refer the questions on the bottom and give me an advice.

Requirements

When initializing NpgsqlConnection with a Connection URI, Npgsql should behave as defined in PostgreSQL's documentation. However, the following features are not supported at this phase.

  • Multiple hosts
  • Multiple ports
  • URI parameter related to functionality Npgsql does not support
  • URI parameter deprecated in Connection URI

High-Level Specification

Refer PostgreSQL's documentation.

For the individual behaviours which the document does not specify, Npgsql conforms to the behaviour of psql. Those are:

  • The while path component of Connection URI is regarded as a database name, excluding the slash at the beginning.
  • Any component in the hierarchical part of the URI can be omitted. For example, postgresql:// and postgresql://:@Otherhost:/? are both valid as a Connection URI. In such a case, the default value applies.
  • What components of the hierarchical part of URI specify, can be overwritten by a corresponding URI parameter.
  • Empty value of a URI parameter means that the default value defined for the parameter applies. The empty value never results in fall-back to the equivalent component in the hierarchical part, nor fall-back to the duplicate parameters that appear earlier. When the PostgreSQL document does not define the default value for a URI parameter, the default value of the corresponding parameter in Connection String applies.
  • Duplicate URI parameters in a URI is valid. In such a case, the later is respected.
  • Connection URI that has an unexpected or unsupported URI parameter is invalid.
  • Connection URI which URI parameter has unexpected or unsupported value is invalid
  • In URI parameters, boolean type values are represented by 0 or 1, which is respectively false or true.

URI Parameters

The followings are specification of connection URI parameters in Npgsql.

Basic Connection

Parameters in Connection URI Corresponding Parameters in Connection String Is documented in PostgreSQL Default value in connection URI Notes
host Host, Server yes localhost
port Port yes same as connection string does
dbname, database, db Database, DB yes same as connection string does only "dbname" is defined in PostgreSQL doc
user, username, user_name, user_id, uid Username, User Name, UserId, User Id, UID yes same as connection string does only "user" is defined in PostgreSQL doc
password, psw, pwd Password, PSW, PWD yes same as connection string does only "password" is defined in PostgreSQL doc
passfile Passfile yes same as connection string does The default path in Npgsql is different from the definition in connection URI
application_name Application Name yes same as connection string does
enlist Enlist no same as connection string does
search_path Search Path no same as connection string does
client_encoding Client Encoding yes same as connection string does
encoding Encoding no same as connection string does
timezone Timezone no same as connection string does

Security and Encryption

Parameters in Connection URI Corresponding Parameters in Connection String Is documented in PostgreSQL Default value in connection URI Notes
sslmode, ssl SSL Mode yes prefer * The alias "ssl" and its acceptable values are defined in the PostgreSQL's documentation
* The default in Connection String is "Disabled"
* Not every the SSL modes defined in connection URI are supported. Supported values in Npgsql are "disable", "perfer" and "require".
trust_server_certificate Trust Server Certificate no same as connection string does
sslcert, client_certificate Client Certificate yes same as connection string does only "sslcert" is defined in PostgreSQL doc
The default path in Npgsql is different from the definition in connection URI
check_certificate_revocation Check Certificate Revocation no same as connection string does
integrated_security Integrated Security no same as connection string does
krbsrvname Kerberos Service Name, Krbsrvname yes same as connection string does
include_realm Include Realm no same as connection string does
persist_security_info Persist Security Info no same as connection string does

Pooling

Parameters in Connection URI Corresponding Parameters in Connection String Is documented in PostgreSQL Default value in connection URI Notes
pooling Pooling no same as connection string does
minimum_pool_size Minimum Pool Size no same as connection string does
maximum_pool_size Maximum Pool Size no same as connection string does
connection_idle_lifetime Connection Idle Lifetime no same as connection string does
connection_pruning_interval Connection Pruning Interval no same as connection string does

Timeouts

Parameters in Connection URI Corresponding Parameters in Connection String Is documented in PostgreSQL Default value in connection URI Notes
connect_timeout Timeout yes same as connection string does
command_timeout Command Timeout no same as connection string does
internal_command_timeout Internal Command Timeout no same as connection string does

Entity Framework

Parameters in Connection URI Corresponding Parameters in Connection String Is documented in PostgreSQL Default value in connection URI Notes
ef_template_database EF Template Database no same as connection string does
ef_admin_database EF Admin Database no same as connection string does

Advanced

Parameters in Connection URI Corresponding Parameters in Connection String Is documented in PostgreSQL Default value in connection URI Notes
query_keepalives_time Keepalive no same as connection string does named it "query_keepalives_time" because "keepalives" is defined for other property in Connection URI. The naming conforms to "keepalives_time"
keepalives TCP Keepalive yes 1 (enabled) the default value in Connection String is "disabled"
keepalives_time TCP Keepalive Time no same as connection string does, which is 0 seconds * The naming conforms to "keepalives" and "keepalives_interval", which are defined in Connection URI.
* What should the default value be? If it is defaulted to 0, property keepalives's default value, which is 1 (enabled), cannot be effective.
* The unit of this parameter is "seconds" in Connection URI but it is "milliseconds" in Connection String
keepalives_interval TCP Keepalive Interval yes behaves as connection string does, which is 0 seconds The unit of this parameter is "seconds" in Connection URI but it is "milliseconds" in Connection String
read_buffer_size Read Buffer Size no same as connection string does
write_buffer_size Write Buffer Size no same as connection string does
socket_receive_buffer_size Socket Receive Buffer Size no same as connection string does
socket_send_buffer_size Socket Send Buffer Size no same as connection string does
max_auto_prepare Max Auto Prepare no same as connection string does
auto_prepare_min_usages Auto Prepare Min Usages no same as connection string does
use_perf_counters Use Perf Counters no same as connection string does
no_reset_on_close No Reset On Close no same as connection string does
load_table_composites Load Table Composites no same as connection string does

Compatibility

Parameters in Connection URI Corresponding Parameters in Connection String Is documented in PostgreSQL Default value in connection URI Notes
server_compatibility_mode Server Compatibility Mode no same as connection string does
convert_infinity_datetime Convert Infinity DateTime no same as connection string does

Unsupported Parameters

The following URI parameters are defined in PostgreSQL's documentation but Npgsql does not have any settings corresponding to them.

  • options
  • keepalives_idle
  • keepalives_count
  • tcp_user_timeout
  • replication
  • gssencmode
  • sslcompression
  • sslkey
  • sslrootcert
  • sslcrl
  • gsslib
  • service
  • target_session_attrs

Deprecated Paramters in Connection URI

The following URI parameters are deprecated in PostgreSQL's documentation and Npgsql does not support those.

  • requiressl

Notes

In this implementation, I handled the host component of Connection URI separately from the parse by System.Uri. It is because System.Uri throws an exception with such URI as described below.

  • Specifying unix-domain socket directory in host component causes System.Uri to throw System.UriFormatException. e.g. postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
  • Omitting host component in authority part causes System.Uri to throw System.UriFormatException, although omitting authority part is fine. For example, postgresql:///dbname is fine but postgresql://user@/dbname is not.
  • Specifying muliple hosts in host component causes System.Uri to throw System.UriFormatException. e.g. postgresql://host1,host2/mydb

Questions

  1. I named Keepalive parameter in Connection String "query_keepalives_time" in Connection URI. It is because "keepalives" is used by another property in Connection URI so that having "keepalive" for Keepalive parameter can be confusing. The naming conforms to keepalives_time URI parameter. Does it sound okay?
  2. What should the default value of URI parameter keepalives_time (TCP Keepalive Time) be? If the parameter is defaulted to 0, which Connection String does, the default value of keepalives URI parameter, which is 1 (enabled), cannot be effective.

make NpgsqlConnection to parse the parameter as a connection URI if it is a URI
remove Category attribute from test code, which was only for debugging during dev
@snow-jallen

Copy link
Copy Markdown

What's the latest on this PR? It looks like it hasn't yet been merged, but it sure would be a nice feature to have. I'd love to not have to re-write my heroku connection strings. Oh boy would that be nice. :)

@roji

roji commented Jan 23, 2020

Copy link
Copy Markdown
Member

I'm sorry this hasn't received more attention - it definitely does look like a lot of effort has gone into it, and I do think it's a valuable addition to Npgsql. There's just so much going on at the moment - but I promise to try to make some time for this soon.

@snow-jallen

Copy link
Copy Markdown

In the meantime, if anyone else doesn't like manually rewriting heroku connection strings here's a bit of code to pull out the connection string from the heroku environment variable and rewrite it for you. https://gist.github.com/snow-jallen/bbcef9a7c50056e227e066010c043a4c


// Connection string hasn't been seen before. Parse it.
Settings = new NpgsqlConnectionStringBuilder(_connectionString);
if (Regex.IsMatch(_connectionString, @"^\w+://"))

@jgilchrist jgilchrist May 31, 2020 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@y-code y-code Jun 9, 2020 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jgilchrist Thank you for reviewing my PR. Yes, I tried System.Uri at first stage, and recognized that there's several problems with it to cover all types of PostgreSQL connection URIs that are documented in PostgreSQL's documentation. I've listed up the problems with System.Uri in Notes section of my first comment in this PR, so please have a look at it. The Notes section is near the bottom of the comment.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah! Sorry, I missed that part of your notes. Thanks - makes sense.

@snow-jallen

Copy link
Copy Markdown

I'm sure glad to see this PR hasn't died or been closed or anything. It'd sure be nice if there were a way to get this wrapped up and into the shipping version of npgsql. Here's hoping. 👍

@roji
roji changed the base branch from dev to main September 17, 2020 14:35

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@y-code apologies once again that it's taken me so long to properly review this.

The PR looks very good - you've obviously invested a lot of work in understanding how PG works around these options, writing thorough tests, etc. I'm hoping you're still interested in getting this merged - I'd like to finally do this.

I've done a first round of reviewing, please take a look. If you want to proceed, can you please rebase and address my comments? We'll go from there.

BTW in some cases, you say that Npgsql looks for files in different places compared to PG (passfile, sslcert), can you provide more details on that? We should match the PG behavior on these.

{
var convertedValue = p.PropertyType.GetTypeInfo().IsEnum && value is string str
? Enum.Parse(p.PropertyType, str)
? Enum.Parse(p.PropertyType, str, true)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit:

Suggested change
? Enum.Parse(p.PropertyType, str, true)
? Enum.Parse(p.PropertyType, str, ignoreCase: true)

[Description("The optional application name parameter to be sent to the backend during connection initiation")]
[DisplayName("Application Name")]
[NpgsqlConnectionStringProperty]
[NpgsqlConnectionURIParameter("application_name", "fallback_application_name")]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure this should have fallback_application_name - it has slightly different behavior compared to application_name (even if we currently don't implement the environment variable).

[Description("The username to connect with. Not required if using IntegratedSecurity.")]
[DisplayName("Username")]
[NpgsqlConnectionStringProperty("User Name", "UserId", "User Id", "UID")]
[NpgsqlConnectionURIParameter("user", "username", "user_name", "user_id", "uid")]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are all these aliases actually supported by PG? If not, I'm not sure we should introduce our own aliases, what would the value of that be?

This is a general question for other properties too.

[Description("Controls whether SSL is required, disabled or preferred, depending on server support.")]
[DisplayName("SSL Mode")]
[NpgsqlConnectionStringProperty]
[NpgsqlConnectionURIParameter("sslmode", "ssl")]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that Npgsql only supports disable/prefer/require, which is a subset of what PG allows. We may want to throw a specific exception informing users about this.

[Description("The maximum connection pool size.")]
[DisplayName("Maximum Pool Size")]
[NpgsqlConnectionStringProperty]
[NpgsqlConnectionURIParameter("maximum_pool_size")]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than manually specifying the snake_case for each option, why not just do the conversion automatically in the attribute when no parameters are given? We even already have NpgsqlSnakeCaseNameTranslator.

/// </summary>
public string? Password { get; protected set; }

public IReadOnlyList<KeyValuePair<string, string?>> Parameters => _parameters;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't seem to be actually used - we can remove it.

Database = Uri.UnescapeDataString(path);

_parameters = uri.Query
.Split(new[] { '?', '&' })

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: can remove new[]


namespace Npgsql.Tests
{
public class ConnectionUriTests : TestBase

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think TestBase can be removed, this is a pure unit test suite (TestBase is about utilities and stuff for actually connecting to PG and executing queries).

}

[Test]
public void InvalidConnectionUri()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: if you want, InvalidArgument and InvalidConnectionURi can be a single parameterized test, where each TestCase gives the URI and the expected exception

}

[Test]
public void ValidConnectionUri3()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A lot of these can be collapsed to a single parameterized test, accepting a URI and, e.g. a 5-value tuple or something. I'd look for opportunities to reduce code here for maintainability.

@y-code

y-code commented Feb 9, 2021

Copy link
Copy Markdown
Author

@roji Thanks for reviewing it. I'm glad to hear from you.
I'll have time for this in one week or so.

@y-code
y-code requested a review from vonzshik as a code owner April 15, 2021 19:08
@borgez

borgez commented Sep 1, 2021

Copy link
Copy Markdown

any plans here?

@snow-jallen

Copy link
Copy Markdown

I for one am definitely looking forward to this feature. :)

@roji

roji commented Sep 1, 2021

Copy link
Copy Markdown
Member

@y-code do you intent to continue working on this?

@awbacker

Copy link
Copy Markdown

Will this ever be merged? 3 years old, basic feature, ...

At this point, maybe just provide a converter to parse "postgres://" stuff into db-context style "host=".

@roji

roji commented Feb 27, 2023

Copy link
Copy Markdown
Member

I'm going to go ahead and close this PR, as the submitter hasn't addressed the review for a few years now. I'd be happy to review a new PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Accept connecting with PostgreSQL URLs instead of connection strings

6 participants