2
# Copyright 2013 Canonical Ltd.
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License version 3, as
6
# published by the Free Software Foundation.
8
# This program is distributed in the hope that it will be useful, but
9
# WITHOUT ANY WARRANTY; without even the implied warranties of
10
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11
# PURPOSE. See the GNU Affero General Public License for more details.
13
# You should have received a copy of the GNU Affero General Public License
14
# along with this program. If not, see <http://www.gnu.org/licenses/>.
22
print('This command option must be run as root.')
26
def assert_postgres():
27
if not os.path.exists('/usr/bin/createdb'):
28
print('postgres must be installed manually')
32
def dbuser_exists(dbconfig):
34
'sudo', '-u', 'postgres', 'psql', '-c',
35
'SELECT usename FROM pg_user WHERE usename=\'%s\';' % dbconfig['USER'],
37
output = subprocess.check_output(args)
38
return '(1 row)' in output
41
def db_exists(dbconfig):
43
'sudo', '-u', 'postgres', 'psql', '-c',
44
'SELECT datname FROM pg_database WHERE datname=\'%s\'' % (
47
output = subprocess.check_output(args)
48
return '(1 row)' in output
51
def create_user(dbconfig):
53
'sudo', '-u', 'postgres', 'createuser',
54
'--no-createdb', '--encrypted', '--login', '--no-superuser',
55
'--no-createrole', '--no-password', dbconfig['USER']
57
subprocess.check_call(args)
59
# Set a password for our new user
61
'sudo', '-u', 'postgres', 'psql', '--quiet', '-c',
62
'ALTER USER \"%s\" WITH PASSWORD \'%s\'' % (
63
dbconfig['USER'], dbconfig['PASSWORD'])
65
subprocess.check_call(args)
68
def _create(dbconfig):
70
'sudo', '-u', 'postgres', 'createdb',
71
'--owner=%s' % dbconfig['USER'],
72
'--template=template0', '--no-password', dbconfig['NAME']
74
subprocess.check_call(args)
77
def create_db(dbconfig):
78
if dbconfig['ENGINE'] != 'django.db.backends.postgresql_psycopg2':
79
print('Unsupported db engine: %s' % dbconfig['ENGINE'])
85
if dbuser_exists(dbconfig):
86
print('user already exists, skipping creation')
87
print(' user can be removed with: dropuser %s' % dbconfig['USER'])
91
if db_exists(dbconfig):
92
print('db already exists')
93
print (' db can be removed with: dropdb %s' % dbconfig['NAME'])