# Path: sesql/results.py
# class SeSQLResultSet(object):
#     """
#     A lazy SeSQL result set
#     It mimicks a bit the Django QuerySet, but doesn't work the same way,
#     and doesn't provide exactly the same methods
#     """
#     def __init__(self, objs, fields):
#         """
#         Constructor
#         Objs must be a list of (class, id) with optionally extra fields
#         """
#         self.objs = objs
#         self.fields = fields
# 
#     def brains(self):
#         """
#         Get the raw objects from SeSQL index, aka the "brains", as dictionnaries
#         """
#         for obj in self.objs:
#             yield dict(zip(self.fields, obj))
# 
#     def count(self):
#         """
#         Count results
#         """
#         return len(self.objs)
#     __len__ = count
# 
#     def iterator(self):
#         """
#         Iterate on self
#         """
#         for obj in self.objs:
#             try:
#                 yield self.load(obj)
#             except config.orm.not_found:
#                 log.warning("Object %r does not exist ! Broken index ?" % (obj,))
#     __iter__ = iterator
# 
#     def all(self):
#         """
#         Get all the results as a list
#         """
#         return list(self)
# 
#     def get(self, index):
#         """
#         Get the row at given index
#         """
#         return self.load(self.objs[index])
#     __getitem__ = get
# 
#     def __getslice__(self, i, j):
#         """
#         Get a slice
#         """
#         res = [ self.load(obj) for obj in self.objs[i:j] ]
#         return res
# 
#     @staticmethod
#     def load(obj):
#         """
#         Get a given object
#         """
#         objclass, objid = obj[:2]
#         objclass = typemap.get_class_by_name(objclass)
#         if not objclass:
#             return config.orm.not_found
#         entry = "%s:%s" % (objclass.__name__, objid)
#         log.debug("Fetching %s" % entry)
#         return config.orm.load_object(objclass, objid)
# 
#     def historize(self, query):
#         """save in the database the query for future processing"""
#         nb_results = self.count()
#         query_text = query.get_fulltext_query()[2][0]
#         config.orm.historize(query=query_text, nb_results=nb_results)
# 
# Path: sesql/index.py
# @index_log_wrap
# @config.orm.transactional
# def index(cursor, obj, message, noindex = False, index_related = True):
#     """
#     Index a Django object into SeSQL, do the real work
#     """
#     log.info("%s : entering" % message)
#     try:
#         classname, objid = get_sesql_id(obj)
#     except (TypeError, AttributeError, ValueError):
#         log.info("%r: can't get classname/id, skipping" % obj)
#         return
# 
#     # Handle dependancies
#     gro = getattr(obj, "get_related_objects_for_indexation", None)
#     if index_related and gro:
#         related = gro()
#         nbrelated = len(related)
#         for item in related:
#             schedule_reindex(item)
#     else:
#         nbrelated = 0
# 
#     log.info("%s : %d dependancies found" % (message, nbrelated))
# 
#     table_name = typemap.typemap.get_table_for(classname)
#     if not table_name:
#         log.info("%s: no table found, skipping" % message)
#         return
# 
#     query = "DELETE FROM %s WHERE id=%%s AND classname=%%s" % table_name
#     cursor.execute(query, (objid, classname))
# 
#     if noindex:
#         log.info("%s : running in 'noindex' mode, only deleteing" % message)
#         return
# 
#     if config.SKIP_CONDITION and config.SKIP_CONDITION(obj):
#         log.info("%s : not indexing because of skip_condition" % message)
#         return
# 
#     log.info("%s : indexing entry in table %s" % (message, table_name))
# 
#     keys, placeholders, results = get_values(obj, config.FIELDS)
# 
#     query = "INSERT INTO %s (%s) VALUES (%s)" % (table_name,
#                                                  ",".join(keys),
#                                                  ",".join(placeholders))
#     cursor.execute(query, results)


from django.core.management.base import BaseCommand
from django.core.management import call_command
from django.db import connection, transaction
from django.db.models import Q
from sesql.results import SeSQLResultSet
from sesql.index import index
import settings
import sys
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.

# SeSQL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with SeSQL.  If not, see <http://www.gnu.org/licenses/>.

"""
This command will index or reindex a single object into SeSQL
Can be used as a test, or to fix a single problem
"""


class Command(BaseCommand):
    help = "Index a single object into SeSQL"

    @transaction.commit_manually
    def handle(self, *apps, **options):
        """
        Handle the command
        """
        if len(apps) != 2:
            print "Syntax : sesqlindex <classname> <objid>"
            sys.exit(1)
        

# Path: sesql/results.py
# class SeSQLResultSet(object):
#     """
#     A lazy SeSQL result set
#     It mimicks a bit the Django QuerySet, but doesn't work the same way,
#     and doesn't provide exactly the same methods
#     """
#     def __init__(self, objs, fields):
#         """
#         Constructor
#         Objs must be a list of (class, id) with optionally extra fields
#         """
#         self.objs = objs
#         self.fields = fields
# 
#     def brains(self):
#         """
#         Get the raw objects from SeSQL index, aka the "brains", as dictionnaries
#         """
#         for obj in self.objs:
#             yield dict(zip(self.fields, obj))
# 
#     def count(self):
#         """
#         Count results
#         """
#         return len(self.objs)
#     __len__ = count
# 
#     def iterator(self):
#         """
#         Iterate on self
#         """
#         for obj in self.objs:
#             try:
#                 yield self.load(obj)
#             except config.orm.not_found:
#                 log.warning("Object %r does not exist ! Broken index ?" % (obj,))
#     __iter__ = iterator
# 
#     def all(self):
#         """
#         Get all the results as a list
#         """
#         return list(self)
# 
#     def get(self, index):
#         """
#         Get the row at given index
#         """
#         return self.load(self.objs[index])
#     __getitem__ = get
# 
#     def __getslice__(self, i, j):
#         """
#         Get a slice
#         """
#         res = [ self.load(obj) for obj in self.objs[i:j] ]
#         return res
# 
#     @staticmethod
#     def load(obj):
#         """
#         Get a given object
#         """
#         objclass, objid = obj[:2]
#         objclass = typemap.get_class_by_name(objclass)
#         if not objclass:
#             return config.orm.not_found
#         entry = "%s:%s" % (objclass.__name__, objid)
#         log.debug("Fetching %s" % entry)
#         return config.orm.load_object(objclass, objid)
# 
#     def historize(self, query):
#         """save in the database the query for future processing"""
#         nb_results = self.count()
#         query_text = query.get_fulltext_query()[2][0]
#         config.orm.historize(query=query_text, nb_results=nb_results)
# 
# Path: sesql/index.py
# @index_log_wrap
# @config.orm.transactional
# def index(cursor, obj, message, noindex = False, index_related = True):
#     """
#     Index a Django object into SeSQL, do the real work
#     """
#     log.info("%s : entering" % message)
#     try:
#         classname, objid = get_sesql_id(obj)
#     except (TypeError, AttributeError, ValueError):
#         log.info("%r: can't get classname/id, skipping" % obj)
#         return
# 
#     # Handle dependancies
#     gro = getattr(obj, "get_related_objects_for_indexation", None)
#     if index_related and gro:
#         related = gro()
#         nbrelated = len(related)
#         for item in related:
#             schedule_reindex(item)
#     else:
#         nbrelated = 0
# 
#     log.info("%s : %d dependancies found" % (message, nbrelated))
# 
#     table_name = typemap.typemap.get_table_for(classname)
#     if not table_name:
#         log.info("%s: no table found, skipping" % message)
#         return
# 
#     query = "DELETE FROM %s WHERE id=%%s AND classname=%%s" % table_name
#     cursor.execute(query, (objid, classname))
# 
#     if noindex:
#         log.info("%s : running in 'noindex' mode, only deleteing" % message)
#         return
# 
#     if config.SKIP_CONDITION and config.SKIP_CONDITION(obj):
#         log.info("%s : not indexing because of skip_condition" % message)
#         return
# 
#     log.info("%s : indexing entry in table %s" % (message, table_name))
# 
#     keys, placeholders, results = get_values(obj, config.FIELDS)
# 
#     query = "INSERT INTO %s (%s) VALUES (%s)" % (table_name,
#                                                  ",".join(keys),
#                                                  ",".join(placeholders))
#     cursor.execute(query, results)


# Path: sesql/management/commands/sesqlindex.py
from django.core.management.base import BaseCommand
from django.core.management import call_command
from django.db import connection, transaction
from django.db.models import Q
from sesql.results import SeSQLResultSet
from sesql.index import index
import settings
import sys

# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.

# SeSQL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with SeSQL.  If not, see <http://www.gnu.org/licenses/>.

"""
This command will index or reindex a single object into SeSQL
Can be used as a test, or to fix a single problem
"""


class Command(BaseCommand):
    help = "Index a single object into SeSQL"

    @transaction.commit_manually
    def handle(self, *apps, **options):
        """
        Handle the command
        """
        if len(apps) != 2:
            print "Syntax : sesqlindex <classname> <objid>"
            sys.exit(1)
        

        obj = SeSQLResultSet.load(apps)