-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpgsql.py
77 lines (66 loc) · 2.26 KB
/
pgsql.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Scripts to manage PostgreSQL users and databases.
"""
from .utils import confirm, DocOptArgs, entrypoint
from ..plumbing.common import Owner, owner_name
from ..tasks import pgsql
@entrypoint
def create(opts: DocOptArgs, owner: Owner):
"""
Create a PostgreSQL database for a member or society.
A corresponding PostgreSQL account will also be created if needed.
Usage: {script} OWNER [DATABASE]
"""
name = owner_name(owner)
database = opts["DATABASE"]
if database == name:
database = None
print("User: {}".format(name))
print("Databases: {}{}".format(name, ", {}".format(database) if database else ""))
confirm("Create these?")
with pgsql.context() as cursor:
result = pgsql.create_account(cursor, owner)
create_user, create_db = result.parts
if create_user:
print("Created account")
else:
print("Account already exists")
if create_db:
print("Created default database {!r}".format(result.value[1]))
else:
print("Default database {!r} already exists".format(result.value[1]))
if database:
result = pgsql.create_database(cursor, owner, database)
if result:
print("Created database {!r}".format(result.value))
else:
print("Database {!r} already exists".format(result.value))
@entrypoint
def passwd(owner: Owner):
"""
Reset a PostgreSQL user's password.
Usage: {script} OWNER
"""
name = owner_name(owner)
confirm("Reset {}'s password?".format(name))
with pgsql.context() as cursor:
pgsql.reset_password(cursor, owner)
print("Password changed")
@entrypoint
def drop(owner: Owner):
"""
Drop a PostgreSQL user and all their databases.
Usage: {script} OWNER
"""
name = owner_name(owner)
with pgsql.context() as cursor:
dbs = pgsql.get_owned_databases(cursor, owner)
print("User: {}".format(name))
if dbs:
print("Databases: {}".format(", ".join(dbs)))
confirm("Delete these?")
with pgsql.context() as cursor:
if pgsql.drop_all_databases(cursor, owner):
print("Dropped databases")
if pgsql.drop_account(cursor, owner):
print("Dropped user")