author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Thu, 02 Jul 2009 10:30:44 +0200 | |
branch | stable |
changeset 2233 | bf3603caaf0d |
parent 2199 | bd0a0f219751 |
child 2354 | 9b4bac626977 |
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 |
|
0 | 306 |
def __init__(self, schema, dbms_helper, dbencoding='UTF-8'): |
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() |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
316 |
|
0 | 317 |
def generate(self, union, args=None, varmap=None): |
318 |
"""return SQL queries and a variable dictionnary from a RQL syntax tree |
|
319 |
||
320 |
:partrqls: a list of couple (rqlst, solutions) |
|
321 |
:args: optional dictionary with values of substitutions used in the query |
|
322 |
:varmap: optional dictionary mapping variable name to a special table |
|
323 |
name, in case the query as to fetch data from temporary tables |
|
324 |
||
325 |
return an sql string and a dictionary with substitutions values |
|
326 |
""" |
|
327 |
if args is None: |
|
328 |
args = {} |
|
329 |
if varmap is None: |
|
330 |
varmap = {} |
|
331 |
self._lock.acquire() |
|
332 |
self._args = args |
|
333 |
self._varmap = varmap |
|
334 |
self._query_attrs = {} |
|
335 |
self._state = None |
|
336 |
try: |
|
337 |
# union query for each rqlst / solution |
|
338 |
sql = self.union_sql(union) |
|
339 |
# we are done |
|
340 |
return sql, self._query_attrs |
|
341 |
finally: |
|
342 |
self._lock.release() |
|
343 |
||
344 |
def union_sql(self, union, needalias=False): # pylint: disable-msg=E0202 |
|
345 |
if len(union.children) == 1: |
|
346 |
return self.select_sql(union.children[0], needalias) |
|
347 |
sqls = ('(%s)' % self.select_sql(select, needalias) |
|
348 |
for select in union.children) |
|
349 |
return '\nUNION ALL\n'.join(sqls) |
|
350 |
||
351 |
def noparen_union_sql(self, union, needalias=False): |
|
352 |
# needed for sqlite backend which doesn't like parentheses around |
|
353 |
# union query. This may cause bug in some condition (sort in one of |
|
354 |
# the subquery) but will work in most case |
|
355 |
# see http://www.sqlite.org/cvstrac/tktview?tn=3074 |
|
356 |
sqls = (self.select_sql(select, needalias) |
|
357 |
for i, select in enumerate(union.children)) |
|
358 |
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
|
359 |
|
0 | 360 |
def select_sql(self, select, needalias=False): |
361 |
"""return SQL queries and a variable dictionnary from a RQL syntax tree |
|
362 |
||
363 |
:select: a selection statement of the syntax tree (`rql.stmts.Select`) |
|
364 |
:solution: a dictionnary containing variables binding. |
|
365 |
A solution's dictionnary has variable's names as key and variable's |
|
366 |
types as values |
|
367 |
:needwrap: boolean telling if the query will be wrapped in an outer |
|
368 |
query (to deal with aggregat and/or grouping) |
|
369 |
""" |
|
370 |
distinct = selectsortterms = select.need_distinct |
|
371 |
sorts = select.orderby |
|
372 |
groups = select.groupby |
|
373 |
having = select.having |
|
374 |
# remember selection, it may be changed and have to be restored |
|
375 |
origselection = select.selection[:] |
|
376 |
# check if the query will have union subquery, if it need sort term |
|
377 |
# selection (union or distinct query) and wrapping (union with groups) |
|
378 |
needwrap = False |
|
379 |
sols = select.solutions |
|
380 |
if len(sols) > 1: |
|
381 |
# remove invariant from solutions |
|
382 |
sols, existssols, unstable = remove_unused_solutions( |
|
383 |
select, sols, self._varmap, self.schema) |
|
384 |
if len(sols) > 1: |
|
385 |
# if there is still more than one solution, a UNION will be |
|
386 |
# generated and so sort terms have to be selected |
|
387 |
selectsortterms = True |
|
388 |
# and if select is using group by or aggregat, a wrapping |
|
389 |
# query will be necessary |
|
390 |
if groups or select.has_aggregat: |
|
391 |
select.select_only_variables() |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
392 |
needwrap = True |
0 | 393 |
else: |
394 |
existssols, unstable = {}, () |
|
395 |
state = StateInfo(existssols, unstable) |
|
396 |
# treat subqueries |
|
397 |
self._subqueries_sql(select, state) |
|
398 |
# generate sql for this select node |
|
399 |
selectidx = [str(term) for term in select.selection] |
|
400 |
if needwrap: |
|
401 |
outerselection = origselection[:] |
|
402 |
if sorts and selectsortterms: |
|
403 |
outerselectidx = [str(term) for term in outerselection] |
|
404 |
if distinct: |
|
405 |
sort_term_selection(sorts, outerselectidx, |
|
406 |
outerselection, groups) |
|
407 |
else: |
|
408 |
outerselectidx = selectidx[:] |
|
409 |
fix_selection(select, selectidx, needwrap, |
|
410 |
selectsortterms and sorts, groups, having) |
|
411 |
if needwrap: |
|
412 |
fselectidx = outerselectidx |
|
413 |
fneedwrap = len(outerselection) != len(origselection) |
|
414 |
else: |
|
415 |
fselectidx = selectidx |
|
416 |
fneedwrap = len(select.selection) != len(origselection) |
|
417 |
if fneedwrap: |
|
418 |
needalias = True |
|
419 |
self._in_wrapping_query = False |
|
420 |
self._state = state |
|
421 |
try: |
|
422 |
sql = self._solutions_sql(select, sols, distinct, needalias or needwrap) |
|
423 |
# generate groups / having before wrapping query selection to |
|
424 |
# get correct column aliases |
|
425 |
self._in_wrapping_query = needwrap |
|
426 |
if groups: |
|
427 |
# no constant should be inserted in GROUP BY else the backend will |
|
428 |
# interpret it as a positional index in the selection |
|
429 |
groups = ','.join(vref.accept(self) for vref in groups |
|
430 |
if not isinstance(vref, Constant)) |
|
431 |
if having: |
|
432 |
# filter out constants as for GROUP BY |
|
433 |
having = ','.join(vref.accept(self) for vref in having |
|
434 |
if not isinstance(vref, Constant)) |
|
435 |
if needwrap: |
|
436 |
sql = '%s FROM (%s) AS T1' % (self._selection_sql(outerselection, distinct, |
|
437 |
needalias), |
|
438 |
sql) |
|
439 |
if groups: |
|
440 |
sql += '\nGROUP BY %s' % groups |
|
441 |
if having: |
|
442 |
sql += '\nHAVING %s' % having |
|
443 |
# sort |
|
444 |
if sorts: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
445 |
sql += '\nORDER BY %s' % ','.join(self._sortterm_sql(sortterm, |
0 | 446 |
fselectidx) |
447 |
for sortterm in sorts) |
|
448 |
if fneedwrap: |
|
449 |
selection = ['T1.C%s' % i for i in xrange(len(origselection))] |
|
450 |
sql = 'SELECT %s FROM (%s) AS T1' % (','.join(selection), sql) |
|
451 |
finally: |
|
452 |
select.selection = origselection |
|
453 |
# limit / offset |
|
454 |
limit = select.limit |
|
455 |
if limit: |
|
456 |
sql += '\nLIMIT %s' % limit |
|
457 |
offset = select.offset |
|
458 |
if offset: |
|
459 |
sql += '\nOFFSET %s' % offset |
|
460 |
return sql |
|
461 |
||
462 |
def _subqueries_sql(self, select, state): |
|
463 |
for i, subquery in enumerate(select.with_): |
|
464 |
sql = self.union_sql(subquery.query, needalias=True) |
|
465 |
tablealias = '_T%s' % i |
|
466 |
sql = '(%s) AS %s' % (sql, tablealias) |
|
467 |
state.subtables[tablealias] = (0, sql) |
|
468 |
for vref in subquery.aliases: |
|
469 |
alias = vref.variable |
|
470 |
alias._q_sqltable = tablealias |
|
471 |
alias._q_sql = '%s.C%s' % (tablealias, alias.colnum) |
|
472 |
||
473 |
def _solutions_sql(self, select, solutions, distinct, needalias): |
|
474 |
sqls = [] |
|
475 |
for solution in solutions: |
|
476 |
self._state.reset(solution) |
|
477 |
# visit restriction subtree |
|
478 |
if select.where is not None: |
|
479 |
self._state.add_restriction(select.where.accept(self)) |
|
480 |
sql = [self._selection_sql(select.selection, distinct, needalias)] |
|
481 |
if self._state.restrictions: |
|
482 |
sql.append('WHERE %s' % ' AND '.join(self._state.restrictions)) |
|
483 |
# add required tables |
|
484 |
assert len(self._state.actual_tables) == 1, self._state.actual_tables |
|
485 |
tables = self._state.actual_tables[-1] |
|
486 |
if tables: |
|
487 |
# sort for test predictability |
|
488 |
sql.insert(1, 'FROM %s' % ', '.join(sorted(tables))) |
|
489 |
elif self._state.restrictions and self.dbms_helper.needs_from_clause: |
|
490 |
sql.insert(1, 'FROM (SELECT 1) AS _T') |
|
491 |
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
|
492 |
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
|
493 |
#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
|
494 |
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
|
495 |
#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
|
496 |
# 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
|
497 |
elif distinct: |
0 | 498 |
return '\nUNION\n'.join(sqls) |
499 |
else: |
|
500 |
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
|
501 |
|
0 | 502 |
def _selection_sql(self, selected, distinct, needaliasing=False): |
503 |
clause = [] |
|
504 |
for term in selected: |
|
505 |
sql = term.accept(self) |
|
506 |
if needaliasing: |
|
507 |
colalias = 'C%s' % len(clause) |
|
508 |
clause.append('%s AS %s' % (sql, colalias)) |
|
509 |
if isinstance(term, VariableRef): |
|
510 |
self._state.aliases[term.name] = colalias |
|
511 |
else: |
|
512 |
clause.append(sql) |
|
513 |
if distinct: |
|
514 |
return 'SELECT DISTINCT %s' % ', '.join(clause) |
|
515 |
return 'SELECT %s' % ', '.join(clause) |
|
516 |
||
517 |
def _sortterm_sql(self, sortterm, selectidx): |
|
518 |
term = sortterm.term |
|
519 |
try: |
|
520 |
sqlterm = str(selectidx.index(str(term)) + 1) |
|
521 |
except ValueError: |
|
522 |
# Constant node or non selected term |
|
523 |
sqlterm = str(term.accept(self)) |
|
524 |
if sortterm.asc: |
|
525 |
return sqlterm |
|
526 |
else: |
|
527 |
return '%s DESC' % sqlterm |
|
528 |
||
529 |
def visit_and(self, et): |
|
530 |
"""generate SQL for a AND subtree""" |
|
531 |
res = [] |
|
532 |
for c in et.children: |
|
533 |
part = c.accept(self) |
|
534 |
if part: |
|
535 |
res.append(part) |
|
536 |
return ' AND '.join(res) |
|
537 |
||
538 |
def visit_or(self, ou): |
|
539 |
"""generate SQL for a OR subtree""" |
|
540 |
res = [] |
|
541 |
for c in ou.children: |
|
542 |
part = c.accept(self) |
|
543 |
if part: |
|
544 |
res.append('(%s)' % part) |
|
545 |
if res: |
|
546 |
if len(res) > 1: |
|
547 |
return '(%s)' % ' OR '.join(res) |
|
548 |
return res[0] |
|
549 |
return '' |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
550 |
|
0 | 551 |
def visit_not(self, node): |
552 |
self._state.push_scope() |
|
553 |
csql = node.children[0].accept(self) |
|
554 |
sqls, tables = self._state.pop_scope() |
|
555 |
if node in self._state.done or not csql: |
|
556 |
# already processed or no sql generated by children |
|
557 |
self._state.actual_tables[-1] += tables |
|
558 |
self._state.restrictions += sqls |
|
559 |
return csql |
|
560 |
if isinstance(node.children[0], Exists): |
|
561 |
assert not sqls, (sqls, str(node.stmt)) |
|
562 |
assert not tables, (tables, str(node.stmt)) |
|
563 |
return 'NOT %s' % csql |
|
564 |
sqls.append(csql) |
|
565 |
if tables: |
|
566 |
select = 'SELECT 1 FROM %s' % ','.join(tables) |
|
567 |
else: |
|
568 |
select = 'SELECT 1' |
|
569 |
if sqls: |
|
570 |
sql = 'NOT EXISTS(%s WHERE %s)' % (select, ' AND '.join(sqls)) |
|
571 |
else: |
|
572 |
sql = 'NOT EXISTS(%s)' % select |
|
573 |
return sql |
|
574 |
||
575 |
def visit_exists(self, exists): |
|
576 |
"""generate SQL name for a exists subquery""" |
|
577 |
sqls = [] |
|
578 |
for dummy in self._state.iter_exists_sols(exists): |
|
579 |
sql = self._visit_exists(exists) |
|
580 |
if sql: |
|
581 |
sqls.append(sql) |
|
582 |
if not sqls: |
|
583 |
return '' |
|
584 |
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
|
585 |
|
0 | 586 |
def _visit_exists(self, exists): |
587 |
self._state.push_scope() |
|
588 |
restriction = exists.children[0].accept(self) |
|
589 |
restrictions, tables = self._state.pop_scope() |
|
590 |
if restriction: |
|
591 |
restrictions.append(restriction) |
|
592 |
restriction = ' AND '.join(restrictions) |
|
593 |
if not restriction: |
|
594 |
return '' |
|
595 |
if not tables: |
|
596 |
# 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
|
597 |
sql = 'SELECT 1 WHERE %s' % restriction |
0 | 598 |
else: |
599 |
sql = 'SELECT 1 FROM %s WHERE %s' % (', '.join(tables), restriction) |
|
600 |
return sql |
|
601 |
||
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
602 |
|
0 | 603 |
def visit_relation(self, relation): |
604 |
"""generate SQL for a relation""" |
|
605 |
rtype = relation.r_type |
|
606 |
# don't care of type constraint statement (i.e. relation_type = 'is') |
|
607 |
if relation.is_types_restriction(): |
|
608 |
return '' |
|
609 |
lhs, rhs = relation.get_parts() |
|
610 |
rschema = self.schema.rschema(rtype) |
|
611 |
if rschema.is_final(): |
|
612 |
if rtype == 'eid' and lhs.variable._q_invariant and \ |
|
613 |
lhs.variable.stinfo['constnode']: |
|
614 |
# special case where this restriction is already generated by |
|
615 |
# some other relation |
|
616 |
return '' |
|
617 |
# attribute relation |
|
618 |
if rtype == 'has_text': |
|
619 |
sql = self._visit_has_text_relation(relation) |
|
620 |
else: |
|
621 |
rhs_vars = rhs.get_nodes(VariableRef) |
|
622 |
if rhs_vars: |
|
623 |
# if variable(s) in the RHS |
|
624 |
sql = self._visit_var_attr_relation(relation, rhs_vars) |
|
625 |
else: |
|
626 |
# no variables in the RHS |
|
627 |
sql = self._visit_attribute_relation(relation) |
|
628 |
if relation.neged(strict=True): |
|
629 |
self._state.done.add(relation.parent) |
|
630 |
sql = 'NOT (%s)' % sql |
|
631 |
else: |
|
632 |
if rtype == 'is' and rhs.operator == 'IS': |
|
633 |
# special case "C is NULL" |
|
634 |
if lhs.name in self._varmap: |
|
635 |
lhssql = self._varmap[lhs.name] |
|
636 |
else: |
|
637 |
lhssql = lhs.accept(self) |
|
638 |
return '%s%s' % (lhssql, rhs.accept(self)) |
|
639 |
if '%s.%s' % (lhs, relation.r_type) in self._varmap: |
|
640 |
# relation has already been processed by a previous step |
|
641 |
return |
|
642 |
if relation.optional: |
|
643 |
# check it has not already been treaten (to get necessary |
|
644 |
# information to add an outer join condition) |
|
645 |
if relation in self._state.done: |
|
646 |
return |
|
647 |
# OPTIONAL relation, generate a left|right outer join |
|
648 |
sql = self._visit_outer_join_relation(relation, rschema) |
|
649 |
elif rschema.inlined: |
|
650 |
sql = self._visit_inlined_relation(relation) |
|
651 |
# elif isinstance(relation.parent, Not): |
|
652 |
# self._state.done.add(relation.parent) |
|
653 |
# # NOT relation |
|
654 |
# sql = self._visit_not_relation(relation, rschema) |
|
655 |
else: |
|
656 |
# regular (non final) relation |
|
657 |
sql = self._visit_relation(relation, rschema) |
|
658 |
return sql |
|
659 |
||
660 |
def _visit_inlined_relation(self, relation): |
|
661 |
lhsvar, _, rhsvar, rhsconst = relation_info(relation) |
|
662 |
# we are sure here to have a lhsvar |
|
663 |
assert lhsvar is not None |
|
664 |
if isinstance(relation.parent, Not): |
|
665 |
self._state.done.add(relation.parent) |
|
666 |
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
|
667 |
# 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
|
668 |
# 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
|
669 |
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
|
670 |
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
|
671 |
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
|
672 |
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
|
673 |
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
|
674 |
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
|
675 |
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
|
676 |
' 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
|
677 |
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
|
678 |
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
|
679 |
', '.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
|
680 |
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
|
681 |
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
|
682 |
sql = '%s IS NULL' % self._inlined_var_sql(lhsvar, relation.r_type) |
0 | 683 |
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
|
684 |
lhssql = self._inlined_var_sql(lhsvar, relation.r_type) |
0 | 685 |
if rhsconst is not None: |
686 |
return '%s=%s' % (lhssql, rhsconst.accept(self)) |
|
687 |
if isinstance(rhsvar, Variable) and not rhsvar.name in self._varmap: |
|
688 |
# if the rhs variable is only linked to this relation, this mean we |
|
689 |
# only want the relation to exists, eg NOT NULL in case of inlined |
|
690 |
# relation |
|
691 |
if len(rhsvar.stinfo['relations']) == 1 and rhsvar._q_invariant: |
|
692 |
return '%s IS NOT NULL' % lhssql |
|
693 |
if rhsvar._q_invariant: |
|
694 |
return self._extra_join_sql(relation, lhssql, rhsvar) |
|
695 |
return '%s=%s' % (lhssql, rhsvar.accept(self)) |
|
696 |
||
697 |
def _process_relation_term(self, relation, rid, termvar, termconst, relfield): |
|
698 |
if termconst or isinstance(termvar, ColumnAlias) or not termvar._q_invariant: |
|
699 |
termsql = termconst and termconst.accept(self) or termvar.accept(self) |
|
700 |
yield '%s.%s=%s' % (rid, relfield, termsql) |
|
701 |
elif termvar._q_invariant: |
|
702 |
# if the variable is mapped, generate restriction anyway |
|
703 |
if termvar.name in self._varmap: |
|
704 |
termsql = termvar.accept(self) |
|
705 |
yield '%s.%s=%s' % (rid, relfield, termsql) |
|
706 |
extrajoin = self._extra_join_sql(relation, '%s.%s' % (rid, relfield), termvar) |
|
707 |
if extrajoin: |
|
708 |
yield extrajoin |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
709 |
|
0 | 710 |
def _visit_relation(self, relation, rschema): |
711 |
"""generate SQL for a relation |
|
712 |
||
713 |
implements optimization 1. |
|
714 |
""" |
|
715 |
if relation.r_type == 'identity': |
|
716 |
# special case "X identity Y" |
|
717 |
lhs, rhs = relation.get_parts() |
|
718 |
if isinstance(relation.parent, Not): |
|
719 |
self._state.done.add(relation.parent) |
|
720 |
return 'NOT %s%s' % (lhs.accept(self), rhs.accept(self)) |
|
721 |
return '%s%s' % (lhs.accept(self), rhs.accept(self)) |
|
722 |
lhsvar, lhsconst, rhsvar, rhsconst = relation_info(relation) |
|
723 |
rid = self._relation_table(relation) |
|
724 |
sqls = [] |
|
725 |
sqls += self._process_relation_term(relation, rid, lhsvar, lhsconst, 'eid_from') |
|
726 |
sqls += self._process_relation_term(relation, rid, rhsvar, rhsconst, 'eid_to') |
|
727 |
sql = ' AND '.join(sqls) |
|
728 |
if rschema.symetric: |
|
729 |
sql = '(%s OR %s)' % (sql, switch_relation_field(sql)) |
|
730 |
return sql |
|
731 |
||
732 |
def _visit_outer_join_relation(self, relation, rschema): |
|
733 |
""" |
|
734 |
left outer join syntax (optional=='right'): |
|
735 |
X relation Y? |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
736 |
|
0 | 737 |
right outer join syntax (optional=='left'): |
738 |
X? relation Y |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
739 |
|
0 | 740 |
full outer join syntaxes (optional=='both'): |
741 |
X? relation Y? |
|
742 |
||
743 |
if relation is inlined: |
|
744 |
if it's a left outer join: |
|
745 |
-> X LEFT OUTER JOIN Y ON (X.relation=Y.eid) |
|
746 |
elif it's a right outer join: |
|
747 |
-> Y LEFT OUTER JOIN X ON (X.relation=Y.eid) |
|
748 |
elif it's a full outer join: |
|
749 |
-> X FULL OUTER JOIN Y ON (X.relation=Y.eid) |
|
750 |
else: |
|
751 |
if it's a left outer join: |
|
752 |
-> X LEFT OUTER JOIN relation ON (relation.eid_from=X.eid) |
|
753 |
LEFT OUTER JOIN Y ON (relation.eid_to=Y.eid) |
|
754 |
elif it's a right outer join: |
|
755 |
-> Y LEFT OUTER JOIN relation ON (relation.eid_to=Y.eid) |
|
756 |
LEFT OUTER JOIN X ON (relation.eid_from=X.eid) |
|
757 |
elif it's a full outer join: |
|
758 |
-> X FULL OUTER JOIN Y ON (X.relation=Y.eid) |
|
759 |
""" |
|
760 |
lhsvar, lhsconst, rhsvar, rhsconst = relation_info(relation) |
|
761 |
if relation.optional == 'right': |
|
762 |
joinattr, restrattr = 'eid_from', 'eid_to' |
|
763 |
else: |
|
764 |
lhsvar, rhsvar = rhsvar, lhsvar |
|
765 |
lhsconst, rhsconst = rhsconst, lhsconst |
|
766 |
joinattr, restrattr = 'eid_to', 'eid_from' |
|
767 |
if relation.optional == 'both': |
|
768 |
outertype = 'FULL' |
|
769 |
else: |
|
770 |
outertype = 'LEFT' |
|
771 |
if rschema.inlined or relation.r_type == 'identity': |
|
772 |
self._state.done.add(relation) |
|
773 |
t1 = self._var_table(lhsvar) |
|
774 |
if relation.r_type == 'identity': |
|
775 |
attr = 'eid' |
|
776 |
else: |
|
777 |
attr = relation.r_type |
|
778 |
# reset lhs/rhs, we need the initial order now |
|
779 |
lhs, rhs = relation.get_variable_parts() |
|
780 |
if '%s.%s' % (lhs.name, attr) in self._varmap: |
|
781 |
lhssql = self._varmap['%s.%s' % (lhs.name, attr)] |
|
782 |
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
|
783 |
lhssql = '%s.%s%s' % (self._var_table(lhs.variable), SQL_PREFIX, attr) |
0 | 784 |
if not rhsvar is None: |
785 |
t2 = self._var_table(rhsvar) |
|
786 |
if t2 is None: |
|
787 |
if rhsconst is not None: |
|
788 |
# inlined relation with invariant as rhs |
|
789 |
condition = '%s=%s' % (lhssql, rhsconst.accept(self)) |
|
790 |
if relation.r_type != 'identity': |
|
791 |
condition = '(%s OR %s IS NULL)' % (condition, lhssql) |
|
792 |
if not lhsvar.stinfo['optrelations']: |
|
793 |
return condition |
|
794 |
self.add_outer_join_condition(lhsvar, t1, condition) |
|
795 |
return |
|
796 |
else: |
|
797 |
condition = '%s=%s' % (lhssql, rhsconst.accept(self)) |
|
798 |
self.add_outer_join_condition(lhsvar, t1, condition) |
|
799 |
join = '%s OUTER JOIN %s ON (%s=%s)' % ( |
|
800 |
outertype, self._state.tables[t2][1], lhssql, rhs.accept(self)) |
|
801 |
self.replace_tables_by_outer_join(join, t1, t2) |
|
802 |
return '' |
|
803 |
lhssql = lhsconst and lhsconst.accept(self) or lhsvar.accept(self) |
|
804 |
rhssql = rhsconst and rhsconst.accept(self) or rhsvar.accept(self) |
|
805 |
rid = self._relation_table(relation) |
|
806 |
if not lhsvar: |
|
807 |
join = '' |
|
808 |
toreplace = [] |
|
809 |
maintable = rid |
|
810 |
else: |
|
811 |
join = '%s OUTER JOIN %s ON (%s.%s=%s' % ( |
|
812 |
outertype, self._state.tables[rid][1], rid, joinattr, lhssql) |
|
813 |
toreplace = [rid] |
|
814 |
maintable = self._var_table(lhsvar) |
|
815 |
if rhsconst: |
|
816 |
join += ' AND %s.%s=%s)' % (rid, restrattr, rhssql) |
|
817 |
else: |
|
818 |
join += ')' |
|
819 |
if not rhsconst: |
|
1122
9f37de24251f
fix rql2sq w/ outer join on subquery result
sylvain.thenault@logilab.fr
parents:
438
diff
changeset
|
820 |
rhstable = rhsvar._q_sqltable |
0 | 821 |
if rhstable: |
822 |
assert rhstable is not None, rhsvar |
|
823 |
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
|
824 |
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
|
825 |
rhssql) |
0 | 826 |
toreplace.append(rhstable) |
827 |
self.replace_tables_by_outer_join(join, maintable, *toreplace) |
|
828 |
return '' |
|
829 |
||
830 |
def _visit_var_attr_relation(self, relation, rhs_vars): |
|
831 |
"""visit an attribute relation with variable(s) in the RHS |
|
832 |
||
833 |
attribute variables are used either in the selection or for |
|
834 |
unification (eg X attr1 A, Y attr2 A). In case of selection, |
|
835 |
nothing to do here. |
|
836 |
""" |
|
837 |
contextrels = {} |
|
838 |
attrvars = self._state.attr_vars |
|
839 |
for var in rhs_vars: |
|
840 |
try: |
|
841 |
contextrels[var.name] = attrvars[var.name] |
|
842 |
except KeyError: |
|
843 |
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
|
844 |
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
|
845 |
# 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
|
846 |
self._var_info(var.variable) |
0 | 847 |
if not contextrels: |
848 |
relation.children[1].accept(self, contextrels) |
|
849 |
return '' |
|
850 |
# at least one variable is already in attr_vars, this means we have to |
|
851 |
# generate unification expression |
|
852 |
lhssql = self._inlined_var_sql(relation.children[0].variable, |
|
853 |
relation.r_type) |
|
854 |
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
|
855 |
|
0 | 856 |
def _visit_attribute_relation(self, relation): |
857 |
"""generate SQL for an attribute relation""" |
|
858 |
lhs, rhs = relation.get_parts() |
|
859 |
rhssql = rhs.accept(self) |
|
860 |
table = self._var_table(lhs.variable) |
|
861 |
if table is None: |
|
862 |
assert relation.r_type == 'eid' |
|
863 |
lhssql = lhs.accept(self) |
|
864 |
else: |
|
865 |
try: |
|
866 |
lhssql = self._varmap['%s.%s' % (lhs.name, relation.r_type)] |
|
867 |
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
|
868 |
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
|
869 |
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
|
870 |
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
|
871 |
lhssql = '%s.%s%s' % (table, SQL_PREFIX, relation.r_type) |
0 | 872 |
try: |
873 |
if relation._q_needcast == 'TODAY': |
|
874 |
sql = 'DATE(%s)%s' % (lhssql, rhssql) |
|
875 |
# XXX which cast function should be used |
|
876 |
#elif relation._q_needcast == 'NOW': |
|
877 |
# sql = 'TIMESTAMP(%s)%s' % (lhssql, rhssql) |
|
878 |
else: |
|
879 |
sql = '%s%s' % (lhssql, rhssql) |
|
880 |
except AttributeError: |
|
881 |
sql = '%s%s' % (lhssql, rhssql) |
|
882 |
if lhs.variable.stinfo['optrelations']: |
|
883 |
self.add_outer_join_condition(lhs.variable, table, sql) |
|
884 |
else: |
|
885 |
return sql |
|
886 |
||
887 |
def _visit_has_text_relation(self, relation): |
|
888 |
"""generate SQL for a has_text relation""" |
|
889 |
lhs, rhs = relation.get_parts() |
|
890 |
const = rhs.children[0] |
|
891 |
alias = self._fti_table(relation) |
|
892 |
jointo = lhs.accept(self) |
|
893 |
restriction = '' |
|
894 |
lhsvar = lhs.variable |
|
895 |
me_is_principal = lhsvar.stinfo.get('principal') is relation |
|
896 |
if me_is_principal: |
|
897 |
if not lhsvar.stinfo['typerels']: |
|
898 |
# the variable is using the fti table, no join needed |
|
899 |
jointo = None |
|
900 |
elif not lhsvar.name in self._varmap: |
|
901 |
# join on entities instead of etype's table to get result for |
|
902 |
# external entities on multisources configurations |
|
903 |
ealias = lhsvar._q_sqltable = lhsvar.name |
|
904 |
jointo = lhsvar._q_sql = '%s.eid' % ealias |
|
905 |
self.add_table('entities AS %s' % ealias, ealias) |
|
906 |
if not lhsvar._q_invariant or len(lhsvar.stinfo['possibletypes']) == 1: |
|
907 |
restriction = " AND %s.type='%s'" % (ealias, self._state.solution[lhs.name]) |
|
908 |
else: |
|
909 |
etypes = ','.join("'%s'" % etype for etype in lhsvar.stinfo['possibletypes']) |
|
910 |
restriction = " AND %s.type IN (%s)" % (ealias, etypes) |
|
911 |
if isinstance(relation.parent, Not): |
|
912 |
self._state.done.add(relation.parent) |
|
913 |
not_ = True |
|
914 |
else: |
|
915 |
not_ = False |
|
916 |
return self.dbms_helper.fti_restriction_sql(alias, const.eval(self._args), |
|
917 |
jointo, not_) + restriction |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
918 |
|
0 | 919 |
def visit_comparison(self, cmp, contextrels=None): |
920 |
"""generate SQL for a comparaison""" |
|
921 |
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
|
922 |
# XXX occurs ? |
0 | 923 |
lhs, rhs = cmp.children |
924 |
else: |
|
925 |
lhs = None |
|
926 |
rhs = cmp.children[0] |
|
927 |
operator = cmp.operator |
|
928 |
if operator in ('IS', 'LIKE', 'ILIKE'): |
|
929 |
if operator == 'ILIKE' and not self.dbms_helper.ilike_support: |
|
930 |
operator = ' LIKE ' |
|
931 |
else: |
|
932 |
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
|
933 |
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
|
934 |
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
|
935 |
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
|
936 |
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
|
937 |
return '%s IS NULL' % lhs.accept(self, contextrels) |
0 | 938 |
elif isinstance(rhs, Function) and rhs.name == 'IN': |
939 |
assert operator == '=' |
|
940 |
operator = ' ' |
|
941 |
if lhs is None: |
|
942 |
return '%s%s'% (operator, rhs.accept(self, contextrels)) |
|
943 |
return '%s%s%s'% (lhs.accept(self, contextrels), operator, |
|
944 |
rhs.accept(self, contextrels)) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
945 |
|
0 | 946 |
def visit_mathexpression(self, mexpr, contextrels=None): |
947 |
"""generate SQL for a mathematic expression""" |
|
948 |
lhs, rhs = mexpr.get_parts() |
|
949 |
# check for string concatenation |
|
950 |
operator = mexpr.operator |
|
951 |
try: |
|
952 |
if mexpr.operator == '+' and mexpr.get_type(self._state.solution, self._args) == 'String': |
|
953 |
operator = '||' |
|
954 |
except CoercionError: |
|
955 |
pass |
|
956 |
return '(%s %s %s)'% (lhs.accept(self, contextrels), operator, |
|
957 |
rhs.accept(self, contextrels)) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
958 |
|
0 | 959 |
def visit_function(self, func, contextrels=None): |
960 |
"""generate SQL name for a function""" |
|
961 |
# 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
|
962 |
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
|
963 |
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
|
964 |
for c in func.children)) |
0 | 965 |
|
966 |
def visit_constant(self, constant, contextrels=None): |
|
967 |
"""generate SQL name for a constant""" |
|
968 |
value = constant.value |
|
969 |
if constant.type is None: |
|
970 |
return 'NULL' |
|
971 |
if constant.type == 'Int' and isinstance(constant.parent, SortTerm): |
|
972 |
return constant.value |
|
973 |
if constant.type in ('Date', 'Datetime'): |
|
974 |
rel = constant.relation() |
|
975 |
if rel is not None: |
|
976 |
rel._q_needcast = value |
|
977 |
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
|
978 |
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
|
979 |
value = self.dbms_helper.boolean_value(value) |
0 | 980 |
if constant.type == 'Substitute': |
981 |
_id = constant.value |
|
982 |
if isinstance(_id, unicode): |
|
983 |
_id = _id.encode() |
|
984 |
else: |
|
985 |
_id = str(id(constant)).replace('-', '', 1) |
|
986 |
if isinstance(value, unicode): |
|
987 |
value = value.encode(self.dbencoding) |
|
988 |
self._query_attrs[_id] = value |
|
989 |
return '%%(%s)s' % _id |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
990 |
|
0 | 991 |
def visit_variableref(self, variableref, contextrels=None): |
992 |
"""get the sql name for a variable reference""" |
|
993 |
# use accept, .variable may be a variable or a columnalias |
|
994 |
return variableref.variable.accept(self, contextrels) |
|
995 |
||
996 |
def visit_columnalias(self, colalias, contextrels=None): |
|
997 |
"""get the sql name for a subquery column alias""" |
|
998 |
if colalias.name in self._varmap: |
|
999 |
sql = self._varmap[colalias.name] |
|
1122
9f37de24251f
fix rql2sq w/ outer join on subquery result
sylvain.thenault@logilab.fr
parents:
438
diff
changeset
|
1000 |
table = sql.split('.', 1)[0] |
9f37de24251f
fix rql2sq w/ outer join on subquery result
sylvain.thenault@logilab.fr
parents:
438
diff
changeset
|
1001 |
colalias._q_sqltable = table |
9f37de24251f
fix rql2sq w/ outer join on subquery result
sylvain.thenault@logilab.fr
parents:
438
diff
changeset
|
1002 |
colalias._q_sql = sql |
9f37de24251f
fix rql2sq w/ outer join on subquery result
sylvain.thenault@logilab.fr
parents:
438
diff
changeset
|
1003 |
self.add_table(table) |
0 | 1004 |
return sql |
1005 |
return colalias._q_sql |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1006 |
|
0 | 1007 |
def visit_variable(self, variable, contextrels=None): |
1008 |
"""get the table name and sql string for a variable""" |
|
1009 |
if contextrels is None and variable.name in self._state.done: |
|
1010 |
if self._in_wrapping_query: |
|
1011 |
return 'T1.%s' % self._state.aliases[variable.name] |
|
1012 |
return variable._q_sql |
|
1013 |
self._state.done.add(variable.name) |
|
1014 |
vtablename = None |
|
1015 |
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
|
1016 |
sql, vtablename = self._var_info(variable) |
0 | 1017 |
elif variable.stinfo['attrvar']: |
1018 |
# attribute variable (systematically used in rhs of final |
|
1019 |
# relation(s)), get table name and sql from any rhs relation |
|
1020 |
sql = self._linked_var_sql(variable, contextrels) |
|
1021 |
elif variable._q_invariant: |
|
1022 |
# since variable is invariant, we know we won't found final relation |
|
1023 |
principal = variable.stinfo['principal'] |
|
1024 |
if principal is None: |
|
1025 |
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
|
1026 |
self.add_table('entities AS %s' % vtablename, vtablename) |
0 | 1027 |
sql = '%s.eid' % vtablename |
1028 |
if variable.stinfo['typerels']: |
|
1029 |
# add additional restriction on entities.type column |
|
1030 |
pts = variable.stinfo['possibletypes'] |
|
1031 |
if len(pts) == 1: |
|
1032 |
etype = iter(variable.stinfo['possibletypes']).next() |
|
1033 |
restr = "%s.type='%s'" % (vtablename, etype) |
|
1034 |
else: |
|
1035 |
etypes = ','.join("'%s'" % et for et in pts) |
|
1036 |
restr = '%s.type IN (%s)' % (vtablename, etypes) |
|
1037 |
self._state.add_restriction(restr) |
|
1038 |
elif principal.r_type == 'has_text': |
|
1039 |
sql = '%s.%s' % (self._fti_table(principal), |
|
1040 |
self.dbms_helper.fti_uid_attr) |
|
1041 |
elif principal in variable.stinfo['rhsrelations']: |
|
1042 |
if self.schema.rschema(principal.r_type).inlined: |
|
1043 |
sql = self._linked_var_sql(variable, contextrels) |
|
1044 |
else: |
|
1045 |
sql = '%s.eid_to' % self._relation_table(principal) |
|
1046 |
else: |
|
1047 |
sql = '%s.eid_from' % self._relation_table(principal) |
|
1048 |
else: |
|
1049 |
# standard variable: get table name according to etype and use .eid |
|
1050 |
# attribute |
|
1051 |
sql, vtablename = self._var_info(variable) |
|
1052 |
variable._q_sqltable = vtablename |
|
1053 |
variable._q_sql = sql |
|
1054 |
return sql |
|
1055 |
||
1056 |
# various utilities ####################################################### |
|
1057 |
||
1058 |
def _extra_join_sql(self, relation, sql, var): |
|
1059 |
# if rhs var is invariant, and this relation is not its principal, |
|
1060 |
# generate extra join |
|
1061 |
try: |
|
1062 |
if not var.stinfo['principal'] is relation: |
|
1063 |
# need a predicable result for tests |
|
1064 |
return '%s=%s' % tuple(sorted((sql, var.accept(self)))) |
|
1065 |
except KeyError: |
|
1066 |
# no principal defined, relation is necessarily the principal and |
|
1067 |
# so nothing to return here |
|
1068 |
pass |
|
1069 |
return '' |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1070 |
|
0 | 1071 |
def _var_info(self, var): |
1072 |
# if current var or one of its attribute is selected , it *must* |
|
1073 |
# appear in the toplevel's FROM even if we're currently visiting |
|
1074 |
# a EXISTS node |
|
1075 |
if var.sqlscope is var.stmt: |
|
1076 |
scope = 0 |
|
1077 |
else: |
|
1078 |
scope = -1 |
|
1079 |
try: |
|
1080 |
sql = self._varmap[var.name] |
|
1081 |
table = sql.split('.', 1)[0] |
|
1082 |
if scope == -1: |
|
1083 |
scope = self._varmap_table_scope(var.stmt, table) |
|
1084 |
self.add_table(table, scope=scope) |
|
1085 |
except KeyError: |
|
1086 |
etype = self._state.solution[var.name] |
|
1087 |
# XXX this check should be moved in rql.stcheck |
|
1088 |
if self.schema.eschema(etype).is_final(): |
|
1089 |
raise BadRQLQuery(var.stmt.root) |
|
1090 |
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
|
1091 |
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
|
1092 |
self.add_table('%s%s AS %s' % (SQL_PREFIX, etype, table), table, scope=scope) |
0 | 1093 |
return sql, table |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1094 |
|
0 | 1095 |
def _inlined_var_sql(self, var, rtype): |
1096 |
try: |
|
1097 |
sql = self._varmap['%s.%s' % (var.name, rtype)] |
|
1098 |
scope = var.sqlscope is var.stmt and 0 or -1 |
|
1099 |
self.add_table(sql.split('.', 1)[0], scope=scope) |
|
1100 |
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
|
1101 |
sql = '%s.%s%s' % (self._var_table(var), SQL_PREFIX, rtype) |
0 | 1102 |
#self._state.done.add(var.name) |
1103 |
return sql |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1104 |
|
0 | 1105 |
def _linked_var_sql(self, variable, contextrels=None): |
1106 |
if contextrels is None: |
|
1107 |
try: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1108 |
return self._varmap[variable.name] |
0 | 1109 |
except KeyError: |
1110 |
pass |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1111 |
rel = (contextrels and contextrels.get(variable.name) or |
0 | 1112 |
variable.stinfo.get('principal') or |
1113 |
iter(variable.stinfo['rhsrelations']).next()) |
|
1114 |
linkedvar = rel.children[0].variable |
|
1115 |
if rel.r_type == 'eid': |
|
1116 |
return linkedvar.accept(self) |
|
1117 |
if isinstance(linkedvar, ColumnAlias): |
|
1118 |
raise BadRQLQuery('variable %s should be selected by the subquery' |
|
1119 |
% variable.name) |
|
1120 |
try: |
|
1121 |
sql = self._varmap['%s.%s' % (linkedvar.name, rel.r_type)] |
|
1122 |
except KeyError: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1123 |
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
|
1124 |
sql = '%s.%s%s' % (linkedvar._q_sqltable, SQL_PREFIX, rel.r_type) |
0 | 1125 |
return sql |
1126 |
||
1127 |
# tables handling ######################################################### |
|
1128 |
||
1129 |
def alias_and_add_table(self, tablename): |
|
1130 |
alias = '%s%s' % (tablename, self._state.count) |
|
1131 |
self._state.count += 1 |
|
1132 |
self.add_table('%s AS %s' % (tablename, alias), alias) |
|
1133 |
return alias |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1134 |
|
0 | 1135 |
def add_table(self, table, key=None, scope=-1): |
1136 |
if key is None: |
|
1137 |
key = table |
|
1138 |
if key in self._state.tables: |
|
1139 |
return |
|
1140 |
self._state.tables[key] = (len(self._state.actual_tables) - 1, table) |
|
1141 |
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
|
1142 |
|
0 | 1143 |
def replace_tables_by_outer_join(self, substitute, lefttable, *tables): |
1144 |
for table in tables: |
|
1145 |
try: |
|
1146 |
scope, alias = self._state.tables[table] |
|
1147 |
self._state.actual_tables[scope].remove(alias) |
|
1148 |
except ValueError: # huum, not sure about what should be done here |
|
1149 |
msg = "%s already used in an outer join, don't know what to do!" |
|
1150 |
raise Exception(msg % table) |
|
1151 |
try: |
|
1152 |
tablealias = self._state.outer_tables[lefttable] |
|
1153 |
actualtables = self._state.actual_tables[-1] |
|
1154 |
except KeyError: |
|
1155 |
tablescope, tablealias = self._state.tables[lefttable] |
|
1156 |
actualtables = self._state.actual_tables[tablescope] |
|
1157 |
outerjoin = '%s %s' % (tablealias, substitute) |
|
1158 |
self._update_outer_tables(lefttable, actualtables, tablealias, outerjoin) |
|
1159 |
for table in tables: |
|
1160 |
self._state.outer_tables[table] = outerjoin |
|
1161 |
||
1162 |
def add_outer_join_condition(self, var, table, condition): |
|
1163 |
try: |
|
1164 |
tablealias = self._state.outer_tables[table] |
|
1165 |
actualtables = self._state.actual_tables[-1] |
|
1166 |
except KeyError: |
|
1167 |
for rel in var.stinfo['optrelations']: |
|
1168 |
self.visit_relation(rel) |
|
1169 |
assert self._state.outer_tables |
|
1170 |
self.add_outer_join_condition(var, table, condition) |
|
1171 |
return |
|
1172 |
before, after = tablealias.split(' AS %s ' % table, 1) |
|
1173 |
beforep, afterp = after.split(')', 1) |
|
1174 |
outerjoin = '%s AS %s %s AND %s) %s' % (before, table, beforep, |
|
1175 |
condition, afterp) |
|
1176 |
self._update_outer_tables(table, actualtables, tablealias, outerjoin) |
|
1177 |
||
1178 |
def _update_outer_tables(self, table, actualtables, oldalias, newalias): |
|
1179 |
actualtables.remove(oldalias) |
|
1180 |
actualtables.append(newalias) |
|
1181 |
# some tables which have already been used as outer table and replaced |
|
1182 |
# by <oldalias> may not be reused here, though their associated value |
|
1183 |
# in the outer_tables dict has to be updated as well |
|
1184 |
for table, outerexpr in self._state.outer_tables.iteritems(): |
|
1185 |
if outerexpr == oldalias: |
|
1186 |
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
|
1187 |
self._state.outer_tables[table] = newalias |
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1188 |
|
0 | 1189 |
def _var_table(self, var): |
1190 |
var.accept(self)#.visit_variable(var) |
|
1191 |
return var._q_sqltable |
|
1192 |
||
1193 |
def _relation_table(self, relation): |
|
1194 |
"""return the table alias used by the given relation""" |
|
1195 |
if relation in self._state.done: |
|
1196 |
return relation._q_sqltable |
|
1197 |
assert not self.schema.rschema(relation.r_type).is_final(), relation.r_type |
|
1198 |
rid = 'rel_%s%s' % (relation.r_type, self._state.count) |
|
1199 |
# 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
|
1200 |
# table of one of it's variable and if that variable belong's to parent |
0 | 1201 |
# scope |
1202 |
for varref in relation.iget_nodes(VariableRef): |
|
1203 |
var = varref.variable |
|
1204 |
if isinstance(var, ColumnAlias): |
|
1205 |
scope = 0 |
|
1206 |
break |
|
1207 |
# XXX may have a principal without being invariant for this generation, |
|
1208 |
# not sure this is a pb or not |
|
1209 |
if var.stinfo.get('principal') is relation and var.sqlscope is var.stmt: |
|
1210 |
scope = 0 |
|
1211 |
break |
|
1212 |
else: |
|
1213 |
scope = -1 |
|
1214 |
self._state.count += 1 |
|
1215 |
self.add_table('%s_relation AS %s' % (relation.r_type, rid), rid, scope=scope) |
|
1216 |
relation._q_sqltable = rid |
|
1217 |
self._state.done.add(relation) |
|
1218 |
return rid |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1219 |
|
0 | 1220 |
def _fti_table(self, relation): |
1221 |
if relation in self._state.done: |
|
1222 |
try: |
|
1223 |
return relation._q_sqltable |
|
1224 |
except AttributeError: |
|
1225 |
pass |
|
1226 |
self._state.done.add(relation) |
|
1227 |
alias = self.alias_and_add_table(self.dbms_helper.fti_table) |
|
1228 |
relation._q_sqltable = alias |
|
1229 |
return alias |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1522
diff
changeset
|
1230 |
|
0 | 1231 |
def _varmap_table_scope(self, select, table): |
1232 |
"""since a varmap table may be used for multiple variable, its scope is |
|
1233 |
the most outer scope of each variables |
|
1234 |
""" |
|
1235 |
scope = -1 |
|
1236 |
for varname, alias in self._varmap.iteritems(): |
|
1237 |
# check '.' in varname since there are 'X.attribute' keys in varmap |
|
1238 |
if not '.' in varname and alias.split('.', 1)[0] == table: |
|
1239 |
if select.defined_vars[varname].sqlscope is select: |
|
1240 |
return 0 |
|
1241 |
return scope |