Python command to Drop and Recreate PostgreSQL databases Atom Feed 0

In Brief A simple command to drop and re-create your project databases... we use this in siafoo.... more
# 's
 1'''
2Distutils command for migrating the siafoo database
3
4Author: Stou Sandalski (stou@icapsid.net)
5License: MIT
6'''
7
8import textwrap
9
10from distutils.cmd import Command
11from subprocess import check_call, PIPE, CalledProcessError
12
13class recreate_database(Command):
14 '''
15 Recreate Siafoo databases
16 '''
17
18 description = 'Migrates database to new format'
19 long_description = textwrap.dedent('')
20
21 user_options = [('release', None, 'Release number'),
22 ('db-name', None, 'Database Name'),
23 ('owner-name', None, 'Database Owner Name'),
24 ('detailed-output', None, 'Supress NOTICE type output')]
25
26 def initialize_options(self):
27 '''
28 Initialize command options
29 '''
30
31 self.release = None
32 self.db_name = None
33 self.owner_name = 'siafoo'
34
35 def finalize_options(self):
36 '''
37 Check and finalize options based on config file values
38 '''
39
40 self.release = int(self.release)
41
42
43
44 if self.db_name:
45 self.databases = [self.db_name]
46 else:
47 self.databases = ['siafoo_db',
48 'siafoo_db_test']
49
50 def run(self):
51 '''
52 Run the command
53 '''
54
55 print '\033[1;32mCleaning databases\033[1;m'
56
57 for db in self.databases:
58 self._drop_db(db)
59
60 print '\033[1;32mCreating databases\033[1;m'
61 for db in self.databases:
62 self._create_db(db)
63
64 def _create_db(self, db_name):
65 '''
66 Create a database
67 '''
68
69 print '\033[1;34m Creating database %s \033[1;m' % db_name
70 return check_call('createdb -U postgres -O %s %s' % (self.owner_name, db_name), shell=True)
71
72 def _drop_db(self, db_name):
73 '''
74 Drop a database
75 '''
76
77 print '\033[1;34m Droping database %s\033[1;m' % db_name
78 try:
79 check_call('dropdb -U postgres %s' % db_name, shell=True, stderr=PIPE, stdout=PIPE)
80 except CalledProcessError:
81 print '\033[1;31mCould not drop database %s\033[1;m' % db_name

A simple command to drop and re-create your project databases... we use this in siafoo.

To use this place it in some package and give the name of the package to setup.cfg like this:

[global]
command_packages=siafoo.commands

then you can run it with:

python setup.py recreate_database