# Path: hecatoncheir/exception.py
# class DriverError(Exception):
#     source = None
# 
#     def __init__(self, value, source=None):
#         self.value = value
#         self.source = source
# 
#     def __str__(self):
#         return self.value
# 
# class ValidationError(Exception):
#     source = None
# 
#     def __init__(self, value, rule, params=None, source=None):
#         self.value = value
#         self.rule = rule
#         self.params = params
#         self.source = source
# 
#     def __str__(self):
#         return self.value
# 
# Path: hecatoncheir/pgsql/PgDriver.py
# class PgDriver(DbDriverBase.DbDriverBase):
#     connstr = None
#     dbuser = None
#     dbpass = None
#     conn = None
#     driver = None
# 
#     def __init__(self, connstr, dbuser, dbpass):
#         self.connstr = connstr
#         self.dbuser = dbuser
#         self.dbpass = dbpass
# 
#         name = "psycopg2"
#         try:
#             self.driver = __import__(name, fromlist=[''])
#         except Exception as e:
#             raise DriverError(
#                 u"Could not load the driver module: %s" % name, source=e)
# 
#     def connect(self):
#         s = self.connstr + " user=" + self.dbuser + " password=" + self.dbpass
#         try:
#             self.conn = self.driver.connect(s)
#         except Exception as e:
#             raise DriverError(
#                 u"Could not connect to the server: %s" %
#                 e.args[0].split('\n')[0], source=e)
# 
#         return True
# 
#     def query_to_resultset(self, query, max_rows=10000, timeout=None):
#         """Build a QueryResult object from the query
# 
#         Args:
#             query (str): a query string to be executed.
#             max_rows (int): max rows which can be kept in a QueryResult object.
# 
#         Returns:
#             QueryResult: an object holding query, column names and result set.
#         """
#         assert query
#         assert isinstance(query, unicode)
#         log.trace('query_to_resultset: start query=%s' % query)
# 
#         res = QueryResult(query)
#         try:
#             if self.conn is None:
#                 self.connect()
# 
#             cur = self.conn.cursor()
#             if timeout and int(timeout) > 0:
#                 cur.execute('set statement_timeout to %d' % (timeout*1000))
# 
#             cur.execute(res.query)
# 
#             desc = []
#             for d in cur.description:
#                 desc.append(d[0])
#             res.column_names = deepcopy(tuple(desc))
# 
#             for i, r in enumerate(cur.fetchall()):
#                 # let's consider the memory size.
#                 if i > max_rows:
#                     raise InternalError(
#                         u'Exceeded the record limit (%d) for QueryResult.' %
#                         max_rows, query=query)
#                 res.resultset.append(deepcopy(r))
#             cur.close()
#         except InternalError as e:
#             raise e
#         except DriverError as e:
#             raise e
#         except Exception as e:
#             msg = unicode(e).split('\n')[0]
#             if msg == 'canceling statement due to statement timeout':
#                 raise QueryTimeout(
#                     "Query timeout: %s" % query,
#                     query=query, source=e)
#             raise QueryError(
#                 "Could not execute a query: %s" % msg,
#                 query=query, source=e)
#         finally:
#             if self.conn:
#                 self.conn.rollback()
# 
#         log.trace('query_to_resultset: end')
#         return res
# 
#     def disconnect(self):
#         if self.conn is None:
#             return False
# 
#         try:
#             self.conn.close()
#         except Exception as e:
#             raise DriverError(
#                 u"Could not disconnect from the server: %s" %
#                 e.args[0].split('\n')[0], source=e)
#         self.conn = None
#         return True
# 
# Path: hecatoncheir/validator/SQLValidator.py
# class SQLValidator():
#     """Base class of SQLValidator
#     """
#     label = None
#     rule = None
#     queryresult = None
# 
#     def __init__(self, label, rule):
#         """Constructor
# 
#         Args:
#             label (str): label
#             rule (list): [column_name(s), query, expr]
#         """
#         assert isinstance(rule, list)
# 
#         self.label = label
#         self.rule = rule
#         self.column_names = rule[0].replace(' ', '').split(',')
#         self.query = rule[1]
# 
#     def validate(self, dbdriver):
#         if dbdriver is None:
#             raise DriverError(
#                 _("Database driver not found."))
# 
#         try:
#             res = dbdriver.q2rs(self.query)
#         except QueryError as e:
#             raise ValidationError(
#                 _("SQL error: ") + "`%s'" % self.query, self.label,
#                 source=e)
# 
#         assert res
#         assert len(res.column_names) == len(res.resultset[0])
#         assert len(res.resultset) == 1
# 
#         kv = {}
#         for k, v in zip(res.column_names, res.resultset[0]):
#             kv[k] = v
# 
#         return validate_eval(kv, self.rule[2])
# 
#     def __repr__(self):
#         return u'SQLValidator:' + repr({'label': self.label, 'rule': self.rule,
#                                         'queryresult': self.queryresult})


import sys
import unittest
from hecatoncheir.exception import DriverError, ValidationError
from hecatoncheir.pgsql import PgDriver
from hecatoncheir.validator import SQLValidator
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

sys.path.append('..')


class TestSQLValidator(unittest.TestCase):
    conn = None

    def setUp(self):

# Path: hecatoncheir/exception.py
# class DriverError(Exception):
#     source = None
# 
#     def __init__(self, value, source=None):
#         self.value = value
#         self.source = source
# 
#     def __str__(self):
#         return self.value
# 
# class ValidationError(Exception):
#     source = None
# 
#     def __init__(self, value, rule, params=None, source=None):
#         self.value = value
#         self.rule = rule
#         self.params = params
#         self.source = source
# 
#     def __str__(self):
#         return self.value
# 
# Path: hecatoncheir/pgsql/PgDriver.py
# class PgDriver(DbDriverBase.DbDriverBase):
#     connstr = None
#     dbuser = None
#     dbpass = None
#     conn = None
#     driver = None
# 
#     def __init__(self, connstr, dbuser, dbpass):
#         self.connstr = connstr
#         self.dbuser = dbuser
#         self.dbpass = dbpass
# 
#         name = "psycopg2"
#         try:
#             self.driver = __import__(name, fromlist=[''])
#         except Exception as e:
#             raise DriverError(
#                 u"Could not load the driver module: %s" % name, source=e)
# 
#     def connect(self):
#         s = self.connstr + " user=" + self.dbuser + " password=" + self.dbpass
#         try:
#             self.conn = self.driver.connect(s)
#         except Exception as e:
#             raise DriverError(
#                 u"Could not connect to the server: %s" %
#                 e.args[0].split('\n')[0], source=e)
# 
#         return True
# 
#     def query_to_resultset(self, query, max_rows=10000, timeout=None):
#         """Build a QueryResult object from the query
# 
#         Args:
#             query (str): a query string to be executed.
#             max_rows (int): max rows which can be kept in a QueryResult object.
# 
#         Returns:
#             QueryResult: an object holding query, column names and result set.
#         """
#         assert query
#         assert isinstance(query, unicode)
#         log.trace('query_to_resultset: start query=%s' % query)
# 
#         res = QueryResult(query)
#         try:
#             if self.conn is None:
#                 self.connect()
# 
#             cur = self.conn.cursor()
#             if timeout and int(timeout) > 0:
#                 cur.execute('set statement_timeout to %d' % (timeout*1000))
# 
#             cur.execute(res.query)
# 
#             desc = []
#             for d in cur.description:
#                 desc.append(d[0])
#             res.column_names = deepcopy(tuple(desc))
# 
#             for i, r in enumerate(cur.fetchall()):
#                 # let's consider the memory size.
#                 if i > max_rows:
#                     raise InternalError(
#                         u'Exceeded the record limit (%d) for QueryResult.' %
#                         max_rows, query=query)
#                 res.resultset.append(deepcopy(r))
#             cur.close()
#         except InternalError as e:
#             raise e
#         except DriverError as e:
#             raise e
#         except Exception as e:
#             msg = unicode(e).split('\n')[0]
#             if msg == 'canceling statement due to statement timeout':
#                 raise QueryTimeout(
#                     "Query timeout: %s" % query,
#                     query=query, source=e)
#             raise QueryError(
#                 "Could not execute a query: %s" % msg,
#                 query=query, source=e)
#         finally:
#             if self.conn:
#                 self.conn.rollback()
# 
#         log.trace('query_to_resultset: end')
#         return res
# 
#     def disconnect(self):
#         if self.conn is None:
#             return False
# 
#         try:
#             self.conn.close()
#         except Exception as e:
#             raise DriverError(
#                 u"Could not disconnect from the server: %s" %
#                 e.args[0].split('\n')[0], source=e)
#         self.conn = None
#         return True
# 
# Path: hecatoncheir/validator/SQLValidator.py
# class SQLValidator():
#     """Base class of SQLValidator
#     """
#     label = None
#     rule = None
#     queryresult = None
# 
#     def __init__(self, label, rule):
#         """Constructor
# 
#         Args:
#             label (str): label
#             rule (list): [column_name(s), query, expr]
#         """
#         assert isinstance(rule, list)
# 
#         self.label = label
#         self.rule = rule
#         self.column_names = rule[0].replace(' ', '').split(',')
#         self.query = rule[1]
# 
#     def validate(self, dbdriver):
#         if dbdriver is None:
#             raise DriverError(
#                 _("Database driver not found."))
# 
#         try:
#             res = dbdriver.q2rs(self.query)
#         except QueryError as e:
#             raise ValidationError(
#                 _("SQL error: ") + "`%s'" % self.query, self.label,
#                 source=e)
# 
#         assert res
#         assert len(res.column_names) == len(res.resultset[0])
#         assert len(res.resultset) == 1
# 
#         kv = {}
#         for k, v in zip(res.column_names, res.resultset[0]):
#             kv[k] = v
# 
#         return validate_eval(kv, self.rule[2])
# 
#     def __repr__(self):
#         return u'SQLValidator:' + repr({'label': self.label, 'rule': self.rule,
#                                         'queryresult': self.queryresult})


# Path: tests/testSQLValidator.py
import sys
import unittest
from hecatoncheir.exception import DriverError, ValidationError
from hecatoncheir.pgsql import PgDriver
from hecatoncheir.validator import SQLValidator

#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

sys.path.append('..')


class TestSQLValidator(unittest.TestCase):
    conn = None

    def setUp(self):

        self.d = PgDriver.PgDriver('host=/tmp dbname=%s' % "dqwbtest", "dqwbuser", "dqwbuser")