|
| 1 | +import psycopg2 |
| 2 | +from psycopg2._psycopg import ProgrammingError |
| 3 | +from config import config |
| 4 | + |
| 5 | +class data_warehouse(object): |
| 6 | + ''' |
| 7 | + This class is used to get data from the Rightside data warehouse. |
| 8 | + The complete data warehouse documentation can be found at |
| 9 | + https://wiki.rightside.net/display/tnt/BI |
| 10 | + ''' |
| 11 | + |
| 12 | + def __init__(self): |
| 13 | + """ |
| 14 | + This method sets the data warehouse connection string from the config. |
| 15 | + """ |
| 16 | + cnf = config() |
| 17 | + dbname = cnf.get('dw_dbname') |
| 18 | + user = cnf.get('dw_user') |
| 19 | + password = cnf.get('dw_password') |
| 20 | + host = cnf.get('dw_host') |
| 21 | + port = cnf.get('dw_port') |
| 22 | + |
| 23 | + self.dw_connection_string = \ |
| 24 | + "dbname='{}' user='{}' password='{}' host='{}' port='{}'".format(dbname,user,password,host,port) |
| 25 | + |
| 26 | + |
| 27 | + def __call__(self, query): |
| 28 | + """ |
| 29 | + This method calls the data warehouse API. |
| 30 | + The complete data warehouse documentation can be found at |
| 31 | + https://wiki.rightside.net/display/tnt/BI |
| 32 | + :param query: A string containing a valid redshift data warehouse query. |
| 33 | + :return: This depends on the query. |
| 34 | + If the query returns records, as in a 'select' query, the records are returned. |
| 35 | + If the query does not return records, as in an 'update' query, a unicode string is returned. |
| 36 | + """ |
| 37 | + with psycopg2.connect(self.dw_connection_string) as conn: |
| 38 | + with conn.cursor() as curs: |
| 39 | + curs.execute(query) |
| 40 | + |
| 41 | + try: |
| 42 | + records = curs.fetchall() |
| 43 | + return records |
| 44 | + except ProgrammingError as e: |
| 45 | + # This error occurs when there are no records to return, |
| 46 | + # for example, queries such as inserts, updates, and unloads. |
| 47 | + message = unicode(e) |
| 48 | + if message == u'no results to fetch': |
| 49 | + return message |
| 50 | + else: |
| 51 | + raise message |
| 52 | + |
| 53 | + |
| 54 | + |
0 commit comments