Package backend :: Package server :: Package rhnSQL
[hide private]
[frames] | no frames]

Source Code for Package backend.server.rhnSQL

  1  # 
  2  # Copyright (c) 2008--2016 Red Hat, Inc. 
  3  # 
  4  # This software is licensed to you under the GNU General Public License, 
  5  # version 2 (GPLv2). There is NO WARRANTY for this software, express or 
  6  # implied, including the implied warranties of MERCHANTABILITY or FITNESS 
  7  # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 
  8  # along with this software; if not, see 
  9  # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. 
 10  # 
 11  # Red Hat trademarks are not licensed under GPLv2. No permission is 
 12  # granted to use or replicate Red Hat trademarks that are incorporated 
 13  # in this software or its documentation. 
 14  # 
 15  # entry points for the rhnSQL module 
 16  # 
 17   
 18  import sys 
 19   
 20  from spacewalk.common.usix import raise_with_tb 
 21  from spacewalk.common.rhnLog import log_debug 
 22  from spacewalk.common.rhnConfig import CFG, initCFG 
 23  from spacewalk.common.rhnException import rhnException 
 24  from spacewalk.common.rhnTB import add_to_seclist 
 25   
 26  # SQL objects 
 27  import sql_table 
 28  import sql_row 
 29  import sql_sequence 
 30  import dbi 
 31  import sql_types 
 32  types = sql_types 
 33   
 34  from const import ORACLE, POSTGRESQL, SUPPORTED_BACKENDS 
 35   
 36  # expose exceptions 
 37  from sql_base import SQLError, SQLSchemaError, SQLConnectError, \ 
 38      SQLStatementPrepareError, Statement, ModifiedRowError 
 39   
 40  # ths module works with a private global __DB object that is 
 41  # instantiated by the initDB call. This object/instance should NEVER, 
 42  # EVER be exposed to the calling applications. 
 43   
 44   
45 -def __init__DB(backend, host, port, username, password, database, sslmode, sslrootcert):
46 """ 47 Establish and check the connection so we can wrap it and handle 48 exceptions. 49 """ 50 # __DB global object created here and pushed into the global namespace. 51 global __DB 52 try: 53 my_db = __DB 54 except NameError: # __DB has not been set up 55 db_class = dbi.get_database_class(backend=backend) 56 __DB = db_class(host, port, username, password, database, sslmode, sslrootcert) 57 __DB.connect() 58 return 59 else: 60 del my_db 61 62 if __DB.is_connected_to(backend, host, port, username, password, 63 database, sslmode, sslrootcert): 64 __DB.check_connection() 65 return 66 67 __DB.commit() 68 __DB.close() 69 # now we have to get a different connection 70 __DB = dbi.get_database_class(backend=backend)( 71 host, port, username, password, database, sslmode, sslrootcert) 72 __DB.connect() 73 return 0
74 75
76 -def __init__DB2(backend, host, port, username, password, database, sslmode, sslrootcert):
77 """ 78 Establish and check the connection so we can wrap it and handle 79 exceptions. 80 """ 81 # __DB2 global object created here and pushed into the global namespace. 82 global __DB2 83 try: 84 my_db = __DB2 85 except NameError: # __DB2 has not been set up 86 db_class = dbi.get_database_class(backend=backend) 87 __DB2 = db_class(host, port, username, password, database, sslmode, sslrootcert) 88 __DB2.connect() 89 return 90 else: 91 del my_db 92 93 if __DB2.is_connected_to(backend, host, port, username, password, 94 database, sslmode, sslrootcert): 95 __DB2.check_connection() 96 return 97 98 __DB2.commit() 99 __DB2.close() 100 # now we have to get a different connection 101 __DB2 = dbi.get_database_class(backend=backend)( 102 host, port, username, password, database, sslmode, sslrootcert) 103 __DB2.connect() 104 return 0
105 106
107 -def initDB(backend=None, host=None, port=None, username=None, 108 password=None, database=None, sslmode=None, sslrootcert=None, initsecond=False):
109 """ 110 Initialize the database. 111 112 Either we get backend and all parameter which means the caller 113 knows what they are doing, or we populate everything from the 114 config files. 115 116 initsecond: If set to True it initialize a second DB connection. 117 By default only one DB connection is needed. 118 """ 119 120 if backend is None: 121 if CFG is None or not CFG.is_initialized(): 122 initCFG('server') 123 backend = CFG.DB_BACKEND 124 host = CFG.DB_HOST 125 port = CFG.DB_PORT 126 database = CFG.DB_NAME 127 username = CFG.DB_USER 128 password = CFG.DB_PASSWORD 129 sslmode = None 130 sslrootcert = None 131 if CFG.DB_SSL_ENABLED: 132 sslmode = 'verify-full' 133 sslrootcert = CFG.DB_SSLROOTCERT 134 135 if backend not in SUPPORTED_BACKENDS: 136 raise rhnException("Unsupported database backend", backend) 137 138 if port: 139 port = int(port) 140 141 # Hide the password 142 add_to_seclist(password) 143 try: 144 if initsecond == False: 145 __init__DB(backend, host, port, username, password, database, sslmode, sslrootcert) 146 else: 147 __init__DB2(backend, host, port, username, password, database, sslmode, sslrootcert) 148 # except (rhnException, SQLError): 149 # raise # pass on, we know those ones 150 # except (KeyboardInterrupt, SystemExit): 151 # raise 152 except SQLConnectError: 153 e = sys.exc_info()[1] 154 try: 155 closeDB() 156 except NameError: 157 pass 158 raise_with_tb(e, sys.exc_info()[2]) 159 except: 160 raise 161 #e_type, e_value = sys.exc_info()[:2] 162 # raise rhnException("Could not initialize Oracle database connection", 163 # str(e_type), str(e_value)) 164 return 0
165 166
167 -def __closeDB2():
168 global __DB2 169 try: 170 my_db = __DB2 171 except NameError: 172 return 173 else: 174 del my_db 175 # can be None 176 if not __DB2: 177 del __DB2 178 return 179 __DB2.commit() 180 __DB2.close() 181 del __DB2 182 return
183 184 # close the database 185 186
187 -def closeDB():
188 global __DB 189 try: 190 my_db = __DB 191 except NameError: 192 __closeDB2() 193 return 194 else: 195 del my_db 196 __DB.commit() 197 __DB.close() 198 del __DB 199 __closeDB2() 200 return
201 202 203 # common function for testing the connection state (ie, __DB defined
204 -def __test_DB():
205 global __DB 206 try: 207 return __DB 208 except NameError: 209 raise_with_tb(SystemError("Not connected to any database!"), sys.exc_info()[2])
210 211
212 -def __test_DB2():
213 global __DB2 214 try: 215 return __DB2 216 except NameError: 217 # try open the connection 218 try: 219 initDB(initsecond=True) 220 return __DB2 221 except NameError: 222 raise_with_tb(SystemError("Not connected to secondary database!"), sys.exc_info()[2])
223 224 # wrapper for a Procedure callable class 225 226
227 -def Procedure(name):
228 db = __test_DB() 229 return db.procedure(name)
230 231 232 # wrapper for a Procedure callable class
233 -def Function(name, ret_type):
234 db = __test_DB() 235 return db.function(name, ret_type)
236 237 238 # Wrapper for the Sequence class
239 -def Sequence(seq):
240 db = __test_DB() 241 return sql_sequence.Sequence(db, seq)
242 243 244 # Wrapper for the Row class
245 -def Row(table, hash_name, hash_value=None):
246 db = __test_DB() 247 return sql_row.Row(db, table, hash_name, hash_value)
248 249 250 # Wrapper for the Table class
251 -def Table(table, hash_name, local_cache=0):
252 db = __test_DB() 253 return sql_table.Table(db, table, hash_name, local_cache)
254 255 256 ########################### 257 # Functions points of entry 258 ########################### 259 260
261 -def cursor():
262 db = __test_DB() 263 return db.cursor()
264 265
266 -def prepare(sql, blob_map=None):
267 db = __test_DB() 268 if isinstance(sql, Statement): 269 sql = sql.statement 270 return db.prepare(sql, blob_map=blob_map)
271 272
273 -def prepare_secondary(sql, blob_map=None):
274 db = __test_DB2() 275 if isinstance(sql, Statement): 276 sql = sql.statement 277 return db.prepare(sql, blob_map=blob_map)
278 279
280 -def execute(sql, *args, **kwargs):
281 db = __test_DB() 282 return db.execute(sql, *args, **kwargs)
283 284
285 -def execute_secondary(sql, *args, **kwargs):
286 db = __test_DB2() 287 return db.execute(sql, *args, **kwargs)
288 289
290 -def fetchall_dict(sql, *args, **kwargs):
291 h = prepare(sql) 292 h.execute(sql, *args, **kwargs) 293 return h.fetchall_dict()
294 295
296 -def fetchone_dict(sql, *args, **kwargs):
297 h = prepare(sql) 298 h.execute(sql, *args, **kwargs) 299 return h.fetchone_dict()
300 301
302 -def commit():
303 db = __test_DB() 304 return db.commit()
305 306
307 -def commit_secondary():
308 db = __test_DB2() 309 return db.commit()
310 311
312 -def rollback(name=None):
313 db = __test_DB() 314 return db.rollback(name)
315 316
317 -def transaction(name):
318 db = __test_DB() 319 return db.transaction(name)
320 321
322 -def TimestampFromTicks(*args, **kwargs):
323 db = __test_DB() 324 return db.TimestampFromTicks(*args, **kwargs)
325 326
327 -def DateFromTicks(*args, **kwargs):
328 db = __test_DB() 329 return db.DateFromTicks(*args, **kwargs)
330 331
332 -def Date(*args, **kwargs):
333 db = __test_DB() 334 return db.Date(*args, **kwargs)
335 336
337 -def clear_log_id():
338 clear_log_id = Procedure("logging.clear_log_id") 339 clear_log_id()
340 341
342 -def set_log_auth(user_id):
343 set_log_auth = Procedure("logging.set_log_auth") 344 set_log_auth(user_id)
345 346
347 -def set_log_auth_login(login):
348 h = prepare("select id from web_contact_all where login = :login") 349 h.execute(login=login) 350 row = h.fetchone_dict() 351 if row: 352 user_id = row['id'] 353 set_log_auth(user_id) 354 else: 355 raise rhnException("No such log user", login)
356 357
358 -def read_lob(lob):
359 if not lob: 360 return None 361 db = __test_DB() 362 return db._read_lob(lob)
363 364
365 -class _Callable(object):
366
367 - def __init__(self, name):
368 self._name = name 369 self._implementor = None
370
371 - def __getattr__(self, name):
372 return self.__class__("%s.%s" % (self._name, name))
373
374 - def __call__(self, *args):
375 proc = self._implementor.__call__(self._name) 376 return proc(*args)
377 378
379 -class _Procedure(_Callable):
380
381 - def __init__(self, name):
382 _Callable.__init__(self, name) 383 self._implementor = Procedure
384 385
386 -class _Function(_Callable):
387
388 - def __init__(self, name):
389 _Callable.__init__(self, name) 390 self._implementor = Function
391 392
393 -class _CallableWrapper(object):
394
395 - def __init__(self, wrapped):
396 self._wrapped = wrapped
397
398 - def __getattr__(self, x):
399 return self._wrapped(x)
400 401 procedure = _CallableWrapper(_Procedure) 402 function = _CallableWrapper(_Function) 403