| 1 |
import subprocess |
| 2 |
|
| 3 |
from django.core.management.base import BaseCommand, CommandError |
| 4 |
from django.db import DEFAULT_DB_ALIAS, connections |
| 5 |
|
| 6 |
|
| 7 |
class Command(BaseCommand): |
| 8 |
help = ( |
| 9 |
"Runs the command-line client for specified database, or the " |
| 10 |
"default database if none is provided." |
| 11 |
) |
| 12 |
|
| 13 |
requires_system_checks = [] |
| 14 |
|
| 15 |
def add_arguments(self, parser): |
| 16 |
parser.add_argument( |
| 17 |
"--database", |
| 18 |
default=DEFAULT_DB_ALIAS, |
| 19 |
choices=tuple(connections), |
| 20 |
help=( |
| 21 |
"Nominates a database onto which to open a shell. Defaults to the " |
| 22 |
'"default" database.' |
| 23 |
), |
| 24 |
) |
| 25 |
parameters = parser.add_argument_group("parameters") |
| 26 |
parameters.add_argument("parameters", nargs="*") |
| 27 |
|
| 28 |
def handle(self, **options): |
| 29 |
connection = connections[options["database"]] |
| 30 |
try: |
| 31 |
connection.client.runshell(options["parameters"]) |
| 32 |
except FileNotFoundError: |
| 33 |
# Note that we're assuming the FileNotFoundError relates to the |
| 34 |
# command missing. It could be raised for some other reason, in |
| 35 |
# which case this error message would be inaccurate. Still, this |
| 36 |
# message catches the common case. |
| 37 |
raise CommandError( |
| 38 |
"You appear not to have the %r program installed or on your path." |
| 39 |
% connection.client.executable_name |
| 40 |
) |
| 41 |
except subprocess.CalledProcessError as e: |
| 42 |
raise CommandError( |
| 43 |
'"%s" returned non-zero exit status %s.' |
| 44 |
% ( |
| 45 |
" ".join(map(str, e.cmd)), |
| 46 |
e.returncode, |
| 47 |
), |
| 48 |
returncode=e.returncode, |
| 49 |
) |