-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodels_sql_query.py
196 lines (148 loc) · 6.14 KB
/
models_sql_query.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# -*- coding: utf-8 -*-
# Copyright 2005,2006,2007,2008 Spike^ekipS <spikeekips@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# 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.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import sys, traceback
from django.core.exceptions import FieldError
from django.db import models, connection
from django.db.models import sql, ObjectDoesNotExist
from django.db.models.sql import constants
from django.db.models.sql.query import get_order_dir
from django.db.models.sql.where import AND, OR
from models_sql_where import WhereNode
import utils, constant, pylucene
lucene = constant.import_lucene()
class Query (sql.Query) :
raw_queries = list()
_query_cache = None
def __init__ (self, index_model, connection, where=WhereNode, ) :
super(Query, self).__init__(index_model, connection, where=WhereNode)
self.index_model = index_model
self.where.set_model(self.index_model)
self.raw_queries = list()
def clone(self, klass=None, **kwargs):
clone = super(Query, self).clone(klass=klass, **kwargs)
clone.where.set_model(self.index_model)
clone.index_model = self.index_model
clone.raw_queries = self.raw_queries
return clone
def __str__ (self) :
(query, ordering, ) = self.as_sql()
return "%s (%s)" % (query.toString(), ordering.toString())
def add_q (self, *args, **kwargs) :
self._query_cache = None
return super(Query, self).add_q(*args, **kwargs)
def add_filter(self, filter_expr, connector=AND, negate=False, trim=False, can_reuse=None):
arg, value = filter_expr
parts = [i for i in constant.LOOKUP_SEP.split(arg) if i.strip()]
if not parts:
raise FieldError("Cannot parse keyword query %r" % arg)
# Work out the lookup type and remove it from "parts", if necessary.
field = parts[0]
if len(parts) == 1 or parts[-1] not in self.query_terms:
lookup_type = "exact"
else:
lookup_type = parts.pop()
# Interpret "__exact=None" as the sql "is NULL"; otherwise, reject all
# uses of None as a query value.
if value is None:
if lookup_type != "exact":
raise ValueError("Cannot use None as a query value")
lookup_type = "isnull"
value = True
elif callable(value):
value = value()
#alias = self.get_initial_alias()
self.where.add((None, field, field, lookup_type, value), connector)
def add_raw_query (self, query) :
self.raw_queries.append(query)
self._query_cache = None
def as_sql (self, with_limits=True, with_col_aliases=False):
if not self._query_cache :
_query = self.where.as_sql(pylucene.BooleanQuery(), qn=self.quote_name_unless_alias)
_ordering = self.get_ordering()
# add model query
if _query is None :
_query = pylucene.BooleanQuery()
if self.raw_queries :
for q in self.raw_queries :
_query.add(
q,
constant.QUERY_BOOLEANS.get("AND"),
)
subquery = pylucene.BooleanQuery()
subquery.add(
pylucene.TermQuery(
pylucene.Term.new(constant.FIELD_NAME_INDEX_MODEL, self.index_model.__class__.__name__)
),
constant.QUERY_BOOLEANS.get("OR"),
)
_query.add(subquery, constant.QUERY_BOOLEANS.get("AND"), )
self._query_cache = (_query, _ordering, )
return self._query_cache
def execute_sql (self, result_type=constants.MULTI) :
try :
(query, ordering, ) = self.as_sql()
except :
traceback.print_exc()
raise
try :
self.searcher = pylucene.Searcher(storage_path=self.index_model._meta.storage_path, )
except Exception, e :
raise
return [self.searcher.search(query, ordering, slice=slice(self.low_mark, self.high_mark)), ]
def get_ordering (self) :
if self.order_by :
ordering = self.order_by
else :
ordering = self.index_model._meta.ordering
if len(ordering) < 1 : # If no ordering, use relevance sort.
return None
else :
_sorts = list()
for i in ordering :
_r = False
_f = i
if i[0] == "?" :
return constant.SORT_RANDOM
if i[0].startswith("-") :
_r = True
_f = i[1:]
if not _f.startswith("__") :
_f = "sort__%s" % _f
_sorts.append(lucene.SortField(_f, _r))
if True not in [i.startswith(constant.FIELD_NAME_PK) or i.startswith("-%s" % constant.FIELD_NAME_PK) for i in ordering] :
_sorts.append(lucene.SortField(constant.FIELD_NAME_PK, _r))
return lucene.Sort(_sorts)
def get_count (self) :
(query, ordering, ) = self.as_sql()
try :
self.searcher = pylucene.Searcher(storage_path=self.index_model._meta.storage_path, )
except Exception, e :
raise
else :
hits = self.searcher.search(query, ordering, slice=slice(self.low_mark, self.high_mark))
if hits is None :
return 0
return len(list(hits))
"""
Description
-----------
ChangeLog
---------
Usage
-----
"""
__author__ = "Spike^ekipS <spikeekips@gmail.com>"