| 1 |
"""Auxillary methods for the UDD"""
|
| 2 |
|
| 3 |
import syck
|
| 4 |
import sys
|
| 5 |
import psycopg2
|
| 6 |
|
| 7 |
# If debug is something that evaluates to True, then print_debug actually prints something
|
| 8 |
debug = 0
|
| 9 |
|
| 10 |
def quote(s):
|
| 11 |
"Quote a string for SQL"
|
| 12 |
return "'" + s.replace("'", "\\'") + "'"
|
| 13 |
|
| 14 |
def null_or_quote(dict, key):
|
| 15 |
"If key is an element of dict, return it quoted. Return NULL otherwise"
|
| 16 |
if key in dict:
|
| 17 |
return quote(dict[key])
|
| 18 |
else:
|
| 19 |
return 'NULL'
|
| 20 |
|
| 21 |
class ConfigException(Exception):
|
| 22 |
def __init__(self, message):
|
| 23 |
Exception(self)
|
| 24 |
self.message = message
|
| 25 |
|
| 26 |
def __str__(self):
|
| 27 |
return "ConfigException: " + self.message
|
| 28 |
|
| 29 |
def open_connection(config):
|
| 30 |
"""Open the connection to the database and return it"""
|
| 31 |
return psycopg2.connect("dbname=" + config['general']['dbname'])
|
| 32 |
|
| 33 |
def load_config(str):
|
| 34 |
"""Load and check configuration from the string"""
|
| 35 |
config = syck.load(str)
|
| 36 |
if not 'general' in config:
|
| 37 |
raise ConfigException('general section not specified')
|
| 38 |
|
| 39 |
general = config['general']
|
| 40 |
|
| 41 |
if not 'dbname' in general:
|
| 42 |
raise ConfigException('dbname not specified')
|
| 43 |
|
| 44 |
if not 'archs' in general:
|
| 45 |
raise ConfigException('archs not specified')
|
| 46 |
|
| 47 |
if not 'types' in general:
|
| 48 |
raise ConfigException('types not specified')
|
| 49 |
|
| 50 |
if not 'debug' in general:
|
| 51 |
general['debug'] = 0
|
| 52 |
|
| 53 |
# Check that the source-entries are well-formed
|
| 54 |
for name in config:
|
| 55 |
if name == 'general':
|
| 56 |
continue
|
| 57 |
|
| 58 |
src = config[name]
|
| 59 |
if not 'type' in src:
|
| 60 |
raise ConfigException('type not specified for "%s"' % name)
|
| 61 |
if src['type'] not in general['types']:
|
| 62 |
raise ConfigException('Type of %s not specified in types' % name)
|
| 63 |
|
| 64 |
return config
|
| 65 |
|
| 66 |
def print_debug(*args):
|
| 67 |
"Print arguments to stdout if debug is set to something that evaluates to true"
|
| 68 |
if debug:
|
| 69 |
sys.stdout.write(*args)
|
| 70 |
sys.stdout.write("\n")
|