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