# 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
from __future__ import with_statement




STEP = 1000

class Command(BaseCommand):
    help = "Update some columns of all already indexed objects in SeSQL"

    option_list = BaseCommand.option_list + (
        make_option('--class',
                    dest='class',
                    default='',
                    help='Limit to given classes (comma-separated)'),
        )

    @transaction.commit_manually
    def update(self, classnames, fields):
        """
        Reindex a single class
        """
        print "=> Starting reindexing columns %s." % ','.join(fields)
        result = longquery(Q(classname__in = classnames))
        nb = len(result)
        print "=> We got %d objects." % nb
        sys.stdout.flush()

        full_tmr = Timer()
        load_tmr = Timer()

# 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

from __future__ import with_statement




STEP = 1000

class Command(BaseCommand):
    help = "Update some columns of all already indexed objects in SeSQL"

    option_list = BaseCommand.option_list + (
        make_option('--class',
                    dest='class',
                    default='',
                    help='Limit to given classes (comma-separated)'),
        )

    @transaction.commit_manually
    def update(self, classnames, fields):
        """
        Reindex a single class
        """
        print "=> Starting reindexing columns %s." % ','.join(fields)
        result = longquery(Q(classname__in = classnames))
        nb = len(result)
        print "=> We got %d objects." % nb
        sys.stdout.flush()

        full_tmr = Timer()
        load_tmr = Timer()

        index_tmr = Timer()