author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Thu, 24 Sep 2009 00:24:21 +0200 | |
changeset 3460 | e4843535db25 |
parent 3245 | 7ef021ac8dec |
child 3689 | deb13e88e037 |
permissions | -rw-r--r-- |
0 | 1 |
"""RQL to SQL generator for native sources. |
2 |
||
3 |
||
4 |
SQL queries optimization |
|
5 |
~~~~~~~~~~~~~~~~~~~~~~~~ |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
6 |
1. CWUser X WHERE X in_group G, G name 'users': |
0 | 7 |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
8 |
CWUser is the only subject entity type for the in_group relation, |
0 | 9 |
which allow us to do :: |
10 |
||
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
11 |
SELECT eid_from FROM in_group, CWGroup |
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
12 |
WHERE in_group.eid_to = CWGroup.eid_from |
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
13 |
AND CWGroup.name = 'users' |
0 | 14 |
|
15 |
||
16 |
2. Any X WHERE X nonfinal1 Y, Y nonfinal2 Z |
|
17 |
||
18 |
-> direct join between nonfinal1 and nonfinal2, whatever X,Y, Z (unless |
|
19 |
inlined...) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
20 |
|
0 | 21 |
NOT IMPLEMENTED (and quite hard to implement) |
22 |
||
23 |
Potential optimization information is collected by the querier, sql generation |
|
24 |
is done according to this information |
|
25 |
||
26 |
||
27 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1862
diff
changeset
|
28 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 29 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1862
diff
changeset
|
30 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 31 |
""" |
32 |
__docformat__ = "restructuredtext en" |
|
33 |
||
34 |
import threading |
|
35 |
||
36 |
from rql import BadRQLQuery, CoercionError |
|
37 |
from rql.stmts import Union, Select |
|
38 |
from rql.nodes import (SortTerm, VariableRef, Constant, Function, Not, |
|
39 |
Variable, ColumnAlias, Relation, SubQuery, Exists) |
|
40 |
||
41 |
from cubicweb import server |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1124
diff
changeset
|
42 |
from cubicweb.server.sqlutils import SQL_PREFIX |
0 | 43 |
from cubicweb.server.utils import cleanup_solutions |
44 |
||
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
45 |
def _new_var(select, varname): |
0 | 46 |
newvar = select.get_variable(varname) |
47 |
if not 'relations' in newvar.stinfo: |
|
48 |
# not yet initialized |
|
49 |
newvar.prepare_annotation() |
|
50 |
newvar.stinfo['scope'] = select |
|
51 |
newvar._q_invariant = False |
|
52 |
return newvar |
|
53 |
||
54 |
def _fill_to_wrap_rel(var, newselect, towrap, schema): |
|
55 |
for rel in var.stinfo['relations'] - var.stinfo['rhsrelations']: |
|
56 |
rschema = schema.rschema(rel.r_type) |
|
57 |
if rschema.inlined: |
|
58 |
towrap.add( (var, rel) ) |
|
59 |
for vref in rel.children[1].iget_nodes(VariableRef): |
|
60 |
newivar = _new_var(newselect, vref.name) |
|
61 |
newselect.selection.append(VariableRef(newivar)) |
|
62 |
_fill_to_wrap_rel(vref.variable, newselect, towrap, schema) |
|
63 |
elif rschema.is_final(): |
|
64 |
towrap.add( (var, rel) ) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
65 |
|
0 | 66 |
def rewrite_unstable_outer_join(select, solutions, unstable, schema): |
67 |
"""if some optional variables are unstable, they should be selected in a |
|
68 |
subquery. This function check this and rewrite the rql syntax tree if |
|
69 |
necessary (in place). Return a boolean telling if the tree has been modified |
|
70 |
""" |
|
71 |
torewrite = set() |
|
72 |
modified = False |
|
73 |
for varname in tuple(unstable): |
|
74 |
var = select.defined_vars[varname] |
|
75 |
if not var.stinfo['optrelations']: |
|
76 |
continue |
|
77 |
modified = True |
|
78 |
unstable.remove(varname) |
|
79 |
torewrite.add(var) |
|
80 |
newselect = Select() |
|
339
c0a0ce6c0428
in some cases (eg ambiguous neged relations), INTERSECT should be used instead of DISTINCT
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
81 |
newselect.need_distinct = newselect.need_intersect = False |
0 | 82 |
myunion = Union() |
83 |
myunion.append(newselect) |
|
84 |
# extract aliases / selection |
|
85 |
newvar = _new_var(newselect, var.name) |
|
86 |
newselect.selection = [VariableRef(newvar)] |
|
87 |
for avar in select.defined_vars.itervalues(): |
|
88 |
if avar.stinfo['attrvar'] is var: |
|
89 |
newavar = _new_var(newselect, avar.name) |
|
90 |
newavar.stinfo['attrvar'] = newvar |
|
91 |
newselect.selection.append(VariableRef(newavar)) |
|
92 |
towrap_rels = set() |
|
93 |
_fill_to_wrap_rel(var, newselect, towrap_rels, schema) |
|
94 |
# extract relations |
|
95 |
for var, rel in towrap_rels: |
|
96 |
newrel = rel.copy(newselect) |
|
97 |
newselect.add_restriction(newrel) |
|
98 |
select.remove_node(rel) |
|
99 |
var.stinfo['relations'].remove(rel) |
|
100 |
newvar.stinfo['relations'].add(newrel) |
|
101 |
if rel.optional in ('left', 'both'): |
|
102 |
newvar.stinfo['optrelations'].add(newrel) |
|
103 |
for vref in newrel.children[1].iget_nodes(VariableRef): |
|
104 |
var = vref.variable |
|
105 |
var.stinfo['relations'].add(newrel) |
|
106 |
var.stinfo['rhsrelations'].add(newrel) |
|
107 |
if rel.optional in ('right', 'both'): |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
108 |
var.stinfo['optrelations'].add(newrel) |
0 | 109 |
# extract subquery solutions |
110 |
solutions = [sol.copy() for sol in solutions] |
|
111 |
cleanup_solutions(newselect, solutions) |
|
112 |
newselect.set_possible_types(solutions) |
|
113 |
# full sub-query |
|
114 |
aliases = [VariableRef(select.get_variable(avar.name, i)) |
|
115 |
for i, avar in enumerate(newselect.selection)] |
|
116 |
select.add_subquery(SubQuery(aliases, myunion), check=False) |
|
117 |
return modified |
|
118 |
||
119 |
def _new_solutions(rqlst, solutions): |
|
120 |
"""first filter out subqueries variables from solutions""" |
|
121 |
newsolutions = [] |
|
122 |
for origsol in solutions: |
|
123 |
asol = {} |
|
124 |
for vname in rqlst.defined_vars: |
|
125 |
asol[vname] = origsol[vname] |
|
126 |
if not asol in newsolutions: |
|
127 |
newsolutions.append(asol) |
|
128 |
return newsolutions |
|
129 |
||
130 |
def remove_unused_solutions(rqlst, solutions, varmap, schema): |
|
131 |
"""cleanup solutions: remove solutions where invariant variables are taking |
|
132 |
different types |
|
133 |
""" |
|
134 |
newsolutions = _new_solutions(rqlst, solutions) |
|
135 |
existssols = {} |
|
136 |
unstable = set() |
|
137 |
for vname, var in rqlst.defined_vars.iteritems(): |
|
138 |
vtype = newsolutions[0][vname] |
|
139 |
if var._q_invariant or vname in varmap: |
|
140 |
for i in xrange(len(newsolutions)-1, 0, -1): |
|
141 |
if vtype != newsolutions[i][vname]: |
|
142 |
newsolutions.pop(i) |
|
143 |
elif not var.scope is rqlst: |
|
144 |
# move appart variables which are in a EXISTS scope and are variating |
|
145 |
try: |
|
146 |
thisexistssols, thisexistsvars = existssols[var.scope] |
|
147 |
except KeyError: |
|
148 |
thisexistssols = [newsolutions[0]] |
|
149 |
thisexistsvars = set() |
|
150 |
existssols[var.scope] = thisexistssols, thisexistsvars |
|
151 |
for i in xrange(len(newsolutions)-1, 0, -1): |
|
152 |
if vtype != newsolutions[i][vname]: |
|
153 |
thisexistssols.append(newsolutions.pop(i)) |
|
154 |
thisexistsvars.add(vname) |
|
155 |
else: |
|
156 |
# remember unstable variables |
|
157 |
for i in xrange(1, len(newsolutions)): |
|
158 |
if vtype != newsolutions[i][vname]: |
|
159 |
unstable.add(vname) |
|
160 |
if len(newsolutions) > 1: |
|
161 |
if rewrite_unstable_outer_join(rqlst, newsolutions, unstable, schema): |
|
162 |
# remove variables extracted to subqueries from solutions |
|
163 |
newsolutions = _new_solutions(rqlst, newsolutions) |
|
164 |
return newsolutions, existssols, unstable |
|
165 |
||
166 |
def relation_info(relation): |
|
167 |
lhs, rhs = relation.get_variable_parts() |
|
168 |
try: |
|
169 |
lhs = lhs.variable |
|
170 |
lhsconst = lhs.stinfo['constnode'] |
|
171 |
except AttributeError: |
|
172 |
lhsconst = lhs |
|
173 |
lhs = None |
|
174 |
except KeyError: |
|
175 |
lhsconst = None # ColumnAlias |
|
176 |
try: |
|
177 |
rhs = rhs.variable |
|
178 |
rhsconst = rhs.stinfo['constnode'] |
|
179 |
except AttributeError: |
|
180 |
rhsconst = rhs |
|
181 |
rhs = None |
|
182 |
except KeyError: |
|
183 |
rhsconst = None # ColumnAlias |
|
184 |
return lhs, lhsconst, rhs, rhsconst |
|
185 |
||
186 |
def switch_relation_field(sql, table=''): |
|
187 |
switchedsql = sql.replace(table + '.eid_from', '__eid_from__') |
|
188 |
switchedsql = switchedsql.replace(table + '.eid_to', |
|
189 |
table + '.eid_from') |
|
190 |
return switchedsql.replace('__eid_from__', table + '.eid_to') |
|
191 |
||
192 |
def sort_term_selection(sorts, selectedidx, rqlst, groups): |
|
193 |
# XXX beurk |
|
194 |
if isinstance(rqlst, list): |
|
195 |
def append(term): |
|
196 |
rqlst.append(term) |
|
197 |
else: |
|
198 |
def append(term): |
|
199 |
rqlst.selection.append(term.copy(rqlst)) |
|
200 |
for sortterm in sorts: |
|
201 |
term = sortterm.term |
|
202 |
if not isinstance(term, Constant) and not str(term) in selectedidx: |
|
203 |
selectedidx.append(str(term)) |
|
204 |
append(term) |
|
205 |
if groups: |
|
206 |
for vref in term.iget_nodes(VariableRef): |
|
207 |
if not vref in groups: |
|
208 |
groups.append(vref) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
209 |
|
0 | 210 |
def fix_selection(rqlst, selectedidx, needwrap, sorts, groups, having): |
211 |
if sorts: |
|
212 |
sort_term_selection(sorts, selectedidx, rqlst, not needwrap and groups) |
|
213 |
if needwrap: |
|
214 |
if groups: |
|
215 |
for vref in groups: |
|
216 |
if not vref.name in selectedidx: |
|
217 |
selectedidx.append(vref.name) |
|
218 |
rqlst.selection.append(vref) |
|
219 |
if having: |
|
220 |
for term in having: |
|
221 |
for vref in term.iget_nodes(VariableRef): |
|
222 |
if not vref.name in selectedidx: |
|
223 |
selectedidx.append(vref.name) |
|
224 |
rqlst.selection.append(vref) |
|
225 |
||
226 |
# IGenerator implementation for RQL->SQL ###################################### |
|
227 |
||
228 |
||
229 |
class StateInfo(object): |
|
230 |
def __init__(self, existssols, unstablevars): |
|
231 |
self.existssols = existssols |
|
232 |
self.unstablevars = unstablevars |
|
233 |
self.subtables = {} |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
234 |
|
0 | 235 |
def reset(self, solution): |
236 |
"""reset some visit variables""" |
|
237 |
self.solution = solution |
|
238 |
self.count = 0 |
|
239 |
self.done = set() |
|
240 |
self.tables = self.subtables.copy() |
|
241 |
self.actual_tables = [[]] |
|
242 |
for _, tsql in self.tables.itervalues(): |
|
243 |
self.actual_tables[-1].append(tsql) |
|
244 |
self.outer_tables = {} |
|
245 |
self.duplicate_switches = [] |
|
246 |
self.attr_vars = {} |
|
247 |
self.aliases = {} |
|
248 |
self.restrictions = [] |
|
249 |
self._restr_stack = [] |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
250 |
|
0 | 251 |
def add_restriction(self, restr): |
252 |
if restr: |
|
253 |
self.restrictions.append(restr) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
254 |
|
0 | 255 |
def iter_exists_sols(self, exists): |
256 |
if not exists in self.existssols: |
|
257 |
yield 1 |
|
258 |
return |
|
259 |
thisexistssols, thisexistsvars = self.existssols[exists] |
|
260 |
origsol = self.solution |
|
261 |
origtables = self.tables |
|
262 |
done = self.done |
|
263 |
for thisexistssol in thisexistssols: |
|
264 |
for vname in self.unstablevars: |
|
265 |
if thisexistssol[vname] != origsol[vname] and vname in thisexistsvars: |
|
266 |
break |
|
267 |
else: |
|
268 |
self.tables = origtables.copy() |
|
269 |
self.solution = thisexistssol |
|
270 |
yield 1 |
|
271 |
# cleanup self.done from stuff specific to exists |
|
272 |
for var in thisexistsvars: |
|
273 |
if var in done: |
|
274 |
done.remove(var) |
|
275 |
for rel in exists.iget_nodes(Relation): |
|
276 |
if rel in done: |
|
277 |
done.remove(rel) |
|
278 |
self.solution = origsol |
|
279 |
self.tables = origtables |
|
280 |
||
281 |
def push_scope(self): |
|
282 |
self.actual_tables.append([]) |
|
283 |
self._restr_stack.append(self.restrictions) |
|
284 |
self.restrictions = [] |
|
285 |
||
286 |
def pop_scope(self): |
|
287 |
restrictions = self.restrictions |
|
288 |
self.restrictions = self._restr_stack.pop() |
|
289 |
return restrictions, self.actual_tables.pop() |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
290 |
|
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
291 |
|
0 | 292 |
class SQLGenerator(object): |
293 |
""" |
|
294 |
generation of SQL from the fully expanded RQL syntax tree |
|
295 |
SQL is designed to be used with a CubicWeb SQL schema |
|
296 |
||
297 |
Groups and sort are not handled here since they should not be handled at |
|
298 |
this level (see cubicweb.server.querier) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
299 |
|
0 | 300 |
we should not have errors here ! |
301 |
||
302 |
WARNING: a CubicWebSQLGenerator instance is not thread safe, but generate is |
|
303 |
protected by a lock |
|
304 |
""" |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
305 |
|
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
306 |
def __init__(self, schema, dbms_helper, dbencoding='UTF-8', attrmap=None): |
0 | 307 |
self.schema = schema |
308 |
self.dbms_helper = dbms_helper |
|
309 |
self.dbencoding = dbencoding |
|
310 |
self.keyword_map = {'NOW' : self.dbms_helper.sql_current_timestamp, |
|
311 |
'TODAY': self.dbms_helper.sql_current_date, |
|
312 |
} |
|
313 |
if not self.dbms_helper.union_parentheses_support: |
|
314 |
self.union_sql = self.noparen_union_sql |
|
315 |
self._lock = threading.Lock() |
|
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
316 |
if attrmap is None: |
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
317 |
attrmap = {} |
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
318 |
self.attr_map = attrmap |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
319 |
|
0 | 320 |
def generate(self, union, args=None, varmap=None): |
321 |
"""return SQL queries and a variable dictionnary from a RQL syntax tree |
|
322 |
||
323 |
:partrqls: a list of couple (rqlst, solutions) |
|
324 |
:args: optional dictionary with values of substitutions used in the query |
|
325 |
:varmap: optional dictionary mapping variable name to a special table |
|
326 |
name, in case the query as to fetch data from temporary tables |
|
327 |
||
328 |
return an sql string and a dictionary with substitutions values |
|
329 |
""" |
|
330 |
if args is None: |
|
331 |
args = {} |
|
332 |
if varmap is None: |
|
333 |
varmap = {} |
|
334 |
self._lock.acquire() |
|
335 |
self._args = args |
|
336 |
self._varmap = varmap |
|
337 |
self._query_attrs = {} |
|
338 |
self._state = None |
|
3238
988a72e59b2b
[querier] fix sql generated w/ NOT relation and shared variable: ensure variable's table is in parent select'scope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2915
diff
changeset
|
339 |
self._not_scope_offset = 0 |
0 | 340 |
try: |
341 |
# union query for each rqlst / solution |
|
342 |
sql = self.union_sql(union) |
|
343 |
# we are done |
|
344 |
return sql, self._query_attrs |
|
345 |
finally: |
|
346 |
self._lock.release() |
|
347 |
||
348 |
def union_sql(self, union, needalias=False): # pylint: disable-msg=E0202 |
|
349 |
if len(union.children) == 1: |
|
350 |
return self.select_sql(union.children[0], needalias) |
|
351 |
sqls = ('(%s)' % self.select_sql(select, needalias) |
|
352 |
for select in union.children) |
|
353 |
return '\nUNION ALL\n'.join(sqls) |
|
354 |
||
355 |
def noparen_union_sql(self, union, needalias=False): |
|
356 |
# needed for sqlite backend which doesn't like parentheses around |
|
357 |
# union query. This may cause bug in some condition (sort in one of |
|
358 |
# the subquery) but will work in most case |
|
359 |
# see http://www.sqlite.org/cvstrac/tktview?tn=3074 |
|
360 |
sqls = (self.select_sql(select, needalias) |
|
361 |
for i, select in enumerate(union.children)) |
|
362 |
return '\nUNION ALL\n'.join(sqls) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
363 |
|
0 | 364 |
def select_sql(self, select, needalias=False): |
365 |
"""return SQL queries and a variable dictionnary from a RQL syntax tree |
|
366 |
||
367 |
:select: a selection statement of the syntax tree (`rql.stmts.Select`) |
|
368 |
:solution: a dictionnary containing variables binding. |
|
369 |
A solution's dictionnary has variable's names as key and variable's |
|
370 |
types as values |
|
371 |
:needwrap: boolean telling if the query will be wrapped in an outer |
|
372 |
query (to deal with aggregat and/or grouping) |
|
373 |
""" |
|
374 |
distinct = selectsortterms = select.need_distinct |
|
375 |
sorts = select.orderby |
|
376 |
groups = select.groupby |
|
377 |
having = select.having |
|
378 |
# remember selection, it may be changed and have to be restored |
|
379 |
origselection = select.selection[:] |
|
380 |
# check if the query will have union subquery, if it need sort term |
|
381 |
# selection (union or distinct query) and wrapping (union with groups) |
|
382 |
needwrap = False |
|
383 |
sols = select.solutions |
|
384 |
if len(sols) > 1: |
|
385 |
# remove invariant from solutions |
|
386 |
sols, existssols, unstable = remove_unused_solutions( |
|
387 |
select, sols, self._varmap, self.schema) |
|
388 |
if len(sols) > 1: |
|
389 |
# if there is still more than one solution, a UNION will be |
|
390 |
# generated and so sort terms have to be selected |
|
391 |
selectsortterms = True |
|
392 |
# and if select is using group by or aggregat, a wrapping |
|
393 |
# query will be necessary |
|
394 |
if groups or select.has_aggregat: |
|
395 |
select.select_only_variables() |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
396 |
needwrap = True |
0 | 397 |
else: |
398 |
existssols, unstable = {}, () |
|
399 |
state = StateInfo(existssols, unstable) |
|
400 |
# treat subqueries |
|
401 |
self._subqueries_sql(select, state) |
|
402 |
# generate sql for this select node |
|
403 |
selectidx = [str(term) for term in select.selection] |
|
404 |
if needwrap: |
|
405 |
outerselection = origselection[:] |
|
406 |
if sorts and selectsortterms: |
|
407 |
outerselectidx = [str(term) for term in outerselection] |
|
408 |
if distinct: |
|
409 |
sort_term_selection(sorts, outerselectidx, |
|
410 |
outerselection, groups) |
|
411 |
else: |
|
412 |
outerselectidx = selectidx[:] |
|
413 |
fix_selection(select, selectidx, needwrap, |
|
414 |
selectsortterms and sorts, groups, having) |
|
415 |
if needwrap: |
|
416 |
fselectidx = outerselectidx |
|
417 |
fneedwrap = len(outerselection) != len(origselection) |
|
418 |
else: |
|
419 |
fselectidx = selectidx |
|
420 |
fneedwrap = len(select.selection) != len(origselection) |
|
421 |
if fneedwrap: |
|
422 |
needalias = True |
|
423 |
self._in_wrapping_query = False |
|
424 |
self._state = state |
|
425 |
try: |
|
426 |
sql = self._solutions_sql(select, sols, distinct, needalias or needwrap) |
|
427 |
# generate groups / having before wrapping query selection to |
|
428 |
# get correct column aliases |
|
429 |
self._in_wrapping_query = needwrap |
|
430 |
if groups: |
|
431 |
# no constant should be inserted in GROUP BY else the backend will |
|
432 |
# interpret it as a positional index in the selection |
|
433 |
groups = ','.join(vref.accept(self) for vref in groups |
|
434 |
if not isinstance(vref, Constant)) |
|
435 |
if having: |
|
436 |
# filter out constants as for GROUP BY |
|
437 |
having = ','.join(vref.accept(self) for vref in having |
|
438 |
if not isinstance(vref, Constant)) |
|
439 |
if needwrap: |
|
440 |
sql = '%s FROM (%s) AS T1' % (self._selection_sql(outerselection, distinct, |
|
441 |
needalias), |
|
442 |
sql) |
|
443 |
if groups: |
|
444 |
sql += '\nGROUP BY %s' % groups |
|
445 |
if having: |
|
446 |
sql += '\nHAVING %s' % having |
|
447 |
# sort |
|
448 |
if sorts: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
449 |
sql += '\nORDER BY %s' % ','.join(self._sortterm_sql(sortterm, |
0 | 450 |
fselectidx) |
451 |
for sortterm in sorts) |
|
452 |
if fneedwrap: |
|
453 |
selection = ['T1.C%s' % i for i in xrange(len(origselection))] |
|
454 |
sql = 'SELECT %s FROM (%s) AS T1' % (','.join(selection), sql) |
|
455 |
finally: |
|
456 |
select.selection = origselection |
|
457 |
# limit / offset |
|
458 |
limit = select.limit |
|
459 |
if limit: |
|
460 |
sql += '\nLIMIT %s' % limit |
|
461 |
offset = select.offset |
|
462 |
if offset: |
|
463 |
sql += '\nOFFSET %s' % offset |
|
464 |
return sql |
|
465 |
||
466 |
def _subqueries_sql(self, select, state): |
|
467 |
for i, subquery in enumerate(select.with_): |
|
468 |
sql = self.union_sql(subquery.query, needalias=True) |
|
469 |
tablealias = '_T%s' % i |
|
470 |
sql = '(%s) AS %s' % (sql, tablealias) |
|
471 |
state.subtables[tablealias] = (0, sql) |
|
472 |
for vref in subquery.aliases: |
|
473 |
alias = vref.variable |
|
474 |
alias._q_sqltable = tablealias |
|
475 |
alias._q_sql = '%s.C%s' % (tablealias, alias.colnum) |
|
476 |
||
477 |
def _solutions_sql(self, select, solutions, distinct, needalias): |
|
478 |
sqls = [] |
|
479 |
for solution in solutions: |
|
480 |
self._state.reset(solution) |
|
481 |
# visit restriction subtree |
|
482 |
if select.where is not None: |
|
483 |
self._state.add_restriction(select.where.accept(self)) |
|
484 |
sql = [self._selection_sql(select.selection, distinct, needalias)] |
|
485 |
if self._state.restrictions: |
|
486 |
sql.append('WHERE %s' % ' AND '.join(self._state.restrictions)) |
|
487 |
# add required tables |
|
488 |
assert len(self._state.actual_tables) == 1, self._state.actual_tables |
|
489 |
tables = self._state.actual_tables[-1] |
|
490 |
if tables: |
|
491 |
# sort for test predictability |
|
492 |
sql.insert(1, 'FROM %s' % ', '.join(sorted(tables))) |
|
493 |
elif self._state.restrictions and self.dbms_helper.needs_from_clause: |
|
494 |
sql.insert(1, 'FROM (SELECT 1) AS _T') |
|
495 |
sqls.append('\n'.join(sql)) |
|
339
c0a0ce6c0428
in some cases (eg ambiguous neged relations), INTERSECT should be used instead of DISTINCT
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
496 |
if select.need_intersect: |
2199
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
497 |
#if distinct or not self.dbms_helper.intersect_all_support: |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
498 |
return '\nINTERSECT\n'.join(sqls) |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
499 |
#else: |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
500 |
# return '\nINTERSECT ALL\n'.join(sqls) |
339
c0a0ce6c0428
in some cases (eg ambiguous neged relations), INTERSECT should be used instead of DISTINCT
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
501 |
elif distinct: |
0 | 502 |
return '\nUNION\n'.join(sqls) |
503 |
else: |
|
504 |
return '\nUNION ALL\n'.join(sqls) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
505 |
|
0 | 506 |
def _selection_sql(self, selected, distinct, needaliasing=False): |
507 |
clause = [] |
|
508 |
for term in selected: |
|
509 |
sql = term.accept(self) |
|
510 |
if needaliasing: |
|
511 |
colalias = 'C%s' % len(clause) |
|
512 |
clause.append('%s AS %s' % (sql, colalias)) |
|
513 |
if isinstance(term, VariableRef): |
|
514 |
self._state.aliases[term.name] = colalias |
|
515 |
else: |
|
516 |
clause.append(sql) |
|
517 |
if distinct: |
|
518 |
return 'SELECT DISTINCT %s' % ', '.join(clause) |
|
519 |
return 'SELECT %s' % ', '.join(clause) |
|
520 |
||
521 |
def _sortterm_sql(self, sortterm, selectidx): |
|
522 |
term = sortterm.term |
|
523 |
try: |
|
524 |
sqlterm = str(selectidx.index(str(term)) + 1) |
|
525 |
except ValueError: |
|
526 |
# Constant node or non selected term |
|
527 |
sqlterm = str(term.accept(self)) |
|
528 |
if sortterm.asc: |
|
529 |
return sqlterm |
|
530 |
else: |
|
531 |
return '%s DESC' % sqlterm |
|
532 |
||
533 |
def visit_and(self, et): |
|
534 |
"""generate SQL for a AND subtree""" |
|
535 |
res = [] |
|
536 |
for c in et.children: |
|
537 |
part = c.accept(self) |
|
538 |
if part: |
|
539 |
res.append(part) |
|
540 |
return ' AND '.join(res) |
|
541 |
||
542 |
def visit_or(self, ou): |
|
543 |
"""generate SQL for a OR subtree""" |
|
544 |
res = [] |
|
545 |
for c in ou.children: |
|
546 |
part = c.accept(self) |
|
547 |
if part: |
|
548 |
res.append('(%s)' % part) |
|
549 |
if res: |
|
550 |
if len(res) > 1: |
|
551 |
return '(%s)' % ' OR '.join(res) |
|
552 |
return res[0] |
|
553 |
return '' |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
554 |
|
0 | 555 |
def visit_not(self, node): |
556 |
self._state.push_scope() |
|
3238
988a72e59b2b
[querier] fix sql generated w/ NOT relation and shared variable: ensure variable's table is in parent select'scope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2915
diff
changeset
|
557 |
if isinstance(node.children[0], Relation): |
988a72e59b2b
[querier] fix sql generated w/ NOT relation and shared variable: ensure variable's table is in parent select'scope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2915
diff
changeset
|
558 |
self._not_scope_offset += 1 |
0 | 559 |
csql = node.children[0].accept(self) |
3238
988a72e59b2b
[querier] fix sql generated w/ NOT relation and shared variable: ensure variable's table is in parent select'scope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2915
diff
changeset
|
560 |
if isinstance(node.children[0], Relation): |
988a72e59b2b
[querier] fix sql generated w/ NOT relation and shared variable: ensure variable's table is in parent select'scope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2915
diff
changeset
|
561 |
self._not_scope_offset -= 1 |
0 | 562 |
sqls, tables = self._state.pop_scope() |
563 |
if node in self._state.done or not csql: |
|
564 |
# already processed or no sql generated by children |
|
565 |
self._state.actual_tables[-1] += tables |
|
566 |
self._state.restrictions += sqls |
|
567 |
return csql |
|
568 |
if isinstance(node.children[0], Exists): |
|
569 |
assert not sqls, (sqls, str(node.stmt)) |
|
570 |
assert not tables, (tables, str(node.stmt)) |
|
571 |
return 'NOT %s' % csql |
|
572 |
sqls.append(csql) |
|
573 |
if tables: |
|
574 |
select = 'SELECT 1 FROM %s' % ','.join(tables) |
|
575 |
else: |
|
576 |
select = 'SELECT 1' |
|
577 |
if sqls: |
|
578 |
sql = 'NOT EXISTS(%s WHERE %s)' % (select, ' AND '.join(sqls)) |
|
579 |
else: |
|
580 |
sql = 'NOT EXISTS(%s)' % select |
|
581 |
return sql |
|
582 |
||
583 |
def visit_exists(self, exists): |
|
584 |
"""generate SQL name for a exists subquery""" |
|
585 |
sqls = [] |
|
586 |
for dummy in self._state.iter_exists_sols(exists): |
|
587 |
sql = self._visit_exists(exists) |
|
588 |
if sql: |
|
589 |
sqls.append(sql) |
|
590 |
if not sqls: |
|
591 |
return '' |
|
592 |
return 'EXISTS(%s)' % ' UNION '.join(sqls) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
593 |
|
0 | 594 |
def _visit_exists(self, exists): |
595 |
self._state.push_scope() |
|
596 |
restriction = exists.children[0].accept(self) |
|
597 |
restrictions, tables = self._state.pop_scope() |
|
598 |
if restriction: |
|
599 |
restrictions.append(restriction) |
|
600 |
restriction = ' AND '.join(restrictions) |
|
601 |
if not restriction: |
|
602 |
return '' |
|
603 |
if not tables: |
|
604 |
# XXX could leave surrounding EXISTS() in this case no? |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
605 |
sql = 'SELECT 1 WHERE %s' % restriction |
0 | 606 |
else: |
607 |
sql = 'SELECT 1 FROM %s WHERE %s' % (', '.join(tables), restriction) |
|
608 |
return sql |
|
609 |
||
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
610 |
|
0 | 611 |
def visit_relation(self, relation): |
612 |
"""generate SQL for a relation""" |
|
613 |
rtype = relation.r_type |
|
614 |
# don't care of type constraint statement (i.e. relation_type = 'is') |
|
615 |
if relation.is_types_restriction(): |
|
616 |
return '' |
|
617 |
lhs, rhs = relation.get_parts() |
|
618 |
rschema = self.schema.rschema(rtype) |
|
619 |
if rschema.is_final(): |
|
620 |
if rtype == 'eid' and lhs.variable._q_invariant and \ |
|
621 |
lhs.variable.stinfo['constnode']: |
|
622 |
# special case where this restriction is already generated by |
|
623 |
# some other relation |
|
624 |
return '' |
|
625 |
# attribute relation |
|
626 |
if rtype == 'has_text': |
|
627 |
sql = self._visit_has_text_relation(relation) |
|
628 |
else: |
|
629 |
rhs_vars = rhs.get_nodes(VariableRef) |
|
630 |
if rhs_vars: |
|
631 |
# if variable(s) in the RHS |
|
632 |
sql = self._visit_var_attr_relation(relation, rhs_vars) |
|
633 |
else: |
|
634 |
# no variables in the RHS |
|
635 |
sql = self._visit_attribute_relation(relation) |
|
636 |
if relation.neged(strict=True): |
|
637 |
self._state.done.add(relation.parent) |
|
638 |
sql = 'NOT (%s)' % sql |
|
639 |
else: |
|
640 |
if rtype == 'is' and rhs.operator == 'IS': |
|
641 |
# special case "C is NULL" |
|
642 |
if lhs.name in self._varmap: |
|
643 |
lhssql = self._varmap[lhs.name] |
|
644 |
else: |
|
645 |
lhssql = lhs.accept(self) |
|
646 |
return '%s%s' % (lhssql, rhs.accept(self)) |
|
647 |
if '%s.%s' % (lhs, relation.r_type) in self._varmap: |
|
648 |
# relation has already been processed by a previous step |
|
649 |
return |
|
650 |
if relation.optional: |
|
651 |
# check it has not already been treaten (to get necessary |
|
652 |
# information to add an outer join condition) |
|
653 |
if relation in self._state.done: |
|
654 |
return |
|
655 |
# OPTIONAL relation, generate a left|right outer join |
|
656 |
sql = self._visit_outer_join_relation(relation, rschema) |
|
657 |
elif rschema.inlined: |
|
658 |
sql = self._visit_inlined_relation(relation) |
|
659 |
else: |
|
660 |
# regular (non final) relation |
|
661 |
sql = self._visit_relation(relation, rschema) |
|
662 |
return sql |
|
663 |
||
664 |
def _visit_inlined_relation(self, relation): |
|
665 |
lhsvar, _, rhsvar, rhsconst = relation_info(relation) |
|
666 |
# we are sure here to have a lhsvar |
|
667 |
assert lhsvar is not None |
|
668 |
if isinstance(relation.parent, Not): |
|
669 |
self._state.done.add(relation.parent) |
|
670 |
if rhsvar is not None and not rhsvar._q_invariant: |
|
2199
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
671 |
# if the lhs variable is only linked to this relation, this mean we |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
672 |
# only want the relation to NOT exists |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
673 |
self._state.push_scope() |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
674 |
lhssql = self._inlined_var_sql(lhsvar, relation.r_type) |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
675 |
rhssql = rhsvar.accept(self) |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
676 |
restrictions, tables = self._state.pop_scope() |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
677 |
restrictions.append('%s=%s' % (lhssql, rhssql)) |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
678 |
if not tables: |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
679 |
sql = 'NOT EXISTS(SELECT 1 WHERE %s)' % ( |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
680 |
' AND '.join(restrictions)) |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
681 |
else: |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
682 |
sql = 'NOT EXISTS(SELECT 1 FROM %s WHERE %s)' % ( |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
683 |
', '.join(tables), ' AND '.join(restrictions)) |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
684 |
else: |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
685 |
lhssql = self._inlined_var_sql(lhsvar, relation.r_type) |
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
686 |
sql = '%s IS NULL' % self._inlined_var_sql(lhsvar, relation.r_type) |
0 | 687 |
return sql |
2199
bd0a0f219751
fix sql generated on NOT inlined_relation queries. Use exists, so no more needs for extra DISTINCT
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2073
diff
changeset
|
688 |
lhssql = self._inlined_var_sql(lhsvar, relation.r_type) |
0 | 689 |
if rhsconst is not None: |
690 |
return '%s=%s' % (lhssql, rhsconst.accept(self)) |
|
691 |
if isinstance(rhsvar, Variable) and not rhsvar.name in self._varmap: |
|
692 |
# if the rhs variable is only linked to this relation, this mean we |
|
693 |
# only want the relation to exists, eg NOT NULL in case of inlined |
|
694 |
# relation |
|
695 |
if len(rhsvar.stinfo['relations']) == 1 and rhsvar._q_invariant: |
|
696 |
return '%s IS NOT NULL' % lhssql |
|
697 |
if rhsvar._q_invariant: |
|
698 |
return self._extra_join_sql(relation, lhssql, rhsvar) |
|
699 |
return '%s=%s' % (lhssql, rhsvar.accept(self)) |
|
700 |
||
701 |
def _process_relation_term(self, relation, rid, termvar, termconst, relfield): |
|
702 |
if termconst or isinstance(termvar, ColumnAlias) or not termvar._q_invariant: |
|
703 |
termsql = termconst and termconst.accept(self) or termvar.accept(self) |
|
704 |
yield '%s.%s=%s' % (rid, relfield, termsql) |
|
705 |
elif termvar._q_invariant: |
|
706 |
# if the variable is mapped, generate restriction anyway |
|
707 |
if termvar.name in self._varmap: |
|
708 |
termsql = termvar.accept(self) |
|
709 |
yield '%s.%s=%s' % (rid, relfield, termsql) |
|
710 |
extrajoin = self._extra_join_sql(relation, '%s.%s' % (rid, relfield), termvar) |
|
711 |
if extrajoin: |
|
712 |
yield extrajoin |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
713 |
|
0 | 714 |
def _visit_relation(self, relation, rschema): |
715 |
"""generate SQL for a relation |
|
716 |
||
717 |
implements optimization 1. |
|
718 |
""" |
|
719 |
if relation.r_type == 'identity': |
|
720 |
# special case "X identity Y" |
|
721 |
lhs, rhs = relation.get_parts() |
|
722 |
if isinstance(relation.parent, Not): |
|
723 |
self._state.done.add(relation.parent) |
|
724 |
return 'NOT %s%s' % (lhs.accept(self), rhs.accept(self)) |
|
725 |
return '%s%s' % (lhs.accept(self), rhs.accept(self)) |
|
726 |
lhsvar, lhsconst, rhsvar, rhsconst = relation_info(relation) |
|
727 |
rid = self._relation_table(relation) |
|
728 |
sqls = [] |
|
729 |
sqls += self._process_relation_term(relation, rid, lhsvar, lhsconst, 'eid_from') |
|
730 |
sqls += self._process_relation_term(relation, rid, rhsvar, rhsconst, 'eid_to') |
|
731 |
sql = ' AND '.join(sqls) |
|
732 |
if rschema.symetric: |
|
733 |
sql = '(%s OR %s)' % (sql, switch_relation_field(sql)) |
|
734 |
return sql |
|
735 |
||
736 |
def _visit_outer_join_relation(self, relation, rschema): |
|
737 |
""" |
|
738 |
left outer join syntax (optional=='right'): |
|
739 |
X relation Y? |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
740 |
|
0 | 741 |
right outer join syntax (optional=='left'): |
742 |
X? relation Y |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
743 |
|
0 | 744 |
full outer join syntaxes (optional=='both'): |
745 |
X? relation Y? |
|
746 |
||
747 |
if relation is inlined: |
|
748 |
if it's a left outer join: |
|
749 |
-> X LEFT OUTER JOIN Y ON (X.relation=Y.eid) |
|
750 |
elif it's a right outer join: |
|
751 |
-> Y LEFT OUTER JOIN X ON (X.relation=Y.eid) |
|
752 |
elif it's a full outer join: |
|
753 |
-> X FULL OUTER JOIN Y ON (X.relation=Y.eid) |
|
754 |
else: |
|
755 |
if it's a left outer join: |
|
756 |
-> X LEFT OUTER JOIN relation ON (relation.eid_from=X.eid) |
|
757 |
LEFT OUTER JOIN Y ON (relation.eid_to=Y.eid) |
|
758 |
elif it's a right outer join: |
|
759 |
-> Y LEFT OUTER JOIN relation ON (relation.eid_to=Y.eid) |
|
760 |
LEFT OUTER JOIN X ON (relation.eid_from=X.eid) |
|
761 |
elif it's a full outer join: |
|
762 |
-> X FULL OUTER JOIN Y ON (X.relation=Y.eid) |
|
763 |
""" |
|
764 |
lhsvar, lhsconst, rhsvar, rhsconst = relation_info(relation) |
|
765 |
if relation.optional == 'right': |
|
766 |
joinattr, restrattr = 'eid_from', 'eid_to' |
|
767 |
else: |
|
768 |
lhsvar, rhsvar = rhsvar, lhsvar |
|
769 |
lhsconst, rhsconst = rhsconst, lhsconst |
|
770 |
joinattr, restrattr = 'eid_to', 'eid_from' |
|
771 |
if relation.optional == 'both': |
|
772 |
outertype = 'FULL' |
|
773 |
else: |
|
774 |
outertype = 'LEFT' |
|
775 |
if rschema.inlined or relation.r_type == 'identity': |
|
776 |
self._state.done.add(relation) |
|
777 |
t1 = self._var_table(lhsvar) |
|
778 |
if relation.r_type == 'identity': |
|
779 |
attr = 'eid' |
|
780 |
else: |
|
781 |
attr = relation.r_type |
|
782 |
# reset lhs/rhs, we need the initial order now |
|
783 |
lhs, rhs = relation.get_variable_parts() |
|
784 |
if '%s.%s' % (lhs.name, attr) in self._varmap: |
|
785 |
lhssql = self._varmap['%s.%s' % (lhs.name, attr)] |
|
786 |
else: |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1124
diff
changeset
|
787 |
lhssql = '%s.%s%s' % (self._var_table(lhs.variable), SQL_PREFIX, attr) |
0 | 788 |
if not rhsvar is None: |
789 |
t2 = self._var_table(rhsvar) |
|
790 |
if t2 is None: |
|
791 |
if rhsconst is not None: |
|
792 |
# inlined relation with invariant as rhs |
|
793 |
condition = '%s=%s' % (lhssql, rhsconst.accept(self)) |
|
794 |
if relation.r_type != 'identity': |
|
795 |
condition = '(%s OR %s IS NULL)' % (condition, lhssql) |
|
796 |
if not lhsvar.stinfo['optrelations']: |
|
797 |
return condition |
|
798 |
self.add_outer_join_condition(lhsvar, t1, condition) |
|
799 |
return |
|
800 |
else: |
|
801 |
condition = '%s=%s' % (lhssql, rhsconst.accept(self)) |
|
802 |
self.add_outer_join_condition(lhsvar, t1, condition) |
|
803 |
join = '%s OUTER JOIN %s ON (%s=%s)' % ( |
|
804 |
outertype, self._state.tables[t2][1], lhssql, rhs.accept(self)) |
|
805 |
self.replace_tables_by_outer_join(join, t1, t2) |
|
806 |
return '' |
|
807 |
lhssql = lhsconst and lhsconst.accept(self) or lhsvar.accept(self) |
|
808 |
rhssql = rhsconst and rhsconst.accept(self) or rhsvar.accept(self) |
|
809 |
rid = self._relation_table(relation) |
|
810 |
if not lhsvar: |
|
811 |
join = '' |
|
812 |
toreplace = [] |
|
813 |
maintable = rid |
|
814 |
else: |
|
815 |
join = '%s OUTER JOIN %s ON (%s.%s=%s' % ( |
|
816 |
outertype, self._state.tables[rid][1], rid, joinattr, lhssql) |
|
817 |
toreplace = [rid] |
|
818 |
maintable = self._var_table(lhsvar) |
|
819 |
if rhsconst: |
|
820 |
join += ' AND %s.%s=%s)' % (rid, restrattr, rhssql) |
|
821 |
else: |
|
822 |
join += ')' |
|
823 |
if not rhsconst: |
|
1122
9f37de24251f
fix rql2sq w/ outer join on subquery result
sylvain.thenault@logilab.fr
parents:
438
diff
changeset
|
824 |
rhstable = rhsvar._q_sqltable |
0 | 825 |
if rhstable: |
826 |
assert rhstable is not None, rhsvar |
|
827 |
join += ' %s OUTER JOIN %s ON (%s.%s=%s)' % ( |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1124
diff
changeset
|
828 |
outertype, self._state.tables[rhstable][1], rid, restrattr, |
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1124
diff
changeset
|
829 |
rhssql) |
0 | 830 |
toreplace.append(rhstable) |
831 |
self.replace_tables_by_outer_join(join, maintable, *toreplace) |
|
832 |
return '' |
|
833 |
||
834 |
def _visit_var_attr_relation(self, relation, rhs_vars): |
|
835 |
"""visit an attribute relation with variable(s) in the RHS |
|
836 |
||
837 |
attribute variables are used either in the selection or for |
|
838 |
unification (eg X attr1 A, Y attr2 A). In case of selection, |
|
839 |
nothing to do here. |
|
840 |
""" |
|
841 |
contextrels = {} |
|
842 |
attrvars = self._state.attr_vars |
|
843 |
for var in rhs_vars: |
|
844 |
try: |
|
845 |
contextrels[var.name] = attrvars[var.name] |
|
846 |
except KeyError: |
|
847 |
attrvars[var.name] = relation |
|
2073
173c646981a7
fix missing from close when using a var map
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
848 |
if var.name in self._varmap: |
173c646981a7
fix missing from close when using a var map
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
849 |
# ensure table is added |
173c646981a7
fix missing from close when using a var map
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
850 |
self._var_info(var.variable) |
0 | 851 |
if not contextrels: |
852 |
relation.children[1].accept(self, contextrels) |
|
853 |
return '' |
|
854 |
# at least one variable is already in attr_vars, this means we have to |
|
855 |
# generate unification expression |
|
856 |
lhssql = self._inlined_var_sql(relation.children[0].variable, |
|
857 |
relation.r_type) |
|
858 |
return '%s%s' % (lhssql, relation.children[1].accept(self, contextrels)) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
859 |
|
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
860 |
def _visit_attribute_relation(self, rel): |
0 | 861 |
"""generate SQL for an attribute relation""" |
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
862 |
lhs, rhs = rel.get_parts() |
0 | 863 |
rhssql = rhs.accept(self) |
864 |
table = self._var_table(lhs.variable) |
|
865 |
if table is None: |
|
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
866 |
assert rel.r_type == 'eid' |
0 | 867 |
lhssql = lhs.accept(self) |
868 |
else: |
|
869 |
try: |
|
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
870 |
lhssql = self._varmap['%s.%s' % (lhs.name, rel.r_type)] |
0 | 871 |
except KeyError: |
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
872 |
mapkey = '%s.%s' % (self._state.solution[lhs.name], rel.r_type) |
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
873 |
if mapkey in self.attr_map: |
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
874 |
lhssql = self.attr_map[mapkey](self, lhs.variable, rel) |
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
875 |
elif rel.r_type == 'eid': |
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1124
diff
changeset
|
876 |
lhssql = lhs.variable._q_sql |
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1124
diff
changeset
|
877 |
else: |
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
878 |
lhssql = '%s.%s%s' % (table, SQL_PREFIX, rel.r_type) |
0 | 879 |
try: |
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
880 |
if rel._q_needcast == 'TODAY': |
0 | 881 |
sql = 'DATE(%s)%s' % (lhssql, rhssql) |
882 |
# XXX which cast function should be used |
|
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
883 |
#elif rel._q_needcast == 'NOW': |
0 | 884 |
# sql = 'TIMESTAMP(%s)%s' % (lhssql, rhssql) |
885 |
else: |
|
886 |
sql = '%s%s' % (lhssql, rhssql) |
|
887 |
except AttributeError: |
|
888 |
sql = '%s%s' % (lhssql, rhssql) |
|
889 |
if lhs.variable.stinfo['optrelations']: |
|
890 |
self.add_outer_join_condition(lhs.variable, table, sql) |
|
891 |
else: |
|
892 |
return sql |
|
893 |
||
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
894 |
def _visit_has_text_relation(self, rel): |
0 | 895 |
"""generate SQL for a has_text relation""" |
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
896 |
lhs, rhs = rel.get_parts() |
0 | 897 |
const = rhs.children[0] |
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
898 |
alias = self._fti_table(rel) |
0 | 899 |
jointo = lhs.accept(self) |
900 |
restriction = '' |
|
901 |
lhsvar = lhs.variable |
|
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
902 |
me_is_principal = lhsvar.stinfo.get('principal') is rel |
0 | 903 |
if me_is_principal: |
904 |
if not lhsvar.stinfo['typerels']: |
|
905 |
# the variable is using the fti table, no join needed |
|
906 |
jointo = None |
|
907 |
elif not lhsvar.name in self._varmap: |
|
908 |
# join on entities instead of etype's table to get result for |
|
909 |
# external entities on multisources configurations |
|
910 |
ealias = lhsvar._q_sqltable = lhsvar.name |
|
911 |
jointo = lhsvar._q_sql = '%s.eid' % ealias |
|
912 |
self.add_table('entities AS %s' % ealias, ealias) |
|
913 |
if not lhsvar._q_invariant or len(lhsvar.stinfo['possibletypes']) == 1: |
|
914 |
restriction = " AND %s.type='%s'" % (ealias, self._state.solution[lhs.name]) |
|
915 |
else: |
|
916 |
etypes = ','.join("'%s'" % etype for etype in lhsvar.stinfo['possibletypes']) |
|
917 |
restriction = " AND %s.type IN (%s)" % (ealias, etypes) |
|
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
918 |
if isinstance(rel.parent, Not): |
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
919 |
self._state.done.add(rel.parent) |
0 | 920 |
not_ = True |
921 |
else: |
|
922 |
not_ = False |
|
923 |
return self.dbms_helper.fti_restriction_sql(alias, const.eval(self._args), |
|
924 |
jointo, not_) + restriction |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
925 |
|
0 | 926 |
def visit_comparison(self, cmp, contextrels=None): |
927 |
"""generate SQL for a comparaison""" |
|
928 |
if len(cmp.children) == 2: |
|
1862
94dc8ccd320b
#343322: should generate IS NULL in sql w/ None values in substitution
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1802
diff
changeset
|
929 |
# XXX occurs ? |
0 | 930 |
lhs, rhs = cmp.children |
931 |
else: |
|
932 |
lhs = None |
|
933 |
rhs = cmp.children[0] |
|
934 |
operator = cmp.operator |
|
935 |
if operator in ('IS', 'LIKE', 'ILIKE'): |
|
936 |
if operator == 'ILIKE' and not self.dbms_helper.ilike_support: |
|
937 |
operator = ' LIKE ' |
|
938 |
else: |
|
939 |
operator = ' %s ' % operator |
|
1862
94dc8ccd320b
#343322: should generate IS NULL in sql w/ None values in substitution
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1802
diff
changeset
|
940 |
elif (operator == '=' and isinstance(rhs, Constant) |
94dc8ccd320b
#343322: should generate IS NULL in sql w/ None values in substitution
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1802
diff
changeset
|
941 |
and rhs.eval(self._args) is None): |
94dc8ccd320b
#343322: should generate IS NULL in sql w/ None values in substitution
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1802
diff
changeset
|
942 |
if lhs is None: |
94dc8ccd320b
#343322: should generate IS NULL in sql w/ None values in substitution
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1802
diff
changeset
|
943 |
return ' IS NULL' |
94dc8ccd320b
#343322: should generate IS NULL in sql w/ None values in substitution
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1802
diff
changeset
|
944 |
return '%s IS NULL' % lhs.accept(self, contextrels) |
0 | 945 |
elif isinstance(rhs, Function) and rhs.name == 'IN': |
946 |
assert operator == '=' |
|
947 |
operator = ' ' |
|
948 |
if lhs is None: |
|
949 |
return '%s%s'% (operator, rhs.accept(self, contextrels)) |
|
950 |
return '%s%s%s'% (lhs.accept(self, contextrels), operator, |
|
951 |
rhs.accept(self, contextrels)) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
952 |
|
0 | 953 |
def visit_mathexpression(self, mexpr, contextrels=None): |
954 |
"""generate SQL for a mathematic expression""" |
|
955 |
lhs, rhs = mexpr.get_parts() |
|
956 |
# check for string concatenation |
|
957 |
operator = mexpr.operator |
|
958 |
try: |
|
959 |
if mexpr.operator == '+' and mexpr.get_type(self._state.solution, self._args) == 'String': |
|
960 |
operator = '||' |
|
961 |
except CoercionError: |
|
962 |
pass |
|
963 |
return '(%s %s %s)'% (lhs.accept(self, contextrels), operator, |
|
964 |
rhs.accept(self, contextrels)) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
965 |
|
0 | 966 |
def visit_function(self, func, contextrels=None): |
967 |
"""generate SQL name for a function""" |
|
968 |
# function_description will check function is supported by the backend |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
969 |
sqlname = self.dbms_helper.func_sqlname(func.name) |
1382
618f6aee8d52
use adbh.func_sqlname for more backend compat
sylvain.thenault@logilab.fr
parents:
1251
diff
changeset
|
970 |
return '%s(%s)' % (sqlname, ', '.join(c.accept(self, contextrels) |
618f6aee8d52
use adbh.func_sqlname for more backend compat
sylvain.thenault@logilab.fr
parents:
1251
diff
changeset
|
971 |
for c in func.children)) |
0 | 972 |
|
973 |
def visit_constant(self, constant, contextrels=None): |
|
974 |
"""generate SQL name for a constant""" |
|
975 |
value = constant.value |
|
976 |
if constant.type is None: |
|
977 |
return 'NULL' |
|
978 |
if constant.type == 'Int' and isinstance(constant.parent, SortTerm): |
|
979 |
return constant.value |
|
980 |
if constant.type in ('Date', 'Datetime'): |
|
981 |
rel = constant.relation() |
|
982 |
if rel is not None: |
|
983 |
rel._q_needcast = value |
|
984 |
return self.keyword_map[value]() |
|
1497
54fc5cc52210
use dbmshelper to generate correct boolean value in rql2sql
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1382
diff
changeset
|
985 |
if constant.type == 'Boolean': |
54fc5cc52210
use dbmshelper to generate correct boolean value in rql2sql
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1382
diff
changeset
|
986 |
value = self.dbms_helper.boolean_value(value) |
0 | 987 |
if constant.type == 'Substitute': |
988 |
_id = constant.value |
|
989 |
if isinstance(_id, unicode): |
|
990 |
_id = _id.encode() |
|
991 |
else: |
|
992 |
_id = str(id(constant)).replace('-', '', 1) |
|
993 |
if isinstance(value, unicode): |
|
994 |
value = value.encode(self.dbencoding) |
|
995 |
self._query_attrs[_id] = value |
|
996 |
return '%%(%s)s' % _id |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
997 |
|
0 | 998 |
def visit_variableref(self, variableref, contextrels=None): |
999 |
"""get the sql name for a variable reference""" |
|
1000 |
# use accept, .variable may be a variable or a columnalias |
|
1001 |
return variableref.variable.accept(self, contextrels) |
|
1002 |
||
1003 |
def visit_columnalias(self, colalias, contextrels=None): |
|
1004 |
"""get the sql name for a subquery column alias""" |
|
1005 |
if colalias.name in self._varmap: |
|
1006 |
sql = self._varmap[colalias.name] |
|
1122
9f37de24251f
fix rql2sq w/ outer join on subquery result
sylvain.thenault@logilab.fr
parents:
438
diff
changeset
|
1007 |
table = sql.split('.', 1)[0] |
9f37de24251f
fix rql2sq w/ outer join on subquery result
sylvain.thenault@logilab.fr
parents:
438
diff
changeset
|
1008 |
colalias._q_sqltable = table |
9f37de24251f
fix rql2sq w/ outer join on subquery result
sylvain.thenault@logilab.fr
parents:
438
diff
changeset
|
1009 |
colalias._q_sql = sql |
9f37de24251f
fix rql2sq w/ outer join on subquery result
sylvain.thenault@logilab.fr
parents:
438
diff
changeset
|
1010 |
self.add_table(table) |
0 | 1011 |
return sql |
1012 |
return colalias._q_sql |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1013 |
|
0 | 1014 |
def visit_variable(self, variable, contextrels=None): |
1015 |
"""get the table name and sql string for a variable""" |
|
1016 |
if contextrels is None and variable.name in self._state.done: |
|
1017 |
if self._in_wrapping_query: |
|
1018 |
return 'T1.%s' % self._state.aliases[variable.name] |
|
1019 |
return variable._q_sql |
|
1020 |
self._state.done.add(variable.name) |
|
1021 |
vtablename = None |
|
1022 |
if contextrels is None and variable.name in self._varmap: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1023 |
sql, vtablename = self._var_info(variable) |
0 | 1024 |
elif variable.stinfo['attrvar']: |
1025 |
# attribute variable (systematically used in rhs of final |
|
1026 |
# relation(s)), get table name and sql from any rhs relation |
|
1027 |
sql = self._linked_var_sql(variable, contextrels) |
|
1028 |
elif variable._q_invariant: |
|
1029 |
# since variable is invariant, we know we won't found final relation |
|
1030 |
principal = variable.stinfo['principal'] |
|
1031 |
if principal is None: |
|
1032 |
vtablename = variable.name |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1124
diff
changeset
|
1033 |
self.add_table('entities AS %s' % vtablename, vtablename) |
0 | 1034 |
sql = '%s.eid' % vtablename |
1035 |
if variable.stinfo['typerels']: |
|
1036 |
# add additional restriction on entities.type column |
|
1037 |
pts = variable.stinfo['possibletypes'] |
|
1038 |
if len(pts) == 1: |
|
1039 |
etype = iter(variable.stinfo['possibletypes']).next() |
|
1040 |
restr = "%s.type='%s'" % (vtablename, etype) |
|
1041 |
else: |
|
1042 |
etypes = ','.join("'%s'" % et for et in pts) |
|
1043 |
restr = '%s.type IN (%s)' % (vtablename, etypes) |
|
1044 |
self._state.add_restriction(restr) |
|
1045 |
elif principal.r_type == 'has_text': |
|
1046 |
sql = '%s.%s' % (self._fti_table(principal), |
|
1047 |
self.dbms_helper.fti_uid_attr) |
|
1048 |
elif principal in variable.stinfo['rhsrelations']: |
|
1049 |
if self.schema.rschema(principal.r_type).inlined: |
|
1050 |
sql = self._linked_var_sql(variable, contextrels) |
|
1051 |
else: |
|
1052 |
sql = '%s.eid_to' % self._relation_table(principal) |
|
1053 |
else: |
|
1054 |
sql = '%s.eid_from' % self._relation_table(principal) |
|
1055 |
else: |
|
1056 |
# standard variable: get table name according to etype and use .eid |
|
1057 |
# attribute |
|
1058 |
sql, vtablename = self._var_info(variable) |
|
1059 |
variable._q_sqltable = vtablename |
|
1060 |
variable._q_sql = sql |
|
1061 |
return sql |
|
1062 |
||
1063 |
# various utilities ####################################################### |
|
1064 |
||
1065 |
def _extra_join_sql(self, relation, sql, var): |
|
1066 |
# if rhs var is invariant, and this relation is not its principal, |
|
1067 |
# generate extra join |
|
1068 |
try: |
|
1069 |
if not var.stinfo['principal'] is relation: |
|
1070 |
# need a predicable result for tests |
|
1071 |
return '%s=%s' % tuple(sorted((sql, var.accept(self)))) |
|
1072 |
except KeyError: |
|
1073 |
# no principal defined, relation is necessarily the principal and |
|
1074 |
# so nothing to return here |
|
1075 |
pass |
|
1076 |
return '' |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1077 |
|
0 | 1078 |
def _var_info(self, var): |
1079 |
# if current var or one of its attribute is selected , it *must* |
|
1080 |
# appear in the toplevel's FROM even if we're currently visiting |
|
1081 |
# a EXISTS node |
|
1082 |
if var.sqlscope is var.stmt: |
|
1083 |
scope = 0 |
|
3238
988a72e59b2b
[querier] fix sql generated w/ NOT relation and shared variable: ensure variable's table is in parent select'scope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2915
diff
changeset
|
1084 |
# don't consider not_scope_offset if the variable is only used in one |
988a72e59b2b
[querier] fix sql generated w/ NOT relation and shared variable: ensure variable's table is in parent select'scope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2915
diff
changeset
|
1085 |
# relation |
988a72e59b2b
[querier] fix sql generated w/ NOT relation and shared variable: ensure variable's table is in parent select'scope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2915
diff
changeset
|
1086 |
elif len(var.stinfo['relations']) > 1: |
988a72e59b2b
[querier] fix sql generated w/ NOT relation and shared variable: ensure variable's table is in parent select'scope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2915
diff
changeset
|
1087 |
scope = -1 - self._not_scope_offset |
0 | 1088 |
else: |
1089 |
scope = -1 |
|
1090 |
try: |
|
1091 |
sql = self._varmap[var.name] |
|
1092 |
table = sql.split('.', 1)[0] |
|
3238
988a72e59b2b
[querier] fix sql generated w/ NOT relation and shared variable: ensure variable's table is in parent select'scope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2915
diff
changeset
|
1093 |
if scope < 0: |
0 | 1094 |
scope = self._varmap_table_scope(var.stmt, table) |
1095 |
self.add_table(table, scope=scope) |
|
1096 |
except KeyError: |
|
1097 |
etype = self._state.solution[var.name] |
|
1098 |
# XXX this check should be moved in rql.stcheck |
|
1099 |
if self.schema.eschema(etype).is_final(): |
|
1100 |
raise BadRQLQuery(var.stmt.root) |
|
1101 |
table = var.name |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1124
diff
changeset
|
1102 |
sql = '%s.%seid' % (table, SQL_PREFIX) |
3245 | 1103 |
self.add_table('%s%s AS %s' % (SQL_PREFIX, etype, table), table, |
1104 |
scope=scope) |
|
0 | 1105 |
return sql, table |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1106 |
|
0 | 1107 |
def _inlined_var_sql(self, var, rtype): |
1108 |
try: |
|
1109 |
sql = self._varmap['%s.%s' % (var.name, rtype)] |
|
1110 |
scope = var.sqlscope is var.stmt and 0 or -1 |
|
1111 |
self.add_table(sql.split('.', 1)[0], scope=scope) |
|
1112 |
except KeyError: |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1124
diff
changeset
|
1113 |
sql = '%s.%s%s' % (self._var_table(var), SQL_PREFIX, rtype) |
0 | 1114 |
#self._state.done.add(var.name) |
1115 |
return sql |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1116 |
|
0 | 1117 |
def _linked_var_sql(self, variable, contextrels=None): |
1118 |
if contextrels is None: |
|
1119 |
try: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1120 |
return self._varmap[variable.name] |
0 | 1121 |
except KeyError: |
1122 |
pass |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1123 |
rel = (contextrels and contextrels.get(variable.name) or |
0 | 1124 |
variable.stinfo.get('principal') or |
1125 |
iter(variable.stinfo['rhsrelations']).next()) |
|
1126 |
linkedvar = rel.children[0].variable |
|
1127 |
if rel.r_type == 'eid': |
|
1128 |
return linkedvar.accept(self) |
|
1129 |
if isinstance(linkedvar, ColumnAlias): |
|
1130 |
raise BadRQLQuery('variable %s should be selected by the subquery' |
|
1131 |
% variable.name) |
|
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
1132 |
mapkey = '%s.%s' % (self._state.solution[linkedvar.name], rel.r_type) |
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
1133 |
if mapkey in self.attr_map: |
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
1134 |
return self.attr_map[mapkey](self, linkedvar, rel) |
0 | 1135 |
try: |
1136 |
sql = self._varmap['%s.%s' % (linkedvar.name, rel.r_type)] |
|
1137 |
except KeyError: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1138 |
linkedvar.accept(self) |
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1124
diff
changeset
|
1139 |
sql = '%s.%s%s' % (linkedvar._q_sqltable, SQL_PREFIX, rel.r_type) |
0 | 1140 |
return sql |
1141 |
||
1142 |
# tables handling ######################################################### |
|
1143 |
||
1144 |
def alias_and_add_table(self, tablename): |
|
1145 |
alias = '%s%s' % (tablename, self._state.count) |
|
1146 |
self._state.count += 1 |
|
1147 |
self.add_table('%s AS %s' % (tablename, alias), alias) |
|
1148 |
return alias |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1149 |
|
0 | 1150 |
def add_table(self, table, key=None, scope=-1): |
1151 |
if key is None: |
|
1152 |
key = table |
|
1153 |
if key in self._state.tables: |
|
1154 |
return |
|
3238
988a72e59b2b
[querier] fix sql generated w/ NOT relation and shared variable: ensure variable's table is in parent select'scope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2915
diff
changeset
|
1155 |
if scope < 0: |
988a72e59b2b
[querier] fix sql generated w/ NOT relation and shared variable: ensure variable's table is in parent select'scope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2915
diff
changeset
|
1156 |
scope = len(self._state.actual_tables) + scope |
2915
651bbe1526b6
[rql2sql] test and fix a bug triggered when editing a ticket in jpl
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2354
diff
changeset
|
1157 |
self._state.tables[key] = (scope, table) |
0 | 1158 |
self._state.actual_tables[scope].append(table) |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1159 |
|
0 | 1160 |
def replace_tables_by_outer_join(self, substitute, lefttable, *tables): |
1161 |
for table in tables: |
|
1162 |
try: |
|
1163 |
scope, alias = self._state.tables[table] |
|
1164 |
self._state.actual_tables[scope].remove(alias) |
|
1165 |
except ValueError: # huum, not sure about what should be done here |
|
1166 |
msg = "%s already used in an outer join, don't know what to do!" |
|
1167 |
raise Exception(msg % table) |
|
1168 |
try: |
|
1169 |
tablealias = self._state.outer_tables[lefttable] |
|
1170 |
actualtables = self._state.actual_tables[-1] |
|
1171 |
except KeyError: |
|
1172 |
tablescope, tablealias = self._state.tables[lefttable] |
|
1173 |
actualtables = self._state.actual_tables[tablescope] |
|
1174 |
outerjoin = '%s %s' % (tablealias, substitute) |
|
1175 |
self._update_outer_tables(lefttable, actualtables, tablealias, outerjoin) |
|
1176 |
for table in tables: |
|
1177 |
self._state.outer_tables[table] = outerjoin |
|
1178 |
||
1179 |
def add_outer_join_condition(self, var, table, condition): |
|
1180 |
try: |
|
1181 |
tablealias = self._state.outer_tables[table] |
|
1182 |
actualtables = self._state.actual_tables[-1] |
|
1183 |
except KeyError: |
|
1184 |
for rel in var.stinfo['optrelations']: |
|
1185 |
self.visit_relation(rel) |
|
1186 |
assert self._state.outer_tables |
|
1187 |
self.add_outer_join_condition(var, table, condition) |
|
1188 |
return |
|
1189 |
before, after = tablealias.split(' AS %s ' % table, 1) |
|
1190 |
beforep, afterp = after.split(')', 1) |
|
1191 |
outerjoin = '%s AS %s %s AND %s) %s' % (before, table, beforep, |
|
1192 |
condition, afterp) |
|
1193 |
self._update_outer_tables(table, actualtables, tablealias, outerjoin) |
|
1194 |
||
1195 |
def _update_outer_tables(self, table, actualtables, oldalias, newalias): |
|
1196 |
actualtables.remove(oldalias) |
|
1197 |
actualtables.append(newalias) |
|
1198 |
# some tables which have already been used as outer table and replaced |
|
1199 |
# by <oldalias> may not be reused here, though their associated value |
|
1200 |
# in the outer_tables dict has to be updated as well |
|
1201 |
for table, outerexpr in self._state.outer_tables.iteritems(): |
|
1202 |
if outerexpr == oldalias: |
|
1203 |
self._state.outer_tables[table] = newalias |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1204 |
self._state.outer_tables[table] = newalias |
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1205 |
|
0 | 1206 |
def _var_table(self, var): |
1207 |
var.accept(self)#.visit_variable(var) |
|
1208 |
return var._q_sqltable |
|
1209 |
||
1210 |
def _relation_table(self, relation): |
|
1211 |
"""return the table alias used by the given relation""" |
|
1212 |
if relation in self._state.done: |
|
1213 |
return relation._q_sqltable |
|
1214 |
assert not self.schema.rschema(relation.r_type).is_final(), relation.r_type |
|
1215 |
rid = 'rel_%s%s' % (relation.r_type, self._state.count) |
|
1216 |
# relation's table is belonging to the root scope if it is the principal |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1217 |
# table of one of it's variable and if that variable belong's to parent |
0 | 1218 |
# scope |
1219 |
for varref in relation.iget_nodes(VariableRef): |
|
1220 |
var = varref.variable |
|
1221 |
if isinstance(var, ColumnAlias): |
|
1222 |
scope = 0 |
|
1223 |
break |
|
1224 |
# XXX may have a principal without being invariant for this generation, |
|
1225 |
# not sure this is a pb or not |
|
1226 |
if var.stinfo.get('principal') is relation and var.sqlscope is var.stmt: |
|
1227 |
scope = 0 |
|
1228 |
break |
|
1229 |
else: |
|
1230 |
scope = -1 |
|
1231 |
self._state.count += 1 |
|
1232 |
self.add_table('%s_relation AS %s' % (relation.r_type, rid), rid, scope=scope) |
|
1233 |
relation._q_sqltable = rid |
|
1234 |
self._state.done.add(relation) |
|
1235 |
return rid |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1236 |
|
0 | 1237 |
def _fti_table(self, relation): |
1238 |
if relation in self._state.done: |
|
1239 |
try: |
|
1240 |
return relation._q_sqltable |
|
1241 |
except AttributeError: |
|
1242 |
pass |
|
1243 |
self._state.done.add(relation) |
|
1244 |
alias = self.alias_and_add_table(self.dbms_helper.fti_table) |
|
1245 |
relation._q_sqltable = alias |
|
1246 |
return alias |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1247 |
|
0 | 1248 |
def _varmap_table_scope(self, select, table): |
1249 |
"""since a varmap table may be used for multiple variable, its scope is |
|
1250 |
the most outer scope of each variables |
|
1251 |
""" |
|
1252 |
scope = -1 |
|
1253 |
for varname, alias in self._varmap.iteritems(): |
|
1254 |
# check '.' in varname since there are 'X.attribute' keys in varmap |
|
1255 |
if not '.' in varname and alias.split('.', 1)[0] == table: |
|
1256 |
if select.defined_vars[varname].sqlscope is select: |
|
1257 |
return 0 |
|
1258 |
return scope |