# Path: sesql/utils.py
# class Timer(object):
#     """
#     A timer object to be used with « with » statement
#     It as a local and global timer
#     """
#     def __init__(self):
#         self._local = self._global = 0.0
#         self._start = time.time()
# 
#     def start(self):
#         self._start = time.time()
# 
#     def stop(self):
#         delta = time.time() - self._start
#         self._local += delta
#         self._global += delta
# 
#     def __enter__(self):
#         self.start()
# 
#     def __exit__(self, *args, **kwargs):
#         self.stop()
# 
#     def get_local(self):
#         return self._local
# 
#     def get_global(self):
#         return self._global
# 
#     def reset(self):
#         self._local = 0
# 
#     def peek(self):
#         res = self.get_local()
#         self.reset()
#         return res
# 
# Path: sesql/index.py
# @index_log_wrap
# @config.orm.transactional
# def update(cursor, obj, message, fields):
#     """
#     Update only specific fields of given object
#     """
#     log.info("%s : entering for fields %s" % (message, ','.join(fields)))
# 
#     table_name = typemap.typemap.get_table_for(obj.__class__)
#     if not table_name:
#         log.info("%s : not table, skipping" % message)
#         return
# 
#     fields = [ fieldmap.fieldmap.get_field(field) for field in fields ]
#     keys, placeholders, results = get_values(obj, fields)
# 
#     pattern = [ '%s=%s' % (k,p) for k,p in zip(keys, placeholders) ]
# 
#     if not pattern:
#         log.info("%s : nothing to update, skipping" % message)
#         return
# 
#     pattern = ",".join(pattern)
# 
#     query = "UPDATE %s SET %s WHERE classname=%%s AND id=%%s" % (table_name,
#                                                                  pattern)
#     cursor.execute(query, results + [ obj.__class__.__name__, obj.id ])
# 
# Path: sesql/typemap.py
# class TypeMap(object):
#     def __init__(self):
#     def all_subclasses(klass, done = None):
#     def all_tables(self):
#     def all_classes(self):
#     def all_class_names(self):
#     def get_class_names_for(self, table):
#     def get_classes_for(self, table):
#     def get_table_for(self, klass):
#     def get_class_by_name(self, klass):
# 
# Path: sesql/longquery.py
# @utils.log_time
# def longquery(query, order=None, limit=None, queryid=None, historize=False,
#               fields = ()):
#     """
#     Perform a long query and return a lazy Django result set
# 
#     If queryid is provided, then the query will be loaded from the
#     cache if possible, and redone else. Be careful, if the query is
#     redone, results may have changed.
# 
#     If fields are specified, will fetch those fields from the index
#     """
#     if queryid:
#         _query_cache.lock.acquire()
#         try:
#             results = _query_cache[queryid]
#             if results:
#                 return results
#             log.warning('Cached query id %r expired, re-querying.' % queryid)
#         finally:
#             _query_cache.lock.release()
# 
#     query = SeSQLQuery(query, order, fields)
#     results = query.longquery(limit)
# 
#     _query_cache.lock.acquire()
#     try:
#         # Generate a new query id, ensuring it's unique
#         if not queryid:
#             while True:
#                 letters = string.ascii_letters + string.digits
#                 queryid = ''.join([ random.choice(letters) for i in range(32) ])
#                 if queryid not in _query_cache:
#                     break
#         _query_cache[queryid] = results
#         results.queryid = queryid
#     finally:
#         _query_cache.lock.release()
# 
#     if historize: # suggest feature hook
#         results.historize(query)
# 
#     return results


import sys
from optparse import make_option
from django.db.models import Q
from django.db import transaction
from django.core.management.base import BaseCommand
from django.core.exceptions import ObjectDoesNotExist
from sesql.utils import Timer
from sesql.index import update
from sesql.typemap import typemap
from sesql.longquery import longquery
                    transaction.rollback()
                    raise
            with index_tmr:
                try:
                    update(obj, fields)
                except:
                    transaction.rollback()
                    raise

            if i % STEP == STEP - 1:
                disp_stats()

            del obj

        disp_stats()

    def handle(self, *fields, **options):
        """
        Handle the command
        """
        if not fields:
            print "Syntax : manage.py sesqlupdate [--class <classes>] <columns>"
            print "  - classes is a comma-separated list of object classes"
            print "  - columns is a (space-seperated) list of columns to reindex"

        if not options['class']:
            classes = typemap.all_class_names()
        else:
            classes = options['class'].split(',')


# Path: sesql/utils.py
# class Timer(object):
#     """
#     A timer object to be used with « with » statement
#     It as a local and global timer
#     """
#     def __init__(self):
#         self._local = self._global = 0.0
#         self._start = time.time()
# 
#     def start(self):
#         self._start = time.time()
# 
#     def stop(self):
#         delta = time.time() - self._start
#         self._local += delta
#         self._global += delta
# 
#     def __enter__(self):
#         self.start()
# 
#     def __exit__(self, *args, **kwargs):
#         self.stop()
# 
#     def get_local(self):
#         return self._local
# 
#     def get_global(self):
#         return self._global
# 
#     def reset(self):
#         self._local = 0
# 
#     def peek(self):
#         res = self.get_local()
#         self.reset()
#         return res
# 
# Path: sesql/index.py
# @index_log_wrap
# @config.orm.transactional
# def update(cursor, obj, message, fields):
#     """
#     Update only specific fields of given object
#     """
#     log.info("%s : entering for fields %s" % (message, ','.join(fields)))
# 
#     table_name = typemap.typemap.get_table_for(obj.__class__)
#     if not table_name:
#         log.info("%s : not table, skipping" % message)
#         return
# 
#     fields = [ fieldmap.fieldmap.get_field(field) for field in fields ]
#     keys, placeholders, results = get_values(obj, fields)
# 
#     pattern = [ '%s=%s' % (k,p) for k,p in zip(keys, placeholders) ]
# 
#     if not pattern:
#         log.info("%s : nothing to update, skipping" % message)
#         return
# 
#     pattern = ",".join(pattern)
# 
#     query = "UPDATE %s SET %s WHERE classname=%%s AND id=%%s" % (table_name,
#                                                                  pattern)
#     cursor.execute(query, results + [ obj.__class__.__name__, obj.id ])
# 
# Path: sesql/typemap.py
# class TypeMap(object):
#     def __init__(self):
#     def all_subclasses(klass, done = None):
#     def all_tables(self):
#     def all_classes(self):
#     def all_class_names(self):
#     def get_class_names_for(self, table):
#     def get_classes_for(self, table):
#     def get_table_for(self, klass):
#     def get_class_by_name(self, klass):
# 
# Path: sesql/longquery.py
# @utils.log_time
# def longquery(query, order=None, limit=None, queryid=None, historize=False,
#               fields = ()):
#     """
#     Perform a long query and return a lazy Django result set
# 
#     If queryid is provided, then the query will be loaded from the
#     cache if possible, and redone else. Be careful, if the query is
#     redone, results may have changed.
# 
#     If fields are specified, will fetch those fields from the index
#     """
#     if queryid:
#         _query_cache.lock.acquire()
#         try:
#             results = _query_cache[queryid]
#             if results:
#                 return results
#             log.warning('Cached query id %r expired, re-querying.' % queryid)
#         finally:
#             _query_cache.lock.release()
# 
#     query = SeSQLQuery(query, order, fields)
#     results = query.longquery(limit)
# 
#     _query_cache.lock.acquire()
#     try:
#         # Generate a new query id, ensuring it's unique
#         if not queryid:
#             while True:
#                 letters = string.ascii_letters + string.digits
#                 queryid = ''.join([ random.choice(letters) for i in range(32) ])
#                 if queryid not in _query_cache:
#                     break
#         _query_cache[queryid] = results
#         results.queryid = queryid
#     finally:
#         _query_cache.lock.release()
# 
#     if historize: # suggest feature hook
#         results.historize(query)
# 
#     return results


# Path: sesql/management/commands/sesqlupdate.py
import sys
from optparse import make_option
from django.db.models import Q
from django.db import transaction
from django.core.management.base import BaseCommand
from django.core.exceptions import ObjectDoesNotExist
from sesql.utils import Timer
from sesql.index import update
from sesql.typemap import typemap
from sesql.longquery import longquery

                    transaction.rollback()
                    raise
            with index_tmr:
                try:
                    update(obj, fields)
                except:
                    transaction.rollback()
                    raise

            if i % STEP == STEP - 1:
                disp_stats()

            del obj

        disp_stats()

    def handle(self, *fields, **options):
        """
        Handle the command
        """
        if not fields:
            print "Syntax : manage.py sesqlupdate [--class <classes>] <columns>"
            print "  - classes is a comma-separated list of object classes"
            print "  - columns is a (space-seperated) list of columns to reindex"

        if not options['class']:
            classes = typemap.all_class_names()
        else:
            classes = options['class'].split(',')


        self.update(classes, fields)