1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 __version__ = "$Revision: 1.4 $"
18 __author__ = "Hilmar Berger <Hilmar.Berger@gmx.net>"
19
20 import sys, string, types, os.path
21
22 _log = gmLog.gmDefLog
23 if __name__ == "__main__":
24
25 _log.SetAllLogLevels(gmLog.lData)
26 _log.Log(gmLog.lData, __version__)
27
28 from gmExceptions import *
29
30
32 """Object holding query strings and associated variable lists grouped together.
33
34 - Every query has to be identified by a unique identifier (string or number).
35 - mQueryStrings holds the query strings returning one or more parameters.
36 - mVarNames holds a list of variables that are to be filled by the query,
37 for this the order of the returned column names map 1:1 onto the
38 variable names
39 - mMappings holds the variables that should be mapped to the query.
40 - mInfos holds arbitrary infos (in a single string) about the query.
41 This can be used for format strings and so on.
42 - These three dictionaries are accessible from other objects.
43 - You must use addEntry to add entries to the dictionaries, though,
44 else the data will be written to the class as static variables.
45 """
46
48 self.mVarNames = {}
49 self.mQueryStrings = {}
50 self.mMappings = {}
51
52 - def addEntry(self, aEntry = None):
53 if aEntry != None:
54 self.mVarNames[aEntry] = None
55 self.mQueryStrings[aEntry] = None
56 self.mMappings[aEntry] = None
57
58
60 """High level API to access drug data
61
62 FIXME: should class Drug not, perhaps, be derived from gmBusinessDBObject ?
63 """
64 _db = None
65
66 - def __init__(self, fastInit=0, queryCfgSource = None):
67 """initialize static variables"""
68
69 self.mVars = {}
70 self.__mQueryGroups = {}
71 self.__mQueryGroupHandlers = {}
72 self.__fastInit=0
73
74
75 if queryCfgSource is None:
76 _log.Log(gmLog.lWarn, "No query configuration source specified")
77
78
79
80 raise TypeError, "No query configuration source specified"
81 else:
82 self.__mQueryCfgSource = queryCfgSource
83 if not self.__getQueries():
84 raise IOError, "cannot load queries"
85
86
87 self.__fastInit = fastInit
88 if fastInit:
89 self.getAllData()
90
91 - def GetData(self, groupName = None, refresh=0):
92 """Get data of QueryGroupHandlers identified by groupName.
93
94 Returns None if the group does not exist or if the query was not
95 successful. Else it returns a dictionary containing all the variables
96 defined for this query.
97 If the query should be repeated instead of the cached data used, you will
98 have to set refresh to 1 (you should do this if some mapped variable was
99 changed).
100 """
101
102 if groupName is None:
103 return None
104
105 if self.__mQueryGroupHandlers.has_key(groupName):
106
107 result = self.__mQueryGroupHandlers[groupName].getData(refresh)
108 return result
109 else:
110 return None
111
113 """fetch data of all standard sub objects"""
114 for s in self.__QueryGroupHandlers.keys():
115 self.GetData(s)
116
117
119 """get query strings and initialize query group objects"""
120
121
122 try:
123 cfgSource = gmCfg.cCfgFile(aFile = self.__mQueryCfgSource, \
124 flags=gmCfg.cfg_SEARCH_STD_DIRS | gmCfg.cfg_IGNORE_CMD_LINE)
125
126 except:
127 exc = sys.exc_info()
128 _log.LogException("Unhandled exception while opening config file [%s]" % self.__mQueryCfgSource, exc, verbose = 0)
129 return None
130
131 cfgData = cfgSource.getCfg()
132 groups = cfgSource.getGroups()
133
134
135
136
137 for entry_group in groups:
138 gtype = cfgSource.get(entry_group, "type")
139
140 if gtype != 'query':
141 continue
142
143 qname = cfgSource.get(entry_group, "querygroup")
144 if qname is None:
145 _log.Log(gmLog.lWarn,"query definition invalid in entry_group %s." % entry_group)
146 continue
147
148 qvars = cfgSource.get(entry_group, "variables")
149 if qvars is None:
150 _log.Log(gmLog.lWarn,"query definition invalid in entry_group %s." % entry_group)
151 continue
152
153
154
155 query = cfgSource.get(entry_group, "query")
156 if query is None or not type(query) == types.ListType:
157 _log.Log(gmLog.lWarn,"query definition invalid in entry_group %s." % entry_group)
158 continue
159
160 qstring = query[0]
161
162 qmappings = cfgSource.get(entry_group, "mappings")
163 if qmappings is None:
164 _log.Log(gmLog.lWarn,"query definition invalid in entry_group %s." % entry_group)
165 continue
166
167
168 if not self.__mQueryGroups.has_key(qname):
169 self.__mQueryGroups[qname] = cQueryGroup()
170 self.__mQueryGroups[qname].addEntry(entry_group)
171
172
173 self.__mQueryGroups[qname].mVarNames[entry_group] = string.split(qvars, ',')
174 self.__mQueryGroups[qname].mMappings[entry_group] = string.split(qmappings, ',')
175 self.__mQueryGroups[qname].mQueryStrings[entry_group] = qstring
176
177
178 for v in string.split(qmappings, ','):
179
180 if v != '':
181 self.mVars[v] = None
182
183
184 for so in self.__mQueryGroups.keys():
185 self.__mQueryGroupHandlers[so] = cQueryGroupHandler(self, so, self.__mQueryGroups[so])
186
187 return 1
188
190 """Object covering groups of related items.
191
192 used to access the backend to fetch all those items at once
193
194 """
195
196 - def __init__(self, aParent=None, aName=None, aQueryGroup=None):
197 self.__mParent = None
198 self.__mDBObject = None
199 self.__mObjectName = None
200 self.__mQueries = cQueryGroup()
201 self.__mData = {}
202
203 if aParent != None:
204 self.__mParent = aParent
205 if aQueryGroup != None:
206 self.__mQueries = aQueryGroup
207 if aName != None:
208 self.__mObjectName = aName
209
211 """returns a dictionary of entry names and its values"""
212
213
214 if refresh == 1:
215 self.__mData = {}
216
217 if len(self.__mData) == 0:
218
219 if self.__fetchBackendData():
220 return self.__mData
221 else:
222 return None
223 else:
224
225 return self.__mData
226
227
229 """try to fetch data from backend"""
230
231
232 for queryName in self.__mQueries.mQueryStrings.keys():
233
234 mappings = self.__mQueries.mMappings[queryName]
235 allVars = []
236 for var in mappings:
237
238 if var != '':
239 allVars.append(self.__mParent.mVars[var])
240
241
242
243 if len(allVars) > 0:
244 querystring = self.__mQueries.mQueryStrings[queryName] % tuple(allVars)
245 else:
246 querystring = self.__mQueries.mQueryStrings[queryName]
247
248
249 try:
250 result = gmPG.run_ro_query('pharmaceutica',querystring)
251 except:
252 _log.Log(gmLog.lWarn, "Query failed.")
253
254
255 if result is None:
256 return None
257
258
259 VarNames = self.__mQueries.mVarNames[queryName]
260 VarNumMax = len(VarNames)
261
262 for vn in VarNames:
263 if not self.__mData.has_key(vn):
264 self.__mData[vn] = []
265
266
267 if len(result) == 1:
268 row = result[0]
269 col_idx = 0
270 cols_avail = len(row)
271 for col_val in row:
272
273 if col_idx > VarNumMax:
274 break
275
276 VarName = VarNames[col_idx]
277
278 self.__mData[VarName] = col_val
279
280 col_idx = col_idx + 1
281
282 else:
283
284 for row in result[:]:
285 col_idx = 0
286 cols_avail = len(row)
287 for col_val in row:
288 if col_idx > VarNumMax:
289 break
290 VarName = VarNames[col_idx]
291 self.__mData[VarName].append(col_val)
292 col_idx = col_idx + 1
293
294
295 return 1
296
297
298
299
300 if __name__ == "__main__":
301 import os.path
302 tmp = os.path.join(os.path.expanduser("~"), ".gnumed", "amis.conf")
303 a = cDrug(0, tmp)
304 x = a.GetData('brand')
305 if x:
306 print x
307 else:
308 print "Query wasn't successful."
309
310 print "-----------------------------------------------------"
311 a.mVars['ID']="3337631600"
312 y=a.GetData('product_info')
313 print y
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363