Plain is headed towards 1.0! Subscribe for development updates →

 1import signal
 2
 3from plain.models.backends.base.client import BaseDatabaseClient
 4
 5
 6class DatabaseClient(BaseDatabaseClient):
 7    executable_name = "psql"
 8
 9    @classmethod
10    def settings_to_cmd_args_env(cls, settings_dict, parameters):
11        args = [cls.executable_name]
12        options = settings_dict.get("OPTIONS", {})
13
14        host = settings_dict.get("HOST")
15        port = settings_dict.get("PORT")
16        dbname = settings_dict.get("NAME")
17        user = settings_dict.get("USER")
18        passwd = settings_dict.get("PASSWORD")
19        passfile = options.get("passfile")
20        service = options.get("service")
21        sslmode = options.get("sslmode")
22        sslrootcert = options.get("sslrootcert")
23        sslcert = options.get("sslcert")
24        sslkey = options.get("sslkey")
25
26        if not dbname and not service:
27            # Connect to the default 'postgres' db.
28            dbname = "postgres"
29        if user:
30            args += ["-U", user]
31        if host:
32            args += ["-h", host]
33        if port:
34            args += ["-p", str(port)]
35        args.extend(parameters)
36        if dbname:
37            args += [dbname]
38
39        env = {}
40        if passwd:
41            env["PGPASSWORD"] = str(passwd)
42        if service:
43            env["PGSERVICE"] = str(service)
44        if sslmode:
45            env["PGSSLMODE"] = str(sslmode)
46        if sslrootcert:
47            env["PGSSLROOTCERT"] = str(sslrootcert)
48        if sslcert:
49            env["PGSSLCERT"] = str(sslcert)
50        if sslkey:
51            env["PGSSLKEY"] = str(sslkey)
52        if passfile:
53            env["PGPASSFILE"] = str(passfile)
54        return args, (env or None)
55
56    def runshell(self, parameters):
57        sigint_handler = signal.getsignal(signal.SIGINT)
58        try:
59            # Allow SIGINT to pass to psql to abort queries.
60            signal.signal(signal.SIGINT, signal.SIG_IGN)
61            super().runshell(parameters)
62        finally:
63            # Restore the original SIGINT handler.
64            signal.signal(signal.SIGINT, sigint_handler)