4 # implements support for SFA records stored in db tables
6 # TODO: Use existing PLC database methods? or keep this separate?
11 from sfa.util.PostgreSQL import *
12 from sfa.trust.gid import *
13 from sfa.util.record import *
14 from sfa.util.debug import *
15 from sfa.util.config import *
16 from sfa.util.filter import *
20 SFA_TABLE_PREFIX = "sfa"
22 def __init__(self, record_filter = None):
24 # pgsql doesn't like table names with "." in them, to replace it with "$"
25 self.tablename = SfaTable.SFA_TABLE_PREFIX
26 self.config = Config()
27 self.db = PostgreSQL(self.config)
30 records = self.find(record_filter)
31 for record in reocrds:
35 sql = "SELECT * from pg_tables"
36 tables = self.db.selectall(sql)
37 tables = filter(lambda row: row['tablename'].startswith(self.SFA_TABLE_PREFIX), tables)
41 def db_fields(self, obj=None):
43 db_fields = self.db.fields(self.SFA_TABLE_PREFIX)
44 return dict( [ (key,value) for (key, value) in obj.items() \
45 if key in db_fields and
46 self.is_writable(key, value, SfaRecord.fields)] )
49 def is_writable (key,value,dict):
50 # if not mentioned, assume it's writable (e.g. deleted ...)
51 if key not in dict: return True
52 # if mentioned but not linked to a Parameter object, idem
53 if not isinstance(dict[key], Parameter): return True
54 # if not marked ro, it's writable
55 if not dict[key].ro: return True
62 querystr = "CREATE TABLE " + self.tablename + " ( \
63 record_id serial PRIMARY KEY , \
65 authority text NOT NULL, \
66 peer_authority text, \
70 date_created timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, \
71 last_updated timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP);"
72 template = "CREATE INDEX %s_%s_idx ON %s (%s);"
73 indexes = [template % ( self.tablename, field, self.tablename, field) \
74 for field in ['hrn', 'type', 'authority', 'peer_authority', 'pointer']]
75 # IF EXISTS doenst exist in postgres < 8.2
77 self.db.do('DROP TABLE IF EXISTS ' + self.tablename)
80 self.db.do('DROP TABLE' + self.tablename)
90 def remove(self, record):
91 query_str = "DELETE FROM %s WHERE record_id = %s" % \
92 (self.tablename, record['record_id'])
95 # if this is a site, remove all records where 'authority' == the
97 if record['type'] == 'authority':
98 sql = " DELETE FROM %s WHERE authority = %s" % \
99 (self.tablename, record['hrn'])
103 def insert(self, record):
104 db_fields = self.db_fields(record)
105 keys = db_fields.keys()
106 values = [self.db.param(key, value) for (key, value) in db_fields.items()]
107 query_str = "INSERT INTO " + self.tablename + \
108 "(" + ",".join(keys) + ") " + \
109 "VALUES(" + ",".join(values) + ")"
110 self.db.do(query_str, db_fields)
112 result = self.find({'hrn': record['hrn'], 'type': record['type'], 'peer_authority': record['peer_authority']})
115 elif isinstance(result, list):
116 record_id = result[0]['record_id']
118 record_id = result['record_id']
122 def update(self, record):
123 db_fields = self.db_fields(record)
124 keys = db_fields.keys()
125 values = [self.db.param(key, value) for (key, value) in db_fields.items()]
126 columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
127 query_str = "UPDATE %s SET %s WHERE record_id = %s" % \
128 (self.tablename, ", ".join(columns), record['record_id'])
129 self.db.do(query_str, db_fields)
132 def quote_string(self, value):
133 return str(self.db.quote(value))
135 def quote(self, value):
136 return self.db.quote(value)
138 def find(self, record_filter = None, columns=None):
142 columns = ",".join(columns)
143 sql = "SELECT %s FROM %s WHERE True " % (columns, self.tablename)
145 if isinstance(record_filter, (list, tuple, set)):
146 ints = filter(lambda x: isinstance(x, (int, long)), record_filter)
147 strs = filter(lambda x: isinstance(x, StringTypes), record_filter)
148 record_filter = Filter(SfaRecord.all_fields, {'record_id': ints, 'hrn': strs})
149 sql += "AND (%s) %s " % record_filter.sql("OR")
150 elif isinstance(record_filter, dict):
151 record_filter = Filter(SfaRecord.all_fields, record_filter)
152 sql += " AND (%s) %s" % record_filter.sql("AND")
153 elif isinstance(record_filter, StringTypes):
154 record_filter = Filter(SfaRecord.all_fields, {'hrn':[record_filter]})
155 sql += " AND (%s) %s" % record_filter.sql("AND")
156 elif isinstance(record_filter, int):
157 record_filter = Filter(SfaRecord.all_fields, {'record_id':[record_filter]})
158 sql += " AND (%s) %s" % record_filter.sql("AND")
160 results = self.db.selectall(sql)
161 if isinstance(results, dict):
165 def findObjects(self, record_filter = None, columns=None):
167 results = self.find(record_filter, columns)
169 for result in results:
170 if result['type'] in ['authority']:
171 result_rec_list.append(AuthorityRecord(dict=result))
172 elif result['type'] in ['node']:
173 result_rec_list.append(NodeRecord(dict=result))
174 elif result['type'] in ['slice']:
175 result_rec_list.append(SliceRecord(dict=result))
176 elif result['type'] in ['user']:
177 result_rec_list.append(UserRecord(dict=result))
179 result_rec_list.append(SfaRecord(dict=result))
180 return result_rec_list
185 self.db.do('DROP TABLE IF EXISTS ' + self.tablename)
188 self.db.do('DROP TABLE ' + self.tablename)
192 def sfa_records_purge(self):