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