Skip to content

Commit 9d49e04

Browse files
authored
PostgreSQL: allow connection parameters to be specified (#7579)
As documented in https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS Multiple parameters are separated by a space.
1 parent b5781a8 commit 9d49e04

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

redash/query_runner/pg.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,15 @@ def _get_ssl_config(configuration):
138138
return ssl_config
139139

140140

141+
def _parse_dsn(configuration):
142+
standard_params = {"user", "password", "host", "port", "dbname"}
143+
params = psycopg2.extensions.parse_dsn(configuration.get("dsn", ""))
144+
overlap = standard_params.intersection(params.keys())
145+
if overlap:
146+
raise ValueError("Extra parameters may not contain {}".format(overlap))
147+
return params
148+
149+
141150
class PostgreSQL(BaseSQLQueryRunner):
142151
noop_query = "SELECT 1"
143152

@@ -151,6 +160,7 @@ def configuration_schema(cls):
151160
"host": {"type": "string", "default": "127.0.0.1"},
152161
"port": {"type": "number", "default": 5432},
153162
"dbname": {"type": "string", "title": "Database Name"},
163+
"dsn": {"type": "string", "default": "application_name=redash", "title": "Parameters"},
154164
"sslmode": {
155165
"type": "string",
156166
"title": "SSL Mode",
@@ -244,6 +254,7 @@ def _get_tables(self, schema):
244254

245255
def _get_connection(self):
246256
self.ssl_config = _get_ssl_config(self.configuration)
257+
self.dsn = _parse_dsn(self.configuration)
247258
connection = psycopg2.connect(
248259
user=self.configuration.get("user"),
249260
password=self.configuration.get("password"),
@@ -252,6 +263,7 @@ def _get_connection(self):
252263
dbname=self.configuration.get("dbname"),
253264
async_=True,
254265
**self.ssl_config,
266+
**self.dsn,
255267
)
256268

257269
return connection

tests/query_runner/test_pg.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,16 @@
11
from unittest import TestCase
22

3-
from redash.query_runner.pg import build_schema
3+
from redash.query_runner.pg import _parse_dsn, build_schema
4+
5+
6+
class TestParameters(TestCase):
7+
def test_parse_dsn(self):
8+
configuration = {"dsn": "application_name=redash connect_timeout=5"}
9+
self.assertDictEqual(_parse_dsn(configuration), {"application_name": "redash", "connect_timeout": "5"})
10+
11+
def test_parse_dsn_not_permitted(self):
12+
configuration = {"dsn": "password=xyz"}
13+
self.assertRaises(ValueError, _parse_dsn, configuration)
414

515

616
class TestBuildSchema(TestCase):

0 commit comments

Comments
 (0)