4 # implements support for SFA records stored in db tables
6 # TODO: Use existing PLC database methods? or keep this separate?
10 from pg import DB, ProgrammingError
12 from sfa.util.PostgreSQL import *
13 from sfa.trust.gid import *
14 from sfa.util.record import *
15 from sfa.util.debug import *
16 from sfa.util.config import *
17 from sfa.util.filter import *
21 SFA_TABLE_PREFIX = "sfa"
23 def __init__(self, record_filter = None):
25 # pgsql doesn't like table names with "." in them, to replace it with "$"
26 self.tablename = SfaTable.SFA_TABLE_PREFIX
27 self.config = Config()
28 self.db = PostgreSQL(self.config)
29 # establish a connection to the pgsql server
30 cninfo = self.config.get_plc_dbinfo()
31 self.cnx = DB(cninfo['dbname'], cninfo['address'], port=cninfo['port'], user=cninfo['user'], passwd=cninfo['password'])
34 records = self.find(record_filter)
35 for record in reocrds:
39 tableList = self.cnx.get_tables()
40 if 'public.' + self.tablename in tableList:
42 if 'public."' + self.tablename + '"' in tableList:
46 def db_fields(self, obj=None):
48 db_fields = self.db.fields(self.SFA_TABLE_PREFIX)
49 return dict( [ (key,value) for (key, value) in obj.items() \
50 if key in db_fields and
51 self.is_writable(key, value, SfaRecord.fields)] )
54 def is_writable (key,value,dict):
55 # if not mentioned, assume it's writable (e.g. deleted ...)
56 if key not in dict: return True
57 # if mentioned but not linked to a Parameter object, idem
58 if not isinstance(dict[key], Parameter): return True
59 # if not marked ro, it's writable
60 if not dict[key].ro: return True
67 querystr = "CREATE TABLE " + self.tablename + " ( \
68 record_id serial PRIMARY KEY , \
70 authority text NOT NULL, \
71 peer_authority text, \
75 date_created timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, \
76 last_updated timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP);"
77 template = "CREATE INDEX %s_%s_idx ON %s (%s);"
78 indexes = [template % ( self.tablename, field, self.tablename, field) \
79 for field in ['hrn', 'type', 'authority', 'peer_authority', 'pointer']]
80 # IF EXISTS doenst exist in postgres < 8.2
82 self.cnx.query('DROP TABLE IF EXISTS ' + self.tablename)
83 except ProgrammingError:
85 self.cnx.query('DROP TABLE ' + self.tablename)
86 except ProgrammingError:
89 self.cnx.query(querystr)
93 def remove(self, record):
94 query_str = "DELETE FROM %s WHERE record_id = %s" % \
95 (self.tablename, record['record_id'])
96 self.cnx.query(query_str)
98 # if this is a site, remove all records where 'authority' == the
100 if record['type'] == 'site':
101 sql = " DELETE FROM %s WHERE authority = %s" % \
102 (self.tablename, record['hrn'])
105 def insert(self, record):
106 db_fields = self.db_fields(record)
107 keys = db_fields.keys()
108 values = [self.db.param(key, value) for (key, value) in db_fields.items()]
109 query_str = "INSERT INTO " + self.tablename + \
110 "(" + ",".join(keys) + ") " + \
111 "VALUES(" + ",".join(values) + ")"
112 self.db.do(query_str, db_fields)
114 result = self.find({'hrn': record['hrn'], 'type': record['type'], 'peer_authority': record['peer_authority']})
117 elif isinstance(result, list):
118 record_id = result[0]['record_id']
120 record_id = result['record_id']
124 def update(self, record):
125 db_fields = self.db_fields(record)
126 keys = db_fields.keys()
127 values = [self.db.param(key, value) for (key, value) in db_fields.items()]
128 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
129 query_str = "UPDATE %s SET %s WHERE record_id = %s" % \
130 (self.tablename, ", ".join(columns), record['record_id'])
131 self.db.do(query_str, db_fields)
134 def quote_string(self, value):
135 return str(self.quote(value))
137 def quote(self, value):
139 Returns quoted version of the specified value.
142 # The pgdb._quote function is good enough for general SQL
143 # quoting, except for array types.
144 if isinstance(value, (list, tuple, set)):
145 return "ARRAY[%s]" % ", ".join(map, self.quote_string, value)
147 return pgdb._quote(value)
149 def find(self, record_filter = None, columns=None):
153 columns = ",".join(columns)
154 sql = "SELECT %s FROM %s WHERE True " % (columns, self.tablename)
156 if isinstance(record_filter, (list, tuple, set)):
157 ints = filter(lambda x: isinstance(x, (int, long)), record_filter)
158 strs = filter(lambda x: isinstance(x, StringTypes), record_filter)
159 record_filter = Filter(SfaRecord.all_fields, {'record_id': ints, 'hrn': strs})
160 sql += "AND (%s) %s " % record_filter.sql("OR")
161 elif isinstance(record_filter, dict):
162 record_filter = Filter(SfaRecord.all_fields, record_filter)
163 sql += " AND (%s) %s" % record_filter.sql("AND")
164 elif isinstance(record_filter, StringTypes):
165 record_filter = Filter(SfaRecord.all_fields, {'hrn':[record_filter]})
166 sql += " AND (%s) %s" % record_filter.sql("AND")
167 elif isinstance(record_filter, int):
168 record_filter = Filter(SfaRecord.all_fields, {'record_id':[record_filter]})
169 sql += " AND (%s) %s" % record_filter.sql("AND")
171 results = self.cnx.query(sql).dictresult()
172 if isinstance(results, dict):
176 def findObjects(self, record_filter = None, columns=None):
178 results = self.find(record_filter, columns)
180 for result in results:
181 if result['type'] in ['authority']:
182 result_rec_list.append(AuthorityRecord(dict=result))
183 elif result['type'] in ['node']:
184 result_rec_list.append(NodeRecord(dict=result))
185 elif result['type'] in ['slice']:
186 result_rec_list.append(SliceRecord(dict=result))
187 elif result['type'] in ['user']:
188 result_rec_list.append(UserRecord(dict=result))
190 result_rec_list.append(SfaRecord(dict=result))
191 return result_rec_list
196 self.cnx.query('DROP TABLE IF EXISTS ' + self.tablename)
197 except ProgrammingError:
199 self.cnx.query('DROP TABLE ' + self.tablename)
200 except ProgrammingError:
204 def sfa_records_purge(cninfo):
206 cnx = DB(cninfo['dbname'], cninfo['address'],
207 port=cninfo['port'], user=cninfo['user'], passwd=cninfo['password'])
208 tableList = cnx.get_tables()
209 for table in tableList:
210 if table.startswith(SfaTable.SFA_TABLE_PREFIX) or \
211 table.startswith('public.' + SfaTable.SFA_TABLE_PREFIX) or \
212 table.startswith('public."' + SfaTable.SFA_TABLE_PREFIX):
213 report.trace("dropping table " + table)
214 cnx.query("DROP TABLE " + table)