[IMP] Use the openerp namespace in YML tests.
[odoo/odoo.git] / openerpcommand / drop.py
1 """
2 Drop a database.
3 """
4
5 import common
6
7 # TODO turn template1 in a parameter
8 # This should be exposed from openerp (currently in
9 # openerp/service/web_services.py).
10 def drop_database(database_name):
11     import openerp
12     db = openerp.sql_db.db_connect('template1')
13     cr = db.cursor()
14     cr.autocommit(True) # avoid transaction block
15     try:
16         # TODO option for doing this.
17         # Try to terminate all other connections that might prevent
18         # dropping the database
19         try:
20             cr.execute("""SELECT pg_terminate_backend(procpid)
21                           FROM pg_stat_activity
22                           WHERE datname = %s AND 
23                                 procpid != pg_backend_pid()""",
24                        (database_name,))
25         except Exception:
26             pass
27
28         try:
29             cr.execute('DROP DATABASE "%s"' % database_name)
30         except Exception, e:
31             print "Can't drop %s" % (database_name,)
32     finally:
33         cr.close()
34
35 def run(args):
36     assert args.database
37     drop_database(args.database)
38
39 def add_parser(subparsers):
40     parser = subparsers.add_parser('drop',
41         description='Drop a database.')
42     parser.add_argument('-d', '--database', metavar='DATABASE',
43         **common.required_or_default('DATABASE', 'the database to create'))
44
45     parser.set_defaults(run=run)