2015-06-17 21:37:09 +08:00
|
|
|
import os
|
2014-03-09 19:00:42 +08:00
|
|
|
import subprocess
|
2009-04-11 19:41:35 +08:00
|
|
|
|
2015-06-17 21:37:09 +08:00
|
|
|
from django.core.files.temp import NamedTemporaryFile
|
2015-01-13 04:20:40 +08:00
|
|
|
from django.db.backends.base.client import BaseDatabaseClient
|
2015-06-17 21:37:09 +08:00
|
|
|
from django.utils.six import print_
|
|
|
|
|
|
|
|
|
|
|
|
def _escape_pgpass(txt):
|
|
|
|
"""
|
|
|
|
Escape a fragment of a PostgreSQL .pgpass file.
|
|
|
|
"""
|
|
|
|
return txt.replace('\\', '\\\\').replace(':', '\\:')
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2008-08-11 20:11:25 +08:00
|
|
|
class DatabaseClient(BaseDatabaseClient):
|
2008-09-09 10:13:58 +08:00
|
|
|
executable_name = 'psql'
|
|
|
|
|
2015-06-17 21:37:09 +08:00
|
|
|
@classmethod
|
2016-06-03 05:03:03 +08:00
|
|
|
def runshell_db(cls, conn_params):
|
2015-06-17 21:37:09 +08:00
|
|
|
args = [cls.executable_name]
|
|
|
|
|
2016-06-03 05:03:03 +08:00
|
|
|
host = conn_params.get('host', '')
|
|
|
|
port = conn_params.get('port', '')
|
|
|
|
dbname = conn_params.get('database', '')
|
|
|
|
user = conn_params.get('user', '')
|
|
|
|
passwd = conn_params.get('password', '')
|
2015-06-17 21:37:09 +08:00
|
|
|
|
|
|
|
if user:
|
|
|
|
args += ['-U', user]
|
|
|
|
if host:
|
|
|
|
args += ['-h', host]
|
|
|
|
if port:
|
|
|
|
args += ['-p', str(port)]
|
2016-06-03 05:03:03 +08:00
|
|
|
args += [dbname]
|
2015-06-17 21:37:09 +08:00
|
|
|
|
|
|
|
temp_pgpass = None
|
|
|
|
try:
|
|
|
|
if passwd:
|
|
|
|
# Create temporary .pgpass file.
|
|
|
|
temp_pgpass = NamedTemporaryFile(mode='w+')
|
|
|
|
try:
|
|
|
|
print_(
|
|
|
|
_escape_pgpass(host) or '*',
|
|
|
|
str(port) or '*',
|
2016-06-03 05:03:03 +08:00
|
|
|
_escape_pgpass(dbname) or '*',
|
2015-06-17 21:37:09 +08:00
|
|
|
_escape_pgpass(user) or '*',
|
|
|
|
_escape_pgpass(passwd),
|
|
|
|
file=temp_pgpass,
|
|
|
|
sep=':',
|
|
|
|
flush=True,
|
|
|
|
)
|
|
|
|
os.environ['PGPASSFILE'] = temp_pgpass.name
|
|
|
|
except UnicodeEncodeError:
|
|
|
|
# If the current locale can't encode the data, we let
|
|
|
|
# the user input the password manually.
|
|
|
|
pass
|
2016-06-28 00:20:40 +08:00
|
|
|
subprocess.check_call(args)
|
2015-06-17 21:37:09 +08:00
|
|
|
finally:
|
|
|
|
if temp_pgpass:
|
|
|
|
temp_pgpass.close()
|
|
|
|
if 'PGPASSFILE' in os.environ: # unit tests need cleanup
|
|
|
|
del os.environ['PGPASSFILE']
|
|
|
|
|
2008-08-11 20:11:25 +08:00
|
|
|
def runshell(self):
|
2016-06-03 05:03:03 +08:00
|
|
|
DatabaseClient.runshell_db(self.connection.get_connection_params())
|