svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.db / org.gvsig.fmap.dal.db.jdbc / src / main / java / org / gvsig / fmap / dal / store / jdbc2 / spi / JDBCHelperBase.java @ 47779
History | View | Annotate | Download (51.9 KB)
1 |
/**
|
---|---|
2 |
* gvSIG. Desktop Geographic Information System.
|
3 |
*
|
4 |
* Copyright (C) 2007-2020 gvSIG Association.
|
5 |
*
|
6 |
* This program is free software; you can redistribute it and/or
|
7 |
* modify it under the terms of the GNU General Public License
|
8 |
* as published by the Free Software Foundation; either version 3
|
9 |
* of the License, or (at your option) any later version.
|
10 |
*
|
11 |
* This program is distributed in the hope that it will be useful,
|
12 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
14 |
* GNU General Public License for more details.
|
15 |
*
|
16 |
* You should have received a copy of the GNU General Public License
|
17 |
* along with this program; if not, write to the Free Software
|
18 |
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
19 |
* MA 02110-1301, USA.
|
20 |
*
|
21 |
* For any additional information, do not hesitate to contact us
|
22 |
* at info AT gvsig.com, or visit our website www.gvsig.com.
|
23 |
*/
|
24 |
package org.gvsig.fmap.dal.store.jdbc2.spi; |
25 |
|
26 |
import java.io.File; |
27 |
import java.sql.Blob; |
28 |
import java.sql.Clob; |
29 |
import java.sql.ResultSet; |
30 |
import java.util.ArrayList; |
31 |
import java.util.HashSet; |
32 |
import java.util.Iterator; |
33 |
import java.util.List; |
34 |
import java.util.function.Predicate; |
35 |
import org.apache.commons.codec.binary.Hex; |
36 |
import org.apache.commons.collections.CollectionUtils; |
37 |
import org.apache.commons.collections.iterators.ReverseListIterator; |
38 |
import org.apache.commons.io.IOUtils; |
39 |
import org.apache.commons.lang3.ArrayUtils; |
40 |
import org.apache.commons.lang3.StringUtils; |
41 |
import org.apache.commons.lang3.builder.ToStringBuilder; |
42 |
import org.apache.commons.lang3.mutable.MutableBoolean; |
43 |
import org.apache.commons.lang3.mutable.MutableObject; |
44 |
import org.apache.commons.lang3.tuple.ImmutablePair; |
45 |
import org.apache.commons.lang3.tuple.Pair; |
46 |
import org.gvsig.expressionevaluator.Code; |
47 |
import org.gvsig.expressionevaluator.Expression; |
48 |
import org.gvsig.expressionevaluator.ExpressionBuilder; |
49 |
import static org.gvsig.expressionevaluator.ExpressionBuilder.FUNCTION_$CONSTANT; |
50 |
import static org.gvsig.expressionevaluator.ExpressionBuilder.FUNCTION_$IDENTIFIER; |
51 |
import org.gvsig.expressionevaluator.ExpressionEvaluatorLocator; |
52 |
import org.gvsig.expressionevaluator.ExpressionEvaluatorManager; |
53 |
import org.gvsig.expressionevaluator.Function; |
54 |
import org.gvsig.expressionevaluator.GeometryExpressionBuilderHelper.GeometrySupportType; |
55 |
import org.gvsig.expressionevaluator.SymbolTable; |
56 |
import org.gvsig.fmap.dal.DALLocator; |
57 |
import org.gvsig.fmap.dal.DataManager; |
58 |
import static org.gvsig.fmap.dal.DataManager.FUNCTION_EXISTS; |
59 |
import static org.gvsig.fmap.dal.DataManager.FUNCTION_FOREIGN_VALUE; |
60 |
import static org.gvsig.fmap.dal.DataManager.FUNCTION_FOREING_VALUE; |
61 |
import org.gvsig.fmap.dal.DataTypes; |
62 |
import org.gvsig.fmap.dal.SQLBuilder; |
63 |
import org.gvsig.fmap.dal.SQLBuilder.Column; |
64 |
import static org.gvsig.fmap.dal.SQLBuilder.PROP_ADD_TABLE_NAME_TO_COLUMNS; |
65 |
import static org.gvsig.fmap.dal.SQLBuilder.PROP_FEATURE_TYPE; |
66 |
import static org.gvsig.fmap.dal.SQLBuilder.PROP_JDBCHELPER; |
67 |
import static org.gvsig.fmap.dal.SQLBuilder.PROP_QUERY; |
68 |
import org.gvsig.fmap.dal.SQLBuilder.SelectBuilder; |
69 |
import org.gvsig.fmap.dal.SupportTransactionsHelper; |
70 |
import org.gvsig.fmap.dal.exception.DataException; |
71 |
import org.gvsig.fmap.dal.exception.InitializeException; |
72 |
import org.gvsig.fmap.dal.expressionevaluator.FeatureAttributeEmulatorExpression; |
73 |
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor; |
74 |
import org.gvsig.fmap.dal.feature.FeatureAttributeEmulator; |
75 |
import org.gvsig.fmap.dal.feature.FeatureQueryOrder; |
76 |
import org.gvsig.fmap.dal.feature.FeatureType; |
77 |
import org.gvsig.fmap.dal.feature.ForeingKey; |
78 |
import org.gvsig.fmap.dal.feature.spi.FeatureProvider; |
79 |
import org.gvsig.fmap.dal.feature.spi.SQLBuilderBase; |
80 |
import org.gvsig.fmap.dal.resource.exception.AccessResourceException; |
81 |
import org.gvsig.fmap.dal.resource.spi.ResourceConsumer; |
82 |
import org.gvsig.fmap.dal.resource.spi.ResourceProvider; |
83 |
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemStoreParameters; |
84 |
import org.gvsig.fmap.dal.spi.DataServerExplorerProviderServices; |
85 |
import org.gvsig.fmap.dal.spi.DataStoreProviderServices; |
86 |
import org.gvsig.fmap.dal.spi.DataTransactionServices; |
87 |
import org.gvsig.fmap.dal.store.db.DBHelper; |
88 |
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters; |
89 |
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters; |
90 |
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParametersBase; |
91 |
import org.gvsig.fmap.dal.store.jdbc.JDBCResourceBase; |
92 |
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters; |
93 |
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParametersBase; |
94 |
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters; |
95 |
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParametersBase; |
96 |
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCCantFetchValueException; |
97 |
import org.gvsig.fmap.dal.store.jdbc2.JDBCConnection; |
98 |
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper; |
99 |
import org.gvsig.fmap.dal.store.jdbc2.JDBCLibrary; |
100 |
import org.gvsig.fmap.dal.store.jdbc2.JDBCServerExplorer; |
101 |
import org.gvsig.fmap.dal.store.jdbc2.JDBCStoreProvider; |
102 |
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils; |
103 |
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory; |
104 |
import org.gvsig.fmap.dal.store.jdbc2.ResulSetControler; |
105 |
import org.gvsig.fmap.dal.store.jdbc2.ResulSetControler.ResultSetEntry; |
106 |
import org.gvsig.fmap.dal.store.jdbc2.impl.ResulSetControlerBase; |
107 |
import org.gvsig.fmap.dal.store.jdbc2.spi.expressionbuilder.formatters.ComputedAttribute; |
108 |
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.OperationsFactoryBase; |
109 |
import org.gvsig.fmap.geom.Geometry; |
110 |
import org.gvsig.fmap.geom.GeometryLocator; |
111 |
import org.gvsig.fmap.geom.GeometryManager; |
112 |
import org.gvsig.tools.dispose.impl.AbstractDisposable; |
113 |
import org.gvsig.tools.evaluator.Evaluator; |
114 |
import org.gvsig.tools.exception.BaseException; |
115 |
import org.gvsig.tools.exception.NotYetImplemented; |
116 |
import org.gvsig.tools.locator.LocatorException; |
117 |
import org.gvsig.tools.util.ContainerUtils; |
118 |
import org.gvsig.tools.visitor.FilteredVisitable; |
119 |
import org.gvsig.tools.visitor.VisitCanceledException; |
120 |
import org.gvsig.tools.visitor.Visitor; |
121 |
import org.slf4j.Logger; |
122 |
import org.slf4j.LoggerFactory; |
123 |
|
124 |
@SuppressWarnings("UseSpecificCatch") |
125 |
public class JDBCHelperBase extends AbstractDisposable implements ResourceConsumer, JDBCHelper { |
126 |
|
127 |
private static final boolean ALLOW_AUTOMATIC_VALUES = true; |
128 |
private static final String QUOTE_FOR_USE_IN_IDENTIFIERS = "\""; |
129 |
private static final String QUOTE_FOR_USE_IN_STRINGS = "'"; |
130 |
|
131 |
protected static final Logger LOGGER = LoggerFactory.getLogger(JDBCHelperBase.class); |
132 |
|
133 |
private ResulSetControler resulSetControler = null; |
134 |
|
135 |
// Quien ha creado este helper.
|
136 |
// Se le reenviaran las notificaciones del recurso asociado al helper.
|
137 |
private ResourceConsumer helperClient = null; |
138 |
|
139 |
private GeometryManager geometryManager = null; |
140 |
|
141 |
private JDBCConnectionParameters connectionParameters;
|
142 |
|
143 |
private JDBCStoreProvider store;
|
144 |
|
145 |
protected OperationsFactory operationsFactory = null; |
146 |
|
147 |
protected SRSSolver srssolver;
|
148 |
|
149 |
protected FeatureType providerFeatureType = null; |
150 |
|
151 |
// protected DataTransactionServices transaction;
|
152 |
|
153 |
protected SupportTransactionsHelper transactionsHelper;
|
154 |
|
155 |
public JDBCHelperBase(JDBCConnectionParameters connectionParameters) {
|
156 |
if (connectionParameters == null) { |
157 |
throw new IllegalArgumentException("Connection parameters can't be null."); |
158 |
} |
159 |
this.connectionParameters = connectionParameters;
|
160 |
this.transactionsHelper = new SupportTransactionsHelper(); |
161 |
|
162 |
// If a particular treatment is required to convert SRS to the
|
163 |
// BBDD format, overwrite JDBCSRSsBase and use it instead of JDBCSRSsDumb.
|
164 |
this.srssolver = new SRSSolverDumb(this); |
165 |
} |
166 |
|
167 |
protected void initialize( |
168 |
ResourceConsumer helperClient, |
169 |
JDBCConnectionParameters connectionParameters, |
170 |
JDBCStoreProvider store |
171 |
) { |
172 |
this.store = store;
|
173 |
this.helperClient = helperClient;
|
174 |
this.connectionParameters = connectionParameters;
|
175 |
initializeResource(connectionParameters); |
176 |
} |
177 |
|
178 |
protected String getResourceType() { |
179 |
return JDBCResourceBase.NAME;
|
180 |
} |
181 |
|
182 |
@Override
|
183 |
public String getProviderName() { |
184 |
return JDBCLibrary.NAME;
|
185 |
} |
186 |
|
187 |
@Override
|
188 |
public GeometrySupportType getGeometrySupportType() {
|
189 |
// El proveedor generico de JDBC guadara las geoemtrias como WKT
|
190 |
return GeometrySupportType.WKT;
|
191 |
} |
192 |
|
193 |
/**
|
194 |
* @return the providerFeatureType
|
195 |
*/
|
196 |
@Override
|
197 |
public FeatureType getProviderFeatureType() {
|
198 |
return providerFeatureType;
|
199 |
} |
200 |
|
201 |
/**
|
202 |
* @param providerFeatureType the providerFeatureType to set
|
203 |
*/
|
204 |
@Override
|
205 |
public void setProviderFeatureType(FeatureType providerFeatureType) { |
206 |
this.providerFeatureType = providerFeatureType;
|
207 |
} |
208 |
|
209 |
|
210 |
@Override
|
211 |
public boolean hasSpatialFunctions() { |
212 |
// Por defecto el proveedor generico de JDBC asume que la BBDD no
|
213 |
// tiene soporte para funciones espaciales.
|
214 |
return false; |
215 |
} |
216 |
|
217 |
@Override
|
218 |
public boolean allowNestedOperations() { |
219 |
return false; |
220 |
} |
221 |
|
222 |
@Override
|
223 |
public boolean canWriteGeometry(int geometryType, int geometrySubtype) { |
224 |
// Como va a guardar las geometrias en WKT, puede escribirlas todas.
|
225 |
return true; |
226 |
} |
227 |
|
228 |
@Override
|
229 |
public JDBCSQLBuilderBase createSQLBuilder() {
|
230 |
return new JDBCSQLBuilderBase(this); |
231 |
} |
232 |
|
233 |
@Override
|
234 |
public String getQuoteForIdentifiers() { |
235 |
return QUOTE_FOR_USE_IN_IDENTIFIERS;
|
236 |
} |
237 |
|
238 |
@Override
|
239 |
public boolean allowAutomaticValues() { |
240 |
return ALLOW_AUTOMATIC_VALUES;
|
241 |
} |
242 |
|
243 |
@Override
|
244 |
public boolean supportOffsetInSelect() { |
245 |
// Asumimos que la BBDD soporta OFFSET
|
246 |
return true; |
247 |
} |
248 |
|
249 |
@Override
|
250 |
public String getQuoteForStrings() { |
251 |
return QUOTE_FOR_USE_IN_STRINGS;
|
252 |
} |
253 |
|
254 |
protected boolean supportCaller(Code.Callable caller) { |
255 |
if (StringUtils.equalsIgnoreCase(caller.name(), FUNCTION_FOREING_VALUE) ||
|
256 |
StringUtils.equalsIgnoreCase(caller.name(), FUNCTION_FOREIGN_VALUE) |
257 |
) { |
258 |
return true; |
259 |
} |
260 |
Function function = caller.function(); |
261 |
if (function == null) { |
262 |
return false; |
263 |
} |
264 |
if (!function.isSQLCompatible()) {
|
265 |
return false; |
266 |
} |
267 |
if (!this.hasSpatialFunctions()) { |
268 |
if (StringUtils.equalsIgnoreCase(function.group(), Function.GROUP_OGC)) {
|
269 |
return false; |
270 |
} |
271 |
} |
272 |
return true; |
273 |
} |
274 |
|
275 |
@Override
|
276 |
@SuppressWarnings("Convert2Lambda") |
277 |
public boolean supportFilter(final FeatureType type, Evaluator filter) { |
278 |
if (filter == null) { |
279 |
// No hay que filtrar nada, asi que se p?ede.
|
280 |
return true; |
281 |
} |
282 |
String sql = filter.getSQL();
|
283 |
if (StringUtils.isEmpty(sql)) {
|
284 |
// Hay un filtro, pero la SQL es null, con lo que no podemos
|
285 |
// filtrar por el.
|
286 |
return false; |
287 |
} |
288 |
return this.supportExpression(type, sql); |
289 |
} |
290 |
|
291 |
@Override
|
292 |
@SuppressWarnings("Convert2Lambda") |
293 |
public boolean supportExpression(final FeatureType type, String sql) { |
294 |
// La expression no es valida si:
|
295 |
// - Hay una subquery especificada en los parametros
|
296 |
// - Si la sql es null.
|
297 |
// - Si se esta usando alguna funcion no-sql en el getSQL
|
298 |
// - Si se esta invocando a metodos de un objeto
|
299 |
// - Si se estan usando funciones OGC y no soportamos funciones espaciales
|
300 |
// - Si se esta usando algun campo calculado en la expresion de filtro.
|
301 |
//
|
302 |
// Un proveedor especifico podria sobreescribir el metodo,
|
303 |
// para hilar mas fino al comprobar si soporta el filtro o no.
|
304 |
//
|
305 |
|
306 |
if (StringUtils.isEmpty(sql)) {
|
307 |
return false; |
308 |
} |
309 |
|
310 |
// if (this.useSubquery()) {
|
311 |
// // Se esta usando una subquery en los parametros de acceso a la
|
312 |
// // BBDD, asi que no podemos filtrar.
|
313 |
// return false;
|
314 |
// }
|
315 |
|
316 |
// Ahora vamos a comprobar que las funciones que se usan son
|
317 |
// compatibles sql, y que no se usan funciones OGC si el
|
318 |
// proveedor dice que no soporta funciones espaciales.
|
319 |
// Tambien comprobaremos que el filtro no usa ningun campo calculado.
|
320 |
final MutableBoolean isCompatible = new MutableBoolean(true); |
321 |
ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager(); |
322 |
Code code = manager.compile(sql); |
323 |
SymbolTable symbolTable = manager.createSymbolTable(); |
324 |
code.link(symbolTable); |
325 |
try {
|
326 |
code.accept(new Visitor() {
|
327 |
@Override
|
328 |
public void visit(Object code_obj) throws VisitCanceledException, BaseException { |
329 |
Code code1 = (Code) code_obj; |
330 |
switch (code1.code()) {
|
331 |
case Code.CALLABLE:
|
332 |
Code.Callable caller = (Code.Callable) code1; |
333 |
if (!supportCaller(caller)) {
|
334 |
isCompatible.setValue(false);
|
335 |
LOGGER.debug("Expression not SQL compatible, use '"+caller.name()+"' ("+sql+")."); |
336 |
throw new VisitCanceledException(); |
337 |
} |
338 |
break;
|
339 |
case Code.METHOD:
|
340 |
isCompatible.setValue(false);
|
341 |
LOGGER.debug("Expression not SQL compatible, use objects methods ("+sql+")."); |
342 |
throw new VisitCanceledException(); |
343 |
case Code.IDENTIFIER:
|
344 |
Code.Identifier identifier = (Code.Identifier) code1; |
345 |
if (type != null) { |
346 |
FeatureAttributeDescriptor attrdesc = type.getAttributeDescriptor(identifier.name()); |
347 |
if (attrdesc != null) { |
348 |
if (attrdesc.isComputed()) {
|
349 |
FeatureAttributeEmulator emulator = attrdesc.getFeatureAttributeEmulator(); |
350 |
if (!(emulator instanceof FeatureAttributeEmulatorExpression)) { |
351 |
LOGGER.debug("Expression not SQL compatible, use calculated field '"+attrdesc.getName()+"' ("+sql+")."); |
352 |
isCompatible.setValue(false);
|
353 |
throw new VisitCanceledException(); |
354 |
} |
355 |
Expression expr = ((FeatureAttributeEmulatorExpression) emulator).getExpression();
|
356 |
if (!supportExpression(type, expr.getPhrase())) {
|
357 |
LOGGER.debug("Expression not SQL compatible, use calculated field '"+attrdesc.getName()+"' ("+expr.getPhrase()+"/"+sql+")."); |
358 |
isCompatible.setValue(false);
|
359 |
throw new VisitCanceledException(); |
360 |
} |
361 |
} |
362 |
} |
363 |
} |
364 |
break;
|
365 |
} |
366 |
} |
367 |
}, new Predicate<FilteredVisitable>() { |
368 |
@Override
|
369 |
public boolean test(FilteredVisitable code0) { |
370 |
if (code0 instanceof Code.Callable) { |
371 |
String name = ((Code.Callable) code0).name();
|
372 |
return StringUtils.equalsIgnoreCase(name, FUNCTION_$CONSTANT) |
373 |
|| StringUtils.equalsIgnoreCase(name, FUNCTION_$IDENTIFIER);
|
374 |
} |
375 |
return false; |
376 |
} |
377 |
}); |
378 |
|
379 |
} catch (VisitCanceledException ex) {
|
380 |
// Do nothing
|
381 |
} catch (Exception ex) { |
382 |
LOGGER.warn("Can't calculate if is SQL compatible.", ex);
|
383 |
} |
384 |
|
385 |
return isCompatible.booleanValue();
|
386 |
} |
387 |
|
388 |
@Override
|
389 |
public boolean supportOrder(FeatureType type, FeatureQueryOrder order) { |
390 |
if (this.useSubquery()) { |
391 |
return false; |
392 |
} |
393 |
if (order == null) { |
394 |
return true; |
395 |
} |
396 |
for (FeatureQueryOrder.FeatureQueryOrderMember member : order.members()) {
|
397 |
if (member.hasEvaluator()) {
|
398 |
if (!this.supportFilter(type, member.getEvaluator())) { |
399 |
return false; |
400 |
} |
401 |
} |
402 |
} |
403 |
return true; |
404 |
} |
405 |
|
406 |
@Override
|
407 |
public OperationsFactory getOperations() {
|
408 |
if (this.operationsFactory == null && !isClosed()) { |
409 |
this.operationsFactory = new OperationsFactoryBase(this); |
410 |
} |
411 |
return operationsFactory;
|
412 |
} |
413 |
|
414 |
protected void initializeResource(JDBCConnectionParameters params) { |
415 |
// Object[] resourceParams = new Object[]{
|
416 |
// params.getUrl(),
|
417 |
// params.getHost(),
|
418 |
// params.getPort(),
|
419 |
// params.getDBName(),
|
420 |
// params.getUser(),
|
421 |
// params.getPassword(),
|
422 |
// params.getJDBCDriverClassName()
|
423 |
// };
|
424 |
//
|
425 |
// try {
|
426 |
// ResourceManagerProviderServices manager
|
427 |
// = (ResourceManagerProviderServices) DALLocator.getResourceManager();
|
428 |
// JDBCResourceBase resource = (JDBCResourceBase) manager.createAddResource(
|
429 |
// this.getResourceType(),
|
430 |
// resourceParams
|
431 |
// );
|
432 |
// this.resource = resource;
|
433 |
// this.resource.addConsumer(this);
|
434 |
// } catch (InitializeException ex) {
|
435 |
// logger.trace("Can't initialize resource (" + ArrayUtils.toString(resourceParams) + ").", ex);
|
436 |
// throw new RuntimeException("Can't initialize resource (" + ArrayUtils.toString(resourceParams) + ").", ex);
|
437 |
// }
|
438 |
|
439 |
} |
440 |
|
441 |
@Override
|
442 |
public String getSourceId() { |
443 |
return this.store.getSourceId(); |
444 |
} |
445 |
|
446 |
@Override
|
447 |
public JDBCResourceBase getResource() {
|
448 |
return null; |
449 |
// return this.resource;
|
450 |
} |
451 |
|
452 |
@Override
|
453 |
public JDBCConnection getConnection() throws AccessResourceException { |
454 |
throw new NotYetImplemented(); |
455 |
} |
456 |
|
457 |
@Override
|
458 |
public JDBCConnection getConnectionWritable() throws AccessResourceException { |
459 |
return this.getConnection(); |
460 |
} |
461 |
|
462 |
@Override
|
463 |
public String getConnectionURL() { |
464 |
return null; |
465 |
} |
466 |
|
467 |
@Override
|
468 |
public JDBCConnectionParameters getConnectionParameters() {
|
469 |
return connectionParameters;
|
470 |
} |
471 |
|
472 |
@Override
|
473 |
protected void doDispose() throws BaseException { |
474 |
JDBCUtils.closeQuietly(this);
|
475 |
} |
476 |
|
477 |
@Override
|
478 |
public void close() throws Exception { |
479 |
JDBCUtils.closeQuietly(this.resulSetControler);
|
480 |
this.resulSetControler = null; |
481 |
this.operationsFactory = null; |
482 |
this.srssolver = null; |
483 |
this.connectionParameters = null; |
484 |
this.helperClient = null; |
485 |
this.geometryManager = null; |
486 |
this.providerFeatureType = null; |
487 |
this.store = null; |
488 |
// this.transaction = null;
|
489 |
this.transactionsHelper.setTransaction(null); |
490 |
} |
491 |
|
492 |
public boolean isClosed() { |
493 |
return this.srssolver == null; |
494 |
} |
495 |
|
496 |
@Override
|
497 |
public boolean closeResourceRequested(ResourceProvider resource) { |
498 |
return this.helperClient.closeResourceRequested(resource); |
499 |
} |
500 |
|
501 |
@Override
|
502 |
public void resourceChanged(ResourceProvider resource) { |
503 |
this.helperClient.resourceChanged(resource);
|
504 |
} |
505 |
|
506 |
@Override
|
507 |
public GeometryManager getGeometryManager() {
|
508 |
if (this.geometryManager == null) { |
509 |
this.geometryManager = GeometryLocator.getGeometryManager();
|
510 |
} |
511 |
return this.geometryManager; |
512 |
} |
513 |
|
514 |
@Override
|
515 |
public ResulSetControler getResulSetControler() {
|
516 |
if (this.resulSetControler == null) { |
517 |
this.resulSetControler = new ResulSetControlerBase(this); |
518 |
} |
519 |
return this.resulSetControler; |
520 |
} |
521 |
|
522 |
@Override
|
523 |
public void fetchFeature(FeatureProvider feature, ResultSetEntry rs) throws DataException { |
524 |
fetchFeature(feature, rs.get(), rs.getColumns(), rs.getExtraValueNames()); |
525 |
} |
526 |
|
527 |
@Override
|
528 |
public void fetchFeature(FeatureProvider feature, ResultSet rs, FeatureAttributeDescriptor[] columns, String[] extraValueNames) throws DataException { |
529 |
Object value;
|
530 |
try {
|
531 |
int rsIndex = 1; |
532 |
for (FeatureAttributeDescriptor column : columns) {
|
533 |
switch (column.getType()) {
|
534 |
case DataTypes.GEOMETRY:
|
535 |
value = this.getGeometryFromColumn(rs, rsIndex++);
|
536 |
if (value != null){ |
537 |
((Geometry)value).setProjection(column.getSRS()); |
538 |
} |
539 |
break;
|
540 |
default:
|
541 |
value = rs.getObject(rsIndex++); |
542 |
if (value instanceof Blob) { |
543 |
Blob blob = (Blob) value; |
544 |
value = blob.getBytes(1, (int) blob.length()); |
545 |
blob.free(); |
546 |
} else if(value instanceof Clob) { |
547 |
Clob clob = (Clob) value; |
548 |
value = new String(IOUtils.toCharArray(clob.getCharacterStream())); |
549 |
clob.free(); |
550 |
} |
551 |
} |
552 |
feature.set(column.getIndex(), value); |
553 |
} |
554 |
if (ArrayUtils.isNotEmpty(extraValueNames)) {
|
555 |
feature.setExtraValueNames(extraValueNames); |
556 |
for (int index = 0; index < extraValueNames.length; index++) { |
557 |
value = rs.getObject(rsIndex++); |
558 |
if (value instanceof Blob) { |
559 |
Blob blob = (Blob) value; |
560 |
value = blob.getBytes(0, (int) blob.length()); |
561 |
blob.free(); |
562 |
} |
563 |
feature.setExtraValue(index, value); |
564 |
} |
565 |
} |
566 |
} catch (Exception ex) { |
567 |
throw new JDBCCantFetchValueException(ex); |
568 |
} |
569 |
} |
570 |
|
571 |
@Override
|
572 |
public Geometry getGeometryFromColumn(ResultSetEntry rs, int index) throws DataException { |
573 |
return getGeometryFromColumn(rs.get(), index);
|
574 |
} |
575 |
|
576 |
@Override
|
577 |
public Geometry getGeometryFromColumn(ResultSet rs, int index) throws DataException { |
578 |
try {
|
579 |
Object value;
|
580 |
Geometry geom; |
581 |
switch (this.getGeometrySupportType()) { |
582 |
case WKB:
|
583 |
value = rs.getBytes(index); |
584 |
if (value == null) { |
585 |
return null; |
586 |
} |
587 |
geom = this.getGeometryManager().createFrom((byte[]) value); |
588 |
if( geom == null ) { |
589 |
LOGGER.debug("Can't get geometry from bytes of column "+index);
|
590 |
} |
591 |
return geom;
|
592 |
|
593 |
case NATIVE:
|
594 |
case EWKB:
|
595 |
value = rs.getBytes(index); |
596 |
if (value == null) { |
597 |
return null; |
598 |
} |
599 |
geom = this.getGeometryManager().createFrom((byte[]) value); |
600 |
if( geom == null ) { |
601 |
LOGGER.debug("Can't get geometry from bytes of column "+index);
|
602 |
} |
603 |
return geom;
|
604 |
case WKT:
|
605 |
default:
|
606 |
value = rs.getString(index); |
607 |
if (value == null) { |
608 |
return null; |
609 |
} |
610 |
geom = this.getGeometryManager().createFrom((String) value); |
611 |
if( geom == null ) { |
612 |
LOGGER.debug("Can't get geometry from bytes of column "+index);
|
613 |
} |
614 |
return geom;
|
615 |
|
616 |
} |
617 |
} catch (Exception ex) { |
618 |
throw new JDBCCantFetchValueException(ex); |
619 |
} |
620 |
} |
621 |
|
622 |
@Override
|
623 |
public FeatureProvider createFeature(FeatureType featureType) throws DataException { |
624 |
return this.store.getStoreServices().createDefaultFeatureProvider(featureType); |
625 |
} |
626 |
|
627 |
@Override
|
628 |
public boolean useSubquery() { |
629 |
if (this.store == null) { |
630 |
return false; |
631 |
} |
632 |
return !StringUtils.isEmpty(this.store.getParameters().getSQL()); |
633 |
} |
634 |
|
635 |
@Override
|
636 |
public SRSSolver getSRSSolver() {
|
637 |
return this.srssolver; |
638 |
} |
639 |
|
640 |
@Override
|
641 |
public JDBCStoreProvider createProvider(
|
642 |
JDBCStoreParameters parameters, |
643 |
DataStoreProviderServices providerServices |
644 |
) throws InitializeException {
|
645 |
|
646 |
JDBCStoreProviderBase theStore = new JDBCStoreProviderBase(
|
647 |
parameters, |
648 |
providerServices, |
649 |
DBHelper.newMetadataContainer(JDBCLibrary.NAME), |
650 |
this
|
651 |
); |
652 |
this.initialize(theStore, parameters, theStore);
|
653 |
return theStore;
|
654 |
} |
655 |
|
656 |
@Override
|
657 |
public JDBCServerExplorer createServerExplorer(
|
658 |
JDBCServerExplorerParameters parameters, |
659 |
DataServerExplorerProviderServices providerServices |
660 |
) throws InitializeException {
|
661 |
|
662 |
JDBCServerExplorer explorer = new JDBCServerExplorerBase(
|
663 |
parameters, |
664 |
providerServices, |
665 |
this
|
666 |
); |
667 |
this.initialize(explorer, parameters, null); |
668 |
return explorer;
|
669 |
} |
670 |
|
671 |
@Override
|
672 |
public JDBCNewStoreParameters createNewStoreParameters() {
|
673 |
return new JDBCNewStoreParametersBase(); |
674 |
} |
675 |
|
676 |
@Override
|
677 |
public JDBCStoreParameters createOpenStoreParameters() {
|
678 |
return new JDBCStoreParametersBase(); |
679 |
} |
680 |
|
681 |
@Override
|
682 |
public JDBCStoreParameters createOpenStoreParameters(JDBCServerExplorerParameters parameters) {
|
683 |
JDBCStoreParameters params = this.createOpenStoreParameters();
|
684 |
params.setHost(parameters.getHost()); |
685 |
params.setPort(parameters.getPort()); |
686 |
params.setDBName(parameters.getDBName()); |
687 |
params.setUser(parameters.getUser()); |
688 |
params.setPassword(parameters.getPassword()); |
689 |
params.setCatalog(parameters.getCatalog()); |
690 |
params.setSchema(parameters.getSchema()); |
691 |
params.setJDBCDriverClassName(parameters.getJDBCDriverClassName()); |
692 |
params.setUrl(parameters.getUrl()); |
693 |
if( parameters instanceof FilesystemStoreParameters ) { |
694 |
File f = ((FilesystemStoreParameters) parameters).getFile();
|
695 |
((FilesystemStoreParameters) params).setFile(f); |
696 |
} |
697 |
params.setBatchSize(parameters.getBatchSize()); |
698 |
return params;
|
699 |
} |
700 |
|
701 |
|
702 |
@Override
|
703 |
public JDBCServerExplorerParameters createServerExplorerParameters() {
|
704 |
return new JDBCServerExplorerParametersBase(); |
705 |
} |
706 |
|
707 |
@Override
|
708 |
public String getSourceId(JDBCStoreParameters params) { |
709 |
StringBuilder builder = new StringBuilder(); |
710 |
builder.append(params.getTable()); |
711 |
builder.append("(");
|
712 |
boolean needComma = false; |
713 |
if( StringUtils.isNotBlank(params.getHost()) ) {
|
714 |
builder.append("host=");
|
715 |
builder.append(params.getHost()); |
716 |
needComma = true;
|
717 |
} |
718 |
if( params.getPort()>0 ) { |
719 |
if (needComma ) {
|
720 |
builder.append(", ");
|
721 |
} |
722 |
builder.append("port=");
|
723 |
builder.append(params.getPort()); |
724 |
needComma = true;
|
725 |
} |
726 |
if( StringUtils.isNotBlank(params.getDBName()) ) {
|
727 |
if (needComma ) {
|
728 |
builder.append(", ");
|
729 |
} |
730 |
builder.append("db=");
|
731 |
builder.append(params.getDBName()); |
732 |
needComma = true;
|
733 |
} |
734 |
if( StringUtils.isNotBlank(params.getSchema()) ) {
|
735 |
if (needComma ) {
|
736 |
builder.append(", ");
|
737 |
} |
738 |
builder.append("schema=");
|
739 |
builder.append(params.getSchema()); |
740 |
needComma = true;
|
741 |
} |
742 |
builder.append(")");
|
743 |
return builder.toString();
|
744 |
} |
745 |
|
746 |
@Override
|
747 |
public boolean isThreadSafe() { |
748 |
return true; |
749 |
} |
750 |
|
751 |
/**
|
752 |
* This method has been overriden in Oracle provider
|
753 |
*
|
754 |
* @param sqlbuilder
|
755 |
* @param type
|
756 |
* @param extra_column_names
|
757 |
*/
|
758 |
@Override
|
759 |
public void processSpecialFunctions( |
760 |
SQLBuilder sqlbuilder, |
761 |
FeatureType type, |
762 |
List<String> extra_column_names) { |
763 |
replaceForeingValueFunction(sqlbuilder, type, extra_column_names); |
764 |
replaceExistsFunction(sqlbuilder, type, extra_column_names); |
765 |
addTableToColumnReferences(sqlbuilder, type); |
766 |
} |
767 |
|
768 |
@SuppressWarnings("Convert2Lambda") |
769 |
protected void replaceExistsFunction( |
770 |
SQLBuilder sqlbuilder, |
771 |
FeatureType type, |
772 |
final List<String> extra_column_names) { |
773 |
|
774 |
// Si lse encuentra una construccion del tipo:
|
775 |
// SELECT ... FROM ... WHERE ... EXISTS(list, 'EXISTS_ID') ...
|
776 |
// se traslada a:
|
777 |
// SELECT ... EXISTS(list) AS EXISTS_ID FROM ... WHERE ... EXISTS(list) ...
|
778 |
// Y se a?ade el valor ESISTS_ID a las columnas extra a recuperar de la consulta.
|
779 |
//
|
780 |
|
781 |
final SQLBuilder.SelectBuilder select = sqlbuilder.select();
|
782 |
final ExpressionBuilder where = select.where();
|
783 |
if (where == null || where.isEmpty() || select.has_group_by() || select.has_aggregate_functions()) { |
784 |
return;
|
785 |
} |
786 |
final List<ExpressionBuilder.Value[]> value_replacements = new ArrayList<>(); |
787 |
where.accept(new ExpressionBuilder.Visitor() {
|
788 |
@Override
|
789 |
public void visit(ExpressionBuilder.Visitable value) { |
790 |
if (!(value instanceof ExpressionBuilder.Function)) { |
791 |
return;
|
792 |
} |
793 |
ExpressionBuilder.Function function = (ExpressionBuilder.Function) value; |
794 |
if (!StringUtils.equalsIgnoreCase(function.name(), FUNCTION_EXISTS)) {
|
795 |
return;
|
796 |
} |
797 |
if (function.parameters().size() != 2) { |
798 |
return;
|
799 |
} |
800 |
ExpressionBuilder.Value arg0 = function.parameters().get(0);
|
801 |
ExpressionBuilder.Value arg1 = function.parameters().get(1);
|
802 |
if (arg1 == null) { |
803 |
return;
|
804 |
} |
805 |
String columnName = (String) ((ExpressionBuilder.Constant) arg1).value(); |
806 |
SQLBuilder.SelectColumnBuilder column = select.column(); |
807 |
column.value( |
808 |
sqlbuilder.expression().function(FUNCTION_EXISTS, arg0) |
809 |
); |
810 |
column.as(columnName); |
811 |
|
812 |
if( extra_column_names!=null ) { |
813 |
extra_column_names.add(columnName); |
814 |
} |
815 |
} |
816 |
}, null);
|
817 |
if (value_replacements.isEmpty()) {
|
818 |
return;
|
819 |
} |
820 |
// Realizamos los reemplazos calculados previamente (value_replacements).
|
821 |
for (ExpressionBuilder.Value[] replaceValue : value_replacements) { |
822 |
ExpressionBuilder.Value target = replaceValue[0];
|
823 |
ExpressionBuilder.Value replacement = replaceValue[1];
|
824 |
sqlbuilder.select().replace(target, replacement); |
825 |
} |
826 |
} |
827 |
|
828 |
@SuppressWarnings("Convert2Lambda") |
829 |
protected void replaceForeingValueFunction( |
830 |
SQLBuilder sqlbuilder, |
831 |
FeatureType type, |
832 |
List<String> extra_column_names) { |
833 |
try {
|
834 |
// See test SQLBuilderTest->testForeingValue()
|
835 |
final ExpressionBuilder where = sqlbuilder.select().where();
|
836 |
// if (where == null || where.isEmpty()) {
|
837 |
// return;
|
838 |
// }
|
839 |
final SQLBuilder.TableNameBuilder table = sqlbuilder.select().from().table();
|
840 |
final ExpressionBuilder expbuilder = sqlbuilder.expression();
|
841 |
|
842 |
final List<String> foreing_value_args; |
843 |
if (extra_column_names == null || sqlbuilder.select().has_group_by() || sqlbuilder.select().has_aggregate_functions() ) { |
844 |
foreing_value_args = new ArrayList<>(); |
845 |
} else {
|
846 |
foreing_value_args = extra_column_names; |
847 |
} |
848 |
final List<ExpressionBuilder.Value[]> value_replacements = new ArrayList<>(); |
849 |
|
850 |
MutableObject<Boolean> hasForeignValueFunctions = new MutableObject<>(false); |
851 |
|
852 |
// Buscamos las llamadas a la funcion "foreing_value" y nos quedamos
|
853 |
// el argumento de esta asi como por que tendriamos que sustituirla
|
854 |
// una vez hechos los left joins que toquen.
|
855 |
sqlbuilder.select().accept(new ExpressionBuilder.Visitor() {
|
856 |
@Override
|
857 |
public void visit(ExpressionBuilder.Visitable value) { |
858 |
// Requiere que sea la funcion "FOREING_VALUE con un solo
|
859 |
// argumento que sea una constante de tipo string.
|
860 |
if (!(value instanceof ExpressionBuilder.Function)) { |
861 |
return;
|
862 |
} |
863 |
ExpressionBuilder.Function function = (ExpressionBuilder.Function) value; |
864 |
if (!(StringUtils.equalsIgnoreCase(function.name(), FUNCTION_FOREIGN_VALUE)
|
865 |
|| StringUtils.equalsIgnoreCase(function.name(), FUNCTION_FOREING_VALUE))) { |
866 |
return;
|
867 |
} |
868 |
if (function.parameters().size() != 1) { |
869 |
return;
|
870 |
} |
871 |
ExpressionBuilder.Value arg = function.parameters().get(0);
|
872 |
if (!(arg instanceof ExpressionBuilder.Constant)) { |
873 |
return;
|
874 |
} |
875 |
Object arg_value = ((ExpressionBuilder.Constant) arg).value();
|
876 |
if (!(arg_value instanceof CharSequence)) { |
877 |
return;
|
878 |
} |
879 |
hasForeignValueFunctions.setValue(true);
|
880 |
String foreing_value_arg = arg_value.toString();
|
881 |
String[] foreingNameParts = StringUtils.split(foreing_value_arg, "[.]"); |
882 |
if (foreingNameParts.length != 2) { |
883 |
// De momento solo tratamos joins entre dos tablas.
|
884 |
return;
|
885 |
} |
886 |
String columnNameLocal = foreingNameParts[0]; |
887 |
String columnNameForeing = foreingNameParts[1]; |
888 |
FeatureAttributeDescriptor attr = type.getAttributeDescriptor(columnNameLocal); |
889 |
if (attr==null) { |
890 |
throw new RuntimeException("Cannot find in feature type attribute:"+columnNameLocal); |
891 |
} |
892 |
if (!attr.isForeingKey()) {
|
893 |
// Uhm... si el argumento no referencia a un campo que es
|
894 |
// clave ajena no lo procesamos.
|
895 |
// ? Deberiamos lanzar un error ?
|
896 |
return;
|
897 |
} |
898 |
// Nos guardaremos por que hay que reemplazar la funcion
|
899 |
// FOREING_VALUE, y su argumento para mas tarde.
|
900 |
ForeingKey foreingKey = attr.getForeingKey(); |
901 |
SQLBuilder.TableNameBuilder foreingTable = sqlbuilder.createTableNameBuilder() |
902 |
.database(table.getDatabase()) |
903 |
.schema(table.getSchema()) |
904 |
.name(foreingKey.getTableName()); |
905 |
// Reemplzaremos la funcion FOREING_VALUE, por el acceso al campo
|
906 |
// que toca de la tabla a la que referencia la clave ajena.
|
907 |
ExpressionBuilder.Variable function_replacement = sqlbuilder.column(foreingTable, columnNameForeing); |
908 |
value_replacements.add( |
909 |
new ExpressionBuilder.Value[]{ |
910 |
function, |
911 |
function_replacement |
912 |
} |
913 |
); |
914 |
if (!foreing_value_args.contains(foreing_value_arg)) {
|
915 |
foreing_value_args.add(foreing_value_arg); |
916 |
} |
917 |
} |
918 |
}, null);
|
919 |
|
920 |
// Si no habia ningun llamada a la funcion FOREING_VALUE, no hay que
|
921 |
// hacer nada.
|
922 |
if ( !hasForeignValueFunctions.getValue() || foreing_value_args.isEmpty()) {
|
923 |
return;
|
924 |
} |
925 |
|
926 |
// Calculamos que referencias de columnas hemos de cambiar para
|
927 |
// que no aparezcan ambiguedades al hacer el join (nombres de
|
928 |
// columna de una y otra tabla que coincidan).
|
929 |
// Para las columnas que puedan dar conflicto se prepara un reemplazo
|
930 |
// de estas que tenga el nombre de tabla.
|
931 |
for (ExpressionBuilder.Variable variable : sqlbuilder.variables()) {
|
932 |
if (variable == null || variable instanceof SQLBuilderBase.ColumnBase) { |
933 |
continue;
|
934 |
} |
935 |
if (ContainerUtils.contains(extra_column_names, variable.name(), ContainerUtils.EQUALS_IGNORECASE_COMPARATOR)) {
|
936 |
continue;
|
937 |
} |
938 |
boolean alreadyReplaced = false; |
939 |
for (String foreingName : foreing_value_args) { |
940 |
String[] foreingNameParts = foreingName.split("[.]"); |
941 |
if (foreingNameParts.length != 2) { |
942 |
continue;
|
943 |
} |
944 |
String columnNameLocal = foreingNameParts[0]; |
945 |
String columnNameForeing = foreingNameParts[1]; |
946 |
if (StringUtils.equalsIgnoreCase(variable.name(), columnNameForeing)) {
|
947 |
if(alreadyReplaced){
|
948 |
throw new RuntimeException("Column reference \""+ columnNameForeing+"\" is ambiguous"); |
949 |
} |
950 |
alreadyReplaced = true;
|
951 |
|
952 |
FeatureAttributeDescriptor attr = type.getAttributeDescriptor(columnNameLocal); |
953 |
if (attr == null) { |
954 |
throw new RuntimeException("Cannot find in feature type attribute:" + columnNameLocal); |
955 |
} |
956 |
if (attr.isForeingKey()) {
|
957 |
// Nos guardaremos por que hay que reemplazar la funcion
|
958 |
// FOREING_VALUE, y su argumento para mas tarde.
|
959 |
ForeingKey foreingKey = attr.getForeingKey(); |
960 |
SQLBuilder.TableNameBuilder foreingTable = sqlbuilder.createTableNameBuilder() |
961 |
.database(table.getDatabase()) |
962 |
.schema(table.getSchema()) |
963 |
.name(foreingKey.getTableName()); |
964 |
ExpressionBuilder.Variable variable_replacement = sqlbuilder.column( |
965 |
foreingTable, |
966 |
variable.name() |
967 |
); |
968 |
value_replacements.add( |
969 |
new ExpressionBuilder.Value[]{ |
970 |
variable, |
971 |
variable_replacement |
972 |
} |
973 |
); |
974 |
} |
975 |
} |
976 |
if (StringUtils.equalsIgnoreCase(variable.name(), columnNameLocal)) {
|
977 |
ExpressionBuilder.Variable variable_replacement = sqlbuilder.column( |
978 |
table, |
979 |
variable.name() |
980 |
); |
981 |
value_replacements.add( |
982 |
new ExpressionBuilder.Value[]{ |
983 |
variable, |
984 |
variable_replacement |
985 |
} |
986 |
); |
987 |
} |
988 |
} |
989 |
} |
990 |
|
991 |
// Realizamos los reemplazos calculados previamente (value_replacements).
|
992 |
for (ExpressionBuilder.Value[] replaceValue : value_replacements) { |
993 |
ExpressionBuilder.Value target = replaceValue[0];
|
994 |
ExpressionBuilder.Value replacement = replaceValue[1];
|
995 |
sqlbuilder.select().replace(target, replacement); |
996 |
} |
997 |
|
998 |
// A?adimos a la SQL los "LEFT JOIN" que toca para poder acceder
|
999 |
// a los valores referenciados por la funcion FOREING_VALUE.
|
1000 |
// Ademas a?adimos los valores referenciados por la funcion FOREING_VALUE
|
1001 |
// como columnas de la SQL para poder acceder a ellos si fuese necesario.
|
1002 |
HashSet usedLeftJoins = new HashSet(); |
1003 |
for (String foreingName : foreing_value_args) { |
1004 |
String[] foreingNameParts = foreingName.split("[.]"); |
1005 |
if (foreingNameParts.length != 2) { |
1006 |
continue;
|
1007 |
} |
1008 |
String columnNameLocal = foreingNameParts[0]; |
1009 |
String columnNameForeing = foreingNameParts[1]; |
1010 |
FeatureAttributeDescriptor attr = type.getAttributeDescriptor(columnNameLocal); |
1011 |
if (attr.isForeingKey()) {
|
1012 |
ForeingKey foreingKey = attr.getForeingKey(); |
1013 |
SQLBuilder.TableNameBuilder foreingTable = sqlbuilder.createTableNameBuilder() |
1014 |
.database(table.getDatabase()) |
1015 |
.schema(table.getSchema()) |
1016 |
.name(foreingKey.getTableName()); |
1017 |
SQLBuilder.TableNameBuilder mainTable = sqlbuilder.createTableNameBuilder() |
1018 |
.database(table.getDatabase()) |
1019 |
.schema(table.getSchema()) |
1020 |
.name(table.getName()); |
1021 |
|
1022 |
if (!usedLeftJoins.contains(foreingTable.getName())) {
|
1023 |
Column v = sqlbuilder.column(mainTable, columnNameLocal); |
1024 |
v.setProperty(PROP_FEATURE_TYPE, type); |
1025 |
v.setProperty(PROP_JDBCHELPER, this);
|
1026 |
v.setProperty(PROP_QUERY, sqlbuilder.select().getProperty(PROP_QUERY)); |
1027 |
|
1028 |
sqlbuilder.select().from() |
1029 |
.left_join( |
1030 |
foreingTable, |
1031 |
expbuilder.eq( |
1032 |
v, |
1033 |
sqlbuilder.column(foreingTable, foreingKey.getCodeName()) |
1034 |
) |
1035 |
); |
1036 |
usedLeftJoins.add(foreingTable.getName()); |
1037 |
} |
1038 |
//No est? claro si debe a?adirse esta columna o no, OJO quitarlo o ponerlo altera los test de H2
|
1039 |
//Si se comentarizan ojo con extra_column_names ya que se habr?n a?adido columnas que no estar?n en la select
|
1040 |
if ( !(sqlbuilder.select().has_group_by() || sqlbuilder.select().has_aggregate_functions()) ) {
|
1041 |
sqlbuilder.select().column().name(foreingTable, columnNameForeing); |
1042 |
} |
1043 |
} |
1044 |
} |
1045 |
|
1046 |
} catch (Throwable th) { |
1047 |
LOGGER.warn("Can't replace FOREIGN_VALUE function.", th);
|
1048 |
throw th;
|
1049 |
} finally {
|
1050 |
// LOGGER.trace("Exit from replaceForeingValueFunction.");
|
1051 |
} |
1052 |
} |
1053 |
|
1054 |
protected void addTableToColumnReferences(SQLBuilder sqlbuilder, FeatureType type) { |
1055 |
SelectBuilder select = sqlbuilder.select(); |
1056 |
List<Pair<SQLBuilder.TableNameBuilder, FeatureType>> tables = new ArrayList<>(); |
1057 |
collectTablesFromSelect(select, tables, type); |
1058 |
|
1059 |
addTableToColumnReferencesInSingleSelect( |
1060 |
sqlbuilder, |
1061 |
select, |
1062 |
tables |
1063 |
); |
1064 |
|
1065 |
} |
1066 |
|
1067 |
private void collectTablesFromSelect(SelectBuilder select, List<Pair<SQLBuilder.TableNameBuilder, FeatureType>> tables, FeatureType type) throws LocatorException { |
1068 |
DataManager dataManager = DALLocator.getDataManager(); |
1069 |
|
1070 |
List<SQLBuilder.JoinBuilder> joins = select.from().getJoins();
|
1071 |
if(!CollectionUtils.isEmpty(joins)){
|
1072 |
for (SQLBuilder.JoinBuilder join : joins) {
|
1073 |
SQLBuilder.TableNameBuilder joinTable = join.getTable(); |
1074 |
FeatureType featureType = dataManager.getStoresRepository().getFeatureType(joinTable.getName()); |
1075 |
if(featureType != null){ |
1076 |
tables.add(new ImmutablePair<>(joinTable,featureType));
|
1077 |
} |
1078 |
} |
1079 |
} |
1080 |
SQLBuilder.TableNameBuilder table = select.from().table(); |
1081 |
if(type == null){ |
1082 |
type = dataManager.getStoresRepository().getFeatureType(table.getName()); |
1083 |
|
1084 |
} |
1085 |
if(type != null){ |
1086 |
tables.add(new ImmutablePair<>(table,type));
|
1087 |
} |
1088 |
} |
1089 |
|
1090 |
protected void addTableToColumnReferencesInSingleSelect(SQLBuilder sqlbuilder, SelectBuilder select, List<Pair<SQLBuilder.TableNameBuilder,FeatureType>> outerTables) { |
1091 |
|
1092 |
final SQLBuilder.TableNameBuilder fromTable = select.from().table();
|
1093 |
|
1094 |
final List<ExpressionBuilder.Value[]> value_replacements = new ArrayList<>(); |
1095 |
List<ExpressionBuilder.Variable> variables = new ArrayList<>(); |
1096 |
// List<ExpressionBuilder.Value> variablesToExclude = new ArrayList<>();
|
1097 |
|
1098 |
select.accept((ExpressionBuilder.Visitable value) -> { |
1099 |
if(value instanceof Column) { |
1100 |
Column c = (Column)value; |
1101 |
if(c.table() == null || !c.table().has_name() || !c.table().has_schema()){ |
1102 |
variables.add(c); |
1103 |
} |
1104 |
|
1105 |
} else if(value instanceof ExpressionBuilder.Variable) { |
1106 |
variables.add((ExpressionBuilder.Variable) value); |
1107 |
} |
1108 |
|
1109 |
}, new ExpressionBuilder.VisitorFilter() {
|
1110 |
@Override
|
1111 |
public boolean skipChildren() { |
1112 |
return true; |
1113 |
} |
1114 |
|
1115 |
@Override
|
1116 |
public boolean accept(ExpressionBuilder.Visitable visitable) { |
1117 |
if(select == visitable){
|
1118 |
return true; |
1119 |
} |
1120 |
if(visitable instanceof SelectBuilder) { |
1121 |
ArrayList<Pair<SQLBuilder.TableNameBuilder, FeatureType>> tables = new ArrayList<>(outerTables); |
1122 |
collectTablesFromSelect((SelectBuilder) visitable, tables, null);
|
1123 |
|
1124 |
addTableToColumnReferencesInSingleSelect(sqlbuilder, (SelectBuilder) visitable, tables); |
1125 |
return false; |
1126 |
} |
1127 |
return true; |
1128 |
} |
1129 |
}); |
1130 |
|
1131 |
for (ExpressionBuilder.Variable variable : variables) {
|
1132 |
ExpressionBuilder.Variable variable_replacement = null;
|
1133 |
|
1134 |
Pair<SQLBuilder.TableNameBuilder, FeatureType> tableNameAndFeatureType = getTableAndFeatureType(outerTables, variable.name()); |
1135 |
if (tableNameAndFeatureType != null) { |
1136 |
SQLBuilder.TableNameBuilder variableTable = tableNameAndFeatureType.getLeft(); |
1137 |
|
1138 |
if (variable instanceof SQLBuilder.Column) { |
1139 |
Column column = (SQLBuilder.Column) variable; |
1140 |
if (column.table() != null && column.table().has_name()) { |
1141 |
if (column.table().has_schema()) {
|
1142 |
//La columna tiene tabla y esquema => No hacemos nada
|
1143 |
} else {
|
1144 |
if(column.table().getName().equals(variableTable.getName())){
|
1145 |
SQLBuilder.TableNameBuilder t = sqlbuilder.createTableNameBuilder() |
1146 |
.name(column.table().getName()) |
1147 |
.schema(variableTable.getSchema()); |
1148 |
variable_replacement = sqlbuilder.column_from( |
1149 |
t, |
1150 |
variable |
1151 |
); |
1152 |
} else {
|
1153 |
if(fromTable.has_schema()){
|
1154 |
SQLBuilder.TableNameBuilder t = sqlbuilder.createTableNameBuilder() |
1155 |
.name(column.table().getName()) |
1156 |
.schema(fromTable.getSchema()); //Mismo esquema que en el FROM
|
1157 |
variable_replacement = sqlbuilder.column_from( |
1158 |
t, |
1159 |
variable |
1160 |
); |
1161 |
} else {
|
1162 |
// No tiene esquema ni podemos averiguarlo => No hacemos nada
|
1163 |
} |
1164 |
} |
1165 |
} |
1166 |
} else {
|
1167 |
column = sqlbuilder.column_from(tableNameAndFeatureType.getLeft(), variable); |
1168 |
column.setProperty(SQLBuilder.PROP_FEATURE_TYPE, tableNameAndFeatureType.getRight()); |
1169 |
variable_replacement = column; |
1170 |
} |
1171 |
} else {
|
1172 |
Column column = sqlbuilder.column_from(tableNameAndFeatureType.getLeft(), variable); |
1173 |
column.setProperty(SQLBuilder.PROP_FEATURE_TYPE, tableNameAndFeatureType.getRight()); |
1174 |
variable_replacement = column; |
1175 |
} |
1176 |
|
1177 |
} else {
|
1178 |
if (variable instanceof SQLBuilder.Column) { |
1179 |
Column column = (SQLBuilder.Column) variable; |
1180 |
if (column.table() == null || !column.table().has_name()) { |
1181 |
variable_replacement = sqlbuilder.column_from( |
1182 |
fromTable, |
1183 |
variable |
1184 |
); |
1185 |
} else if (!column.table().has_schema()) { |
1186 |
if(fromTable.has_schema()){
|
1187 |
SQLBuilder.TableNameBuilder t = sqlbuilder.createTableNameBuilder() |
1188 |
.name(column.table().getName()) |
1189 |
.schema(fromTable.getSchema()); //Mismo esquema que en el FROM
|
1190 |
variable_replacement = sqlbuilder.column_from( |
1191 |
t, |
1192 |
variable |
1193 |
); |
1194 |
} else {
|
1195 |
// No tiene esquema ni podemos averiguarlo => No hacemos nada
|
1196 |
} |
1197 |
} |
1198 |
} else {
|
1199 |
if( StringUtils.equals(fromTable.getName(), variable.name()) ) {
|
1200 |
LOGGER.debug("Uff, la variable coincide con el nombre de la tabla...\nNo esta nada claro que haya que ponerle el prefijo,\nde momento no hacemos nada.");
|
1201 |
} else {
|
1202 |
variable_replacement = sqlbuilder.column_from( |
1203 |
fromTable, |
1204 |
variable |
1205 |
); |
1206 |
} |
1207 |
} |
1208 |
} |
1209 |
if(variable_replacement != null){ |
1210 |
value_replacements.add( |
1211 |
new ExpressionBuilder.Value[]{ |
1212 |
variable, |
1213 |
variable_replacement |
1214 |
} |
1215 |
); |
1216 |
} |
1217 |
|
1218 |
} |
1219 |
|
1220 |
for (ExpressionBuilder.Value[] replaceValue : value_replacements) { |
1221 |
ExpressionBuilder.Value target = replaceValue[0];
|
1222 |
ExpressionBuilder.Value replacement = replaceValue[1];
|
1223 |
Boolean addTableName = (Boolean) target.getProperty(PROP_ADD_TABLE_NAME_TO_COLUMNS); |
1224 |
if(addTableName == null || !addTableName){ |
1225 |
continue;
|
1226 |
} |
1227 |
select.replace(target, replacement); |
1228 |
} |
1229 |
|
1230 |
} |
1231 |
|
1232 |
protected Pair<SQLBuilder.TableNameBuilder, FeatureType> getTableAndFeatureType(List<Pair<SQLBuilder.TableNameBuilder, FeatureType>> outerTables, String columnName) { |
1233 |
// ListIterator<Pair<SQLBuilder.TableNameBuilder, FeatureType>> it = outerTables.listIterator(outerTables.size());
|
1234 |
//
|
1235 |
// while (it.hasPrevious()) {
|
1236 |
// Pair<SQLBuilder.TableNameBuilder, FeatureType> pair = it.previous();
|
1237 |
// FeatureType featureType = pair.getRight();
|
1238 |
// if(featureType.get(columnName) != null){
|
1239 |
// return pair;
|
1240 |
// }
|
1241 |
// }
|
1242 |
|
1243 |
// ListIterator<Pair<SQLBuilder.TableNameBuilder, FeatureType>> it = new ReverseListIterator(outerTables);
|
1244 |
// while (it.hasNext()) {
|
1245 |
// Pair<SQLBuilder.TableNameBuilder, FeatureType> pair = it.next();
|
1246 |
// FeatureType featureType = pair.getRight();
|
1247 |
// if(featureType.get(columnName) != null){
|
1248 |
// return pair;
|
1249 |
// }
|
1250 |
// }
|
1251 |
|
1252 |
for (Iterator<Pair<SQLBuilder.TableNameBuilder, FeatureType>> iterator = new ReverseListIterator(outerTables); iterator.hasNext();) { |
1253 |
Pair<SQLBuilder.TableNameBuilder, FeatureType> pair = iterator.next(); |
1254 |
FeatureType featureType = pair.getRight(); |
1255 |
if(featureType.get(columnName) != null){ |
1256 |
return pair;
|
1257 |
} |
1258 |
} |
1259 |
|
1260 |
return null; |
1261 |
} |
1262 |
|
1263 |
@Override
|
1264 |
public void setTransaction(DataTransactionServices transaction) { |
1265 |
this.transactionsHelper.setTransaction(transaction);
|
1266 |
} |
1267 |
|
1268 |
@Override
|
1269 |
public String toString() { |
1270 |
try {
|
1271 |
ToStringBuilder builder = new ToStringBuilder(this); |
1272 |
builder.append("hash", String.format("%x", this.hashCode())); |
1273 |
builder.append("url", this.connectionParameters.getUrl()); |
1274 |
return builder.toString();
|
1275 |
} catch (Exception e) { |
1276 |
return super.toString(); |
1277 |
} |
1278 |
} |
1279 |
|
1280 |
@Override
|
1281 |
public String getConnectionProviderStatus() { |
1282 |
return ""; |
1283 |
} |
1284 |
|
1285 |
@Override
|
1286 |
public void expandCalculedColumns(JDBCSQLBuilderBase sqlbuilder) { |
1287 |
ComputedAttribute computedAttributeFormater = new ComputedAttribute(sqlbuilder, sqlbuilder.formatter());
|
1288 |
for (int i = 0; i < 10; i++) { |
1289 |
List<Pair<ExpressionBuilder.Variable, ExpressionBuilder.Value>> variablesToReplace = new ArrayList<>(); |
1290 |
sqlbuilder.accept((ExpressionBuilder.Visitable value) -> { |
1291 |
if (computedAttributeFormater.canApply((ExpressionBuilder.Value) value)) {
|
1292 |
ExpressionBuilder.Variable variable = (ExpressionBuilder.Variable) value; |
1293 |
ExpressionBuilder.Value replace = computedAttributeFormater.expandedValue(variable); |
1294 |
variablesToReplace.add(Pair.of(variable, replace)); |
1295 |
} |
1296 |
}, null);
|
1297 |
if (variablesToReplace.isEmpty()) {
|
1298 |
break;
|
1299 |
} |
1300 |
for (Pair<ExpressionBuilder.Variable, ExpressionBuilder.Value> entry : variablesToReplace) {
|
1301 |
ExpressionBuilder.Value variable = entry.getKey(); |
1302 |
ExpressionBuilder.Value replace = entry.getValue(); |
1303 |
Boolean addTableName = (Boolean) variable.getProperty(PROP_ADD_TABLE_NAME_TO_COLUMNS); |
1304 |
if (addTableName != null && addTableName) { |
1305 |
sqlbuilder.setProperties(replace, null, PROP_ADD_TABLE_NAME_TO_COLUMNS,true); |
1306 |
} |
1307 |
sqlbuilder.select().replace(variable, replace); |
1308 |
} |
1309 |
} |
1310 |
} |
1311 |
|
1312 |
@Override
|
1313 |
public DataTransactionServices getTransaction() {
|
1314 |
return (DataTransactionServices) this.transactionsHelper.getTransaction(); |
1315 |
} |
1316 |
|
1317 |
public ConnectionProvider getConnectionProvider() {
|
1318 |
return new FakeConnectionProvider(connectionParameters); |
1319 |
} |
1320 |
|
1321 |
protected String getConnectionProviderKey(JDBCConnectionParameters connectionParameters) { |
1322 |
String pass = Hex.encodeHexString((connectionParameters.getPassword()+"").getBytes()); |
1323 |
// String pass = connectionParameters.getPassword();
|
1324 |
return connectionParameters.getUrl() + ";user:"+connectionParameters.getUser()+"@"+pass; |
1325 |
} |
1326 |
|
1327 |
} |