class FablikQueriesImplementation:
    def start_routine(self, config):
        self.database = None
        self.base_lib = FablikBaseRoutines(config)

        self.synchronize(config)

    def synchronize(self, config):
        self.debug = config.get('DEBUG', False)
        self.base_lib.synchronize(config)
        self.db_interfaces = {}

        self.database = self.base_lib.get_database_connection()

        self.interface_manager = FablikInterfaces.InterfaceManager(config)

    def stop_routine(self):
        pass

    def loadInterface(self, iface_id):
        db_conn = self.interface_manager.getDatabaseInterfaceByID(iface_id)

        self.db_interfaces[iface_id] = db_conn

    def buildQuery(self, sql_query_sid, filters_map):
        query = self.database.execute(SQL.get_query % sql_query_sid)
        if not query:
            raise Exception('Query with SID %s is not found' % sql_query_sid)

        (qid, interface_id, query, description) = query[0]

        optional_exprs = re.findall('\?(.+)\?', query)
        for op_expr in optional_exprs:
            filters = re.findall('%\(\s*(\w+)\s*\)', op_expr)
            for val in filters:
                if val not in filters_map:
                    query = query.replace('?%s?'%op_expr,'')
                    continue

            query = query.replace('?%s?'%op_expr, op_expr)

        try:
            query = query % filters_map
        except KeyError, key:
            raise Exception('Filter %s is not found. But it should be!' % key)

        return (query, interface_id)
class FablikManagementImplementation:
    def start_routine(self, config):
        self.syncronize_application(config)

    def syncronize_application(self, config):
        self.base_lib = FablikBaseRoutines(config)
        self.database = self.base_lib.get_database_connection()

        self.debug = config.get('DEBUG',False)

    def stop_routine(self):
        del self.base_lib

    def createDepartment(self, request):
        err_code, err_message = (FBE_OK, 'ok')
        department_id = -1

        try:
            user_id = self.base_lib.auth_by_session(request.session_id)

            is_sid_exist = self.database.execute(SQL.check_department_sid % (request.sid, 0))
            if is_sid_exist:
                raise Exception (1, 'Department with SID "%s" is already exist in database'%request.sid)

            if not request.description:
                request.description = ''
            if not request.parent_id:
                request.parent_id = 'NULL'

            department_id = self.database.execute(SQL.insert_department %
                        (request.parent_id, request.sid, request.name, request.description), is_commit=True)

            department_id = department_id[0][0]
        except Exception, e_obj:
            err_code, err_message = parse_exception(e_obj, self.debug)

        return IO.ResponseCreateDepartment(ret_code=err_code, ret_message=err_message, department_id=department_id)