1
1
import errno
2
2
import subprocess
3
+ import sys
3
4
4
5
from django .db import connections
5
6
from django .core .management .commands import dbshell
@@ -18,18 +19,46 @@ def handle(self, **options):
18
19
cmd = dbclis .get (connection .vendor )
19
20
if cmd :
20
21
try :
22
+ # attempt to use mycli/pgcli
21
23
getattr (self , cmd )(connection )
22
24
return
23
25
except OSError , e :
24
- if e .errno != errno .ENOENT :
25
- self .stderr .write ("Could not start %s: %s" % (cmd , str (e )))
26
+ if self ._is_virtualenv :
27
+ try :
28
+ # retry without explicitly without virtualenv
29
+ getattr (self , cmd )(connection , ignore_virtualenv = True )
30
+ return
31
+ except OSError , e :
32
+ if e .errno != errno .ENOENT :
33
+ self .stderr .write ("Could not start %s: %s" % (cmd , str (e )))
34
+ else :
35
+ if e .errno != errno .ENOENT :
36
+ self .stderr .write ("Could not start %s: %s" % (cmd , str (e )))
26
37
38
+ # default to system mysql/psql
27
39
super (Command , self ).handle (** options )
28
40
29
- def pgcli (self , connection ):
41
+ @property
42
+ def _is_virtualenv (self ):
43
+ # sys.real_prefix is only set if inside virtualenv
44
+ return hasattr (sys , 'real_prefix' )
45
+
46
+ @property
47
+ def _python_path (self ):
48
+ path = '{}/bin/' .format (sys .prefix ) if self ._is_virtualenv else ''
49
+ return path
50
+
51
+ def _get_cli_command (self , cli , ignore_virtualenv = False ):
52
+ cli_command = '{}{}' .format (
53
+ '' if ignore_virtualenv else self ._python_path ,
54
+ cli , # 'pgcli' or 'mycli'
55
+ )
56
+ return cli_command
57
+
58
+ def pgcli (self , connection , ignore_virtualenv = False ):
30
59
# argument code copied from Django
31
60
settings_dict = connection .settings_dict
32
- args = ['pgcli' ]
61
+ args = [self . _get_cli_command ( 'pgcli' , ignore_virtualenv = ignore_virtualenv ) ]
33
62
if settings_dict ['USER' ]:
34
63
args += ["-U" , settings_dict ['USER' ]]
35
64
if settings_dict ['HOST' ]:
@@ -40,10 +69,10 @@ def pgcli(self, connection):
40
69
41
70
subprocess .call (args )
42
71
43
- def mycli (self , connection ):
72
+ def mycli (self , connection , ignore_virtualenv = False ):
44
73
# argument code copied from Django
45
74
settings_dict = connection .settings_dict
46
- args = ['mycli' ]
75
+ args = [self . _get_cli_command ( 'mycli' , ignore_virtualenv = ignore_virtualenv ) ]
47
76
db = settings_dict ['OPTIONS' ].get ('db' , settings_dict ['NAME' ])
48
77
user = settings_dict ['OPTIONS' ].get ('user' , settings_dict ['USER' ])
49
78
passwd = settings_dict ['OPTIONS' ].get ('passwd' , settings_dict ['PASSWORD' ])
0 commit comments