36d40e9788099dc6734f4c2343b52c20c7793bf5
[sfa.git] / geni / util / genitable.py
1 # genitable.py
2 #
3 # implements support for geni records stored in db tables
4 #
5 # TODO: Use existing PLC database methods? or keep this separate?
6
7 import report
8
9 from pg import DB, ProgrammingError
10 from gid import *
11 from record import *
12
13 GENI_TABLE_PREFIX = "geni$"
14
15 class GeniTable():
16     def __init__(self, create=False, hrn="unspecified.default.registry", cninfo=None):
17         global GENI_TABLE_PREFIX
18
19         self.hrn = hrn
20
21         # pgsql doesn't like table names with "." in them, to replace it with "$"
22         self.tablename = GENI_TABLE_PREFIX + self.hrn.replace(".", "$")
23
24         # establish a connection to the pgsql server
25         self.cnx = DB(cninfo['dbname'], cninfo['address'], port=cninfo['port'], user=cninfo['user'], passwd=cninfo['password'])
26
27         # if asked to create the table, then create it
28         if create:
29             self.create()
30
31     def exists(self):
32         tableList = self.cnx.get_tables()
33         if 'public.' + self.tablename in tableList:
34             return True
35         if 'public."' + self.tablename + '"' in tableList:
36             return True
37         return False
38
39     def create(self):
40         querystr = "CREATE TABLE " + self.tablename + " ( \
41                 key text, \
42                 name text, \
43                 gid text, \
44                 type text, \
45                 pointer integer);"
46
47         # IF EXISTS doenst exist in postgres < 8.2
48         try:
49             self.cnx.query('DROP TABLE IF EXISTS ' + self.tablename)
50         except ProgrammingError:
51             try:
52                 self.cnx.query('DROP TABLE ' + self.tablename)
53             except ProgrammingError:
54                 pass
55         
56         self.cnx.query(querystr)
57
58     def remove(self, record):
59         query_str = "DELETE FROM " + self.tablename + " WHERE key = '" + record.get_key() + "'"
60         self.cnx.query(query_str)
61
62     def insert(self, record):
63         fieldnames = ["key"] + record.get_field_names()
64         fieldvals = record.get_field_value_strings(fieldnames)
65         query_str = "INSERT INTO " + self.tablename + \
66                        "(" + ",".join(fieldnames) + ") " + \
67                        "VALUES(" + ",".join(fieldvals) + ")"
68         #print query_str
69         self.cnx.query(query_str)
70
71     def update(self, record):
72         names = record.get_field_names()
73         pairs = []
74         for name in names:
75            val = record.get_field_value_string(name)
76            pairs.append(name + " = " + val)
77         update = ", ".join(pairs)
78
79         query_str = "UPDATE " + self.tablename+ " SET " + update + " WHERE key = '" + record.get_key() + "'"
80         #print query_str
81         self.cnx.query(query_str)
82
83     def find_dict(self, type, value, searchfield):
84         query_str = "SELECT * FROM " + self.tablename + " WHERE " + searchfield + " = '" + str(value) + "'"
85         dict_list = self.cnx.query(query_str).dictresult()
86         result_dict_list = []
87         for dict in dict_list:
88            if (type=="*") or (dict['type'] == type):
89                result_dict_list.append(dict)
90         return result_dict_list
91
92     def find(self, type, value, searchfield):
93         result_dict_list = self.find_dict(type, value, searchfield)
94         result_rec_list = []
95         for dict in result_dict_list:
96             result_rec_list.append(GeniRecord(dict=dict))
97         return result_rec_list
98
99     def resolve_dict(self, type, hrn):
100         return self.find_dict(type, hrn, "name")
101
102     def resolve(self, type, hrn):
103         return self.find(type, hrn, "name")
104
105     def list_dict(self):
106         query_str = "SELECT * FROM " + self.tablename
107         result_dict_list = self.cnx.query(query_str).dictresult()
108         return result_dict_list
109
110     def list(self):
111         result_dict_list = self.list_dict()
112         result_rec_list = []
113         for dict in result_dict_list:
114             result_rec_list.append(GeniRecord(dict=dict))
115         return result_rec_list
116
117 def set_geni_table_prefix(x):
118     global GENI_TABLE_PREFIX
119
120     GENI_TABLE_PREFIX = x
121
122 def geni_records_purge(cninfo):
123     global GENI_TABLE_PREFIX
124
125     cnx = DB(cninfo['dbname'], cninfo['address'], port=cninfo['port'], user=cninfo['user'], passwd=cninfo['password'])
126     tableList = cnx.get_tables()
127     for table in tableList:
128         if table.startswith(GENI_TABLE_PREFIX) or \
129            table.startswith('public.' + GENI_TABLE_PREFIX) or \
130            table.startswith('public."' + GENI_TABLE_PREFIX):
131                report.trace("dropping table " + table)
132                cnx.query("DROP TABLE " + table)