Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

db: Add support for key-value pair DSNs in postgresql #4072

Merged
merged 2 commits into from
Sep 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions tests/test_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,3 +281,20 @@ def test_optimistic_locking(node_factory, bitcoind):
l1.rpc.newaddr()

assert(l1.daemon.is_in_log(r'Optimistic lock on the database failed'))


@unittest.skipIf(os.environ.get('TEST_DB_PROVIDER', None) != 'postgres', "Only applicable to postgres")
def test_psql_key_value_dsn(node_factory, db_provider, monkeypatch):
from pyln.testing.db import PostgresDb

# Override get_dsn method to use the key-value style DSN
def get_dsn(self):
print("hello")
return "postgres://host=127.0.0.1 port={port} user=postgres password=password dbname={dbname}".format(
port=self.port, dbname=self.dbname
)

monkeypatch.setattr(PostgresDb, "get_dsn", get_dsn)
l1 = node_factory.get_node()
opt = [o for o in l1.daemon.cmd_line if '--wallet' in o][0]
assert('host=127.0.0.1' in opt)
19 changes: 18 additions & 1 deletion wallet/db_postgres.c
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,24 @@

static bool db_postgres_setup(struct db *db)
{
db->conn = PQconnectdb(db->filename);
size_t prefix_len = strlen("postgres://");

/* We attempt to parse the connection string without the `postgres://`
prefix first, so we can correctly handle the key-value-pair style of
DSN that postgresql supports. If that fails we try with the full
string, which matches the `scheme://user:password@host:port/dbname`
style of DSNs. The call to `PQconninfoParse` here is just to verify
`PQconnectdb` would be able to parse it correctly, that's why the
result is discarded again immediately. */
PQconninfoOption *info =
PQconninfoParse(db->filename + prefix_len, NULL);

if (info != NULL) {
PQconninfoFree(info);
db->conn = PQconnectdb(db->filename + prefix_len);
} else {
db->conn = PQconnectdb(db->filename);
}

if (PQstatus(db->conn) != CONNECTION_OK) {
db->error = tal_fmt(db, "Could not connect to %s: %s", db->filename, PQerrorMessage(db->conn));
Expand Down