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