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