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