psycopg2/libpq will read connection parameters from environment variables, provided an empty (not-None) connection string is passed.
<https://www.postgresql.org/docs/current/libpq-envars.html>
Fixes: #4562
# pg8000
engine = create_engine('postgresql+pg8000://scott:tiger@localhost/mydatabase')
+With the psycopg2 DBAPI, you can omit any connection parameters that are defined as
+`PG... environment variables <https://www.postgresql.org/docs/current/libpq-envars.html>`_.
+If *all* your connection parameters are defined as environment variables, you can
+specify an empty URL::
+
+ engine = create_engine('postgresql://')
+
+Again, this works only with the psycopg2 DBAPI.
+
More notes on connecting to PostgreSQL at :ref:`postgresql_toplevel`.
MySQL
.. _psycopg2_execution_options:
+Environment Connection Parameters
+----------------------------------
+
+psycopg2, via its underlying ``libpq`` client library, allows any connection
+parameters to be omitted that are defined as `PG... environment variables
+<https://www.postgresql.org/docs/current/libpq-envars.html>`_. If *all* your
+required connection parameters are defined as environment variables, you can
+specify an empty URL::
+
+ create_engine("postgresql+psycopg2://")
+
Per-Statement/Connection Execution Options
-------------------------------------------
def create_connect_args(self, url):
opts = url.translate_connect_args(username="user")
- if "port" in opts:
- opts["port"] = int(opts["port"])
- opts.update(url.query)
- return ([], opts)
+ if opts:
+ if "port" in opts:
+ opts["port"] = int(opts["port"])
+ opts.update(url.query)
+ return ([], opts)
+ else:
+ return ([''], opts)
def is_disconnect(self, e, connection, cursor):
if isinstance(e, self.dbapi.Error):
from sqlalchemy import text
from sqlalchemy import TypeDecorator
from sqlalchemy.dialects.postgresql import base as postgresql
+from sqlalchemy.dialects.postgresql import psycopg2 as psycopg2_dialect
from sqlalchemy.engine import engine_from_config
from sqlalchemy.engine import url
from sqlalchemy.testing import engines
e = engine_from_config(config, _initialize=False)
eq_(e.dialect.use_native_unicode, True)
+ def test_psycopg2_empty_connection_string(self):
+ dialect = psycopg2_dialect.dialect()
+ u = url.make_url("postgresql://")
+ cargs, cparams = dialect.create_connect_args(u)
+ assert cargs == ['']
+ assert cparams == {}
+
+ def test_psycopg2_nonempty_connection_string(self):
+ dialect = psycopg2_dialect.dialect()
+ u = url.make_url("postgresql://host")
+ cargs, cparams = dialect.create_connect_args(u)
+ assert cargs == []
+ assert cparams == {"host": "host"}
+
class BatchInsertsTest(fixtures.TablesTest):
__only_on__ = "postgresql+psycopg2"