# Path: rwslib/extras/local_cv.py
# class SQLLiteDBAdapter(BaseDBAdapter):
#     """Variant that makes SQLLite SQL"""
# 
#     def __init__(self, db):
#         """Receives a SQLLiteDB to populate"""
#         BaseDBAdapter.__init__(self)
#         self.conn = db
# 
#     def _processDDL(self):
#         """Generate and process table SQL, SQLLite version"""
#         sql_statements = self._generateDDL()
# 
#         logging.info('Generating sqllite tables')
#         for stmt in sql_statements:
#             c = self.conn.cursor()
#             c.execute(stmt)
#             self.conn.commit()
# 
#     def _generateDDL(self):
#         """Generate DDL statements for SQLLite"""
#         sql = []
#         # Next convert each set of columns into a table structure
#         for dataset_name in sorted(self.datasets.keys()):
# 
#             # SQL to drop the table if it already exists
#             sql.append('''drop table if exists %s;''' % dataset_name)
# 
#             # Generate the SQL for the cols
#             cols = self.datasets[dataset_name]
#             col_defs = []
#             for col in cols:
#                 sql_datatype = self.getSQLDataType(col["vartype"])
#                 col_defs.append("%s %s" % (col["varname"], sql_datatype,))
# 
#             stmt = 'CREATE TABLE %s (%s)' % (dataset_name, ','.join(col_defs))
#             sql.append(stmt)
# 
#         return sql
# 
#     @staticmethod
#     def getSQLDataType(dtype):
#         """Return SQLLite data type for a Rave view data type"""
#         return dict(num="NUMERIC", char="TEXT")[dtype]
# 
#     def _processDML(self, dataset_name, cols, reader):
#         """Overridden version of create DML for SQLLite"""
#         sql_template = self._generateInsertStatement(dataset_name, cols)
# 
#         # Now insert in batch, reader is a list of rows to insert at this point
#         c = self.conn.cursor()
#         c.executemany(sql_template, reader)
#         self.conn.commit()
# 
#     def _generateInsertStatement(self, dataset_name, cols):
#         """Generates a sql INSERT template"""
#         col_names = [col["varname"] for col in cols]
# 
#         # Generate question mark placeholders
#         qms = ','.join(['?' for x in col_names])
# 
#         return 'INSERT INTO %s (%s) values (%s)' % (dataset_name, ','.join(col_names), qms)
# 
# class LocalCVBuilder(object):
#     """
#     Does the work of pulling data from Rave via RWS. All database activities are delegated to the db_adapter.
#     """
# 
#     def __init__(self, rws_connection, project_name, environment, db_adapter):
#         self.rws_connection = rws_connection
#         self.project_name = project_name
#         self.environment = environment
#         self.db_adapter = db_adapter
# 
#     @staticmethod
#     def name_type_from_viewname(viewname):
#         """Have format V_<studyname>_<view>[_RAW], return name and view type REGULAR or RAW"""
#         matched = VIEW_REX.match(viewname)
#         return matched.group('view'), matched.group('type') or 'REGULAR'
# 
#     def execute(self):
#         """Generate local DB, pulling metadata and data from RWSConnection"""
# 
#         logging.info('Requesting view metadata for project %s' % self.project_name)
#         project_csv_meta = self.rws_connection.send_request(ProjectMetaDataRequest(self.project_name))
# 
#         # Process it into a set of tables
#         self.db_adapter.processMetaData(project_csv_meta)
# 
#         # Get the data for the study
#         for dataset_name in self.db_adapter.datasets.keys():
#             logging.info('Requesting data from dataset %s' % dataset_name)
#             form_name, _type = self.name_type_from_viewname(dataset_name)
#             form_data = self.rws_connection.send_request(
#                 FormDataRequest(self.project_name, self.environment, _type, form_name))
# 
#             # Now process the form_data into the db of choice
#             logging.info('Populating dataset %s' % dataset_name)
#             self.db_adapter.processFormData(form_data, dataset_name)
# 
#         logging.info('Process complete')


import unittest
from rwslib.extras.local_cv import SQLLiteDBAdapter, LocalCVBuilder
        self.assertEqual(True, 'project TEXT' in sql[1])


    def test_insert_gen(self):
        """Test generation of insert statements"""
        self.tested.processFormData(enrol_data, 'V_SIMPLESTUDY_ENROL')

        first_line = self.tested.conn.cursor.sql[0][0]
        first_statement = first_line[0]
        first_values = first_line[1]

        #Check sql construction
        self.assertEqual(first_statement.startswith('INSERT INTO V_SIMPLESTUDY_ENROL (userid,projectid,project'), True)
        self.assertEqual('SUBID,BIRTHDT,BIRTHDT_RAW,BIRTHDT_INT,BIRTHDT_YYYY,BIRTHDT_MM,BIRTHDT_DD)' in first_statement, True)

        #Check values
        self.assertEqual('457',first_values[0]) #First value
        self.assertEqual('26',first_values[-1]) #Last value


class TestSQLDataType(unittest.TestCase):
    def test_sql_typefor(self):

        sqlite_db = None
        tested = SQLLiteDBAdapter(sqlite_db)
        self.assertEqual(tested.getSQLDataType("num"), "NUMERIC")
        self.assertEqual(tested.getSQLDataType("char"), "TEXT")

class TestNameTypeFromViewname(unittest.TestCase):
    def test_name_type_from_viewname(self):

# Path: rwslib/extras/local_cv.py
# class SQLLiteDBAdapter(BaseDBAdapter):
#     """Variant that makes SQLLite SQL"""
# 
#     def __init__(self, db):
#         """Receives a SQLLiteDB to populate"""
#         BaseDBAdapter.__init__(self)
#         self.conn = db
# 
#     def _processDDL(self):
#         """Generate and process table SQL, SQLLite version"""
#         sql_statements = self._generateDDL()
# 
#         logging.info('Generating sqllite tables')
#         for stmt in sql_statements:
#             c = self.conn.cursor()
#             c.execute(stmt)
#             self.conn.commit()
# 
#     def _generateDDL(self):
#         """Generate DDL statements for SQLLite"""
#         sql = []
#         # Next convert each set of columns into a table structure
#         for dataset_name in sorted(self.datasets.keys()):
# 
#             # SQL to drop the table if it already exists
#             sql.append('''drop table if exists %s;''' % dataset_name)
# 
#             # Generate the SQL for the cols
#             cols = self.datasets[dataset_name]
#             col_defs = []
#             for col in cols:
#                 sql_datatype = self.getSQLDataType(col["vartype"])
#                 col_defs.append("%s %s" % (col["varname"], sql_datatype,))
# 
#             stmt = 'CREATE TABLE %s (%s)' % (dataset_name, ','.join(col_defs))
#             sql.append(stmt)
# 
#         return sql
# 
#     @staticmethod
#     def getSQLDataType(dtype):
#         """Return SQLLite data type for a Rave view data type"""
#         return dict(num="NUMERIC", char="TEXT")[dtype]
# 
#     def _processDML(self, dataset_name, cols, reader):
#         """Overridden version of create DML for SQLLite"""
#         sql_template = self._generateInsertStatement(dataset_name, cols)
# 
#         # Now insert in batch, reader is a list of rows to insert at this point
#         c = self.conn.cursor()
#         c.executemany(sql_template, reader)
#         self.conn.commit()
# 
#     def _generateInsertStatement(self, dataset_name, cols):
#         """Generates a sql INSERT template"""
#         col_names = [col["varname"] for col in cols]
# 
#         # Generate question mark placeholders
#         qms = ','.join(['?' for x in col_names])
# 
#         return 'INSERT INTO %s (%s) values (%s)' % (dataset_name, ','.join(col_names), qms)
# 
# class LocalCVBuilder(object):
#     """
#     Does the work of pulling data from Rave via RWS. All database activities are delegated to the db_adapter.
#     """
# 
#     def __init__(self, rws_connection, project_name, environment, db_adapter):
#         self.rws_connection = rws_connection
#         self.project_name = project_name
#         self.environment = environment
#         self.db_adapter = db_adapter
# 
#     @staticmethod
#     def name_type_from_viewname(viewname):
#         """Have format V_<studyname>_<view>[_RAW], return name and view type REGULAR or RAW"""
#         matched = VIEW_REX.match(viewname)
#         return matched.group('view'), matched.group('type') or 'REGULAR'
# 
#     def execute(self):
#         """Generate local DB, pulling metadata and data from RWSConnection"""
# 
#         logging.info('Requesting view metadata for project %s' % self.project_name)
#         project_csv_meta = self.rws_connection.send_request(ProjectMetaDataRequest(self.project_name))
# 
#         # Process it into a set of tables
#         self.db_adapter.processMetaData(project_csv_meta)
# 
#         # Get the data for the study
#         for dataset_name in self.db_adapter.datasets.keys():
#             logging.info('Requesting data from dataset %s' % dataset_name)
#             form_name, _type = self.name_type_from_viewname(dataset_name)
#             form_data = self.rws_connection.send_request(
#                 FormDataRequest(self.project_name, self.environment, _type, form_name))
# 
#             # Now process the form_data into the db of choice
#             logging.info('Populating dataset %s' % dataset_name)
#             self.db_adapter.processFormData(form_data, dataset_name)
# 
#         logging.info('Process complete')


# Path: rwslib/tests/test_local_cv.py
import unittest
from rwslib.extras.local_cv import SQLLiteDBAdapter, LocalCVBuilder

        self.assertEqual(True, 'project TEXT' in sql[1])


    def test_insert_gen(self):
        """Test generation of insert statements"""
        self.tested.processFormData(enrol_data, 'V_SIMPLESTUDY_ENROL')

        first_line = self.tested.conn.cursor.sql[0][0]
        first_statement = first_line[0]
        first_values = first_line[1]

        #Check sql construction
        self.assertEqual(first_statement.startswith('INSERT INTO V_SIMPLESTUDY_ENROL (userid,projectid,project'), True)
        self.assertEqual('SUBID,BIRTHDT,BIRTHDT_RAW,BIRTHDT_INT,BIRTHDT_YYYY,BIRTHDT_MM,BIRTHDT_DD)' in first_statement, True)

        #Check values
        self.assertEqual('457',first_values[0]) #First value
        self.assertEqual('26',first_values[-1]) #Last value


class TestSQLDataType(unittest.TestCase):
    def test_sql_typefor(self):

        sqlite_db = None
        tested = SQLLiteDBAdapter(sqlite_db)
        self.assertEqual(tested.getSQLDataType("num"), "NUMERIC")
        self.assertEqual(tested.getSQLDataType("char"), "TEXT")

class TestNameTypeFromViewname(unittest.TestCase):
    def test_name_type_from_viewname(self):

        self.assertEqual(LocalCVBuilder.name_type_from_viewname("V_SIMPLESTUDY_ENROL")[0],"ENROL")