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