c58505658b00db012035d3b518cd39555f8c0608
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 if not db_exists(self.config):
87 db_create(self.config)
89 if __debug__:
90 print >>hyperdb.DEBUG, '+++ open database connection +++'
92 db = getattr(self.config, 'POSTGRESQL_DATABASE')
93 try:
94 self.conn = psycopg.connect(**db)
95 except psycopg.OperationalError, message:
96 raise hyperdb.DatabaseError, message
98 self.cursor = self.conn.cursor()
100 try:
101 self.load_dbschema()
102 except:
103 self.rollback()
104 self.init_dbschema()
105 self.sql("CREATE TABLE schema (schema TEXT)")
106 self.sql("CREATE TABLE ids (name VARCHAR(255), num INT4)")
107 self.sql("CREATE INDEX ids_name_idx ON ids(name)")
108 self.create_version_2_tables()
110 def create_version_2_tables(self):
111 self.cursor.execute('CREATE TABLE otks (otk_key VARCHAR(255), '
112 'otk_value VARCHAR(255), otk_time FLOAT(20))')
113 self.cursor.execute('CREATE INDEX otks_key_idx ON otks(otk_key)')
114 self.cursor.execute('CREATE TABLE sessions (s_key VARCHAR(255), '
115 's_last_use FLOAT(20), s_user VARCHAR(255))')
116 self.cursor.execute('CREATE INDEX sessions_key_idx ON sessions(s_key)')
118 def __repr__(self):
119 return '<roundpsycopgsql 0x%x>' % id(self)
121 def sql_stringquote(self, value):
122 ''' psycopg.QuotedString returns a "buffer" object with the
123 single-quotes around it... '''
124 return str(psycopg.QuotedString(str(value)))[1:-1]
126 def sql_index_exists(self, table_name, index_name):
127 sql = 'select count(*) from pg_indexes where ' \
128 'tablename=%s and indexname=%s'%(self.arg, self.arg)
129 self.cursor.execute(sql, (table_name, index_name))
130 return self.cursor.fetchone()[0]
132 def create_class_table(self, spec):
133 cols, mls = self.determine_columns(spec.properties.items())
134 cols.append('id')
135 cols.append('__retired__')
136 scols = ',' . join(['"%s" VARCHAR(255)' % x for x in cols])
137 sql = 'CREATE TABLE "_%s" (%s)' % (spec.classname, scols)
139 if __debug__:
140 print >>hyperdb.DEBUG, 'create_class', (self, sql)
142 self.cursor.execute(sql)
143 return cols, mls
145 def create_journal_table(self, spec):
146 cols = ',' . join(['"%s" VARCHAR(255)' % x
147 for x in 'nodeid date tag action params' . split()])
148 sql = 'CREATE TABLE "%s__journal" (%s)'%(spec.classname, cols)
150 if __debug__:
151 print >>hyperdb.DEBUG, 'create_class', (self, sql)
153 self.cursor.execute(sql)
155 def create_multilink_table(self, spec, ml):
156 sql = '''CREATE TABLE "%s_%s" (linkid VARCHAR(255),
157 nodeid VARCHAR(255))''' % (spec.classname, ml)
159 if __debug__:
160 print >>hyperdb.DEBUG, 'create_class', (self, sql)
162 self.cursor.execute(sql)
164 class Class(rdbms_common.Class):
165 pass
166 class IssueClass(rdbms_common.IssueClass):
167 pass
168 class FileClass(rdbms_common.FileClass):
169 pass