# Path: memsql_loader/util/command.py
# class Command(object):
#     def __init__(self, options):
#         self.options = options
#         self.ensure_bootstrapped()
#         self.run()
# 
#     @staticmethod
#     def configure(parser, subparsers):
#         raise NotImplemented('Every command needs a static configure(...) method')
# 
#     def ensure_bootstrapped(self):
#         if not bootstrap.check_bootstrapped():
#             bootstrap.bootstrap()
# 
#     def run():
#         raise NotImplemented('Every command needs a run method, otherwise not much is going to happen')
# 
# Path: memsql_loader/util/log.py
# def setup(log_path=None, stdout_enabled=True):
# def update_verbosity(debug=False, extra_verbose=False):
#     def __call__(self, parser, namespace, value, option_string=None):
#     def __call__(self, parser, namespace, value, option_string=None):
#     def __call__(self, parser, namespace, value, option_string=None):
# def configure(parser):
# def get_logger(name, level=None):
#     def format(self, record):
#     def __init__(self, name, level=logging.DEBUG):
# class _SetDebug(argparse.Action):
# class _SetStdout(argparse.Action):
# class _SetLogPath(argparse.Action):
# class Formatter(logging.Formatter):
# class Logger(logging.Logger):
# 
# Path: memsql_loader/loader_db/tasks.py
# class Tasks(apsw_sql_step_queue.APSWSQLStepQueue):
#     def __init__(self):
#         storage = LoaderStorage()
#         super(Tasks, self).__init__('tasks', storage, execution_ttl=api.shared.TASKS_TTL, task_handler_class=TaskHandler)
# 
#     # NOTE: This method overrides bulk_finish on APSWSQLStepQueue so that it
#     # finishes tasks even if they are currently running.
#     def bulk_finish(self, result='cancelled', extra_predicate=None):
#         extra_predicate_sql, extra_predicate_args = (
#             self._build_extra_predicate(extra_predicate))
# 
#         with self.storage.transaction() as cursor:
#             now = unix_timestamp(datetime.utcnow())
#             affected_rows = apsw_helpers.query(cursor, '''
#                 SELECT * from %s
#                 WHERE
#                     finished IS NULL
#                     %s
#             ''' % (self.table_name, extra_predicate_sql),
#                 **extra_predicate_args)
#             apsw_helpers.query(cursor, '''
#                 UPDATE %s
#                 SET
#                     execution_id = 0,
#                     last_contact = datetime(:now, 'unixepoch'),
#                     update_count = update_count + 1,
#                     steps = '[]',
#                     started = datetime(:now, 'unixepoch'),
#                     finished = datetime(:now, 'unixepoch'),
#                     result = :result
#                 WHERE
#                     finished IS NULL
#                     %s
#             ''' % (self.table_name, extra_predicate_sql),
#                 now=now,
#                 result=result,
#                 **extra_predicate_args)
# 
#         return len(affected_rows)
# 
#     def get_tasks_in_state(self, state, extra_predicate=None):
#         extra_predicate_sql, extra_predicate_args = (
#             self._build_extra_predicate(extra_predicate))
# 
#         query_params = api.shared.TaskState.projection_params()
#         if len(state) == 1:
#             state_list = "('" + str(state[0]) + "')"
#         else:
#             state_list = str(tuple(str(v) for v in state ))
#         query_params.update(extra_predicate_args)
#         with self.storage.cursor() as cursor:
#             rows = apsw_helpers.query(cursor, '''
#                 SELECT *
#                 FROM %s
#                 WHERE
#                     %s IN %s
#                     %s
#                 ORDER BY id ASC
#             ''' % (self.table_name, api.shared.TaskState.PROJECTION, state_list, extra_predicate_sql),
#                 **query_params)
# 
#         return [ api.shared.task_load_row(row) for row in rows ]


from memsql_loader.util.command import Command
from memsql_loader.util import log
from memsql_loader.loader_db.tasks import Tasks


class CancelTask(Command):
    @staticmethod
    def configure(parser, subparsers):
        subparser = subparsers.add_parser('cancel-task', help='Cancel a specific task')
        subparser.set_defaults(command=CancelTask)

        subparser.add_argument('task_id', type=int,
            help='The ID of the task to cancel')

    def run(self):

# Path: memsql_loader/util/command.py
# class Command(object):
#     def __init__(self, options):
#         self.options = options
#         self.ensure_bootstrapped()
#         self.run()
# 
#     @staticmethod
#     def configure(parser, subparsers):
#         raise NotImplemented('Every command needs a static configure(...) method')
# 
#     def ensure_bootstrapped(self):
#         if not bootstrap.check_bootstrapped():
#             bootstrap.bootstrap()
# 
#     def run():
#         raise NotImplemented('Every command needs a run method, otherwise not much is going to happen')
# 
# Path: memsql_loader/util/log.py
# def setup(log_path=None, stdout_enabled=True):
# def update_verbosity(debug=False, extra_verbose=False):
#     def __call__(self, parser, namespace, value, option_string=None):
#     def __call__(self, parser, namespace, value, option_string=None):
#     def __call__(self, parser, namespace, value, option_string=None):
# def configure(parser):
# def get_logger(name, level=None):
#     def format(self, record):
#     def __init__(self, name, level=logging.DEBUG):
# class _SetDebug(argparse.Action):
# class _SetStdout(argparse.Action):
# class _SetLogPath(argparse.Action):
# class Formatter(logging.Formatter):
# class Logger(logging.Logger):
# 
# Path: memsql_loader/loader_db/tasks.py
# class Tasks(apsw_sql_step_queue.APSWSQLStepQueue):
#     def __init__(self):
#         storage = LoaderStorage()
#         super(Tasks, self).__init__('tasks', storage, execution_ttl=api.shared.TASKS_TTL, task_handler_class=TaskHandler)
# 
#     # NOTE: This method overrides bulk_finish on APSWSQLStepQueue so that it
#     # finishes tasks even if they are currently running.
#     def bulk_finish(self, result='cancelled', extra_predicate=None):
#         extra_predicate_sql, extra_predicate_args = (
#             self._build_extra_predicate(extra_predicate))
# 
#         with self.storage.transaction() as cursor:
#             now = unix_timestamp(datetime.utcnow())
#             affected_rows = apsw_helpers.query(cursor, '''
#                 SELECT * from %s
#                 WHERE
#                     finished IS NULL
#                     %s
#             ''' % (self.table_name, extra_predicate_sql),
#                 **extra_predicate_args)
#             apsw_helpers.query(cursor, '''
#                 UPDATE %s
#                 SET
#                     execution_id = 0,
#                     last_contact = datetime(:now, 'unixepoch'),
#                     update_count = update_count + 1,
#                     steps = '[]',
#                     started = datetime(:now, 'unixepoch'),
#                     finished = datetime(:now, 'unixepoch'),
#                     result = :result
#                 WHERE
#                     finished IS NULL
#                     %s
#             ''' % (self.table_name, extra_predicate_sql),
#                 now=now,
#                 result=result,
#                 **extra_predicate_args)
# 
#         return len(affected_rows)
# 
#     def get_tasks_in_state(self, state, extra_predicate=None):
#         extra_predicate_sql, extra_predicate_args = (
#             self._build_extra_predicate(extra_predicate))
# 
#         query_params = api.shared.TaskState.projection_params()
#         if len(state) == 1:
#             state_list = "('" + str(state[0]) + "')"
#         else:
#             state_list = str(tuple(str(v) for v in state ))
#         query_params.update(extra_predicate_args)
#         with self.storage.cursor() as cursor:
#             rows = apsw_helpers.query(cursor, '''
#                 SELECT *
#                 FROM %s
#                 WHERE
#                     %s IN %s
#                     %s
#                 ORDER BY id ASC
#             ''' % (self.table_name, api.shared.TaskState.PROJECTION, state_list, extra_predicate_sql),
#                 **query_params)
# 
#         return [ api.shared.task_load_row(row) for row in rows ]


# Path: memsql_loader/cli/cancel_task.py
from memsql_loader.util.command import Command
from memsql_loader.util import log
from memsql_loader.loader_db.tasks import Tasks



class CancelTask(Command):
    @staticmethod
    def configure(parser, subparsers):
        subparser = subparsers.add_parser('cancel-task', help='Cancel a specific task')
        subparser.set_defaults(command=CancelTask)

        subparser.add_argument('task_id', type=int,
            help='The ID of the task to cancel')

    def run(self):

        self.logger = log.get_logger('CancelTask')