removed another bunch of references to geni
[sfa.git] / sfa / util / table.py
1 ### $Id$
2 ### $URL$
3 #
4 # implements support for SFA records stored in db tables
5 #
6 # TODO: Use existing PLC database methods? or keep this separate?
7
8 import report
9 import pgdb
10 from pg import DB, ProgrammingError
11
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 *
18
19 class SfaTable(list):
20
21     SFA_TABLE_PREFIX = "sfa"
22
23     def __init__(self, record_filter = None):
24
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'])
32
33         if record_filter:
34             records = self.find(record_filter)
35             for record in reocrds:
36                 self.append(record)             
37
38     def exists(self):
39         tableList = self.cnx.get_tables()
40         if 'public.' + self.tablename in tableList:
41             return True
42         if 'public."' + self.tablename + '"' in tableList:
43             return True
44         return False
45
46     def db_fields(self, obj=None):
47         
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)] )      
52
53     @staticmethod
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
61
62         return False
63
64
65     def create(self):
66         
67         querystr = "CREATE TABLE " + self.tablename + " ( \
68                 record_id serial PRIMARY KEY , \
69                 hrn text NOT NULL, \
70                 authority text NOT NULL, \
71                 peer_authority text, \
72                 gid text, \
73                 type text NOT NULL, \
74                 pointer integer, \
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
81         try:
82             self.cnx.query('DROP TABLE IF EXISTS ' + self.tablename)
83         except ProgrammingError:
84             try:
85                 self.cnx.query('DROP TABLE ' + self.tablename)
86             except ProgrammingError:
87                 pass
88          
89         self.cnx.query(querystr)
90         for index in indexes:
91             self.cnx.query(index)
92
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)
97         
98         # if this is a site, remove all records where 'authority' == the 
99         # site's hrn
100         if record['type'] == 'site':
101             sql = " DELETE FROM %s WHERE authority = %s" % \
102                     (self.tablename, record['hrn'])
103             self.cnx.query(sql) 
104
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)
113         self.db.commit()
114         result = self.find({'hrn': record['hrn'], 'type': record['type'], 'peer_authority': record['peer_authority']})
115         if not result:
116             record_id = None
117         elif isinstance(result, list):
118             record_id = result[0]['record_id']
119         else:
120             record_id = result['record_id']
121
122         return record_id
123
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)
132         self.db.commit()
133
134     def quote_string(self, value):
135         return str(self.quote(value))
136
137     def quote(self, value):
138         """
139         Returns quoted version of the specified value.
140         """
141
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)
146         else:
147             return pgdb._quote(value)
148
149     def find(self, record_filter = None, columns=None):
150         if not columns:
151             columns = "*"
152         else:
153             columns = ",".join(columns)
154         sql = "SELECT %s FROM %s WHERE True " % (columns, self.tablename)
155         
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")
170
171         results = self.cnx.query(sql).dictresult()
172         if isinstance(results, dict):
173             results = [results]
174         return results
175
176     def findObjects(self, record_filter = None, columns=None):
177         
178         results = self.find(record_filter, columns) 
179         result_rec_list = []
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))
189             else:
190                 result_rec_list.append(SfaRecord(dict=result))
191         return result_rec_list
192
193
194     def drop(self):
195         try:
196             self.cnx.query('DROP TABLE IF EXISTS ' + self.tablename)
197         except ProgrammingError:
198             try:
199                 self.cnx.query('DROP TABLE ' + self.tablename)
200             except ProgrammingError:
201                 pass
202     
203     @staticmethod
204     def sfa_records_purge(cninfo):
205
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)