[psycopg] pass extra_args down to connect()

Lets the user pass things like 'service' or 'sslmode'. Closes #74171

authorJulien Cristau <julien.cristau@logilab.fr>
changeset7e9fc3d08dab
branchdefault
phasepublic
hiddenno
parent revision#c0b344ec946e [postgres] Add an adapter for the psycopg2cffi driver, which works great with pypy
child revision#900d91d54f45 [mysql] Fix SQL command in sql_change_col_type()
files modified by this revision
__init__.py
postgres.py
# HG changeset patch
# User Julien Cristau <julien.cristau@logilab.fr>
# Date 1394200964 -3600
# Fri Mar 07 15:02:44 2014 +0100
# Node ID 7e9fc3d08dab8e8bae45c96203d9f57a0cfd52a0
# Parent c0b344ec946e9b02445468bc80d40de383df6f08
[psycopg] pass extra_args down to connect()

Lets the user pass things like 'service' or 'sslmode'.
Closes #74171

diff --git a/__init__.py b/__init__.py
@@ -84,11 +84,13 @@
1      return mod
2 
3  def get_connection(driver='postgres', host='', database='', user='',
4                    password='', port='', quiet=False, drivers=_PREFERED_DRIVERS,
5                    pywrap=False, extra_args=None):
6 -    """return a db connection according to given arguments"""
7 +    """return a db connection according to given arguments
8 +
9 +    extra_args is an optional string that is appended to the DSN"""
10      _ensure_module_loaded(driver)
11      module, modname = _import_driver_module(driver, drivers)
12      try:
13          adapter = _ADAPTER_DIRECTORY.get_adapter(driver, modname)
14      except NoAdapterFound as err:
diff --git a/postgres.py b/postgres.py
@@ -73,18 +73,24 @@
15          db.DBAPIAdapter.__init__(self, native_module, pywrap)
16          self._init_psycopg2()
17 
18      def connect(self, host='', database='', user='', password='', port='', extra_args=None):
19          """Handles psycopg connection format"""
20 +        args = {}
21          if host:
22 -            cnx_string = 'host=%s  dbname=%s  user=%s' % (host, database, user)
23 -        else:
24 -            cnx_string = 'dbname=%s  user=%s' % (database, user)
25 +            args.setdefault('host', host)
26 +        if database:
27 +            args.setdefault('dbname', database)
28 +        if user:
29 +            args.setdefault('user', user)
30          if port:
31 -            cnx_string += ' port=%s' % port
32 +            args.setdefault('port', port)
33          if password:
34 -            cnx_string = '%s password=%s' % (cnx_string, password)
35 +            args.setdefault('password', password)
36 +        cnx_string = ' '.join('%s=%s' % item for item in args.iteritems())
37 +        if extra_args is not None:
38 +            cnx_string += ' ' + extra_args
39          cnx = self._native_module.connect(cnx_string)
40          cnx.set_isolation_level(1)
41          return self._wrap_if_needed(cnx)
42 
43      def _init_psycopg2(self):