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