a09086b50db3bdb992cc9e91876d338eba21d39b
1 #
2 # Copyright (c) 2003 Martynas Sklyzmantas, Andrey Lebedev <andrey@micro.lt>
3 #
4 # This module is free software, and you may redistribute it and/or modify
5 # under the same terms as Python, so long as this copyright message and
6 # disclaimer are retained in their original form.
7 #
8 '''Postgresql backend via psycopg for Roundup.'''
9 __docformat__ = 'restructuredtext'
12 import os, shutil, popen2, time
13 import psycopg
15 from roundup import hyperdb, date
16 from roundup.backends import rdbms_common
18 def db_create(config):
19 """Clear all database contents and drop database itself"""
20 if __debug__:
21 print >> hyperdb.DEBUG, '+++ create database +++'
22 name = config.POSTGRESQL_DATABASE['database']
23 n = 0
24 while n < 10:
25 cout,cin = popen2.popen4('createdb %s'%name)
26 cin.close()
27 response = cout.read().split('\n')[0]
28 if response.find('FATAL') != -1:
29 raise RuntimeError, response
30 elif response.find('ERROR') != -1:
31 if not response.find('is being accessed by other users') != -1:
32 raise RuntimeError, response
33 if __debug__:
34 print >> hyperdb.DEBUG, '+++ SLEEPING +++'
35 time.sleep(1)
36 n += 1
37 continue
38 return
39 raise RuntimeError, '10 attempts to create database failed'
41 def db_nuke(config, fail_ok=0):
42 """Clear all database contents and drop database itself"""
43 if __debug__:
44 print >> hyperdb.DEBUG, '+++ nuke database +++'
45 name = config.POSTGRESQL_DATABASE['database']
46 n = 0
47 if os.path.exists(config.DATABASE):
48 shutil.rmtree(config.DATABASE)
49 while n < 10:
50 cout,cin = popen2.popen4('dropdb %s'%name)
51 cin.close()
52 response = cout.read().split('\n')[0]
53 if response.endswith('does not exist') and fail_ok:
54 return
55 elif response.find('FATAL') != -1:
56 raise RuntimeError, response
57 elif response.find('ERROR') != -1:
58 if not response.find('is being accessed by other users') != -1:
59 raise RuntimeError, response
60 if __debug__:
61 print >> hyperdb.DEBUG, '+++ SLEEPING +++'
62 time.sleep(1)
63 n += 1
64 continue
65 return
66 raise RuntimeError, '10 attempts to nuke database failed'
68 def db_exists(config):
69 """Check if database already exists"""
70 db = getattr(config, 'POSTGRESQL_DATABASE')
71 try:
72 conn = psycopg.connect(**db)
73 conn.close()
74 if __debug__:
75 print >> hyperdb.DEBUG, '+++ database exists +++'
76 return 1
77 except:
78 if __debug__:
79 print >> hyperdb.DEBUG, '+++ no database +++'
80 return 0
82 class Database(rdbms_common.Database):
83 arg = '%s'
85 def sql_open_connection(self):
86 db = getattr(self.config, 'POSTGRESQL_DATABASE')
87 try:
88 conn = psycopg.connect(**db)
89 except psycopg.OperationalError, message:
90 raise hyperdb.DatabaseError, message
92 cursor = conn.cursor()
94 return (conn, cursor)
96 def open_connection(self):
97 if not db_exists(self.config):
98 db_create(self.config)
100 if __debug__:
101 print >>hyperdb.DEBUG, '+++ open database connection +++'
103 self.conn, self.cursor = self.sql_open_connection()
105 try:
106 self.load_dbschema()
107 except:
108 self.rollback()
109 self.init_dbschema()
110 self.sql("CREATE TABLE schema (schema TEXT)")
111 self.sql("CREATE TABLE ids (name VARCHAR(255), num INT4)")
112 self.sql("CREATE INDEX ids_name_idx ON ids(name)")
113 self.create_version_2_tables()
115 def create_version_2_tables(self):
116 self.cursor.execute('CREATE TABLE otks (otk_key VARCHAR(255), '
117 'otk_value VARCHAR(255), otk_time FLOAT(20))')
118 self.cursor.execute('CREATE INDEX otks_key_idx ON otks(otk_key)')
119 self.cursor.execute('CREATE TABLE sessions (session_key VARCHAR(255), '
120 'session_time FLOAT(20), session_value VARCHAR(255))')
121 self.cursor.execute('CREATE INDEX sessions_key_idx ON '
122 'sessions(session_key)')
124 def add_actor_column(self):
125 # update existing tables to have the new actor column
126 tables = self.database_schema['tables']
127 for name in tables.keys():
128 self.cursor.execute('ALTER TABLE _%s add __actor '
129 'VARCHAR(255)'%name)
131 def __repr__(self):
132 return '<roundpsycopgsql 0x%x>' % id(self)
134 def sql_stringquote(self, value):
135 ''' psycopg.QuotedString returns a "buffer" object with the
136 single-quotes around it... '''
137 return str(psycopg.QuotedString(str(value)))[1:-1]
139 def sql_index_exists(self, table_name, index_name):
140 sql = 'select count(*) from pg_indexes where ' \
141 'tablename=%s and indexname=%s'%(self.arg, self.arg)
142 self.cursor.execute(sql, (table_name, index_name))
143 return self.cursor.fetchone()[0]
145 def create_class_table(self, spec):
146 cols, mls = self.determine_columns(spec.properties.items())
147 cols.append('id')
148 cols.append('__retired__')
149 scols = ',' . join(['"%s" VARCHAR(255)' % x for x in cols])
150 sql = 'CREATE TABLE "_%s" (%s)' % (spec.classname, scols)
152 if __debug__:
153 print >>hyperdb.DEBUG, 'create_class', (self, sql)
155 self.cursor.execute(sql)
156 self.create_class_table_indexes(spec)
157 return cols, mls
159 def create_journal_table(self, spec):
160 cols = ',' . join(['"%s" VARCHAR(255)' % x
161 for x in 'nodeid date tag action params' . split()])
162 sql = 'CREATE TABLE "%s__journal" (%s)'%(spec.classname, cols)
164 if __debug__:
165 print >>hyperdb.DEBUG, 'create_class', (self, sql)
167 self.cursor.execute(sql)
168 self.create_journal_table_indexes(spec)
170 def create_multilink_table(self, spec, ml):
171 sql = '''CREATE TABLE "%s_%s" (linkid VARCHAR(255),
172 nodeid VARCHAR(255))''' % (spec.classname, ml)
174 if __debug__:
175 print >>hyperdb.DEBUG, 'create_class', (self, sql)
177 self.cursor.execute(sql)
178 self.create_multilink_table_indexes(spec, ml)
180 class Class(rdbms_common.Class):
181 pass
182 class IssueClass(rdbms_common.IssueClass):
183 pass
184 class FileClass(rdbms_common.FileClass):
185 pass