mirror of
https://github.com/ebean-orm/ebean.git
synced 2026-11-18 14:58:47 +00:00
initial add of EbeanORM server based on v2.8.1
This commit is contained in:
1 parent
2b74d0f9d9
commit
96ce4c0ddf
1188 files changed
+135034
No files matched your search
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.avaje.ebean.bean.BeanCollection;
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
|
||||
/**
|
||||
* Continue the fetch using a Background thread. The client knows when this has
|
||||
* finished by checking to see if beanList.finishedFetch() is true.
|
||||
*/
|
||||
public class BackgroundFetch implements Callable<Integer> {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(BackgroundFetch.class.getName());
|
||||
|
||||
private final CQuery<?> cquery;
|
||||
|
||||
private final SpiTransaction transaction;
|
||||
|
||||
/**
|
||||
* Create the BackgroundFetch.
|
||||
*/
|
||||
public BackgroundFetch(CQuery<?> cquery) {
|
||||
this.cquery = cquery;
|
||||
this.transaction = cquery.getTransaction();
|
||||
}
|
||||
|
||||
/**
|
||||
* Continue the fetch.
|
||||
*/
|
||||
public Integer call() {
|
||||
try {
|
||||
|
||||
BeanCollection<?> bc = cquery.continueFetchingInBackground();
|
||||
|
||||
return bc.size();
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
return Integer.valueOf(0);
|
||||
|
||||
} finally {
|
||||
try {
|
||||
cquery.close();
|
||||
} catch (Exception e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
try {
|
||||
// we must have our own transaction for background fetching
|
||||
// and this performs the rollback... returning the
|
||||
// connection back into the connection pool.
|
||||
transaction.rollback();
|
||||
} catch (Exception e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append("BackgroundFetch ").append(cquery);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.avaje.ebeaninternal.api.BeanIdList;
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
|
||||
|
||||
/**
|
||||
* Continue the fetch using a Background thread. The client knows when this has
|
||||
* finished by checking to see if beanList.finishedFetch() is true.
|
||||
*/
|
||||
public class BackgroundIdFetch implements Callable<Integer> {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(BackgroundIdFetch.class.getName());
|
||||
|
||||
private final ResultSet rset;
|
||||
|
||||
private final PreparedStatement pstmt;
|
||||
|
||||
private final SpiTransaction transaction;
|
||||
|
||||
private final DbReadContext ctx;
|
||||
|
||||
private final BeanDescriptor<?> beanDescriptor;
|
||||
|
||||
private final BeanIdList idList;
|
||||
/**
|
||||
* Create the BackgroundFetch.
|
||||
*/
|
||||
public BackgroundIdFetch(SpiTransaction transaction,
|
||||
ResultSet rset, PreparedStatement pstmt,
|
||||
DbReadContext ctx, BeanDescriptor<?> beanDescriptor,
|
||||
BeanIdList idList) {
|
||||
|
||||
this.ctx = ctx;
|
||||
this.transaction = transaction;
|
||||
this.rset = rset;
|
||||
this.pstmt = pstmt;
|
||||
this.beanDescriptor = beanDescriptor;
|
||||
this.idList = idList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Continue the fetch.
|
||||
*/
|
||||
public Integer call() {
|
||||
try {
|
||||
int startSize = idList.getIdList().size();
|
||||
int rowsRead = 0;
|
||||
while (rset.next()){
|
||||
Object idValue = beanDescriptor.getIdBinder().read(ctx);
|
||||
idList.add(idValue);
|
||||
ctx.getDataReader().resetColumnPosition();
|
||||
rowsRead++;
|
||||
}
|
||||
|
||||
if (logger.isLoggable(Level.INFO)){
|
||||
logger.info("BG FetchIds read:"+rowsRead+" total:"+(startSize+rowsRead));
|
||||
}
|
||||
|
||||
return rowsRead;
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
return 0;
|
||||
|
||||
} finally {
|
||||
try {
|
||||
close();
|
||||
} catch (Exception e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
try {
|
||||
// we must have our own transaction for background fetching
|
||||
// and this performs the rollback... returning the
|
||||
// connection back into the connection pool.
|
||||
transaction.rollback();
|
||||
} catch (Exception e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void close() {
|
||||
try {
|
||||
if (rset != null) {
|
||||
rset.close();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
try {
|
||||
if (pstmt != null) {
|
||||
pstmt.close();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
/**
|
||||
* A base object for query Future objects.
|
||||
*
|
||||
* @author rbygrave
|
||||
*
|
||||
* @param <T> the entity bean type
|
||||
*/
|
||||
public abstract class BaseFuture<T> implements Future<T> {
|
||||
|
||||
private final FutureTask<T> futureTask;
|
||||
|
||||
public BaseFuture(FutureTask<T> futureTask) {
|
||||
this.futureTask = futureTask;
|
||||
}
|
||||
|
||||
public boolean cancel(boolean mayInterruptIfRunning) {
|
||||
return futureTask.cancel(mayInterruptIfRunning);
|
||||
}
|
||||
|
||||
public T get() throws InterruptedException, ExecutionException {
|
||||
return futureTask.get();
|
||||
}
|
||||
|
||||
public T get(long timeout, TimeUnit unit)
|
||||
throws InterruptedException, ExecutionException, TimeoutException {
|
||||
|
||||
return futureTask.get(timeout, unit);
|
||||
}
|
||||
|
||||
public boolean isCancelled() {
|
||||
return futureTask.isCancelled();
|
||||
}
|
||||
|
||||
public boolean isDone() {
|
||||
return futureTask.isDone();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
import com.avaje.ebean.bean.BeanCollection;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.core.RelationalQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import com.avaje.ebeaninternal.server.util.BeanCollectionFactory;
|
||||
import com.avaje.ebeaninternal.server.util.BeanCollectionParams;
|
||||
|
||||
/**
|
||||
* Wraps a BeanCollection with helper methods to add beans.
|
||||
* <p>
|
||||
* Helps adding the bean to the underlying set list or map.
|
||||
* </p>
|
||||
*/
|
||||
public final class BeanCollectionWrapper {
|
||||
|
||||
/**
|
||||
* Flag set if this builds a Map rather than a Collection.
|
||||
*/
|
||||
private final boolean isMap;
|
||||
|
||||
/**
|
||||
* The type.
|
||||
*/
|
||||
private final SpiQuery.Type queryType;
|
||||
|
||||
/**
|
||||
* A property name used as key for a Map.
|
||||
*/
|
||||
private final String mapKey;
|
||||
|
||||
/**
|
||||
* The actual BeanCollection.
|
||||
*/
|
||||
private final BeanCollection<?> beanCollection;
|
||||
|
||||
/**
|
||||
* Collection type of BeanCollection.
|
||||
*/
|
||||
private final Collection<Object> collection;
|
||||
|
||||
/**
|
||||
* Map type of BeanCollection.
|
||||
*/
|
||||
private final Map<Object,Object> map;
|
||||
|
||||
/**
|
||||
* The associated BeanDescriptor.
|
||||
*/
|
||||
private final BeanDescriptor<?> desc;
|
||||
|
||||
/**
|
||||
* The number of rows added.
|
||||
*/
|
||||
private int rowCount;
|
||||
|
||||
public BeanCollectionWrapper(RelationalQueryRequest request) {
|
||||
|
||||
this.desc = null;
|
||||
this.queryType = request.getQueryType();
|
||||
this.mapKey = request.getQuery().getMapKey();
|
||||
this.isMap = SpiQuery.Type.MAP.equals(queryType);
|
||||
|
||||
this.beanCollection = createBeanCollection(queryType);
|
||||
this.collection = getCollection(isMap);
|
||||
this.map = getMap(isMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create based on a Find.
|
||||
*/
|
||||
public BeanCollectionWrapper(OrmQueryRequest<?> request) {
|
||||
|
||||
this.desc = request.getBeanDescriptor();
|
||||
this.queryType = request.getQueryType();
|
||||
this.mapKey = request.getQuery().getMapKey();
|
||||
this.isMap = SpiQuery.Type.MAP.equals(queryType);
|
||||
|
||||
this.beanCollection = createBeanCollection(queryType);
|
||||
this.collection = getCollection(isMap);
|
||||
this.map = getMap(isMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create based on a ManyType and mapKey. Note the mapKey is only used if
|
||||
* the manyType is a Map.
|
||||
* <p>
|
||||
* modifyListening is set to true if this is a collection used to hold
|
||||
* ManyToMany associated objects.
|
||||
* </p>
|
||||
*/
|
||||
public BeanCollectionWrapper(BeanPropertyAssocMany<?> manyProp) {
|
||||
|
||||
this.queryType = manyProp.getManyType().getQueryType();
|
||||
this.mapKey = manyProp.getMapKey();
|
||||
this.desc = manyProp.getTargetDescriptor();
|
||||
this.isMap = SpiQuery.Type.MAP.equals(queryType);
|
||||
|
||||
this.beanCollection = createBeanCollection(queryType);
|
||||
this.collection = getCollection(isMap);
|
||||
this.map = getMap(isMap);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
private Map<Object,Object> getMap(boolean isMap) {
|
||||
return isMap ? (Map)beanCollection : null;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Collection<Object> getCollection(boolean isMap) {
|
||||
return isMap ? null : (Collection<Object>)beanCollection ;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying BeanCollection.
|
||||
*/
|
||||
public BeanCollection<?> getBeanCollection() {
|
||||
return beanCollection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a BeanCollection of the correct type.
|
||||
*/
|
||||
private BeanCollection<?> createBeanCollection(SpiQuery.Type manyType) {
|
||||
BeanCollectionParams p = new BeanCollectionParams(manyType);
|
||||
return BeanCollectionFactory.create(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this wraps a Map rather than a set or list.
|
||||
*/
|
||||
public boolean isMap() {
|
||||
return isMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the number of rows added to this wrapper.
|
||||
*/
|
||||
public int size() {
|
||||
return rowCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the bean to the collection held in this wrapper.
|
||||
*/
|
||||
public void add(Object bean) {
|
||||
add(bean, beanCollection);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the bean to the collection passed.
|
||||
*
|
||||
* @param bean
|
||||
* the bean to add
|
||||
* @param collection
|
||||
* the collection or map to add the bean to
|
||||
*/
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void add(Object bean, Object collection) {
|
||||
if (bean == null) {
|
||||
return;
|
||||
}
|
||||
rowCount++;
|
||||
if (isMap) {
|
||||
Object keyValue = null;
|
||||
if (mapKey != null) {
|
||||
// use the value for the property
|
||||
keyValue = desc.getValue(bean, mapKey);
|
||||
} else {
|
||||
// use the uniqueId for this
|
||||
keyValue = desc.getId(bean);
|
||||
}
|
||||
|
||||
Map mapColl = (Map) collection;
|
||||
mapColl.put(keyValue, bean);
|
||||
} else {
|
||||
((Collection) collection).add(bean);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifically add to a Collection.
|
||||
*/
|
||||
public void addToCollection(Object bean) {
|
||||
collection.add(bean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifically add to this as a Map with a known key.
|
||||
*/
|
||||
public void addToMap(Object bean, Object key) {
|
||||
map.put(key, bean);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,879 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebean.QueryIterator;
|
||||
import com.avaje.ebean.QueryListener;
|
||||
import com.avaje.ebean.bean.BeanCollection;
|
||||
import com.avaje.ebean.bean.BeanCollectionAdd;
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
import com.avaje.ebean.bean.EntityBeanIntercept;
|
||||
import com.avaje.ebean.bean.NodeUsageCollector;
|
||||
import com.avaje.ebean.bean.NodeUsageListener;
|
||||
import com.avaje.ebean.bean.ObjectGraphNode;
|
||||
import com.avaje.ebean.bean.PersistenceContext;
|
||||
import com.avaje.ebeaninternal.api.LoadContext;
|
||||
import com.avaje.ebeaninternal.api.SpiExpressionList;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery.Mode;
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
import com.avaje.ebeaninternal.server.autofetch.AutoFetchManager;
|
||||
import com.avaje.ebeaninternal.server.core.Message;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.core.SpiOrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanCollectionHelp;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanCollectionHelpFactory;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
|
||||
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
|
||||
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
|
||||
import com.avaje.ebeaninternal.server.querydefn.OrmQueryProperties;
|
||||
import com.avaje.ebeaninternal.server.transaction.DefaultPersistenceContext;
|
||||
import com.avaje.ebeaninternal.server.type.DataBind;
|
||||
import com.avaje.ebeaninternal.server.type.DataReader;
|
||||
|
||||
/**
|
||||
* An object that represents a SqlSelect statement.
|
||||
* <p>
|
||||
* The SqlSelect is based on a tree (Object Graph). The tree is traversed to see
|
||||
* what parts are included in the tree according to the value of
|
||||
* find.getInclude();
|
||||
* </p>
|
||||
* <p>
|
||||
* The tree structure is flattened into a SqlSelectChain. The SqlSelectChain is
|
||||
* the key object used in reading the flat resultSet back into Objects.
|
||||
* </p>
|
||||
*/
|
||||
public class CQuery<T> implements DbReadContext, CancelableQuery {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(CQuery.class.getName());
|
||||
|
||||
private static final int GLOBAL_ROW_LIMIT = 1000000;
|
||||
|
||||
/**
|
||||
* The resultSet rows read.
|
||||
*/
|
||||
private int rowCount;
|
||||
|
||||
/**
|
||||
* The number of master EntityBeans loaded.
|
||||
*/
|
||||
private int loadedBeanCount;
|
||||
|
||||
/**
|
||||
* Flag set when no more rows are in the resultSet.
|
||||
*/
|
||||
private boolean noMoreRows;
|
||||
/**
|
||||
* Id of loaded 'master' bean.
|
||||
*/
|
||||
private Object loadedBeanId;
|
||||
/**
|
||||
* Flag set when 'master' bean changed.
|
||||
*/
|
||||
boolean loadedBeanChanged;
|
||||
/**
|
||||
* The 'master' bean just loaded.
|
||||
*/
|
||||
private Object loadedBean;
|
||||
|
||||
/**
|
||||
* Holds the previous loaded bean.
|
||||
*/
|
||||
private Object prevLoadedBean;
|
||||
|
||||
/**
|
||||
* The detail bean just loaded.
|
||||
*/
|
||||
private Object loadedManyBean;
|
||||
|
||||
/**
|
||||
* The previous 'detail' collection remembered so that for manyToMany we can
|
||||
* turn on the modify listening.
|
||||
*/
|
||||
private Object prevDetailCollection;
|
||||
|
||||
/**
|
||||
* The current 'detail' collection being populated.
|
||||
*/
|
||||
private Object currentDetailCollection;
|
||||
|
||||
/**
|
||||
* The 'master' collection being populated.
|
||||
*/
|
||||
private final BeanCollection<T> collection;
|
||||
/**
|
||||
* The help for the 'master' collection.
|
||||
*/
|
||||
private final BeanCollectionHelp<T> help;
|
||||
|
||||
/**
|
||||
* The overall find request wrapper object.
|
||||
*/
|
||||
private final OrmQueryRequest<T> request;
|
||||
|
||||
private final BeanDescriptor<T> desc;
|
||||
|
||||
private final SpiQuery<T> query;
|
||||
|
||||
private final QueryListener<T> queryListener;
|
||||
|
||||
private Map<String,String> currentPathMap;
|
||||
|
||||
private String currentPrefix;
|
||||
|
||||
/**
|
||||
* Flag set true when reading 'master' and 'detail' beans.
|
||||
*/
|
||||
private final boolean manyIncluded;
|
||||
|
||||
/**
|
||||
* Where clause predicates.
|
||||
*/
|
||||
private final CQueryPredicates predicates;
|
||||
|
||||
/**
|
||||
* Object handling the SELECT generation and reading.
|
||||
*/
|
||||
private final SqlTree sqlTree;
|
||||
|
||||
private final boolean rawSql;
|
||||
|
||||
/**
|
||||
* The final sql that is generated.
|
||||
*/
|
||||
private final String sql;
|
||||
|
||||
/**
|
||||
* Where clause to show in logs when using an existing query plan.
|
||||
*/
|
||||
private final String logWhereSql;
|
||||
|
||||
/**
|
||||
* Set to true if the row number column is included in the sql.
|
||||
*/
|
||||
private final boolean rowNumberIncluded;
|
||||
|
||||
/**
|
||||
* Tree that knows how to build the master and detail beans from the
|
||||
* resultSet.
|
||||
*/
|
||||
private final SqlTreeNode rootNode;
|
||||
|
||||
/**
|
||||
* For master detail query.
|
||||
*/
|
||||
private final BeanPropertyAssocMany<?> manyProperty;
|
||||
|
||||
/**
|
||||
* The many property Expression language object.
|
||||
*/
|
||||
private final ElPropertyValue manyPropertyEl;
|
||||
|
||||
private final int backgroundFetchAfter;
|
||||
|
||||
private final int maxRowsLimit;
|
||||
|
||||
/**
|
||||
* Flag set when backgroundFetchAfter limit is hit.
|
||||
*/
|
||||
private boolean hasHitBackgroundFetchAfter;
|
||||
|
||||
private final PersistenceContext persistenceContext;
|
||||
|
||||
private DataReader dataReader;
|
||||
|
||||
/**
|
||||
* The statement used to create the resultSet.
|
||||
*/
|
||||
private PreparedStatement pstmt;
|
||||
|
||||
private boolean cancelled;
|
||||
|
||||
private String bindLog;
|
||||
|
||||
private final CQueryPlan queryPlan;
|
||||
|
||||
private long startNano;
|
||||
|
||||
private final Mode queryMode;
|
||||
|
||||
private final boolean autoFetchProfiling;
|
||||
|
||||
private final ObjectGraphNode autoFetchParentNode;
|
||||
|
||||
private final AutoFetchManager autoFetchManager;
|
||||
private final WeakReference<NodeUsageListener> autoFetchManagerRef;
|
||||
|
||||
private int executionTimeMicros;
|
||||
|
||||
private final Boolean readOnly;
|
||||
|
||||
private final SpiExpressionList<?> filterMany;
|
||||
|
||||
/**
|
||||
* Create the Sql select based on the request.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public CQuery(OrmQueryRequest<T> request, CQueryPredicates predicates, CQueryPlan queryPlan) {
|
||||
this.request = request;
|
||||
this.queryPlan = queryPlan;
|
||||
this.query = request.getQuery();
|
||||
this.queryMode = query.getMode();
|
||||
|
||||
this.readOnly = request.isReadOnly();
|
||||
|
||||
this.autoFetchManager = query.getAutoFetchManager();
|
||||
this.autoFetchProfiling = autoFetchManager != null;
|
||||
this.autoFetchParentNode = autoFetchProfiling ? query.getParentNode() : null;
|
||||
this.autoFetchManagerRef = autoFetchProfiling ? new WeakReference<NodeUsageListener>(autoFetchManager) : null;
|
||||
|
||||
// set the generated sql back to the query
|
||||
// so its available to the user...
|
||||
query.setGeneratedSql(queryPlan.getSql());
|
||||
|
||||
this.sqlTree = queryPlan.getSqlTree();
|
||||
this.rootNode = sqlTree.getRootNode();
|
||||
|
||||
this.manyProperty = sqlTree.getManyProperty();
|
||||
this.manyPropertyEl = sqlTree.getManyPropertyEl();
|
||||
this.manyIncluded = sqlTree.isManyIncluded();
|
||||
if (manyIncluded) {
|
||||
// get filter to put on the collection for reuse with refresh
|
||||
String manyPropertyName = sqlTree.getManyPropertyName();
|
||||
OrmQueryProperties chunk = query.getDetail().getChunk(manyPropertyName, false);
|
||||
this.filterMany = chunk.getFilterMany();
|
||||
} else {
|
||||
this.filterMany = null;
|
||||
}
|
||||
|
||||
this.sql = queryPlan.getSql();
|
||||
this.rawSql = queryPlan.isRawSql();
|
||||
this.rowNumberIncluded = queryPlan.isRowNumberIncluded();
|
||||
this.logWhereSql = queryPlan.getLogWhereSql();
|
||||
this.desc = request.getBeanDescriptor();
|
||||
this.predicates = predicates;
|
||||
|
||||
this.queryListener = query.getListener();
|
||||
if (queryListener == null) {
|
||||
// normal, use the one from the transaction
|
||||
this.persistenceContext = request.getPersistenceContext();
|
||||
} else {
|
||||
// 'Row Level Transaction Context'...
|
||||
// local transaction context that will be reset
|
||||
// after each 'master' bean is sent to the listener
|
||||
this.persistenceContext = new DefaultPersistenceContext();
|
||||
}
|
||||
|
||||
this.maxRowsLimit = query.getMaxRows() > 0 ? query.getMaxRows() : GLOBAL_ROW_LIMIT;
|
||||
this.backgroundFetchAfter = query.getBackgroundFetchAfter() > 0 ? query.getBackgroundFetchAfter() : Integer.MAX_VALUE;
|
||||
|
||||
this.help = createHelp(request);
|
||||
this.collection = (BeanCollection<T>)(help != null ? help.createEmpty(false) : null);
|
||||
}
|
||||
|
||||
private BeanCollectionHelp<T> createHelp(OrmQueryRequest<T> request) {
|
||||
if (request.isFindById()) {
|
||||
return null;
|
||||
} else {
|
||||
SpiQuery.Type manyType = request.getQuery().getType();
|
||||
if (manyType == null){
|
||||
// subQuery compiled for InQueryExpression
|
||||
return null;
|
||||
}
|
||||
return BeanCollectionHelpFactory.create(request);
|
||||
}
|
||||
}
|
||||
|
||||
public Boolean isReadOnly() {
|
||||
return readOnly;
|
||||
}
|
||||
|
||||
public void propagateState(Object e) {
|
||||
if (Boolean.TRUE.equals(readOnly)){
|
||||
if (e instanceof EntityBean){
|
||||
((EntityBean)e)._ebean_getIntercept().setReadOnly(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public DataReader getDataReader() {
|
||||
return dataReader;
|
||||
}
|
||||
|
||||
public Mode getQueryMode() {
|
||||
return queryMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if we want to return vanilla (not enhanced) objects.
|
||||
*/
|
||||
public boolean isVanillaMode() {
|
||||
return request.isVanillaMode();
|
||||
}
|
||||
|
||||
public CQueryPredicates getPredicates() {
|
||||
return predicates;
|
||||
}
|
||||
|
||||
public LoadContext getGraphContext() {
|
||||
return request.getGraphContext();
|
||||
}
|
||||
|
||||
public SpiOrmQueryRequest<?> getQueryRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
synchronized (this) {
|
||||
this.cancelled = true;
|
||||
if (pstmt != null){
|
||||
try {
|
||||
pstmt.cancel();
|
||||
} catch (SQLException e){
|
||||
String msg = "Error cancelling query";
|
||||
throw new PersistenceException(msg, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean prepareBindExecuteQuery() throws SQLException {
|
||||
|
||||
synchronized (this) {
|
||||
if (cancelled || query.isCancelled()){
|
||||
// cancelled before we started
|
||||
cancelled = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
startNano = System.nanoTime();
|
||||
|
||||
// prepare
|
||||
SpiTransaction t = request.getTransaction();
|
||||
Connection conn = t.getInternalConnection();
|
||||
pstmt = conn.prepareStatement(sql);
|
||||
|
||||
if (query.getTimeout() > 0){
|
||||
pstmt.setQueryTimeout(query.getTimeout());
|
||||
}
|
||||
if (query.getBufferFetchSizeHint() > 0){
|
||||
pstmt.setFetchSize(query.getBufferFetchSizeHint());
|
||||
}
|
||||
|
||||
DataBind dataBind = new DataBind(pstmt);
|
||||
|
||||
// bind keys for encrypted properties
|
||||
queryPlan.bindEncryptedProperties(dataBind);
|
||||
|
||||
bindLog = predicates.bind(dataBind);
|
||||
|
||||
// executeQuery
|
||||
ResultSet rset = pstmt.executeQuery();
|
||||
dataReader = queryPlan.createDataReader(rset);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the resources.
|
||||
* <p>
|
||||
* The jdbc resultSet and statement need to be closed. Its important that
|
||||
* this method is called.
|
||||
* </p>
|
||||
*/
|
||||
public void close() {
|
||||
try {
|
||||
if (dataReader != null) {
|
||||
dataReader.close();
|
||||
dataReader = null;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
try {
|
||||
if (pstmt != null) {
|
||||
pstmt.close();
|
||||
pstmt = null;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
}
|
||||
|
||||
// /**
|
||||
// * Return the reference options used to define cache use.
|
||||
// */
|
||||
// public ReferenceOptions getReferenceOptionsFor(BeanPropertyAssocOne<?> beanProp) {
|
||||
//
|
||||
// String beanPropName = beanProp.getName();
|
||||
// if (currentPrefix != null){
|
||||
// beanPropName = currentPrefix+"."+beanPropName;
|
||||
// }
|
||||
// //ReferenceOptions opt = referenceOptionsMap.get(beanPropName);
|
||||
// if (opt == null){
|
||||
// OrmQueryProperties chunk = queryDetail.getChunk(beanPropName, false);
|
||||
// if (chunk != null) {
|
||||
// // get the options from the query
|
||||
// opt = chunk.getReferenceOptions();
|
||||
// }
|
||||
// if (opt == null){
|
||||
// // get the default options defined for the target bean type
|
||||
// opt = beanProp.getTargetDescriptor().getReferenceOptions();
|
||||
// }
|
||||
// referenceOptionsMap.put(beanPropName, opt);
|
||||
// }
|
||||
//
|
||||
// return opt;
|
||||
// }
|
||||
|
||||
/**
|
||||
* Return the persistence context.
|
||||
*/
|
||||
public PersistenceContext getPersistenceContext(){
|
||||
return persistenceContext;
|
||||
}
|
||||
|
||||
public void setLoadedBean(Object bean, Object id) {
|
||||
if (id != null && id.equals(loadedBeanId)) {
|
||||
// master/detail loading with master bean
|
||||
// unchanged. NB Using id to avoid any issue
|
||||
// with equals not being implemented
|
||||
|
||||
} else {
|
||||
if (manyIncluded) {
|
||||
if (rowCount > 1) {
|
||||
loadedBeanChanged = true;
|
||||
}
|
||||
this.prevLoadedBean = loadedBean;
|
||||
this.loadedBeanId = id;
|
||||
}
|
||||
this.loadedBean = bean;
|
||||
}
|
||||
}
|
||||
|
||||
public void setLoadedManyBean(Object manyValue) {
|
||||
this.loadedManyBean = manyValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the last read bean.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public T getLoadedBean() {
|
||||
if (manyIncluded) {
|
||||
if (prevDetailCollection instanceof BeanCollection<?>) {
|
||||
((BeanCollection<?>)prevDetailCollection).setModifyListening(manyProperty.getModifyListenMode());
|
||||
|
||||
} else if (currentDetailCollection instanceof BeanCollection<?>) {
|
||||
((BeanCollection<?>)currentDetailCollection).setModifyListening(manyProperty.getModifyListenMode());
|
||||
}
|
||||
}
|
||||
|
||||
if (prevLoadedBean != null) {
|
||||
return (T)prevLoadedBean;
|
||||
} else {
|
||||
return (T)loadedBean;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasMoreRows() throws SQLException {
|
||||
synchronized (this) {
|
||||
if (cancelled){
|
||||
return false;
|
||||
}
|
||||
return dataReader.next();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a row from the result set returning a bean.
|
||||
* <p>
|
||||
* If the query includes a many then the first object in the returned array
|
||||
* is the one/master and the second the many/detail.
|
||||
* </p>
|
||||
*/
|
||||
private boolean readRow() throws SQLException {
|
||||
|
||||
synchronized (this) {
|
||||
if (cancelled){
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!dataReader.next()){
|
||||
return false;
|
||||
}
|
||||
|
||||
rowCount++;
|
||||
dataReader.resetColumnPosition();
|
||||
|
||||
if (rowNumberIncluded) {
|
||||
// row_number() column used for limit features
|
||||
dataReader.incrementPos(1);
|
||||
}
|
||||
|
||||
rootNode.load(this, null);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public int getQueryExecutionTimeMicros(){
|
||||
return executionTimeMicros;
|
||||
}
|
||||
|
||||
public boolean readBean() throws SQLException {
|
||||
|
||||
boolean result = readBeanInternal(true);
|
||||
|
||||
updateExecutionStatistics();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean readBeanInternal(boolean inForeground) throws SQLException {
|
||||
|
||||
if (loadedBeanCount >= maxRowsLimit) {
|
||||
collection.setHasMoreRows(hasMoreRows());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (inForeground && loadedBeanCount >= backgroundFetchAfter) {
|
||||
hasHitBackgroundFetchAfter = true;
|
||||
collection.setFinishedFetch(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!manyIncluded) {
|
||||
// simple query... no details...
|
||||
return readRow();
|
||||
}
|
||||
|
||||
if (noMoreRows) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (rowCount == 0) {
|
||||
if (!readRow()) {
|
||||
// no rows at all...
|
||||
return false;
|
||||
} else {
|
||||
createNewDetailCollection();
|
||||
}
|
||||
}
|
||||
|
||||
if (readIntoCurrentDetailCollection()) {
|
||||
createNewDetailCollection();
|
||||
// return prevLoadedBean
|
||||
return true;
|
||||
|
||||
} else {
|
||||
// return loadedBean
|
||||
prevDetailCollection = null;
|
||||
prevLoadedBean = null;
|
||||
noMoreRows = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean readIntoCurrentDetailCollection() throws SQLException {
|
||||
while (readRow()) {
|
||||
if (loadedBeanChanged) {
|
||||
loadedBeanChanged = false;
|
||||
return true;
|
||||
} else {
|
||||
addToCurrentDetailCollection();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private BeanCollectionAdd currentDetailAdd;
|
||||
|
||||
private void createNewDetailCollection() {
|
||||
prevDetailCollection = currentDetailCollection;
|
||||
if (queryMode.equals(Mode.LAZYLOAD_MANY)){
|
||||
// just populate the current collection
|
||||
currentDetailCollection = manyPropertyEl.elGetValue(loadedBean);
|
||||
} else {
|
||||
// create a new collection to populate and assign to the bean
|
||||
currentDetailCollection = manyProperty.createEmpty(request.isVanillaMode());
|
||||
manyPropertyEl.elSetValue(loadedBean, currentDetailCollection, false, false);
|
||||
}
|
||||
|
||||
if (filterMany != null && !request.isVanillaMode()){
|
||||
// remember the for use with a refresh
|
||||
((BeanCollection<?>)currentDetailCollection).setFilterMany(filterMany);
|
||||
}
|
||||
|
||||
// the manyKey is always null for this case, just using default mapKey on the property
|
||||
currentDetailAdd = manyProperty.getBeanCollectionAdd(currentDetailCollection, null);
|
||||
addToCurrentDetailCollection();
|
||||
}
|
||||
|
||||
private void addToCurrentDetailCollection() {
|
||||
if (loadedManyBean != null) {
|
||||
currentDetailAdd.addBean(loadedManyBean);
|
||||
}
|
||||
}
|
||||
|
||||
public BeanCollection<T> continueFetchingInBackground() throws SQLException {
|
||||
readTheRows(false);
|
||||
collection.setFinishedFetch(true);
|
||||
return collection;
|
||||
}
|
||||
|
||||
public BeanCollection<T> readCollection() throws SQLException {
|
||||
|
||||
readTheRows(true);
|
||||
|
||||
updateExecutionStatistics();
|
||||
|
||||
return collection;
|
||||
}
|
||||
|
||||
protected void updateExecutionStatistics() {
|
||||
try {
|
||||
long exeNano = System.nanoTime() - startNano;
|
||||
executionTimeMicros = (int)exeNano/1000;
|
||||
|
||||
if (autoFetchProfiling){
|
||||
autoFetchManager.collectQueryInfo(autoFetchParentNode, loadedBeanCount, executionTimeMicros);
|
||||
}
|
||||
queryPlan.executionTime(loadedBeanCount, executionTimeMicros);
|
||||
|
||||
} catch (Exception e){
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
}
|
||||
|
||||
public QueryIterator<T> readIterate(int bufferSize, OrmQueryRequest<T> request) {
|
||||
|
||||
if (bufferSize > 0){
|
||||
return new CQueryIteratorWithBuffer<T>(this, request, bufferSize);
|
||||
|
||||
} else {
|
||||
return new CQueryIteratorSimple<T>(this, request);
|
||||
}
|
||||
}
|
||||
|
||||
private void readTheRows(boolean inForeground) throws SQLException {
|
||||
while (hasNextBean(inForeground)) {
|
||||
if (queryListener != null) {
|
||||
queryListener.process(getLoadedBean());
|
||||
|
||||
} else {
|
||||
// add to the list/set/map
|
||||
help.add(collection, getLoadedBean());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected boolean hasNextBean(boolean inForeground) throws SQLException {
|
||||
|
||||
if (!readBeanInternal(inForeground)) {
|
||||
return false;
|
||||
|
||||
} else {
|
||||
loadedBeanCount++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public String getLoadedRowDetail() {
|
||||
if (!manyIncluded) {
|
||||
return String.valueOf(rowCount);
|
||||
} else {
|
||||
return loadedBeanCount + ":" + rowCount;
|
||||
}
|
||||
}
|
||||
|
||||
public void register(String path, EntityBeanIntercept ebi){
|
||||
|
||||
path = getPath(path);
|
||||
request.getGraphContext().register(path, ebi);
|
||||
}
|
||||
|
||||
public void register(String path, BeanCollection<?> bc){
|
||||
|
||||
path = getPath(path);
|
||||
request.getGraphContext().register(path, bc);
|
||||
}
|
||||
|
||||
|
||||
public boolean useBackgroundToContinueFetch() {
|
||||
return hasHitBackgroundFetchAfter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the query name.
|
||||
*/
|
||||
public String getName() {
|
||||
return query.getName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this is a raw sql query as opposed to Ebean generated sql.
|
||||
*/
|
||||
public boolean isRawSql() {
|
||||
return rawSql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the where predicate for display in the transaction log.
|
||||
*/
|
||||
public String getLogWhereSql() {
|
||||
return logWhereSql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the property that is associated with the many. There can only be
|
||||
* one per SqlSelect. This can be null.
|
||||
*/
|
||||
public BeanPropertyAssocMany<?> getManyProperty() {
|
||||
return manyProperty;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the summary of the sql.
|
||||
*/
|
||||
public String getSummary() {
|
||||
return sqlTree.getSummary();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the SqlSelectChain. This is the flattened structure that
|
||||
* represents this query.
|
||||
*/
|
||||
public SqlTree getSqlTree() {
|
||||
return sqlTree;
|
||||
}
|
||||
|
||||
public String getBindLog() {
|
||||
return bindLog;
|
||||
}
|
||||
|
||||
public SpiTransaction getTransaction() {
|
||||
return request.getTransaction();
|
||||
}
|
||||
|
||||
public String getBeanType() {
|
||||
return desc.getFullName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the short bean name.
|
||||
*/
|
||||
public String getBeanName() {
|
||||
return desc.getName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the generated sql.
|
||||
*/
|
||||
public String getGeneratedSql() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a PersistenceException including interesting information like the bindLog and sql used.
|
||||
*/
|
||||
public PersistenceException createPersistenceException(SQLException e) {
|
||||
|
||||
return createPersistenceException(e, getTransaction(), bindLog, sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a PersistenceException including interesting information like the bindLog and sql used.
|
||||
*/
|
||||
public static PersistenceException createPersistenceException(SQLException e, SpiTransaction t, String bindLog, String sql) {
|
||||
|
||||
if (t.isLogSummary()) {
|
||||
// log the error to the transaction log
|
||||
String errMsg = StringHelper.replaceStringMulti(e.getMessage(), new String[] { "\r", "\n" }, "\\n ");
|
||||
String msg = "ERROR executing query: bindLog[" + bindLog + "] error[" + errMsg + "]";
|
||||
t.logInternal(msg);
|
||||
}
|
||||
|
||||
// ensure 'rollback' is logged if queryOnly transaction
|
||||
t.getConnection();
|
||||
|
||||
// build a decent error message for the exception
|
||||
String m = Message.msg("fetch.sqlerror", e.getMessage(), bindLog, sql);
|
||||
return new PersistenceException(m, e);
|
||||
}
|
||||
|
||||
/**
|
||||
* Should we create profileNodes for beans created in this query.
|
||||
* <p>
|
||||
* This is true for all queries except lazy load bean queries.
|
||||
* </p>
|
||||
*/
|
||||
public boolean isAutoFetchProfiling() {
|
||||
// need query.isProfiling() because we just take the data
|
||||
// from the lazy loaded or refreshed beans and put it into the already
|
||||
// existing beans which are already collecting usage information
|
||||
return autoFetchProfiling && query.isUsageProfiling();
|
||||
}
|
||||
|
||||
private String getPath(String propertyName) {
|
||||
|
||||
if (currentPrefix == null){
|
||||
return propertyName;
|
||||
} else if (propertyName == null) {
|
||||
return currentPrefix;
|
||||
}
|
||||
|
||||
String path = currentPathMap.get(propertyName);
|
||||
if (path != null){
|
||||
return path;
|
||||
} else {
|
||||
return currentPrefix+"."+propertyName;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void profileBean(EntityBeanIntercept ebi, String prefix) {
|
||||
|
||||
ObjectGraphNode node = request.getGraphContext().getObjectGraphNode(prefix);
|
||||
|
||||
ebi.setNodeUsageCollector(new NodeUsageCollector(node, autoFetchManagerRef));
|
||||
}
|
||||
|
||||
public void setCurrentPrefix(String currentPrefix, Map<String,String> currentPathMap) {
|
||||
this.currentPrefix = currentPrefix;
|
||||
this.currentPathMap = currentPathMap;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebean.BackgroundExecutor;
|
||||
import com.avaje.ebean.RawSql;
|
||||
import com.avaje.ebean.RawSql.ColumnMapping;
|
||||
import com.avaje.ebean.RawSql.ColumnMapping.Column;
|
||||
import com.avaje.ebean.RawSqlBuilder;
|
||||
import com.avaje.ebean.config.GlobalProperties;
|
||||
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
|
||||
import com.avaje.ebean.config.dbplatform.SqlLimitRequest;
|
||||
import com.avaje.ebean.config.dbplatform.SqlLimitResponse;
|
||||
import com.avaje.ebean.config.dbplatform.SqlLimiter;
|
||||
import com.avaje.ebean.text.PathProperties;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
|
||||
import com.avaje.ebeaninternal.server.persist.Binder;
|
||||
import com.avaje.ebeaninternal.server.querydefn.OrmQueryDetail;
|
||||
import com.avaje.ebeaninternal.server.querydefn.OrmQueryLimitRequest;
|
||||
|
||||
/**
|
||||
* Generates the SQL SELECT statements taking into account the physical
|
||||
* deployment properties.
|
||||
*/
|
||||
public class CQueryBuilder implements Constants {
|
||||
|
||||
private final String tableAliasPlaceHolder;
|
||||
private final String columnAliasPrefix;
|
||||
|
||||
private final SqlLimiter sqlLimiter;
|
||||
|
||||
private final RawSqlSelectClauseBuilder sqlSelectBuilder;
|
||||
private final CQueryBuilderRawSql rawSqlHandler;
|
||||
|
||||
private final Binder binder;
|
||||
|
||||
private final BackgroundExecutor backgroundExecutor;
|
||||
|
||||
private final boolean selectCountWithAlias;
|
||||
|
||||
private DatabasePlatform dbPlatform;
|
||||
|
||||
/**
|
||||
* Create the SqlGenSelect.
|
||||
*/
|
||||
public CQueryBuilder(BackgroundExecutor backgroundExecutor, DatabasePlatform dbPlatform, Binder binder) {
|
||||
|
||||
this.backgroundExecutor = backgroundExecutor;
|
||||
this.binder = binder;
|
||||
this.tableAliasPlaceHolder = GlobalProperties.get("ebean.tableAliasPlaceHolder", "${ta}");
|
||||
this.columnAliasPrefix = GlobalProperties.get("ebean.columnAliasPrefix", "c");
|
||||
this.sqlSelectBuilder = new RawSqlSelectClauseBuilder(dbPlatform, binder);
|
||||
|
||||
this.sqlLimiter = dbPlatform.getSqlLimiter();
|
||||
this.rawSqlHandler = new CQueryBuilderRawSql(sqlLimiter, dbPlatform);
|
||||
|
||||
this.selectCountWithAlias = dbPlatform.isSelectCountWithAlias();
|
||||
|
||||
this.dbPlatform = dbPlatform;
|
||||
}
|
||||
|
||||
/**
|
||||
* split the order by claus on the field delimiter and prefix each field with
|
||||
* the relation name
|
||||
*/
|
||||
public static String prefixOrderByFields(String name, String orderBy) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String token : orderBy.split(",")) {
|
||||
if (sb.length() > 0) {
|
||||
sb.append(", ");
|
||||
}
|
||||
|
||||
sb.append(name);
|
||||
sb.append(".");
|
||||
sb.append(token.trim());
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the row count query.
|
||||
*/
|
||||
public <T> CQueryFetchIds buildFetchIdsQuery(OrmQueryRequest<T> request) {
|
||||
|
||||
SpiQuery<T> query = request.getQuery();
|
||||
|
||||
query.setSelectId();
|
||||
|
||||
CQueryPredicates predicates = new CQueryPredicates(binder, request);
|
||||
CQueryPlan queryPlan = request.getQueryPlan();
|
||||
if (queryPlan != null) {
|
||||
// skip building the SqlTree and Sql string
|
||||
predicates.prepare(false);
|
||||
String sql = queryPlan.getSql();
|
||||
return new CQueryFetchIds(request, predicates, sql, backgroundExecutor);
|
||||
|
||||
}
|
||||
|
||||
// use RawSql or generated Sql
|
||||
predicates.prepare(true);
|
||||
|
||||
SqlTree sqlTree = createSqlTree(request, predicates);
|
||||
SqlLimitResponse s = buildSql(null, request, predicates, sqlTree);
|
||||
String sql = s.getSql();
|
||||
|
||||
// cache the query plan
|
||||
queryPlan = new CQueryPlan(sql, sqlTree, false, s.isIncludesRowNumberColumn(), predicates.getLogWhereSql());
|
||||
|
||||
request.putQueryPlan(queryPlan);
|
||||
return new CQueryFetchIds(request, predicates, sql, backgroundExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the row count query.
|
||||
*/
|
||||
public <T> CQueryRowCount buildRowCountQuery(OrmQueryRequest<T> request) {
|
||||
|
||||
SpiQuery<T> query = request.getQuery();
|
||||
|
||||
// always set the order by to null for row count query
|
||||
query.setOrder(null);
|
||||
|
||||
boolean hasMany = !query.getManyWhereJoins().isEmpty();
|
||||
|
||||
query.setSelectId();
|
||||
|
||||
String sqlSelect = "select count(*)";
|
||||
if (hasMany) {
|
||||
// need to count distinct id's ...
|
||||
query.setDistinct(true);
|
||||
sqlSelect = null;
|
||||
}
|
||||
|
||||
CQueryPredicates predicates = new CQueryPredicates(binder, request);
|
||||
CQueryPlan queryPlan = request.getQueryPlan();
|
||||
if (queryPlan != null) {
|
||||
// skip building the SqlTree and Sql string
|
||||
predicates.prepare(false);
|
||||
String sql = queryPlan.getSql();
|
||||
return new CQueryRowCount(request, predicates, sql);
|
||||
}
|
||||
|
||||
predicates.prepare(true);
|
||||
|
||||
SqlTree sqlTree = createSqlTree(request, predicates);
|
||||
SqlLimitResponse s = buildSql(sqlSelect, request, predicates, sqlTree);
|
||||
String sql = s.getSql();
|
||||
if (hasMany) {
|
||||
sql = "select count(*) from ( " + sql + ")";
|
||||
if (selectCountWithAlias) {
|
||||
sql += " as c";
|
||||
}
|
||||
}
|
||||
|
||||
// cache the query plan
|
||||
queryPlan = new CQueryPlan(sql, sqlTree, false, s.isIncludesRowNumberColumn(), predicates.getLogWhereSql());
|
||||
request.putQueryPlan(queryPlan);
|
||||
|
||||
return new CQueryRowCount(request, predicates, sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the SQL Select statement as a String. Converts logical property
|
||||
* names to physical deployment column names.
|
||||
*/
|
||||
public <T> CQuery<T> buildQuery(OrmQueryRequest<T> request) {
|
||||
|
||||
if (request.isSqlSelect()) {
|
||||
return sqlSelectBuilder.build(request);
|
||||
}
|
||||
|
||||
CQueryPredicates predicates = new CQueryPredicates(binder, request);
|
||||
|
||||
CQueryPlan queryPlan = request.getQueryPlan();
|
||||
if (queryPlan != null) {
|
||||
// Reuse the query plan so skip generating SqlTree and SQL.
|
||||
// We do prepare and bind the new parameters
|
||||
predicates.prepare(false);
|
||||
return new CQuery<T>(request, predicates, queryPlan);
|
||||
}
|
||||
|
||||
// RawSql or Generated Sql query
|
||||
|
||||
// Prepare the where, having and order by clauses.
|
||||
// This also parses them from logical property names to
|
||||
// database columns and determines 'includes'.
|
||||
|
||||
// We need to check these 'includes' for extra joins
|
||||
// that are not included via select
|
||||
predicates.prepare(true);
|
||||
|
||||
// Build the tree structure that represents the query.
|
||||
SqlTree sqlTree = createSqlTree(request, predicates);
|
||||
SqlLimitResponse res = buildSql(null, request, predicates, sqlTree);
|
||||
|
||||
boolean rawSql = request.isRawSql();
|
||||
if (rawSql) {
|
||||
queryPlan = new CQueryPlanRawSql(request, res, sqlTree, predicates.getLogWhereSql());
|
||||
|
||||
} else {
|
||||
queryPlan = new CQueryPlan(request, res, sqlTree, rawSql, predicates.getLogWhereSql(), null);
|
||||
}
|
||||
|
||||
// cache the query plan because we can reuse it and also
|
||||
// gather query performance statistics based on it.
|
||||
request.putQueryPlan(queryPlan);
|
||||
|
||||
return new CQuery<T>(request, predicates, queryPlan);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the SqlTree.
|
||||
* <p>
|
||||
* The SqlTree is immutable after construction and so is safe to use by
|
||||
* concurrent threads.
|
||||
* </p>
|
||||
* <p>
|
||||
* The predicates is used to add additional joins that come from the where or
|
||||
* order by clauses that are not already included for the select clause.
|
||||
* </p>
|
||||
*/
|
||||
private SqlTree createSqlTree(OrmQueryRequest<?> request, CQueryPredicates predicates) {
|
||||
|
||||
if (request.isRawSql()) {
|
||||
return createRawSqlSqlTree(request, predicates);
|
||||
}
|
||||
|
||||
return new SqlTreeBuilder(tableAliasPlaceHolder, columnAliasPrefix, request, predicates).build();
|
||||
}
|
||||
|
||||
private SqlTree createRawSqlSqlTree(OrmQueryRequest<?> request, CQueryPredicates predicates) {
|
||||
|
||||
BeanDescriptor<?> descriptor = request.getBeanDescriptor();
|
||||
ColumnMapping columnMapping = request.getQuery().getRawSql().getColumnMapping();
|
||||
|
||||
PathProperties pathProps = new PathProperties();
|
||||
|
||||
// convert list of columns into (tree like) PathProperties
|
||||
Iterator<Column> it = columnMapping.getColumns();
|
||||
while (it.hasNext()) {
|
||||
RawSql.ColumnMapping.Column column = it.next();
|
||||
String propertyName = column.getPropertyName();
|
||||
if (!RawSqlBuilder.IGNORE_COLUMN.equals(propertyName)) {
|
||||
|
||||
ElPropertyValue el = descriptor.getElGetValue(propertyName);
|
||||
if (el == null) {
|
||||
String msg = "Property [" + propertyName + "] not found on " + descriptor.getFullName();
|
||||
throw new PersistenceException(msg);
|
||||
}
|
||||
BeanProperty beanProperty = el.getBeanProperty();
|
||||
if (beanProperty.isId()) {
|
||||
// For @Id properties we chop off the last part of the path
|
||||
propertyName = SplitName.parent(propertyName);
|
||||
} else if (beanProperty instanceof BeanPropertyAssocOne<?>) {
|
||||
String msg = "Column [" + column.getDbColumn() + "] mapped to complex Property[" + propertyName + "]";
|
||||
msg += ". It should be mapped to a simple property (proably the Id property). ";
|
||||
throw new PersistenceException(msg);
|
||||
}
|
||||
if (propertyName != null) {
|
||||
String[] pathProp = SplitName.split(propertyName);
|
||||
pathProps.addToPath(pathProp[0], pathProp[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OrmQueryDetail detail = new OrmQueryDetail();
|
||||
|
||||
// transfer PathProperties into OrmQueryDetail
|
||||
Iterator<String> pathIt = pathProps.getPaths().iterator();
|
||||
while (pathIt.hasNext()) {
|
||||
String path = pathIt.next();
|
||||
Set<String> props = pathProps.get(path);
|
||||
detail.getChunk(path, true).setDefaultProperties(null, props);
|
||||
}
|
||||
|
||||
// build SqlTree based on OrmQueryDetail of the RawSql
|
||||
return new SqlTreeBuilder(request, predicates, detail).build();
|
||||
}
|
||||
|
||||
private SqlLimitResponse buildSql(String selectClause, OrmQueryRequest<?> request, CQueryPredicates predicates, SqlTree select) {
|
||||
|
||||
SpiQuery<?> query = request.getQuery();
|
||||
|
||||
RawSql rawSql = query.getRawSql();
|
||||
if (rawSql != null) {
|
||||
return rawSqlHandler.buildSql(request, predicates, rawSql.getSql());
|
||||
}
|
||||
|
||||
BeanPropertyAssocMany<?> manyProp = select.getManyProperty();
|
||||
|
||||
boolean useSqlLimiter = false;
|
||||
|
||||
StringBuilder sb = new StringBuilder(500);
|
||||
|
||||
if (selectClause != null) {
|
||||
sb.append(selectClause);
|
||||
|
||||
} else {
|
||||
|
||||
useSqlLimiter = (query.hasMaxRowsOrFirstRow() && manyProp == null);
|
||||
|
||||
if (!useSqlLimiter) {
|
||||
sb.append("select ");
|
||||
if (query.isDistinct()) {
|
||||
sb.append("distinct ");
|
||||
}
|
||||
}
|
||||
|
||||
sb.append(select.getSelectSql());
|
||||
}
|
||||
|
||||
sb.append(" ").append(NEW_LINE);
|
||||
sb.append("from ");
|
||||
|
||||
// build the from clause potentially with joins
|
||||
// required only for the predicates
|
||||
sb.append(select.getFromSql());
|
||||
|
||||
String inheritanceWhere = select.getInheritanceWhereSql();
|
||||
|
||||
boolean hasWhere = false;
|
||||
if (inheritanceWhere.length() > 0) {
|
||||
sb.append(" ").append(NEW_LINE).append("where");
|
||||
sb.append(inheritanceWhere);
|
||||
hasWhere = true;
|
||||
}
|
||||
|
||||
if (request.isFindById() || query.getId() != null) {
|
||||
if (hasWhere) {
|
||||
sb.append(" and ");
|
||||
} else {
|
||||
sb.append(NEW_LINE).append("where ");
|
||||
}
|
||||
|
||||
BeanDescriptor<?> desc = request.getBeanDescriptor();
|
||||
String idSql = desc.getIdBinderIdSql();
|
||||
if (idSql.isEmpty()) {
|
||||
throw new IllegalStateException("Executing FindById query on entity bean " + desc.getName()
|
||||
+ " that doesn't have an @Id property??");
|
||||
}
|
||||
sb.append(idSql).append(" ");
|
||||
hasWhere = true;
|
||||
}
|
||||
|
||||
String dbWhere = predicates.getDbWhere();
|
||||
if (!isEmpty(dbWhere)) {
|
||||
if (!hasWhere) {
|
||||
hasWhere = true;
|
||||
sb.append(" ").append(NEW_LINE).append("where ");
|
||||
} else {
|
||||
sb.append("and ");
|
||||
}
|
||||
sb.append(dbWhere);
|
||||
}
|
||||
|
||||
String dbFilterMany = predicates.getDbFilterMany();
|
||||
if (!isEmpty(dbFilterMany)) {
|
||||
if (!hasWhere) {
|
||||
sb.append(" ").append(NEW_LINE).append("where ");
|
||||
} else {
|
||||
sb.append("and ");
|
||||
}
|
||||
sb.append(dbFilterMany);
|
||||
}
|
||||
|
||||
String dbOrderBy = predicates.getDbOrderBy();
|
||||
if (dbOrderBy != null) {
|
||||
sb.append(" ").append(NEW_LINE);
|
||||
sb.append("order by ").append(dbOrderBy);
|
||||
}
|
||||
|
||||
if (useSqlLimiter) {
|
||||
// use LIMIT/OFFSET, ROW_NUMBER() or rownum type SQL query limitation
|
||||
SqlLimitRequest r = new OrmQueryLimitRequest(sb.toString(), dbOrderBy, query, dbPlatform);
|
||||
return sqlLimiter.limit(r);
|
||||
|
||||
} else {
|
||||
|
||||
return new SqlLimitResponse(dbPlatform.completeSql(sb.toString(), query), false);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private boolean isEmpty(String s) {
|
||||
return s == null || s.length() == 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import com.avaje.ebean.RawSql;
|
||||
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
|
||||
import com.avaje.ebean.config.dbplatform.SqlLimitResponse;
|
||||
import com.avaje.ebean.config.dbplatform.SqlLimiter;
|
||||
import com.avaje.ebeaninternal.api.BindParams;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.querydefn.OrmQueryLimitRequest;
|
||||
import com.avaje.ebeaninternal.server.util.BindParamsParser;
|
||||
|
||||
public class CQueryBuilderRawSql implements Constants {
|
||||
|
||||
private final SqlLimiter sqlLimiter;
|
||||
private final DatabasePlatform dbPlatform;
|
||||
|
||||
CQueryBuilderRawSql(SqlLimiter sqlLimiter, DatabasePlatform dbPlatform) {
|
||||
this.sqlLimiter = sqlLimiter;
|
||||
this.dbPlatform = dbPlatform;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the full SQL Select statement for the request.
|
||||
*/
|
||||
public SqlLimitResponse buildSql(OrmQueryRequest<?> request, CQueryPredicates predicates, RawSql.Sql rsql) {
|
||||
|
||||
if (!rsql.isParsed()){
|
||||
String sql = rsql.getUnparsedSql();
|
||||
BindParams bindParams = request.getQuery().getBindParams();
|
||||
if (bindParams != null && bindParams.requiresNamedParamsPrepare()){
|
||||
// convert named parameters into positioned parameters
|
||||
sql = BindParamsParser.parse(bindParams, sql);
|
||||
}
|
||||
|
||||
return new SqlLimitResponse(sql, false);
|
||||
}
|
||||
|
||||
String orderBy = getOrderBy(predicates, rsql);
|
||||
|
||||
// build the actual sql String
|
||||
String sql = buildMainQuery(orderBy, request, predicates, rsql);
|
||||
|
||||
SpiQuery<?> query = request.getQuery();
|
||||
if (query.hasMaxRowsOrFirstRow() && sqlLimiter != null) {
|
||||
// wrap with a limit offset or ROW_NUMBER() etc
|
||||
return sqlLimiter.limit(new OrmQueryLimitRequest(sql, orderBy, query, dbPlatform));
|
||||
|
||||
} else {
|
||||
// add back select keyword (it was removed to support sqlQueryLimiter)
|
||||
String prefix = "select "+ (rsql.isDistinct() ? "distinct " : "");
|
||||
sql = prefix + sql;
|
||||
return new SqlLimitResponse(sql, false);
|
||||
}
|
||||
}
|
||||
|
||||
private String buildMainQuery(String orderBy, OrmQueryRequest<?> request, CQueryPredicates predicates, RawSql.Sql sql) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(sql.getPreFrom());
|
||||
sb.append(" ");
|
||||
sb.append(NEW_LINE);
|
||||
|
||||
String s = sql.getPreWhere();
|
||||
BindParams bindParams = request.getQuery().getBindParams();
|
||||
if (bindParams != null && bindParams.requiresNamedParamsPrepare()){
|
||||
// convert named parameters into positioned parameters
|
||||
// Named Parameters only allowed prior to dynamic where
|
||||
// clause (so not allowed in having etc - use unparsed)
|
||||
s = BindParamsParser.parse(bindParams, s);
|
||||
}
|
||||
sb.append(s);
|
||||
sb.append(" ");
|
||||
|
||||
String dynamicWhere = null;
|
||||
if (request.getQuery().getId() != null) {
|
||||
// need to convert this as well. This avoids the
|
||||
// assumption that id has its proper dbColumn assigned
|
||||
// which may change if using multiple raw sql statements
|
||||
// against the same bean.
|
||||
BeanDescriptor<?> descriptor = request.getBeanDescriptor();
|
||||
//FIXME: I think this is broken... needs to be logical
|
||||
// and then parsed for RawSqlSelect...
|
||||
dynamicWhere = descriptor.getIdBinderIdSql();
|
||||
}
|
||||
|
||||
String dbWhere = predicates.getDbWhere();
|
||||
if (!isEmpty(dbWhere)) {
|
||||
if (dynamicWhere == null) {
|
||||
dynamicWhere = dbWhere;
|
||||
} else {
|
||||
dynamicWhere += " and " + dbWhere;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isEmpty(dynamicWhere)) {
|
||||
sb.append(NEW_LINE);
|
||||
if (sql.isAndWhereExpr()) {
|
||||
sb.append("and ");
|
||||
} else {
|
||||
sb.append("where ");
|
||||
}
|
||||
sb.append(dynamicWhere);
|
||||
sb.append(" ");
|
||||
}
|
||||
|
||||
String preHaving = sql.getPreHaving();
|
||||
if (!isEmpty(preHaving)) {
|
||||
sb.append(NEW_LINE);
|
||||
sb.append(preHaving);
|
||||
sb.append(" ");
|
||||
}
|
||||
|
||||
String dbHaving = predicates.getDbHaving();
|
||||
if (!isEmpty(dbHaving)) {
|
||||
sb.append(" ");
|
||||
sb.append(NEW_LINE);
|
||||
if (sql.isAndHavingExpr()) {
|
||||
sb.append("and ");
|
||||
} else {
|
||||
sb.append("having ");
|
||||
}
|
||||
sb.append(dbHaving);
|
||||
sb.append(" ");
|
||||
}
|
||||
|
||||
if (!isEmpty(orderBy)) {
|
||||
sb.append(NEW_LINE);
|
||||
sb.append(" order by ").append(orderBy);
|
||||
}
|
||||
|
||||
return sb.toString().trim();
|
||||
}
|
||||
|
||||
private boolean isEmpty(String s) {
|
||||
return s == null || s.length() == 0;
|
||||
}
|
||||
|
||||
private String getOrderBy(CQueryPredicates predicates, RawSql.Sql sql) {
|
||||
String orderBy = predicates.getDbOrderBy();
|
||||
if (orderBy != null) {
|
||||
return orderBy;
|
||||
} else {
|
||||
return sql.getOrderBy();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.avaje.ebean.BackgroundExecutor;
|
||||
import com.avaje.ebean.QueryIterator;
|
||||
import com.avaje.ebean.bean.BeanCollection;
|
||||
import com.avaje.ebean.bean.BeanCollectionTouched;
|
||||
import com.avaje.ebean.bean.ObjectGraphNode;
|
||||
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
|
||||
import com.avaje.ebeaninternal.api.BeanIdList;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.jmx.MAdminLogging;
|
||||
import com.avaje.ebeaninternal.server.persist.Binder;
|
||||
|
||||
/**
|
||||
* Handles the Object Relational fetching.
|
||||
*/
|
||||
public class CQueryEngine {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(CQueryEngine.class.getName());
|
||||
|
||||
private final CQueryBuilder queryBuilder;
|
||||
|
||||
private final MAdminLogging logControl;
|
||||
|
||||
private final BackgroundExecutor backgroundExecutor;
|
||||
|
||||
private final int defaultSecondaryQueryBatchSize = 100;
|
||||
|
||||
public CQueryEngine(DatabasePlatform dbPlatform, MAdminLogging logControl, Binder binder, BackgroundExecutor backgroundExecutor) {
|
||||
|
||||
this.logControl = logControl;
|
||||
this.backgroundExecutor = backgroundExecutor;
|
||||
this.queryBuilder = new CQueryBuilder(backgroundExecutor, dbPlatform, binder);
|
||||
}
|
||||
|
||||
public <T> CQuery<T> buildQuery(OrmQueryRequest<T> request) {
|
||||
return queryBuilder.buildQuery(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build and execute the find Id's query.
|
||||
*/
|
||||
public <T> BeanIdList findIds(OrmQueryRequest<T> request) {
|
||||
|
||||
CQueryFetchIds rcQuery = queryBuilder.buildFetchIdsQuery(request);
|
||||
try {
|
||||
|
||||
String sql = rcQuery.getGeneratedSql();
|
||||
sql = sql.replace(Constants.NEW_LINE, ' ');
|
||||
|
||||
if (logControl.isDebugGeneratedSql()) {
|
||||
System.out.println(sql);
|
||||
}
|
||||
request.logSql(sql);
|
||||
|
||||
BeanIdList list = rcQuery.findIds();
|
||||
|
||||
if (request.isLogSummary()) {
|
||||
request.getTransaction().logInternal(rcQuery.getSummary());
|
||||
}
|
||||
|
||||
if (!list.isFetchingInBackground() && request.getQuery().isFutureFetch()) {
|
||||
// end the transaction for futureFindIds (it had it's own one)
|
||||
logger.fine("Future findIds completed!");
|
||||
request.getTransaction().end();
|
||||
}
|
||||
|
||||
return list;
|
||||
|
||||
} catch (SQLException e) {
|
||||
throw CQuery.createPersistenceException(e, request.getTransaction(), rcQuery.getBindLog(), rcQuery.getGeneratedSql());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build and execute the row count query.
|
||||
*/
|
||||
public <T> int findRowCount(OrmQueryRequest<T> request) {
|
||||
|
||||
CQueryRowCount rcQuery = queryBuilder.buildRowCountQuery(request);
|
||||
try {
|
||||
|
||||
String sql = rcQuery.getGeneratedSql();
|
||||
sql = sql.replace(Constants.NEW_LINE, ' ');
|
||||
|
||||
if (logControl.isDebugGeneratedSql()) {
|
||||
System.out.println(sql);
|
||||
}
|
||||
request.logSql(sql);
|
||||
|
||||
int rowCount = rcQuery.findRowCount();
|
||||
|
||||
if (request.isLogSummary()) {
|
||||
request.getTransaction().logInternal(rcQuery.getSummary());
|
||||
}
|
||||
|
||||
if (request.getQuery().isFutureFetch()) {
|
||||
logger.fine("Future findRowCount completed!");
|
||||
request.getTransaction().end();
|
||||
}
|
||||
|
||||
return rowCount;
|
||||
|
||||
} catch (SQLException e) {
|
||||
throw CQuery.createPersistenceException(e, request.getTransaction(), rcQuery.getBindLog(), rcQuery.getGeneratedSql());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read many beans using an iterator (except you need to close() the iterator
|
||||
* when you have finished).
|
||||
*/
|
||||
public <T> QueryIterator<T> findIterate(OrmQueryRequest<T> request) {
|
||||
|
||||
CQuery<T> cquery = queryBuilder.buildQuery(request);
|
||||
request.setCancelableQuery(cquery);
|
||||
|
||||
try {
|
||||
|
||||
if (logControl.isDebugGeneratedSql()) {
|
||||
logSqlToConsole(cquery);
|
||||
}
|
||||
|
||||
if (request.isLogSql()) {
|
||||
logSql(cquery);
|
||||
}
|
||||
|
||||
if (!cquery.prepareBindExecuteQuery()) {
|
||||
// query has been cancelled already
|
||||
logger.finest("Future fetch already cancelled");
|
||||
return null;
|
||||
}
|
||||
|
||||
int iterateBufferSize = request.getSecondaryQueriesMinBatchSize(defaultSecondaryQueryBatchSize);
|
||||
|
||||
QueryIterator<T> readIterate = cquery.readIterate(iterateBufferSize, request);
|
||||
|
||||
if (request.isLogSummary()) {
|
||||
logFindManySummary(cquery);
|
||||
}
|
||||
|
||||
return readIterate;
|
||||
|
||||
} catch (SQLException e) {
|
||||
throw cquery.createPersistenceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a list/map/set of beans.
|
||||
*/
|
||||
public <T> BeanCollection<T> findMany(OrmQueryRequest<T> request) {
|
||||
|
||||
// flag indicating whether we need to close the resources...
|
||||
boolean useBackgroundToContinueFetch = false;
|
||||
|
||||
CQuery<T> cquery = queryBuilder.buildQuery(request);
|
||||
request.setCancelableQuery(cquery);
|
||||
|
||||
try {
|
||||
|
||||
if (logControl.isDebugGeneratedSql()) {
|
||||
logSqlToConsole(cquery);
|
||||
}
|
||||
if (request.isLogSql()) {
|
||||
logSql(cquery);
|
||||
}
|
||||
|
||||
if (!cquery.prepareBindExecuteQuery()) {
|
||||
// query has been cancelled already
|
||||
logger.finest("Future fetch already cancelled");
|
||||
return null;
|
||||
}
|
||||
|
||||
BeanCollection<T> beanCollection = cquery.readCollection();
|
||||
|
||||
BeanCollectionTouched collectionTouched = request.getQuery().getBeanCollectionTouched();
|
||||
if (collectionTouched != null) {
|
||||
// register a listener that wants to be notified when the
|
||||
// bean collection is first used
|
||||
beanCollection.setBeanCollectionTouched(collectionTouched);
|
||||
}
|
||||
|
||||
if (cquery.useBackgroundToContinueFetch()) {
|
||||
// stop the request from putting connection back into pool
|
||||
// before background fetching is finished.
|
||||
request.setBackgroundFetching();
|
||||
useBackgroundToContinueFetch = true;
|
||||
BackgroundFetch fetch = new BackgroundFetch(cquery);
|
||||
|
||||
FutureTask<Integer> future = new FutureTask<Integer>(fetch);
|
||||
beanCollection.setBackgroundFetch(future);
|
||||
backgroundExecutor.execute(future);
|
||||
}
|
||||
|
||||
if (request.isLogSummary()) {
|
||||
logFindManySummary(cquery);
|
||||
}
|
||||
|
||||
request.executeSecondaryQueries(defaultSecondaryQueryBatchSize);
|
||||
|
||||
return beanCollection;
|
||||
|
||||
} catch (SQLException e) {
|
||||
throw cquery.createPersistenceException(e);// request, e,
|
||||
// cquery.getBindLog(),
|
||||
// cquery.getGeneratedSql());
|
||||
|
||||
} finally {
|
||||
if (useBackgroundToContinueFetch) {
|
||||
// left closing resources to BackgroundFetch...
|
||||
} else {
|
||||
if (cquery != null) {
|
||||
cquery.close();
|
||||
}
|
||||
if (request.getQuery().isFutureFetch()) {
|
||||
// end the transaction for futureFindIds
|
||||
// as it had it's own transaction
|
||||
logger.fine("Future fetch completed!");
|
||||
request.getTransaction().end();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and return a single bean using its unique id.
|
||||
*/
|
||||
public <T> T find(OrmQueryRequest<T> request) {
|
||||
|
||||
T bean = null;
|
||||
|
||||
CQuery<T> cquery = queryBuilder.buildQuery(request);
|
||||
|
||||
try {
|
||||
if (logControl.isDebugGeneratedSql()) {
|
||||
logSqlToConsole(cquery);
|
||||
}
|
||||
if (request.isLogSql()) {
|
||||
logSql(cquery);
|
||||
}
|
||||
|
||||
cquery.prepareBindExecuteQuery();
|
||||
|
||||
if (cquery.readBean()) {
|
||||
bean = cquery.getLoadedBean();
|
||||
}
|
||||
|
||||
if (request.isLogSummary()) {
|
||||
logFindBeanSummary(cquery);
|
||||
}
|
||||
|
||||
request.executeSecondaryQueries(defaultSecondaryQueryBatchSize);
|
||||
|
||||
return bean;
|
||||
|
||||
} catch (SQLException e) {
|
||||
throw cquery.createPersistenceException(e);
|
||||
|
||||
} finally {
|
||||
cquery.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Log the generated SQL to the console.
|
||||
*/
|
||||
private void logSqlToConsole(CQuery<?> cquery) {
|
||||
|
||||
SpiQuery<?> query = cquery.getQueryRequest().getQuery();
|
||||
String loadMode = query.getLoadMode();
|
||||
String loadDesc = query.getLoadDescription();
|
||||
|
||||
String sql = cquery.getGeneratedSql();
|
||||
String summary = cquery.getSummary();
|
||||
|
||||
StringBuilder sb = new StringBuilder(1000);
|
||||
sb.append("<sql ");
|
||||
if (query.isAutofetchTuned()) {
|
||||
sb.append("tuned='true' ");
|
||||
}
|
||||
if (loadMode != null) {
|
||||
sb.append("mode='").append(loadMode).append("' ");
|
||||
}
|
||||
sb.append("summary='").append(summary);
|
||||
if (loadDesc != null) {
|
||||
sb.append("' load='").append(loadDesc);
|
||||
}
|
||||
sb.append("' >");
|
||||
sb.append(Constants.NEW_LINE);
|
||||
sb.append(sql);
|
||||
sb.append(Constants.NEW_LINE).append("</sql>");
|
||||
|
||||
System.out.println(sb.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Log the generated SQL to the transaction log.
|
||||
*/
|
||||
private void logSql(CQuery<?> query) {
|
||||
|
||||
String sql = query.getGeneratedSql();
|
||||
sql = sql.replace(Constants.NEW_LINE, ' ');
|
||||
query.getTransaction().logInternal(sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* Log the FindById summary to the transaction log.
|
||||
*/
|
||||
private void logFindBeanSummary(CQuery<?> q) {
|
||||
|
||||
SpiQuery<?> query = q.getQueryRequest().getQuery();
|
||||
String loadMode = query.getLoadMode();
|
||||
String loadDesc = query.getLoadDescription();
|
||||
String lazyLoadProp = query.getLazyLoadProperty();
|
||||
ObjectGraphNode node = query.getParentNode();
|
||||
String originKey;
|
||||
if (node == null || node.getOriginQueryPoint() == null) {
|
||||
originKey = null;
|
||||
} else {
|
||||
originKey = node.getOriginQueryPoint().getKey();
|
||||
}
|
||||
|
||||
StringBuilder msg = new StringBuilder(200);
|
||||
msg.append("FindBean ");
|
||||
if (loadMode != null) {
|
||||
msg.append("mode[").append(loadMode).append("] ");
|
||||
}
|
||||
msg.append("type[").append(q.getBeanName()).append("] ");
|
||||
if (query.isAutofetchTuned()) {
|
||||
msg.append("tuned[true] ");
|
||||
}
|
||||
if (originKey != null) {
|
||||
msg.append("origin[").append(originKey).append("] ");
|
||||
}
|
||||
if (lazyLoadProp != null) {
|
||||
msg.append("lazyLoadProp[").append(lazyLoadProp).append("] ");
|
||||
}
|
||||
if (loadDesc != null) {
|
||||
msg.append("load[").append(loadDesc).append("] ");
|
||||
}
|
||||
msg.append("exeMicros[").append(q.getQueryExecutionTimeMicros());
|
||||
msg.append("] rows[").append(q.getLoadedRowDetail());
|
||||
msg.append("] bind[").append(q.getBindLog()).append("]");
|
||||
|
||||
q.getTransaction().logInternal(msg.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Log the FindMany to the transaction log.
|
||||
*/
|
||||
private void logFindManySummary(CQuery<?> q) {
|
||||
|
||||
SpiQuery<?> query = q.getQueryRequest().getQuery();
|
||||
String loadMode = query.getLoadMode();
|
||||
String loadDesc = query.getLoadDescription();
|
||||
String lazyLoadProp = query.getLazyLoadProperty();
|
||||
ObjectGraphNode node = query.getParentNode();
|
||||
|
||||
String originKey;
|
||||
if (node == null || node.getOriginQueryPoint() == null) {
|
||||
originKey = null;
|
||||
} else {
|
||||
originKey = node.getOriginQueryPoint().getKey();
|
||||
}
|
||||
|
||||
StringBuilder msg = new StringBuilder(200);
|
||||
msg.append("FindMany ");
|
||||
if (loadMode != null) {
|
||||
msg.append("mode[").append(loadMode).append("] ");
|
||||
}
|
||||
msg.append("type[").append(q.getBeanName()).append("] ");
|
||||
if (query.isAutofetchTuned()) {
|
||||
msg.append("tuned[true] ");
|
||||
}
|
||||
if (originKey != null) {
|
||||
msg.append("origin[").append(originKey).append("] ");
|
||||
}
|
||||
if (lazyLoadProp != null) {
|
||||
msg.append("lazyLoadProp[").append(lazyLoadProp).append("] ");
|
||||
}
|
||||
if (loadDesc != null) {
|
||||
msg.append("load[").append(loadDesc).append("] ");
|
||||
}
|
||||
msg.append("exeMicros[").append(q.getQueryExecutionTimeMicros());
|
||||
msg.append("] rows[").append(q.getLoadedRowDetail());
|
||||
msg.append("] name[").append(q.getName());
|
||||
msg.append("] predicates[").append(q.getLogWhereSql());
|
||||
msg.append("] bind[").append(q.getBindLog()).append("]");
|
||||
|
||||
q.getTransaction().logInternal(msg.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.avaje.ebean.BackgroundExecutor;
|
||||
import com.avaje.ebean.bean.BeanCollection;
|
||||
import com.avaje.ebean.bean.EntityBeanIntercept;
|
||||
import com.avaje.ebean.bean.PersistenceContext;
|
||||
import com.avaje.ebeaninternal.api.BeanIdList;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery.Mode;
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.core.SpiOrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
|
||||
import com.avaje.ebeaninternal.server.type.DataBind;
|
||||
import com.avaje.ebeaninternal.server.type.DataReader;
|
||||
import com.avaje.ebeaninternal.server.type.RsetDataReader;
|
||||
|
||||
/**
|
||||
* Executes the select row count query.
|
||||
*/
|
||||
public class CQueryFetchIds {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(CQueryFetchIds.class.getName());
|
||||
|
||||
/**
|
||||
* The overall find request wrapper object.
|
||||
*/
|
||||
private final OrmQueryRequest<?> request;
|
||||
|
||||
private final BeanDescriptor<?> desc;
|
||||
|
||||
private final SpiQuery<?> query;
|
||||
|
||||
private final BackgroundExecutor backgroundExecutor;
|
||||
|
||||
/**
|
||||
* Where clause predicates.
|
||||
*/
|
||||
private final CQueryPredicates predicates;
|
||||
|
||||
/**
|
||||
* The final sql that is generated.
|
||||
*/
|
||||
private final String sql;
|
||||
|
||||
private RsetDataReader dataReader;
|
||||
|
||||
/**
|
||||
* The statement used to create the resultSet.
|
||||
*/
|
||||
private PreparedStatement pstmt;
|
||||
|
||||
private String bindLog;
|
||||
|
||||
private long startNano;
|
||||
|
||||
private int executionTimeMicros;
|
||||
|
||||
private int rowCount;
|
||||
|
||||
private final int maxRows;
|
||||
private final int bgFetchAfter;
|
||||
|
||||
/**
|
||||
* Create the Sql select based on the request.
|
||||
*/
|
||||
public CQueryFetchIds(OrmQueryRequest<?> request, CQueryPredicates predicates,
|
||||
String sql, BackgroundExecutor backgroundExecutor) {
|
||||
|
||||
this.backgroundExecutor = backgroundExecutor;
|
||||
this.request = request;
|
||||
this.query = request.getQuery();
|
||||
this.sql = sql;
|
||||
this.maxRows = query.getMaxRows();
|
||||
this.bgFetchAfter = query.getBackgroundFetchAfter();
|
||||
|
||||
query.setGeneratedSql(sql);
|
||||
|
||||
this.desc = request.getBeanDescriptor();
|
||||
this.predicates = predicates;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a summary description of this query.
|
||||
*/
|
||||
public String getSummary() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("FindIds exeMicros[").append(executionTimeMicros)
|
||||
.append("] rows[").append(rowCount)
|
||||
.append("] type[").append(desc.getName())
|
||||
.append("] predicates[").append(predicates.getLogWhereSql())
|
||||
.append("] bind[").append(bindLog).append("]");
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the bind log.
|
||||
*/
|
||||
public String getBindLog() {
|
||||
return bindLog;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the generated sql.
|
||||
*/
|
||||
public String getGeneratedSql() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
public SpiOrmQueryRequest<?> getQueryRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query returning the row count.
|
||||
*/
|
||||
public BeanIdList findIds() throws SQLException {
|
||||
|
||||
boolean useBackgroundToContinueFetch = false;
|
||||
|
||||
startNano = System.nanoTime();
|
||||
|
||||
try {
|
||||
// get the list that we are going to put the id's into.
|
||||
// This was already set so that it is available to be
|
||||
// read by other threads (it is a synchronised list)
|
||||
List<Object> idList = query.getIdList();
|
||||
if (idList == null){
|
||||
// running in foreground thread (not FutureIds query)
|
||||
idList = Collections.synchronizedList(new ArrayList<Object>());
|
||||
query.setIdList(idList);
|
||||
}
|
||||
|
||||
BeanIdList result = new BeanIdList(idList);
|
||||
|
||||
SpiTransaction t = request.getTransaction();
|
||||
Connection conn = t.getInternalConnection();
|
||||
pstmt = conn.prepareStatement(sql);
|
||||
|
||||
if (query.getBufferFetchSizeHint() > 0){
|
||||
pstmt.setFetchSize(query.getBufferFetchSizeHint());
|
||||
}
|
||||
|
||||
if (query.getTimeout() > 0){
|
||||
pstmt.setQueryTimeout(query.getTimeout());
|
||||
}
|
||||
|
||||
bindLog = predicates.bind(new DataBind(pstmt));
|
||||
|
||||
ResultSet rset = pstmt.executeQuery();
|
||||
dataReader = new RsetDataReader(rset);
|
||||
|
||||
boolean hitMaxRows = false;
|
||||
boolean hasMoreRows = false;
|
||||
rowCount = 0;
|
||||
|
||||
DbReadContext ctx = new DbContext();
|
||||
|
||||
while (rset.next()){
|
||||
Object idValue = desc.getIdBinder().read(ctx);
|
||||
idList.add(idValue);
|
||||
// reset back to 0
|
||||
dataReader.resetColumnPosition();
|
||||
rowCount++;
|
||||
|
||||
if (maxRows > 0 && rowCount == maxRows) {
|
||||
hitMaxRows = true;
|
||||
hasMoreRows = rset.next();
|
||||
break;
|
||||
|
||||
} else if (bgFetchAfter > 0 && rowCount >= bgFetchAfter) {
|
||||
useBackgroundToContinueFetch = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (hitMaxRows){
|
||||
result.setHasMore(hasMoreRows);
|
||||
}
|
||||
|
||||
if (useBackgroundToContinueFetch){
|
||||
// tell the request not to end the transaction
|
||||
// as we leave that up to the BackgroundIdFetch
|
||||
request.setBackgroundFetching();
|
||||
|
||||
// submit background future task
|
||||
BackgroundIdFetch bgFetch = new BackgroundIdFetch(t, rset, pstmt, ctx, desc, result);
|
||||
FutureTask<Integer> future = new FutureTask<Integer>(bgFetch);
|
||||
backgroundExecutor.execute(future);
|
||||
|
||||
// set on result so we can use the futureTask to wait
|
||||
result.setBackgroundFetch(future);
|
||||
}
|
||||
|
||||
long exeNano = System.nanoTime() - startNano;
|
||||
executionTimeMicros = (int)exeNano/1000;
|
||||
|
||||
return result;
|
||||
|
||||
} finally {
|
||||
if (useBackgroundToContinueFetch) {
|
||||
// left closing resources to BackgroundFetch...
|
||||
} else {
|
||||
close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the resources.
|
||||
* <p>
|
||||
* The jdbc resultSet and statement need to be closed. Its important that
|
||||
* this method is called.
|
||||
* </p>
|
||||
*/
|
||||
private void close() {
|
||||
try {
|
||||
if (dataReader != null) {
|
||||
dataReader.close();
|
||||
dataReader = null;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
try {
|
||||
if (pstmt != null) {
|
||||
pstmt.close();
|
||||
pstmt = null;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class DbContext implements DbReadContext {
|
||||
|
||||
public void propagateState(Object e) {
|
||||
throw new RuntimeException("Not Called");
|
||||
}
|
||||
|
||||
public Mode getQueryMode() {
|
||||
return Mode.NORMAL;
|
||||
}
|
||||
|
||||
public DataReader getDataReader() {
|
||||
return dataReader;
|
||||
}
|
||||
|
||||
public boolean isVanillaMode() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public Boolean isReadOnly() {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
|
||||
public boolean isRawSql() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void register(String path, EntityBeanIntercept ebi){
|
||||
}
|
||||
|
||||
public void register(String path, BeanCollection<?> bc){
|
||||
}
|
||||
|
||||
public BeanPropertyAssocMany<?> getManyProperty() {
|
||||
// always null
|
||||
return null;
|
||||
}
|
||||
|
||||
public PersistenceContext getPersistenceContext() {
|
||||
// always null
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isAutoFetchProfiling() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void profileBean(EntityBeanIntercept ebi, String prefix) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
public void setCurrentPrefix(String currentPrefix,Map<String, String> pathMap) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
public void setLoadedBean(Object loadedBean, Object id) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
public void setLoadedManyBean(Object loadedBean) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebean.QueryIterator;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
|
||||
/**
|
||||
* QueryIterator that does not require a buffer for secondary queries.
|
||||
*
|
||||
* @author rbygrave
|
||||
*/
|
||||
class CQueryIteratorSimple<T> implements QueryIterator<T> {
|
||||
|
||||
private final CQuery<T> cquery;
|
||||
private final OrmQueryRequest<T> request;
|
||||
|
||||
CQueryIteratorSimple(CQuery<T> cquery, OrmQueryRequest<T> request){
|
||||
this.cquery = cquery;
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
try {
|
||||
return cquery.hasNextBean(true);
|
||||
} catch (SQLException e){
|
||||
throw cquery.createPersistenceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public T next() {
|
||||
return cquery.getLoadedBean();
|
||||
}
|
||||
|
||||
public void close() {
|
||||
cquery.updateExecutionStatistics();
|
||||
cquery.close();
|
||||
request.endTransIfRequired();
|
||||
}
|
||||
|
||||
public void remove() {
|
||||
throw new PersistenceException("Remove not allowed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebean.QueryIterator;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
|
||||
/**
|
||||
* A QueryIterator that uses a buffer to execute secondary queries periodically.
|
||||
*
|
||||
* @author rbygrave
|
||||
*/
|
||||
class CQueryIteratorWithBuffer<T> implements QueryIterator<T> {
|
||||
|
||||
private final CQuery<T> cquery;
|
||||
private final int bufferSize;
|
||||
private final OrmQueryRequest<T> request;
|
||||
private final ArrayList<T> buffer;
|
||||
|
||||
private boolean moreToLoad = true;
|
||||
|
||||
CQueryIteratorWithBuffer(CQuery<T> cquery, OrmQueryRequest<T> request, int bufferSize) {
|
||||
this.cquery = cquery;
|
||||
this.request = request;
|
||||
this.bufferSize = bufferSize;
|
||||
this.buffer = new ArrayList<T>(bufferSize);
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
try {
|
||||
if (buffer.isEmpty() && moreToLoad) {
|
||||
// load buffer
|
||||
int i = -1;
|
||||
while (moreToLoad && ++i < bufferSize) {
|
||||
if (cquery.hasNextBean(true)) {
|
||||
buffer.add(cquery.getLoadedBean());
|
||||
} else {
|
||||
moreToLoad = false;
|
||||
}
|
||||
}
|
||||
// execute secondary queries
|
||||
request.executeSecondaryQueries(bufferSize);
|
||||
}
|
||||
return !buffer.isEmpty();
|
||||
|
||||
} catch (SQLException e) {
|
||||
throw cquery.createPersistenceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public T next() {
|
||||
return buffer.remove(0);
|
||||
}
|
||||
|
||||
public void close() {
|
||||
cquery.updateExecutionStatistics();
|
||||
cquery.close();
|
||||
request.endTransIfRequired();
|
||||
}
|
||||
|
||||
public void remove() {
|
||||
throw new PersistenceException("Remove not allowed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebean.OrderBy;
|
||||
import com.avaje.ebean.OrderBy.Property;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssoc;
|
||||
import com.avaje.ebeaninternal.server.deploy.id.IdBinder;
|
||||
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
|
||||
|
||||
/**
|
||||
* Creates the order by expression clause.
|
||||
*/
|
||||
public class CQueryOrderBy {
|
||||
|
||||
private final BeanDescriptor<?> desc;
|
||||
|
||||
private final SpiQuery<?> query;
|
||||
|
||||
/**
|
||||
* Create the logical order by clause.
|
||||
*/
|
||||
public static String parse(BeanDescriptor<?> desc, SpiQuery<?> query) {
|
||||
return new CQueryOrderBy(desc, query).parseInternal();
|
||||
}
|
||||
|
||||
private CQueryOrderBy(BeanDescriptor<?> desc, SpiQuery<?> query) {
|
||||
this.desc = desc;
|
||||
this.query = query;
|
||||
}
|
||||
|
||||
private String parseInternal() {
|
||||
|
||||
OrderBy<?> orderBy = query.getOrderBy();
|
||||
if (orderBy == null){
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
List<Property> properties = orderBy.getProperties();
|
||||
if (properties.isEmpty()){
|
||||
// order by clause removed by filterMany()
|
||||
return null;
|
||||
}
|
||||
for (int i = 0; i < properties.size(); i++) {
|
||||
if (i > 0){
|
||||
sb.append(", ");
|
||||
}
|
||||
Property p = properties.get(i);
|
||||
String expression = parseProperty(p);
|
||||
sb.append(expression);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String parseProperty(Property p) {
|
||||
|
||||
String propName = p.getProperty();
|
||||
ElPropertyValue el = desc.getElGetValue(propName);
|
||||
if (el == null){
|
||||
return p.toStringFormat();
|
||||
}
|
||||
|
||||
BeanProperty beanProperty = el.getBeanProperty();
|
||||
if (beanProperty instanceof BeanPropertyAssoc<?>){
|
||||
BeanPropertyAssoc<?> ap = (BeanPropertyAssoc<?>)beanProperty;
|
||||
IdBinder idBinder = ap.getTargetDescriptor().getIdBinder();
|
||||
return idBinder.getOrderBy(el.getElName(), p.isAscending());
|
||||
}
|
||||
|
||||
return p.toStringFormat();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import com.avaje.ebean.config.dbplatform.SqlLimitResponse;
|
||||
import com.avaje.ebean.meta.MetaQueryStatistic;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
import com.avaje.ebeaninternal.server.type.DataBind;
|
||||
import com.avaje.ebeaninternal.server.type.DataReader;
|
||||
import com.avaje.ebeaninternal.server.type.RsetDataReader;
|
||||
|
||||
/**
|
||||
* Represents a query for a given SQL statement.
|
||||
* <p>
|
||||
* This can be executed multiple times with different bind parameters.
|
||||
* </p>
|
||||
* <p>
|
||||
* That is, the sql including the where clause, order by clause etc must be
|
||||
* exactly the same to share the same query plan with the only difference being
|
||||
* bind values.
|
||||
* </p>
|
||||
* <p>
|
||||
* This is useful in that is common in OLTP type applications that the same
|
||||
* query will be executed quite a lot just with different bind values. With this
|
||||
* query plan we can bypass some of the query statement generation (for
|
||||
* performance) and collect statistics on the number and average execution
|
||||
* times. This is turn can be used to identify queries that could be looked at
|
||||
* for performance tuning.
|
||||
* </p>
|
||||
*/
|
||||
public class CQueryPlan {
|
||||
|
||||
private final boolean autofetchTuned;
|
||||
|
||||
private final int hash;
|
||||
|
||||
private final boolean rawSql;
|
||||
|
||||
private final boolean rowNumberIncluded;
|
||||
|
||||
private final String sql;
|
||||
|
||||
private final String logWhereSql;
|
||||
|
||||
private final SqlTree sqlTree;
|
||||
|
||||
/**
|
||||
* Encrypted properties required additional binding.
|
||||
*/
|
||||
private final BeanProperty[] encryptedProps;
|
||||
|
||||
private CQueryStats queryStats = new CQueryStats();
|
||||
|
||||
/**
|
||||
* Create a query plan based on a OrmQueryRequest.
|
||||
*/
|
||||
public CQueryPlan(OrmQueryRequest<?> request, SqlLimitResponse sqlRes, SqlTree sqlTree,
|
||||
boolean rawSql, String logWhereSql, String luceneQueryDescription) {
|
||||
|
||||
this.hash = request.getQueryPlanHash();
|
||||
this.autofetchTuned = request.getQuery().isAutofetchTuned();
|
||||
if (sqlRes != null){
|
||||
this.sql = sqlRes.getSql();
|
||||
this.rowNumberIncluded = sqlRes.isIncludesRowNumberColumn();
|
||||
} else {
|
||||
this.sql = luceneQueryDescription;
|
||||
this.rowNumberIncluded = false;
|
||||
}
|
||||
this.sqlTree = sqlTree;
|
||||
this.rawSql = rawSql;
|
||||
this.logWhereSql = logWhereSql;
|
||||
this.encryptedProps = sqlTree.getEncryptedProps();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a query plan for a raw sql query.
|
||||
*/
|
||||
public CQueryPlan(String sql, SqlTree sqlTree,
|
||||
boolean rawSql, boolean rowNumberIncluded, String logWhereSql) {
|
||||
|
||||
this.hash = 0;
|
||||
this.autofetchTuned = false;
|
||||
this.sql = sql;
|
||||
this.sqlTree = sqlTree;
|
||||
this.rawSql = rawSql;
|
||||
this.rowNumberIncluded = rowNumberIncluded;
|
||||
this.logWhereSql = logWhereSql;
|
||||
this.encryptedProps = sqlTree.getEncryptedProps();
|
||||
}
|
||||
|
||||
public boolean isLucene() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public DataReader createDataReader(ResultSet rset){
|
||||
|
||||
return new RsetDataReader(rset);
|
||||
}
|
||||
|
||||
public void bindEncryptedProperties(DataBind dataBind) throws SQLException {
|
||||
if (encryptedProps != null){
|
||||
for (int i = 0; i < encryptedProps.length; i++) {
|
||||
String key = encryptedProps[i].getEncryptKey().getStringValue();
|
||||
dataBind.setString(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isAutofetchTuned() {
|
||||
return autofetchTuned;
|
||||
}
|
||||
|
||||
public int getHash() {
|
||||
return hash;
|
||||
}
|
||||
|
||||
public String getSql() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
public SqlTree getSqlTree() {
|
||||
return sqlTree;
|
||||
}
|
||||
|
||||
public boolean isRawSql() {
|
||||
return rawSql;
|
||||
}
|
||||
|
||||
public boolean isRowNumberIncluded() {
|
||||
return rowNumberIncluded;
|
||||
}
|
||||
|
||||
public String getLogWhereSql() {
|
||||
return logWhereSql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the query statistics.
|
||||
*/
|
||||
public void resetStatistics() {
|
||||
queryStats = new CQueryStats();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an execution time against this query plan;
|
||||
*/
|
||||
public void executionTime(int loadedBeanCount, int timeMicros) {
|
||||
// Atomic operation
|
||||
queryStats = queryStats.add(loadedBeanCount, timeMicros);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current query statistics.
|
||||
*/
|
||||
public CQueryStats getQueryStats() {
|
||||
return queryStats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the time this query plan was last used.
|
||||
*/
|
||||
public long getLastQueryTime(){
|
||||
return queryStats.getLastQueryTime();
|
||||
}
|
||||
|
||||
public MetaQueryStatistic createMetaQueryStatistic(String beanName) {
|
||||
return queryStats.createMetaQueryStatistic(beanName, this);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebean.RawSql.ColumnMapping;
|
||||
import com.avaje.ebean.config.dbplatform.SqlLimitResponse;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.type.DataReader;
|
||||
import com.avaje.ebeaninternal.server.type.RsetDataReaderIndexed;
|
||||
|
||||
public class CQueryPlanRawSql extends CQueryPlan {
|
||||
|
||||
private final int[] rsetIndexPositions;
|
||||
|
||||
public CQueryPlanRawSql(OrmQueryRequest<?> request, SqlLimitResponse sqlRes, SqlTree sqlTree, String logWhereSql) {
|
||||
|
||||
super(request, sqlRes, sqlTree, true, logWhereSql, null);
|
||||
|
||||
this.rsetIndexPositions = createIndexPositions(request, sqlTree);
|
||||
}
|
||||
|
||||
public DataReader createDataReader(ResultSet rset){
|
||||
|
||||
return new RsetDataReaderIndexed(rset, rsetIndexPositions, isRowNumberIncluded());
|
||||
}
|
||||
|
||||
|
||||
private int[] createIndexPositions(OrmQueryRequest<?> request, SqlTree sqlTree) {
|
||||
|
||||
List<String> chain = sqlTree.buildSelectExpressionChain();
|
||||
ColumnMapping columnMapping = request.getQuery().getRawSql().getColumnMapping();
|
||||
|
||||
int[] indexPositions = new int[chain.size()];
|
||||
|
||||
for (int i = 0; i < chain.size(); i++) {
|
||||
String expr = chain.get(i);
|
||||
int indexPos = 1 + columnMapping.getIndexPosition(expr);
|
||||
indexPositions[i] = indexPos;
|
||||
}
|
||||
|
||||
return indexPositions;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.avaje.ebeaninternal.api.BindParams;
|
||||
import com.avaje.ebeaninternal.api.SpiExpressionList;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
import com.avaje.ebeaninternal.api.BindParams.OrderedList;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import com.avaje.ebeaninternal.server.deploy.DeployParser;
|
||||
import com.avaje.ebeaninternal.server.persist.Binder;
|
||||
import com.avaje.ebeaninternal.server.querydefn.OrmQueryProperties;
|
||||
import com.avaje.ebeaninternal.server.type.DataBind;
|
||||
import com.avaje.ebeaninternal.server.util.BindParamsParser;
|
||||
import com.avaje.ebeaninternal.util.DefaultExpressionRequest;
|
||||
|
||||
/**
|
||||
* Compile Query Predicates.
|
||||
* <p>
|
||||
* This includes the where and having expressions which can be made up of
|
||||
* Strings with named parameters or Expression objects.
|
||||
* </p>
|
||||
* <p>
|
||||
* This builds the appropriate bits of where and having clauses and binds the
|
||||
* named parameters and expression values into the prepared statement.
|
||||
* </p>
|
||||
*/
|
||||
public class CQueryPredicates {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(CQueryPredicates.class.getName());
|
||||
|
||||
private final Binder binder;
|
||||
|
||||
private final OrmQueryRequest<?> request;
|
||||
|
||||
private final SpiQuery<?> query;
|
||||
|
||||
private final Object idValue;
|
||||
|
||||
/**
|
||||
* Flag set if this is a SqlSelect type query.
|
||||
*/
|
||||
private boolean rawSql;
|
||||
|
||||
/**
|
||||
* Named bind parameters.
|
||||
*/
|
||||
private final BindParams bindParams;
|
||||
|
||||
/**
|
||||
* Named bind parameters for the having clause.
|
||||
*/
|
||||
private OrderedList havingNamedParams;
|
||||
|
||||
/**
|
||||
* Bind values from the where expressions.
|
||||
*/
|
||||
private ArrayList<Object> filterManyExprBindValues;
|
||||
|
||||
/**
|
||||
* SQL generated from the where expressions.
|
||||
*/
|
||||
private String filterManyExprSql;
|
||||
|
||||
/**
|
||||
* Bind values from the where expressions.
|
||||
*/
|
||||
private ArrayList<Object> whereExprBindValues;
|
||||
|
||||
/**
|
||||
* SQL generated from the where expressions.
|
||||
*/
|
||||
private String whereExprSql;
|
||||
|
||||
/**
|
||||
* SQL generated from where with named parameters.
|
||||
*/
|
||||
private String whereRawSql;
|
||||
|
||||
/**
|
||||
* Bind values for having expression.
|
||||
*/
|
||||
private ArrayList<Object> havingExprBindValues;
|
||||
|
||||
/**
|
||||
* SQL generated from the having expression.
|
||||
*/
|
||||
private String havingExprSql;
|
||||
|
||||
/**
|
||||
* SQL generated from having with named parameters.
|
||||
*/
|
||||
private String havingRawSql;
|
||||
|
||||
private String dbHaving;
|
||||
|
||||
/**
|
||||
* logicalWhere with property names converted to db columns.
|
||||
*/
|
||||
private String dbWhere;
|
||||
|
||||
/**
|
||||
* Filter than can apply to a many fetch join.
|
||||
*/
|
||||
private String dbFilterMany;
|
||||
|
||||
/**
|
||||
* The order by clause.
|
||||
*/
|
||||
private String logicalOrderBy;
|
||||
|
||||
private String dbOrderBy;
|
||||
|
||||
/**
|
||||
* Includes from where and order by clauses.
|
||||
*/
|
||||
private Set<String> predicateIncludes;
|
||||
|
||||
public CQueryPredicates(Binder binder, OrmQueryRequest<?> request) {
|
||||
this.binder = binder;
|
||||
this.request = request;
|
||||
this.query = request.getQuery();
|
||||
this.bindParams = query.getBindParams();
|
||||
this.idValue = query.getId();
|
||||
}
|
||||
|
||||
public String bind(DataBind dataBind) throws SQLException {
|
||||
|
||||
StringBuilder bindLog = new StringBuilder();
|
||||
|
||||
if (idValue != null) {
|
||||
// this is a find by id type query...
|
||||
request.getBeanDescriptor().bindId(dataBind, idValue);
|
||||
bindLog.append(idValue);
|
||||
}
|
||||
|
||||
if (bindParams != null) {
|
||||
// bind named and positioned parameters...
|
||||
binder.bind(bindParams, dataBind, bindLog);
|
||||
}
|
||||
|
||||
if (whereExprBindValues != null) {
|
||||
|
||||
for (int i = 0; i < whereExprBindValues.size(); i++) {
|
||||
Object bindValue = whereExprBindValues.get(i);
|
||||
binder.bindObject(dataBind, bindValue);
|
||||
if (i > 0 || idValue != null) {
|
||||
bindLog.append(", ");
|
||||
}
|
||||
bindLog.append(bindValue);
|
||||
}
|
||||
}
|
||||
|
||||
if (filterManyExprBindValues != null) {
|
||||
|
||||
for (int i = 0; i < filterManyExprBindValues.size(); i++) {
|
||||
Object bindValue = filterManyExprBindValues.get(i);
|
||||
binder.bindObject(dataBind, bindValue);
|
||||
if (i > 0 || idValue != null) {
|
||||
bindLog.append(", ");
|
||||
}
|
||||
bindLog.append(bindValue);
|
||||
}
|
||||
}
|
||||
|
||||
if (havingNamedParams != null) {
|
||||
// bind named parameters in having...
|
||||
bindLog.append(" havingNamed ");
|
||||
binder.bind(havingNamedParams.list(), dataBind, bindLog);
|
||||
}
|
||||
|
||||
if (havingExprBindValues != null) {
|
||||
// bind having expression...
|
||||
bindLog.append(" having ");
|
||||
for (int i = 0; i < havingExprBindValues.size(); i++) {
|
||||
Object bindValue = havingExprBindValues.get(i);
|
||||
binder.bindObject(dataBind, bindValue);
|
||||
if (i > 0) {
|
||||
bindLog.append(", ");
|
||||
}
|
||||
bindLog.append(bindValue);
|
||||
}
|
||||
}
|
||||
|
||||
return bindLog.toString();
|
||||
}
|
||||
|
||||
private void buildBindHavingRawSql(boolean buildSql, boolean parseRaw, DeployParser deployParser) {
|
||||
if (buildSql || bindParams != null) {
|
||||
// having clause with named parameters...
|
||||
havingRawSql = query.getAdditionalHaving();
|
||||
if (parseRaw) {
|
||||
havingRawSql = deployParser.parse(havingRawSql);
|
||||
}
|
||||
if (havingRawSql != null && bindParams != null) {
|
||||
// convert and order named parameters if required
|
||||
havingNamedParams = BindParamsParser.parseNamedParams(bindParams, havingRawSql);
|
||||
havingRawSql = havingNamedParams.getPreparedSql();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert named parameters into an OrderedList.
|
||||
*/
|
||||
private void buildBindWhereRawSql(boolean buildSql, boolean parseRaw, DeployParser parser) {
|
||||
if (buildSql || bindParams != null) {
|
||||
whereRawSql = buildWhereRawSql();
|
||||
boolean hasRaw = !"".equals(whereRawSql);
|
||||
if (hasRaw && parseRaw) {
|
||||
// parse with encrypted property awareness. This means that if we have
|
||||
// an
|
||||
// encrypted property we will insert special named parameter place
|
||||
// holders
|
||||
// for binding the encryption key values
|
||||
parser.setEncrypted(true);
|
||||
whereRawSql = parser.parse(whereRawSql);
|
||||
parser.setEncrypted(false);
|
||||
}
|
||||
|
||||
if (bindParams != null) {
|
||||
if (hasRaw) {
|
||||
whereRawSql = BindParamsParser.parse(bindParams, whereRawSql, request.getBeanDescriptor());
|
||||
|
||||
} else if (query.isRawSql() && !buildSql) {
|
||||
// RawSql query hit cached query plan. Need to convert
|
||||
// named parameters into positioned parameters so that
|
||||
// the named parameters are bound
|
||||
String s = query.getRawSql().getSql().getPreWhere();
|
||||
if (bindParams.requiresNamedParamsPrepare()) {
|
||||
BindParamsParser.parse(bindParams, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String buildWhereRawSql() {
|
||||
// this is the where part of a OQL query which
|
||||
// may contain bind parameters...
|
||||
String whereRaw = query.getRawWhereClause();
|
||||
if (whereRaw == null) {
|
||||
whereRaw = "";
|
||||
}
|
||||
// add any additional stuff to the where clause
|
||||
String additionalWhere = query.getAdditionalWhere();
|
||||
if (additionalWhere != null) {
|
||||
whereRaw += additionalWhere;
|
||||
}
|
||||
return whereRaw;
|
||||
}
|
||||
|
||||
public void prepare(boolean buildSql) {
|
||||
|
||||
DeployParser deployParser = request.createDeployParser();
|
||||
|
||||
prepare(buildSql, true, deployParser);
|
||||
}
|
||||
|
||||
public void prepareRawSql(DeployParser deployParser) {
|
||||
prepare(true, false, deployParser);
|
||||
}
|
||||
|
||||
/**
|
||||
* This combines the sql from named/positioned parameters and expressions.
|
||||
*/
|
||||
private void prepare(boolean buildSql, boolean parseRaw, DeployParser deployParser) {
|
||||
|
||||
buildBindWhereRawSql(buildSql, parseRaw, deployParser);
|
||||
buildBindHavingRawSql(buildSql, parseRaw, deployParser);
|
||||
|
||||
SpiExpressionList<?> whereExp = query.getWhereExpressions();
|
||||
if (whereExp != null) {
|
||||
DefaultExpressionRequest whereReq = new DefaultExpressionRequest(request, deployParser);
|
||||
whereExprBindValues = whereExp.buildBindValues(whereReq);
|
||||
if (buildSql) {
|
||||
whereExprSql = whereExp.buildSql(whereReq);
|
||||
}
|
||||
}
|
||||
|
||||
BeanPropertyAssocMany<?> manyProperty = request.getManyProperty();
|
||||
if (manyProperty != null) {
|
||||
OrmQueryProperties chunk = query.getDetail().getChunk(manyProperty.getName(), false);
|
||||
SpiExpressionList<?> filterMany = chunk.getFilterMany();
|
||||
if (filterMany != null) {
|
||||
DefaultExpressionRequest filterReq = new DefaultExpressionRequest(request, deployParser);
|
||||
filterManyExprBindValues = filterMany.buildBindValues(filterReq);
|
||||
if (buildSql) {
|
||||
filterManyExprSql = filterMany.buildSql(filterReq);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// having expression
|
||||
SpiExpressionList<?> havingExpr = query.getHavingExpressions();
|
||||
if (havingExpr != null) {
|
||||
DefaultExpressionRequest havingReq = new DefaultExpressionRequest(request, deployParser);
|
||||
havingExprBindValues = havingExpr.buildBindValues(havingReq);
|
||||
if (buildSql) {
|
||||
havingExprSql = havingExpr.buildSql(havingReq);
|
||||
}
|
||||
}
|
||||
|
||||
if (buildSql) {
|
||||
parsePropertiesToDbColumns(deployParser);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse/Convert property names to database columns in the where and order by
|
||||
* clauses etc.
|
||||
*/
|
||||
private void parsePropertiesToDbColumns(DeployParser deployParser) {
|
||||
|
||||
dbWhere = deriveWhere(deployParser);
|
||||
dbFilterMany = deriveFilterMany(deployParser);
|
||||
dbHaving = deriveHaving(deployParser);
|
||||
|
||||
// order by is dependent on the manyProperty (if there is one)
|
||||
logicalOrderBy = deriveOrderByWithMany(request.getManyProperty());
|
||||
if (logicalOrderBy != null) {
|
||||
dbOrderBy = deployParser.parse(logicalOrderBy);
|
||||
}
|
||||
|
||||
predicateIncludes = deployParser.getIncludes();
|
||||
}
|
||||
|
||||
private String deriveFilterMany(DeployParser deployParser) {
|
||||
if (isEmpty(filterManyExprSql)) {
|
||||
return null;
|
||||
} else {
|
||||
return deployParser.parse(filterManyExprSql);
|
||||
}
|
||||
}
|
||||
|
||||
private String deriveWhere(DeployParser deployParser) {
|
||||
return parse(whereRawSql, whereExprSql, deployParser);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the table alias place holders.
|
||||
*/
|
||||
public void parseTableAlias(SqlTreeAlias alias) {
|
||||
if (dbWhere != null) {
|
||||
// use the where table alias
|
||||
dbWhere = alias.parseWhere(dbWhere);
|
||||
}
|
||||
if (dbFilterMany != null) {
|
||||
// use the select table alias
|
||||
dbFilterMany = alias.parse(dbFilterMany);
|
||||
}
|
||||
if (dbHaving != null) {
|
||||
dbHaving = alias.parseWhere(dbHaving);
|
||||
}
|
||||
if (dbOrderBy != null) {
|
||||
dbOrderBy = alias.parse(dbOrderBy);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isEmpty(String s) {
|
||||
return s == null || s.length() == 0;
|
||||
}
|
||||
|
||||
private String parse(String raw, String expr, DeployParser deployParser) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (!isEmpty(raw)) {
|
||||
sb.append(raw);
|
||||
}
|
||||
if (!isEmpty(expr)) {
|
||||
if (sb.length() > 0) {
|
||||
sb.append(" and ");
|
||||
}
|
||||
sb.append(deployParser.parse(expr));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String deriveHaving(DeployParser deployParser) {
|
||||
return parse(havingRawSql, havingExprSql, deployParser);
|
||||
}
|
||||
|
||||
private String parseOrderBy() {
|
||||
|
||||
return CQueryOrderBy.parse(request.getBeanDescriptor(), query);
|
||||
}
|
||||
|
||||
/**
|
||||
* There is a many property so we need to make sure the ordering is
|
||||
* appropriate.
|
||||
*/
|
||||
private String deriveOrderByWithMany(BeanPropertyAssocMany<?> manyProp) {
|
||||
|
||||
if (manyProp == null) {
|
||||
return parseOrderBy();
|
||||
}
|
||||
|
||||
String orderBy = parseOrderBy();
|
||||
|
||||
BeanDescriptor<?> desc = request.getBeanDescriptor();
|
||||
String orderById = desc.getDefaultOrderBy();
|
||||
|
||||
if (orderBy == null) {
|
||||
orderBy = orderById;
|
||||
}
|
||||
|
||||
// check for default ordering on the many property...
|
||||
String manyOrderBy = manyProp.getFetchOrderBy();
|
||||
if (manyOrderBy != null) {
|
||||
orderBy = orderBy + ", " + CQueryBuilder.prefixOrderByFields(manyProp.getName(), manyOrderBy);
|
||||
}
|
||||
|
||||
if (request.isFindById()) {
|
||||
// only one master bean so should be fine...
|
||||
return orderBy;
|
||||
}
|
||||
|
||||
if (orderBy.startsWith(orderById)) {
|
||||
return orderBy;
|
||||
}
|
||||
|
||||
// more than one top level row may be returned so
|
||||
// we need to make sure their is an order by on the
|
||||
// top level first (to ensure master/detail construction).
|
||||
|
||||
int manyPos = orderBy.indexOf(manyProp.getName());
|
||||
int idPos = orderBy.indexOf(" " + orderById);
|
||||
|
||||
if (manyPos == -1) {
|
||||
// no ordering of the many
|
||||
if (idPos == -1) {
|
||||
// append the orderById so that master level objects are ordered
|
||||
// even if the orderBy is not unique for the master object
|
||||
return orderBy + ", " + orderById;
|
||||
}
|
||||
// orderById is already in the order by clause
|
||||
return orderBy;
|
||||
}
|
||||
|
||||
if (idPos > -1 && idPos < manyPos) {
|
||||
// its all ok, id property appears before a many property
|
||||
|
||||
} else {
|
||||
if (idPos > manyPos) {
|
||||
// there was an error with the order by...
|
||||
String msg = "A Query on [" + desc + "] includes a join to a 'many' association [" + manyProp.getName();
|
||||
msg += "] with an incorrect orderBy [" + orderBy + "]. The id property [" + orderById + "]";
|
||||
msg += " must come before the many property [" + manyProp.getName() + "] in the orderBy.";
|
||||
msg += " Ebean has automatically modified the orderBy clause to do this.";
|
||||
|
||||
logger.log(Level.WARNING, msg);
|
||||
}
|
||||
|
||||
// the id needs to come before the manyPropName
|
||||
orderBy = orderBy.substring(0, manyPos) + orderById + ", " + orderBy.substring(manyPos);
|
||||
}
|
||||
|
||||
return orderBy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the bind values for the where expression.
|
||||
*/
|
||||
public ArrayList<Object> getWhereExprBindValues() {
|
||||
return whereExprBindValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the db column version of the combined where clause.
|
||||
*/
|
||||
public String getDbHaving() {
|
||||
return dbHaving;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the db column version of the combined where clause.
|
||||
*/
|
||||
public String getDbWhere() {
|
||||
return dbWhere;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a db filter for filtering many fetch joins.
|
||||
*/
|
||||
public String getDbFilterMany() {
|
||||
return dbFilterMany;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the db column version of the order by clause.
|
||||
*/
|
||||
public String getDbOrderBy() {
|
||||
return dbOrderBy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the includes required for the where and order by clause.
|
||||
*/
|
||||
public Set<String> getPredicateIncludes() {
|
||||
return predicateIncludes;
|
||||
}
|
||||
|
||||
/**
|
||||
* The where sql with named bind parameters converted to ?.
|
||||
*/
|
||||
public String getWhereRawSql() {
|
||||
return whereRawSql;
|
||||
}
|
||||
|
||||
/**
|
||||
* The where sql from the expression objects.
|
||||
*/
|
||||
public String getWhereExpressionSql() {
|
||||
return whereExprSql;
|
||||
}
|
||||
|
||||
/**
|
||||
* The having sql with named bind parameters converted to ?.
|
||||
*/
|
||||
public String getHavingRawSql() {
|
||||
return havingRawSql;
|
||||
}
|
||||
|
||||
/**
|
||||
* The having sql from the expression objects.
|
||||
*/
|
||||
public String getHavingExpressionSql() {
|
||||
return havingExprSql;
|
||||
}
|
||||
|
||||
public String getLogWhereSql() {
|
||||
if (rawSql) {
|
||||
return "";
|
||||
}
|
||||
if (dbWhere == null && dbFilterMany == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (dbWhere != null) {
|
||||
sb.append(dbWhere);
|
||||
}
|
||||
if (dbFilterMany != null) {
|
||||
if (sb.length() > 0) {
|
||||
sb.append(" and ");
|
||||
}
|
||||
sb.append(dbFilterMany);
|
||||
}
|
||||
String logPred = sb.toString();
|
||||
if (logPred.length() > 400) {
|
||||
logPred = logPred.substring(0, 400) + " ...";
|
||||
}
|
||||
return logPred;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.core.SpiOrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.type.DataBind;
|
||||
|
||||
/**
|
||||
* Executes the select row count query.
|
||||
*/
|
||||
public class CQueryRowCount {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(CQueryRowCount.class.getName());
|
||||
|
||||
/**
|
||||
* The overall find request wrapper object.
|
||||
*/
|
||||
private final OrmQueryRequest<?> request;
|
||||
|
||||
private final BeanDescriptor<?> desc;
|
||||
|
||||
private final SpiQuery<?> query;
|
||||
|
||||
/**
|
||||
* Where clause predicates.
|
||||
*/
|
||||
private final CQueryPredicates predicates;
|
||||
|
||||
/**
|
||||
* The final sql that is generated.
|
||||
*/
|
||||
private final String sql;
|
||||
|
||||
/**
|
||||
* The resultSet that is read and converted to objects.
|
||||
*/
|
||||
private ResultSet rset;
|
||||
|
||||
/**
|
||||
* The statement used to create the resultSet.
|
||||
*/
|
||||
private PreparedStatement pstmt;
|
||||
|
||||
private String bindLog;
|
||||
|
||||
private long startNano;
|
||||
|
||||
private int executionTimeMicros;
|
||||
|
||||
private int rowCount;
|
||||
|
||||
/**
|
||||
* Create the Sql select based on the request.
|
||||
*/
|
||||
public CQueryRowCount(OrmQueryRequest<?> request, CQueryPredicates predicates, String sql) {
|
||||
this.request = request;
|
||||
this.query = request.getQuery();
|
||||
this.sql = sql;
|
||||
|
||||
query.setGeneratedSql(sql);
|
||||
|
||||
this.desc = request.getBeanDescriptor();
|
||||
this.predicates = predicates;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a summary description of this query.
|
||||
*/
|
||||
public String getSummary() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("FindRowCount exeMicros[").append(executionTimeMicros)
|
||||
.append("] rows[").append(rowCount)
|
||||
.append("] type[").append(desc.getFullName())
|
||||
.append("] predicates[").append(predicates.getLogWhereSql())
|
||||
.append("] bind[").append(bindLog).append("]");
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the bind log.
|
||||
*/
|
||||
public String getBindLog() {
|
||||
return bindLog;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the generated sql.
|
||||
*/
|
||||
public String getGeneratedSql() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
public SpiOrmQueryRequest<?> getQueryRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query returning the row count.
|
||||
*/
|
||||
public int findRowCount() throws SQLException {
|
||||
|
||||
startNano = System.nanoTime();
|
||||
try {
|
||||
|
||||
SpiTransaction t = request.getTransaction();
|
||||
Connection conn = t.getInternalConnection();
|
||||
pstmt = conn.prepareStatement(sql);
|
||||
|
||||
if (query.getTimeout() > 0){
|
||||
pstmt.setQueryTimeout(query.getTimeout());
|
||||
}
|
||||
|
||||
bindLog = predicates.bind(new DataBind(pstmt));
|
||||
|
||||
rset = pstmt.executeQuery();
|
||||
|
||||
if (!rset.next()){
|
||||
throw new PersistenceException("Expecting 1 row but got none?");
|
||||
}
|
||||
|
||||
rowCount = rset.getInt(1);
|
||||
|
||||
long exeNano = System.nanoTime() - startNano;
|
||||
executionTimeMicros = (int)exeNano/1000;
|
||||
|
||||
return rowCount;
|
||||
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the resources.
|
||||
* <p>
|
||||
* The jdbc resultSet and statement need to be closed. Its important that
|
||||
* this method is called.
|
||||
* </p>
|
||||
*/
|
||||
private void close() {
|
||||
try {
|
||||
if (rset != null) {
|
||||
rset.close();
|
||||
rset = null;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
try {
|
||||
if (pstmt != null) {
|
||||
pstmt.close();
|
||||
pstmt = null;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import com.avaje.ebean.meta.MetaQueryStatistic;
|
||||
|
||||
/**
|
||||
* Statistics for query plan that can accumulate.
|
||||
*/
|
||||
public final class CQueryStats {
|
||||
|
||||
private final int count;
|
||||
|
||||
private final int totalLoadedBeanCount;
|
||||
|
||||
private final int totalTimeMicros;
|
||||
|
||||
private final long startCollecting;
|
||||
|
||||
private final long lastQueryTime;
|
||||
|
||||
public CQueryStats() {
|
||||
count = 0;
|
||||
totalLoadedBeanCount = 0;
|
||||
totalTimeMicros = 0;
|
||||
startCollecting = System.currentTimeMillis();
|
||||
lastQueryTime = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accumulate/Increment the statistics based on the previous statistics.
|
||||
*/
|
||||
public CQueryStats(CQueryStats previous, int loadedBeanCount, int timeMicros) {
|
||||
count = previous.count + 1;
|
||||
totalLoadedBeanCount = previous.totalLoadedBeanCount + loadedBeanCount;
|
||||
totalTimeMicros = previous.totalTimeMicros + timeMicros;
|
||||
startCollecting = previous.startCollecting;
|
||||
lastQueryTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public CQueryStats add(int loadedBeanCount, int timeMicros) {
|
||||
return new CQueryStats(this, loadedBeanCount, timeMicros);
|
||||
}
|
||||
|
||||
public int getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public int getAverageTimeMicros() {
|
||||
if (count == 0) {
|
||||
return 0;
|
||||
} else {
|
||||
return totalTimeMicros / count;
|
||||
}
|
||||
}
|
||||
|
||||
public int getTotalLoadedBeanCount() {
|
||||
return totalLoadedBeanCount;
|
||||
}
|
||||
|
||||
public int getTotalTimeMicros() {
|
||||
return totalTimeMicros;
|
||||
}
|
||||
|
||||
public long getStartCollecting() {
|
||||
return startCollecting;
|
||||
}
|
||||
|
||||
public long getLastQueryTime() {
|
||||
return lastQueryTime;
|
||||
}
|
||||
|
||||
public MetaQueryStatistic createMetaQueryStatistic(String beanName, CQueryPlan qp) {
|
||||
return new MetaQueryStatistic(qp.isAutofetchTuned(), beanName, qp.getHash(),
|
||||
qp.getSql(), count, totalLoadedBeanCount, totalTimeMicros, startCollecting, lastQueryTime);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import com.avaje.ebean.Query;
|
||||
import com.avaje.ebean.Transaction;
|
||||
import com.avaje.ebeaninternal.api.SpiEbeanServer;
|
||||
|
||||
/**
|
||||
* Base object for making query execution into Callable's.
|
||||
*
|
||||
* @author rbygrave
|
||||
*
|
||||
* @param <T> the entity bean type
|
||||
*/
|
||||
public abstract class CallableQuery<T> {
|
||||
|
||||
protected final Query<T> query;
|
||||
|
||||
protected final SpiEbeanServer server;
|
||||
|
||||
protected final Transaction t;
|
||||
|
||||
public CallableQuery(SpiEbeanServer server, Query<T> query, Transaction t) {
|
||||
this.server = server;
|
||||
this.query = query;
|
||||
this.t = t;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import com.avaje.ebean.Query;
|
||||
import com.avaje.ebean.Transaction;
|
||||
import com.avaje.ebeaninternal.api.SpiEbeanServer;
|
||||
|
||||
/**
|
||||
* Represent the fetch Id's query as a Callable.
|
||||
*
|
||||
* @param <T> the entity bean type
|
||||
*/
|
||||
public class CallableQueryIds<T> extends CallableQuery<T> implements Callable<List<Object>> {
|
||||
|
||||
|
||||
public CallableQueryIds(SpiEbeanServer server, Query<T> query, Transaction t) {
|
||||
super(server, query, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the find Id's query returning the list of Id's.
|
||||
*/
|
||||
public List<Object> call() throws Exception {
|
||||
// we have already made a copy of the query
|
||||
// this way the same query instance is available to the
|
||||
// QueryFutureIds (as so has access to the List before it is done)
|
||||
return server.findIdsWithCopy(query, t);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import com.avaje.ebean.Query;
|
||||
import com.avaje.ebean.Transaction;
|
||||
import com.avaje.ebeaninternal.api.SpiEbeanServer;
|
||||
|
||||
/**
|
||||
* Represent the findList query as a Callable.
|
||||
*
|
||||
* @param <T> the entity bean type
|
||||
*/
|
||||
public class CallableQueryList<T> extends CallableQuery<T> implements Callable<List<T>> {
|
||||
|
||||
|
||||
public CallableQueryList(SpiEbeanServer server, Query<T> query, Transaction t) {
|
||||
super(server, query, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query returning the resulting List.
|
||||
*/
|
||||
public List<T> call() throws Exception {
|
||||
return server.findList(query, t);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import com.avaje.ebean.Query;
|
||||
import com.avaje.ebean.Transaction;
|
||||
import com.avaje.ebeaninternal.api.SpiEbeanServer;
|
||||
|
||||
/**
|
||||
* Represent the findRowCount query as a Callable.
|
||||
*
|
||||
* @param <T> the entity bean type
|
||||
*/
|
||||
public class CallableQueryRowCount<T> extends CallableQuery<T> implements Callable<Integer> {
|
||||
|
||||
|
||||
public CallableQueryRowCount(SpiEbeanServer server, Query<T> query, Transaction t) {
|
||||
super(server, query, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query returning the row count.
|
||||
*/
|
||||
public Integer call() throws Exception {
|
||||
return server.findRowCountWithCopy(query, t);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import com.avaje.ebean.EbeanServer;
|
||||
import com.avaje.ebean.SqlQuery;
|
||||
import com.avaje.ebean.SqlRow;
|
||||
import com.avaje.ebean.Transaction;
|
||||
|
||||
/**
|
||||
* Represent the SQL query findList as a Callable.
|
||||
*/
|
||||
public class CallableSqlQueryList implements Callable<List<SqlRow>> {
|
||||
|
||||
private final SqlQuery query;
|
||||
|
||||
private final EbeanServer server;
|
||||
|
||||
private final Transaction t;
|
||||
|
||||
public CallableSqlQueryList(EbeanServer server, SqlQuery query, Transaction t) {
|
||||
this.server = server;
|
||||
this.query = query;
|
||||
this.t = t;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query returning the resulting list.
|
||||
*/
|
||||
public List<SqlRow> call() throws Exception {
|
||||
return server.findList(query, t);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
/**
|
||||
* Defines a cancelable query.
|
||||
* <p>
|
||||
* Typically holds a representation of the PreparedStatement to perform the
|
||||
* actual cancel.
|
||||
* </p>
|
||||
*/
|
||||
public interface CancelableQuery {
|
||||
|
||||
/**
|
||||
* Cancel the query.
|
||||
* <p>
|
||||
* For JDBC this translates to calling cancel on the PreparedStatement.
|
||||
* </p>
|
||||
*/
|
||||
public void cancel();
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
/**
|
||||
* Constants used in find processing.
|
||||
*/
|
||||
public interface Constants {
|
||||
|
||||
/**
|
||||
* the new line character used.
|
||||
* <p>
|
||||
* Note that this is removed for logging sql to the transaction log.
|
||||
* </p>
|
||||
*/
|
||||
public static final char NEW_LINE = '\n';
|
||||
|
||||
/**
|
||||
* The carriage return character.
|
||||
*/
|
||||
public static final char CARRIAGE_RETURN = '\r';
|
||||
|
||||
/**
|
||||
* literal used for SQL LIMIT in MySql and Postgres.
|
||||
*/
|
||||
public static final String LIMIT = "limit";
|
||||
|
||||
/**
|
||||
* Literal used for SQL LIMIT OFFSET clause in MySql and Postgres.
|
||||
*/
|
||||
public static final String OFFSET = "offset";
|
||||
|
||||
/**
|
||||
* ROW_NUMBER() OVER (ORDER BY
|
||||
*/
|
||||
public static final String ROW_NUMBER_OVER = "row_number() over (order by ";
|
||||
|
||||
/**
|
||||
* ) as rn,
|
||||
*/
|
||||
public static final String ROW_NUMBER_AS = ") as rn, ";
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
|
||||
import com.avaje.ebeaninternal.server.deploy.TableJoinColumn;
|
||||
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
|
||||
import com.avaje.ebeaninternal.server.util.ArrayStack;
|
||||
|
||||
public class DefaultDbSqlContext implements DbSqlContext {
|
||||
|
||||
private static final String NEW_LINE = "\n";
|
||||
|
||||
private static final String COMMA = ", ";
|
||||
|
||||
private static final String PERIOD = ".";
|
||||
|
||||
private final String tableAliasPlaceHolder;
|
||||
|
||||
private final String columnAliasPrefix;
|
||||
|
||||
private final ArrayStack<String> tableAliasStack = new ArrayStack<String>();
|
||||
|
||||
private final ArrayStack<String> joinStack = new ArrayStack<String>();
|
||||
|
||||
private final ArrayStack<String> prefixStack = new ArrayStack<String>();
|
||||
|
||||
private final boolean useColumnAlias;
|
||||
|
||||
private int columnIndex;
|
||||
|
||||
private StringBuilder sb = new StringBuilder(140);
|
||||
|
||||
/**
|
||||
* A Set used to make sure formula joins are only added once to a query.
|
||||
*/
|
||||
private HashSet<String> formulaJoins;
|
||||
|
||||
private HashSet<String> tableJoins;
|
||||
|
||||
private SqlTreeAlias alias;
|
||||
|
||||
private String currentPrefix;
|
||||
|
||||
private ArrayList<BeanProperty> encryptedProps;
|
||||
|
||||
/**
|
||||
* Construct for FROM clause (no column alias used).
|
||||
*/
|
||||
public DefaultDbSqlContext(SqlTreeAlias alias, String tableAliasPlaceHolder) {
|
||||
this.tableAliasPlaceHolder = tableAliasPlaceHolder;
|
||||
this.columnAliasPrefix = null;
|
||||
this.useColumnAlias = false;
|
||||
this.alias = alias;
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct for SELECT clause (with column alias settings).
|
||||
*/
|
||||
public DefaultDbSqlContext(SqlTreeAlias alias, String tableAliasPlaceHolder, String columnAliasPrefix,
|
||||
boolean alwaysUseColumnAlias) {
|
||||
this.alias = alias;
|
||||
this.tableAliasPlaceHolder = tableAliasPlaceHolder;
|
||||
this.columnAliasPrefix = columnAliasPrefix;
|
||||
this.useColumnAlias = alwaysUseColumnAlias;
|
||||
}
|
||||
|
||||
public void addEncryptedProp(BeanProperty p) {
|
||||
if (encryptedProps == null){
|
||||
encryptedProps = new ArrayList<BeanProperty>();
|
||||
}
|
||||
encryptedProps.add(p);
|
||||
}
|
||||
|
||||
public BeanProperty[] getEncryptedProps() {
|
||||
if (encryptedProps == null){
|
||||
return null;
|
||||
}
|
||||
|
||||
return encryptedProps.toArray(new BeanProperty[encryptedProps.size()]);
|
||||
}
|
||||
|
||||
public String peekJoin() {
|
||||
return joinStack.peek();
|
||||
}
|
||||
|
||||
public void popJoin() {
|
||||
joinStack.pop();
|
||||
}
|
||||
|
||||
public void pushJoin(String node) {
|
||||
joinStack.push(node);
|
||||
}
|
||||
|
||||
public void addJoin(String type, String table, TableJoinColumn[] cols, String a1, String a2) {
|
||||
|
||||
if (tableJoins == null) {
|
||||
tableJoins = new HashSet<String>();
|
||||
}
|
||||
|
||||
String joinKey = table + "-" + a1 + "-" + a2;
|
||||
if (tableJoins.contains(joinKey)) {
|
||||
return;
|
||||
}
|
||||
|
||||
tableJoins.add(joinKey);
|
||||
|
||||
sb.append(NEW_LINE);
|
||||
sb.append(type);
|
||||
|
||||
sb.append(" ").append(table).append(" ");
|
||||
sb.append(a2);
|
||||
|
||||
sb.append(" on ");
|
||||
|
||||
for (int i = 0; i < cols.length; i++) {
|
||||
TableJoinColumn pair = cols[i];
|
||||
if (i > 0) {
|
||||
sb.append(" and ");
|
||||
}
|
||||
|
||||
sb.append(a2);
|
||||
sb.append(".").append(pair.getForeignDbColumn());
|
||||
sb.append(" = ");
|
||||
sb.append(a1);
|
||||
sb.append(".").append(pair.getLocalDbColumn());
|
||||
}
|
||||
|
||||
sb.append(" ");
|
||||
}
|
||||
|
||||
public String getTableAlias(String prefix) {
|
||||
return alias.getTableAlias(prefix);
|
||||
}
|
||||
|
||||
public String getTableAliasManyWhere(String prefix) {
|
||||
return alias.getTableAliasManyWhere(prefix);
|
||||
}
|
||||
|
||||
public void pushSecondaryTableAlias(String alias) {
|
||||
tableAliasStack.push(alias);
|
||||
}
|
||||
|
||||
public String getRelativePrefix(String propName) {
|
||||
|
||||
return currentPrefix == null ? propName : currentPrefix + "." + propName;
|
||||
}
|
||||
|
||||
public void pushTableAlias(String prefix) {
|
||||
// store the currentPrefix on a stack
|
||||
prefixStack.push(currentPrefix);
|
||||
currentPrefix = prefix;
|
||||
tableAliasStack.push(getTableAlias(prefix));
|
||||
}
|
||||
|
||||
public void popTableAlias() {
|
||||
tableAliasStack.pop();
|
||||
// pop the currentPrefix from the stack
|
||||
currentPrefix = prefixStack.pop();;
|
||||
}
|
||||
|
||||
public StringBuilder getBuffer() {
|
||||
return sb;
|
||||
}
|
||||
|
||||
public DefaultDbSqlContext append(String s) {
|
||||
sb.append(s);
|
||||
return this;
|
||||
}
|
||||
|
||||
public DefaultDbSqlContext append(char s) {
|
||||
sb.append(s);
|
||||
return this;
|
||||
}
|
||||
|
||||
public void appendFormulaJoin(String sqlFormulaJoin, boolean forceOuterJoin) {
|
||||
|
||||
// replace ${ta} place holder with the real table alias...
|
||||
String tableAlias = tableAliasStack.peek();
|
||||
String converted = StringHelper.replaceString(sqlFormulaJoin, tableAliasPlaceHolder, tableAlias);
|
||||
|
||||
if (formulaJoins == null) {
|
||||
formulaJoins = new HashSet<String>();
|
||||
|
||||
} else if (formulaJoins.contains(converted)) {
|
||||
// skip adding a formula join because
|
||||
// the same join has already been added.
|
||||
return;
|
||||
}
|
||||
|
||||
// we only want to add this join once
|
||||
formulaJoins.add(converted);
|
||||
|
||||
sb.append(NEW_LINE);
|
||||
|
||||
if (forceOuterJoin) {
|
||||
if ("join".equals(sqlFormulaJoin.substring(0, 4).toLowerCase())) {
|
||||
// prepend left outer as we are in the 'many' part
|
||||
append(" left outer ");
|
||||
}
|
||||
}
|
||||
|
||||
sb.append(converted);
|
||||
sb.append(" ");
|
||||
}
|
||||
|
||||
public void appendFormulaSelect(String sqlFormulaSelect) {
|
||||
|
||||
String tableAlias = tableAliasStack.peek();
|
||||
String converted = StringHelper.replaceString(sqlFormulaSelect, tableAliasPlaceHolder, tableAlias);
|
||||
|
||||
sb.append(COMMA);
|
||||
sb.append(converted);
|
||||
}
|
||||
|
||||
public void appendColumn(String column) {
|
||||
appendColumn(tableAliasStack.peek(), column);
|
||||
}
|
||||
|
||||
public void appendColumn(String tableAlias, String column) {
|
||||
sb.append(COMMA);
|
||||
|
||||
if (column.indexOf("${}") > -1){
|
||||
// support DB functions such as lower() etc
|
||||
// with the use of secondary columns
|
||||
String x = StringHelper.replaceString(column, "${}", tableAlias);
|
||||
sb.append(x);
|
||||
} else {
|
||||
sb.append(tableAlias);
|
||||
sb.append(PERIOD);
|
||||
sb.append(column);
|
||||
}
|
||||
if (useColumnAlias) {
|
||||
sb.append(" ");
|
||||
sb.append(columnAliasPrefix);
|
||||
sb.append(columnIndex);
|
||||
}
|
||||
columnIndex++;
|
||||
}
|
||||
|
||||
public String peekTableAlias() {
|
||||
return tableAliasStack.peek();
|
||||
}
|
||||
|
||||
public void appendRawColumn(String rawcolumnWithTableAlias) {
|
||||
sb.append(COMMA);
|
||||
sb.append(rawcolumnWithTableAlias);
|
||||
|
||||
if (useColumnAlias) {
|
||||
sb.append(" ");
|
||||
sb.append(columnAliasPrefix);
|
||||
sb.append(columnIndex);
|
||||
}
|
||||
columnIndex++;
|
||||
}
|
||||
|
||||
public int length() {
|
||||
return sb.length();
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
String s = sb.toString();
|
||||
sb = new StringBuilder();
|
||||
return s;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "DefaultDbSqlContext: "+sb.toString();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import com.avaje.ebean.QueryIterator;
|
||||
import com.avaje.ebean.bean.BeanCollection;
|
||||
import com.avaje.ebean.event.BeanFinder;
|
||||
import com.avaje.ebeaninternal.api.BeanIdList;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryEngine;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptorManager;
|
||||
|
||||
/**
|
||||
* Main Finder implementation.
|
||||
*/
|
||||
public class DefaultOrmQueryEngine implements OrmQueryEngine {
|
||||
|
||||
/**
|
||||
* Find using predicates
|
||||
*/
|
||||
private final CQueryEngine queryEngine;
|
||||
|
||||
/**
|
||||
* Create the Finder.
|
||||
*/
|
||||
public DefaultOrmQueryEngine(BeanDescriptorManager descMgr, CQueryEngine queryEngine) {
|
||||
|
||||
this.queryEngine = queryEngine;
|
||||
}
|
||||
|
||||
public <T> int findRowCount(OrmQueryRequest<T> request){
|
||||
|
||||
return queryEngine.findRowCount(request);
|
||||
}
|
||||
|
||||
public <T> BeanIdList findIds(OrmQueryRequest<T> request){
|
||||
|
||||
return queryEngine.findIds(request);
|
||||
}
|
||||
|
||||
|
||||
public <T> QueryIterator<T> findIterate(OrmQueryRequest<T> request) {
|
||||
|
||||
// LIMITATION: You can not use QueryIterator to load bean cache
|
||||
|
||||
SpiTransaction t = request.getTransaction();
|
||||
|
||||
// before we perform a query, we need to flush any
|
||||
// previous persist requests that are queued/batched.
|
||||
// The query may read data affected by those requests.
|
||||
t.flushBatch();
|
||||
|
||||
return queryEngine.findIterate(request);
|
||||
}
|
||||
|
||||
public <T> BeanCollection<T> findMany(OrmQueryRequest<T> request) {
|
||||
|
||||
SpiQuery<T> query = request.getQuery();
|
||||
|
||||
BeanCollection<T> result = null;
|
||||
|
||||
SpiTransaction t = request.getTransaction();
|
||||
|
||||
// before we perform a query, we need to flush any
|
||||
// previous persist requests that are queued/batched.
|
||||
// The query may read data affected by those requests.
|
||||
t.flushBatch();
|
||||
|
||||
BeanFinder<T> finder = request.getBeanFinder();
|
||||
if (finder != null) {
|
||||
// this bean type has its own specific finder
|
||||
result = finder.findMany(request);
|
||||
} else {
|
||||
result = queryEngine.findMany(request);
|
||||
}
|
||||
|
||||
if (query.isLoadBeanCache()){
|
||||
// load the individual beans into the bean cache
|
||||
BeanDescriptor<T> descriptor = request.getBeanDescriptor();
|
||||
Collection<T> c = result.getActualDetails();
|
||||
for (T bean : c) {
|
||||
descriptor.cachePutBeanData(bean);
|
||||
}
|
||||
}
|
||||
|
||||
if (!result.isEmpty() && query.isUseQueryCache()){
|
||||
// load the query result into the query cache
|
||||
request.putToQueryCache(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Find a single bean using its unique id.
|
||||
*/
|
||||
public <T> T findId(OrmQueryRequest<T> request) {
|
||||
|
||||
T result = null;
|
||||
|
||||
SpiTransaction t = request.getTransaction();
|
||||
|
||||
if (t.isBatchFlushOnQuery()){
|
||||
// before we perform a query, we need to flush any
|
||||
// previous persist requests that are queued/batched.
|
||||
// The query may read data affected by those requests.
|
||||
t.flushBatch();
|
||||
}
|
||||
|
||||
BeanFinder<T> finder = request.getBeanFinder();
|
||||
if (finder != null) {
|
||||
result = finder.find(request);
|
||||
} else {
|
||||
result = queryEngine.find(request);
|
||||
}
|
||||
|
||||
if (result != null && request.isUseBeanCache()){
|
||||
request.getBeanDescriptor().cachePutBeanData(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebean.SqlQueryListener;
|
||||
import com.avaje.ebean.SqlRow;
|
||||
import com.avaje.ebean.bean.BeanCollection;
|
||||
import com.avaje.ebean.config.GlobalProperties;
|
||||
import com.avaje.ebeaninternal.api.BindParams;
|
||||
import com.avaje.ebeaninternal.api.SpiSqlQuery;
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
import com.avaje.ebeaninternal.server.core.Message;
|
||||
import com.avaje.ebeaninternal.server.core.RelationalQueryEngine;
|
||||
import com.avaje.ebeaninternal.server.core.RelationalQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.jmx.MAdminLogging;
|
||||
import com.avaje.ebeaninternal.server.persist.Binder;
|
||||
import com.avaje.ebeaninternal.server.type.DataBind;
|
||||
import com.avaje.ebeaninternal.server.util.BindParamsParser;
|
||||
|
||||
/**
|
||||
* Perform native sql fetches.
|
||||
*/
|
||||
public class DefaultRelationalQueryEngine implements RelationalQueryEngine {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(DefaultRelationalQueryEngine.class.getName());
|
||||
|
||||
private final int defaultMaxRows;
|
||||
|
||||
private final Binder binder;
|
||||
|
||||
private final String dbTrueValue;
|
||||
|
||||
public DefaultRelationalQueryEngine(MAdminLogging logControl, Binder binder, String dbTrueValue) {
|
||||
this.binder = binder;
|
||||
this.defaultMaxRows = GlobalProperties.getInt("nativesql.defaultmaxrows",100000);
|
||||
this.dbTrueValue = dbTrueValue == null ? "true" : dbTrueValue;
|
||||
}
|
||||
|
||||
public Object findMany(RelationalQueryRequest request) {
|
||||
|
||||
SpiSqlQuery query = request.getQuery();
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
SpiTransaction t = request.getTransaction();
|
||||
Connection conn = t.getInternalConnection();
|
||||
ResultSet rset = null;
|
||||
PreparedStatement pstmt = null;
|
||||
|
||||
// flag indicating whether we need to close the resources...
|
||||
boolean useBackgroundToContinueFetch = false;
|
||||
|
||||
String sql = query.getQuery();
|
||||
|
||||
BindParams bindParams = query.getBindParams();
|
||||
|
||||
if (!bindParams.isEmpty()) {
|
||||
// convert any named parameters if required
|
||||
sql = BindParamsParser.parse(bindParams, sql);
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
String bindLog = "";
|
||||
String[] propNames = null;
|
||||
|
||||
synchronized (query) {
|
||||
if (query.isCancelled()){
|
||||
logger.finest("Query already cancelled");
|
||||
return null;
|
||||
}
|
||||
|
||||
// synchronise for query.cancel() support
|
||||
pstmt = conn.prepareStatement(sql);
|
||||
|
||||
if (query.getTimeout() > 0){
|
||||
pstmt.setQueryTimeout(query.getTimeout());
|
||||
}
|
||||
if (query.getBufferFetchSizeHint() > 0){
|
||||
pstmt.setFetchSize(query.getBufferFetchSizeHint());
|
||||
}
|
||||
|
||||
if (!bindParams.isEmpty()) {
|
||||
bindLog = binder.bind(bindParams, new DataBind(pstmt));
|
||||
}
|
||||
|
||||
if (request.isLogSql()) {
|
||||
String sOut = sql.replace(Constants.NEW_LINE, ' ');
|
||||
sOut = sOut.replace(Constants.CARRIAGE_RETURN, ' ');
|
||||
t.logInternal(sOut);
|
||||
}
|
||||
|
||||
rset = pstmt.executeQuery();
|
||||
|
||||
propNames = getPropertyNames(rset);
|
||||
}
|
||||
|
||||
// calculate the initialCapacity of the Map to reduce
|
||||
// rehashing for queries with 12+ columns
|
||||
float initCap = (propNames.length) / 0.7f;
|
||||
int estimateCapacity = (int) initCap + 1;
|
||||
|
||||
// determine the maxRows limit
|
||||
int maxRows = defaultMaxRows;
|
||||
if (query.getMaxRows() >= 1) {
|
||||
maxRows = query.getMaxRows();
|
||||
}
|
||||
|
||||
boolean hasHitMaxRows = false;
|
||||
|
||||
int loadRowCount = 0;
|
||||
|
||||
SqlQueryListener listener = query.getListener();
|
||||
|
||||
BeanCollectionWrapper wrapper = new BeanCollectionWrapper(request);
|
||||
boolean isMap = wrapper.isMap();
|
||||
String mapKey = query.getMapKey();
|
||||
|
||||
SqlRow bean = null;
|
||||
|
||||
while (rset.next()) {
|
||||
synchronized (query) {
|
||||
// synchronise for query.cancel() support
|
||||
if (!query.isCancelled()){
|
||||
bean = readRow(request, rset, propNames, estimateCapacity);
|
||||
}
|
||||
}
|
||||
if (bean != null){
|
||||
// bean can be null if query cancelled
|
||||
if (listener != null) {
|
||||
listener.process(bean);
|
||||
|
||||
} else {
|
||||
if (isMap) {
|
||||
Object keyValue = bean.get(mapKey);
|
||||
wrapper.addToMap(bean, keyValue);
|
||||
} else {
|
||||
wrapper.addToCollection(bean);
|
||||
}
|
||||
}
|
||||
|
||||
loadRowCount++;
|
||||
|
||||
if (loadRowCount == maxRows) {
|
||||
// break, as we have hit the max rows to fetch...
|
||||
hasHitMaxRows = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BeanCollection<?> beanColl = wrapper.getBeanCollection();
|
||||
|
||||
if (hasHitMaxRows) {
|
||||
if (rset.next()) {
|
||||
// there are more rows available after the maxRows limit
|
||||
beanColl.setHasMoreRows(true);
|
||||
}
|
||||
}
|
||||
|
||||
if (!useBackgroundToContinueFetch) {
|
||||
beanColl.setFinishedFetch(true);
|
||||
}
|
||||
|
||||
if (request.isLogSummary()) {
|
||||
|
||||
long exeTime = System.currentTimeMillis() - startTime;
|
||||
|
||||
String msg = "SqlQuery rows[" + loadRowCount + "] time[" + exeTime + "] bind["
|
||||
+ bindLog + "] finished[" + beanColl.isFinishedFetch() + "]";
|
||||
|
||||
t.logInternal(msg);
|
||||
}
|
||||
|
||||
if (query.isCancelled()){
|
||||
logger.fine("Query was cancelled during execution rows:"+loadRowCount);
|
||||
}
|
||||
|
||||
return beanColl;
|
||||
|
||||
} catch (Exception e) {
|
||||
String m = Message.msg("fetch.error", e.getMessage(), sql);
|
||||
throw new PersistenceException(m, e);
|
||||
|
||||
} finally {
|
||||
if (!useBackgroundToContinueFetch) {
|
||||
try {
|
||||
if (rset != null) {
|
||||
rset.close();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
try {
|
||||
if (pstmt != null) {
|
||||
pstmt.close();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the list of property names.
|
||||
*/
|
||||
protected String[] getPropertyNames(ResultSet rset) throws SQLException {
|
||||
|
||||
ArrayList<String> propNames = new ArrayList<String>();
|
||||
|
||||
ResultSetMetaData rsmd = rset.getMetaData();
|
||||
|
||||
int columnsPlusOne = rsmd.getColumnCount()+1;
|
||||
|
||||
|
||||
for (int i = 1; i < columnsPlusOne; i++) {
|
||||
String columnName = rsmd.getColumnLabel(i);
|
||||
// will convert columnName to lower case
|
||||
propNames.add(columnName);
|
||||
}
|
||||
|
||||
return (String[]) propNames.toArray(new String[propNames.size()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the row from the ResultSet and return as a MapBean.
|
||||
*/
|
||||
protected SqlRow readRow(RelationalQueryRequest request, ResultSet rset,
|
||||
String[] propNames, int initialCapacity) throws SQLException {
|
||||
|
||||
// by default a map will rehash on the 12th entry
|
||||
// it will be pretty common to have 12 or more entries so
|
||||
// to reduce rehashing I am trying to estimate a good
|
||||
// initial capacity for the MapBean to use.
|
||||
SqlRow bean = new DefaultSqlRow(initialCapacity, 0.75f, dbTrueValue);
|
||||
|
||||
int index = 0;
|
||||
|
||||
for (int i = 0; i < propNames.length; i++) {
|
||||
index++;
|
||||
Object value = rset.getObject(index);
|
||||
bean.set(propNames[i], value);
|
||||
}
|
||||
|
||||
return bean;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Date;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import com.avaje.ebean.SqlQuery;
|
||||
import com.avaje.ebean.SqlRow;
|
||||
import com.avaje.ebeaninternal.server.core.BasicTypeConverter;
|
||||
|
||||
/**
|
||||
* Used to return raw SQL query results.
|
||||
* <p>
|
||||
* Refer to {@link SqlQuery} for examples.
|
||||
* </p>
|
||||
* <p>
|
||||
* There are convenience methods such as getInteger(), getBigDecimal() etc. The
|
||||
* reason for these methods is that the values put into this map often come
|
||||
* straight from the JDBC resultSet. Depending on the JDBC driver it may put a
|
||||
* different type into a given property. For example an Integer, BigDecimal,
|
||||
* Double could all be put into a property depending on the JDBC driver used.
|
||||
* These convenience methods automatically convert the value as required
|
||||
* returning the type you expect.
|
||||
* </p>
|
||||
*/
|
||||
public class DefaultSqlRow implements SqlRow {
|
||||
|
||||
static final long serialVersionUID = -3120927797041336242L;
|
||||
|
||||
private final String dbTrueValue;
|
||||
|
||||
/**
|
||||
* The underlying map of property data.
|
||||
*/
|
||||
Map<String, Object> map;
|
||||
|
||||
/**
|
||||
* Create with a specific Map implementation.
|
||||
* <p>
|
||||
* The default Map implementation is LinkedHashMap.
|
||||
* </p>
|
||||
*/
|
||||
public DefaultSqlRow(Map<String, Object> map, String dbTrueValue) {
|
||||
this.map = map;
|
||||
this.dbTrueValue = dbTrueValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MapBean based on a LinkedHashMap with default
|
||||
* initialCapacity (of 16).
|
||||
*/
|
||||
public DefaultSqlRow(String dbTrueValue) {
|
||||
this.map = new LinkedHashMap<String, Object>();
|
||||
this.dbTrueValue = dbTrueValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create with an initialCapacity and loadFactor.
|
||||
* <p>
|
||||
* The defaults of these are 16 and 0.75.
|
||||
* </p>
|
||||
* <p>
|
||||
* Note that the Map will rehash the contents when the number of keys in
|
||||
* this map reaches its threshold (initialCapacity * loadFactor).
|
||||
* </p>
|
||||
*/
|
||||
public DefaultSqlRow(int initialCapacity, float loadFactor, String dbTrueValue) {
|
||||
this.map = new LinkedHashMap<String, Object>(initialCapacity, loadFactor);
|
||||
this.dbTrueValue = dbTrueValue;
|
||||
}
|
||||
|
||||
public Iterator<String> keys() {
|
||||
return map.keySet().iterator();
|
||||
}
|
||||
|
||||
public Object remove(Object name) {
|
||||
name = ((String) name).toLowerCase();
|
||||
return map.remove(name);
|
||||
}
|
||||
|
||||
public Object get(Object name) {
|
||||
name = ((String) name).toLowerCase();
|
||||
return map.get(name);
|
||||
}
|
||||
|
||||
public Object put(String name, Object value) {
|
||||
return setInternal(name, value);
|
||||
}
|
||||
|
||||
public Object set(String name, Object value) {
|
||||
return setInternal(name, value);
|
||||
}
|
||||
|
||||
private Object setInternal(String name, Object newValue) {
|
||||
// MapBean properties are always lowercase
|
||||
name = name.toLowerCase();
|
||||
|
||||
// valueList = null;
|
||||
return map.put(name, newValue);
|
||||
}
|
||||
|
||||
public UUID getUUID(String name) {
|
||||
Object val = get(name);
|
||||
return BasicTypeConverter.toUUID(val);
|
||||
}
|
||||
|
||||
public Boolean getBoolean(String name) {
|
||||
Object val = get(name);
|
||||
return BasicTypeConverter.toBoolean(val, dbTrueValue);
|
||||
}
|
||||
|
||||
public Integer getInteger(String name) {
|
||||
Object val = get(name);
|
||||
return BasicTypeConverter.toInteger(val);
|
||||
}
|
||||
|
||||
public BigDecimal getBigDecimal(String name) {
|
||||
Object val = get(name);
|
||||
return BasicTypeConverter.toBigDecimal(val);
|
||||
}
|
||||
|
||||
public Long getLong(String name) {
|
||||
Object val = get(name);
|
||||
return BasicTypeConverter.toLong(val);
|
||||
}
|
||||
|
||||
public Double getDouble(String name) {
|
||||
Object val = get(name);
|
||||
return BasicTypeConverter.toDouble(val);
|
||||
}
|
||||
|
||||
public Float getFloat(String name) {
|
||||
Object val = get(name);
|
||||
return BasicTypeConverter.toFloat(val);
|
||||
}
|
||||
|
||||
public String getString(String name) {
|
||||
Object val = get(name);
|
||||
return BasicTypeConverter.toString(val);
|
||||
}
|
||||
|
||||
public java.util.Date getUtilDate(String name) {
|
||||
Object val = get(name);
|
||||
return BasicTypeConverter.toUtilDate(val);
|
||||
}
|
||||
|
||||
public Date getDate(String name) {
|
||||
Object val = get(name);
|
||||
return BasicTypeConverter.toDate(val);
|
||||
}
|
||||
|
||||
public Timestamp getTimestamp(String name) {
|
||||
Object val = get(name);
|
||||
return BasicTypeConverter.toTimestamp(val);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return map.toString();
|
||||
}
|
||||
|
||||
// ------------------------------------
|
||||
// Normal map methods...
|
||||
|
||||
public void clear() {
|
||||
map.clear();
|
||||
}
|
||||
|
||||
public boolean containsKey(Object key) {
|
||||
key = ((String) key).toLowerCase();
|
||||
return map.containsKey(key);
|
||||
}
|
||||
|
||||
public boolean containsValue(Object value) {
|
||||
return map.containsValue(value);
|
||||
}
|
||||
|
||||
public Set<Map.Entry<String, Object>> entrySet() {
|
||||
return map.entrySet();
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return map.isEmpty();
|
||||
}
|
||||
|
||||
public Set<String> keySet() {
|
||||
return map.keySet();
|
||||
}
|
||||
|
||||
public void putAll(Map<? extends String, ? extends Object> t) {
|
||||
map.putAll(t);
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return map.size();
|
||||
}
|
||||
|
||||
public Collection<Object> values() {
|
||||
return map.values();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
import com.avaje.ebean.Page;
|
||||
|
||||
public class LimitOffsetList<T> implements List<T> {
|
||||
|
||||
private final LimitOffsetPagingQuery<T> owner;
|
||||
|
||||
private List<T> localCopy;
|
||||
|
||||
public LimitOffsetList(LimitOffsetPagingQuery<T> owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
private void ensureLocalCopy() {
|
||||
if (localCopy == null){
|
||||
localCopy = new ArrayList<T>();
|
||||
|
||||
int pgIndex = 0;
|
||||
while(true){
|
||||
Page<T> page = owner.getPage(pgIndex++);
|
||||
List<T> list = page.getList();
|
||||
localCopy.addAll(list);
|
||||
if (!page.hasNext()){
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasNext(int position){
|
||||
return owner.hasNext(position);
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
localCopy = new ArrayList<T>();
|
||||
}
|
||||
|
||||
public T get(int index) {
|
||||
if (localCopy != null){
|
||||
return localCopy.get(index);
|
||||
} else {
|
||||
return owner.get(index);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
if (localCopy != null){
|
||||
return localCopy.isEmpty();
|
||||
} else {
|
||||
return owner.getTotalRowCount() == 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int size() {
|
||||
if (localCopy != null){
|
||||
return localCopy.size();
|
||||
} else {
|
||||
return owner.getTotalRowCount();
|
||||
}
|
||||
}
|
||||
|
||||
public Iterator<T> iterator() {
|
||||
if (localCopy != null){
|
||||
return localCopy.iterator();
|
||||
} else {
|
||||
return new ListItr(this, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public ListIterator<T> listIterator() {
|
||||
if (localCopy != null){
|
||||
return localCopy.listIterator();
|
||||
} else {
|
||||
return new ListItr(this, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public ListIterator<T> listIterator(int index) {
|
||||
if (localCopy != null){
|
||||
return localCopy.listIterator(index);
|
||||
} else {
|
||||
return new ListItr(this, index);
|
||||
}
|
||||
}
|
||||
|
||||
public List<T> subList(int fromIndex, int toIndex) {
|
||||
if (localCopy != null){
|
||||
return localCopy.subList(fromIndex, toIndex);
|
||||
} else {
|
||||
//FIXME: subList not implemented ...
|
||||
throw new RuntimeException("Not implemented at this point");
|
||||
}
|
||||
}
|
||||
|
||||
public int lastIndexOf(Object o) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.lastIndexOf(o);
|
||||
}
|
||||
|
||||
public void add(int index, T element) {
|
||||
ensureLocalCopy();
|
||||
localCopy.add(index, element);
|
||||
}
|
||||
|
||||
public boolean add(T o) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.add(o);
|
||||
}
|
||||
|
||||
public boolean addAll(Collection<? extends T> c) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.addAll(c);
|
||||
}
|
||||
|
||||
public boolean addAll(int index, Collection<? extends T> c) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.addAll(index, c);
|
||||
}
|
||||
|
||||
public boolean contains(Object o) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.contains(o);
|
||||
}
|
||||
|
||||
public boolean containsAll(Collection<?> c) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.containsAll(c);
|
||||
}
|
||||
|
||||
public int indexOf(Object o) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.indexOf(o);
|
||||
}
|
||||
|
||||
public T remove(int index) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.remove(index);
|
||||
}
|
||||
|
||||
public boolean remove(Object o) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.remove(o);
|
||||
}
|
||||
|
||||
public boolean removeAll(Collection<?> c) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.removeAll(c);
|
||||
}
|
||||
|
||||
public boolean retainAll(Collection<?> c) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.retainAll(c);
|
||||
}
|
||||
|
||||
public T set(int index, T element) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.set(index, element);
|
||||
}
|
||||
|
||||
|
||||
public Object[] toArray() {
|
||||
ensureLocalCopy();
|
||||
return localCopy.toArray();
|
||||
}
|
||||
|
||||
public <K> K[] toArray(K[] a) {
|
||||
ensureLocalCopy();
|
||||
return localCopy.toArray(a);
|
||||
}
|
||||
|
||||
private class ListItr implements ListIterator<T> {
|
||||
|
||||
private LimitOffsetList<T> ownerList;
|
||||
private int position;
|
||||
|
||||
ListItr(LimitOffsetList<T> ownerList, int position) {
|
||||
this.ownerList = ownerList;
|
||||
this.position = position;
|
||||
}
|
||||
|
||||
public void add(T o) {
|
||||
ownerList.add(position++, o);
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
return ownerList.hasNext(position);
|
||||
}
|
||||
|
||||
public boolean hasPrevious() {
|
||||
return position > 0;
|
||||
}
|
||||
|
||||
public T next() {
|
||||
return ownerList.get(position++);
|
||||
}
|
||||
|
||||
public int nextIndex() {
|
||||
return position;
|
||||
}
|
||||
|
||||
public T previous() {
|
||||
return get(--position);
|
||||
}
|
||||
|
||||
public int previousIndex() {
|
||||
return position - 1;
|
||||
}
|
||||
|
||||
public void remove() {
|
||||
throw new RuntimeException("Not supported yet");
|
||||
}
|
||||
|
||||
public void set(T o) {
|
||||
throw new RuntimeException("Not supported yet");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebean.FutureList;
|
||||
import com.avaje.ebean.Page;
|
||||
import com.avaje.ebean.bean.BeanCollection;
|
||||
import com.avaje.ebean.bean.BeanCollectionTouched;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
|
||||
/**
|
||||
* Page implementation based on limit offset types of queries.
|
||||
*
|
||||
* @author rbygrave
|
||||
*
|
||||
* @param <T>
|
||||
* the entity bean type
|
||||
*/
|
||||
public class LimitOffsetPage<T> implements Page<T>, BeanCollectionTouched {
|
||||
|
||||
private final int pageIndex;
|
||||
|
||||
private final LimitOffsetPagingQuery<T> owner;
|
||||
|
||||
private FutureList<T> futureList;
|
||||
|
||||
public LimitOffsetPage(int pageIndex, LimitOffsetPagingQuery<T> owner) {
|
||||
this.pageIndex = pageIndex;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
public FutureList<T> getFutureList() {
|
||||
|
||||
if (futureList == null) {
|
||||
SpiQuery<T> originalQuery = owner.getSpiQuery();
|
||||
SpiQuery<T> copy = originalQuery.copy();
|
||||
copy.setPersistenceContext(originalQuery.getPersistenceContext());
|
||||
|
||||
int pageSize = owner.getPageSize();
|
||||
copy.setFirstRow(pageIndex * pageSize);
|
||||
copy.setMaxRows(pageSize);
|
||||
copy.setBeanCollectionTouched(this);
|
||||
futureList = owner.getServer().findFutureList(copy, null);
|
||||
}
|
||||
|
||||
return futureList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform fetch ahead when the list is first accessed.
|
||||
*/
|
||||
public void notifyTouched(BeanCollection<?> c) {
|
||||
if (c.hasMoreRows()) {
|
||||
owner.fetchAheadIfRequired(pageIndex);
|
||||
}
|
||||
}
|
||||
|
||||
public List<T> getList() {
|
||||
try {
|
||||
return getFutureList().get();
|
||||
} catch (Exception e) {
|
||||
throw new PersistenceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public boolean hasNext() {
|
||||
return ((BeanCollection<T>) getList()).hasMoreRows();
|
||||
}
|
||||
|
||||
public boolean hasPrev() {
|
||||
return pageIndex > 0;
|
||||
}
|
||||
|
||||
public Page<T> next() {
|
||||
return owner.getPage(pageIndex + 1);
|
||||
}
|
||||
|
||||
public Page<T> prev() {
|
||||
return owner.getPage(pageIndex - 1);
|
||||
}
|
||||
|
||||
public int getPageIndex() {
|
||||
return pageIndex;
|
||||
}
|
||||
|
||||
public int getTotalPageCount() {
|
||||
return owner.getTotalPageCount();
|
||||
}
|
||||
|
||||
public int getTotalRowCount() {
|
||||
return owner.getTotalRowCount();
|
||||
}
|
||||
|
||||
public String getDisplayXtoYofZ(String to, String of) {
|
||||
|
||||
int first = pageIndex * owner.getPageSize() + 1;
|
||||
int last = first + getList().size() - 1;
|
||||
int total = getTotalRowCount();
|
||||
|
||||
return first+to+last+of+total;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebean.EbeanServer;
|
||||
import com.avaje.ebean.Page;
|
||||
import com.avaje.ebean.PagingList;
|
||||
import com.avaje.ebeaninternal.api.Monitor;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
|
||||
public class LimitOffsetPagingQuery<T> implements PagingList<T> {
|
||||
|
||||
private transient EbeanServer server;
|
||||
|
||||
private final SpiQuery<T> query;
|
||||
|
||||
private final List<LimitOffsetPage<T>> pages = new ArrayList<LimitOffsetPage<T>>();
|
||||
|
||||
private final Monitor monitor = new Monitor();
|
||||
|
||||
private final int pageSize;
|
||||
|
||||
private boolean fetchAhead = true;
|
||||
|
||||
private Future<Integer> futureRowCount;
|
||||
|
||||
public LimitOffsetPagingQuery(EbeanServer server, SpiQuery<T> query, int pageSize) {
|
||||
this.query = query;
|
||||
this.pageSize = pageSize;
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
public EbeanServer getServer() {
|
||||
return server;
|
||||
}
|
||||
|
||||
public void setServer(EbeanServer server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
public SpiQuery<T> getSpiQuery() {
|
||||
return query;
|
||||
}
|
||||
|
||||
public PagingList<T> setFetchAhead(boolean fetchAhead) {
|
||||
this.fetchAhead = fetchAhead;
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<T> getAsList() {
|
||||
return new LimitOffsetList<T>(this);
|
||||
}
|
||||
|
||||
public Future<Integer> getFutureRowCount() {
|
||||
synchronized (monitor) {
|
||||
if (futureRowCount == null){
|
||||
futureRowCount = server.findFutureRowCount(query, null);
|
||||
}
|
||||
return futureRowCount;
|
||||
}
|
||||
}
|
||||
|
||||
private LimitOffsetPage<T> internalGetPage(int i){
|
||||
synchronized (monitor) {
|
||||
int ps = pages.size();
|
||||
if (ps <= i){
|
||||
for (int j = ps; j <= i; j++) {
|
||||
LimitOffsetPage<T> p = new LimitOffsetPage<T>(j, this);
|
||||
pages.add(p);
|
||||
}
|
||||
}
|
||||
return pages.get(i);
|
||||
}
|
||||
}
|
||||
|
||||
protected void fetchAheadIfRequired(int pageIndex){
|
||||
synchronized (monitor) {
|
||||
// Already checked in LimitOffsetPage that there is another page
|
||||
if (fetchAhead){
|
||||
// fetchAhead is turned on so get the next page and trigger query
|
||||
LimitOffsetPage<T> nextPage = internalGetPage(pageIndex + 1);
|
||||
nextPage.getFutureList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void refresh() {
|
||||
synchronized (monitor) {
|
||||
futureRowCount = null;
|
||||
pages.clear();
|
||||
}
|
||||
}
|
||||
|
||||
public Page<T> getPage(int i) {
|
||||
return internalGetPage(i);
|
||||
}
|
||||
|
||||
protected boolean hasNext(int position){
|
||||
return position < getTotalRowCount();
|
||||
}
|
||||
|
||||
protected T get(int rowIndex){
|
||||
int pg = rowIndex / pageSize;
|
||||
int offset = rowIndex % pageSize;
|
||||
|
||||
Page<T> page = getPage(pg);
|
||||
return page.getList().get(offset);
|
||||
}
|
||||
|
||||
public int getTotalPageCount() {
|
||||
|
||||
int rowCount = getTotalRowCount();
|
||||
if (rowCount == 0){
|
||||
return 0;
|
||||
} else {
|
||||
return ((rowCount-1) / pageSize) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPageSize() {
|
||||
return pageSize;
|
||||
}
|
||||
|
||||
public int getTotalRowCount() {
|
||||
try {
|
||||
return getFutureRowCount().get();
|
||||
} catch (Exception e) {
|
||||
throw new PersistenceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
|
||||
public class LoadedPropertiesCache {
|
||||
|
||||
static ConcurrentHashMap<Integer, Set<String>> cache = new ConcurrentHashMap<Integer, Set<String>>(250, 0.75f, 16);
|
||||
|
||||
public static Set<String> get(int partialHash, Set<String> partialProps, BeanDescriptor<?> desc){
|
||||
|
||||
int manyHash = desc.getNamesOfManyPropsHash();
|
||||
int totalHash = 37*partialHash + manyHash;
|
||||
|
||||
Integer key = Integer.valueOf(totalHash);
|
||||
|
||||
Set<String> includedProps = cache.get(key);
|
||||
|
||||
if (includedProps == null){
|
||||
// its not in the cache so build it
|
||||
LinkedHashSet<String> mergeNames = new LinkedHashSet<String>();
|
||||
mergeNames.addAll(partialProps);
|
||||
if (manyHash != 0){
|
||||
mergeNames.addAll(desc.getNamesOfManyProps());
|
||||
}
|
||||
|
||||
// we want it to be immutable and cache it
|
||||
includedProps = Collections.unmodifiableSet(mergeNames);
|
||||
cache.put(key, includedProps);
|
||||
}
|
||||
|
||||
return includedProps;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.FutureTask;
|
||||
|
||||
import com.avaje.ebean.FutureIds;
|
||||
import com.avaje.ebean.Query;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
|
||||
/**
|
||||
* Default implementation of FutureIds.
|
||||
*/
|
||||
public class QueryFutureIds<T> extends BaseFuture<List<Object>> implements FutureIds<T> {
|
||||
|
||||
private final SpiQuery<T> query;
|
||||
|
||||
public QueryFutureIds(SpiQuery<T> query, FutureTask<List<Object>> futureTask) {
|
||||
super(futureTask);
|
||||
this.query = query;
|
||||
}
|
||||
|
||||
public Query<T> getQuery() {
|
||||
return query;
|
||||
}
|
||||
|
||||
public List<Object> getPartialIds() {
|
||||
return query.getIdList();
|
||||
}
|
||||
|
||||
public boolean cancel(boolean mayInterruptIfRunning) {
|
||||
query.cancel();
|
||||
return super.cancel(mayInterruptIfRunning);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.FutureTask;
|
||||
|
||||
import com.avaje.ebean.FutureList;
|
||||
import com.avaje.ebean.Query;
|
||||
|
||||
/**
|
||||
* Default implementation for FutureList.
|
||||
*/
|
||||
public class QueryFutureList<T> extends BaseFuture<List<T>> implements FutureList<T> {
|
||||
|
||||
private final Query<T> query;
|
||||
|
||||
|
||||
public QueryFutureList(Query<T> query, FutureTask<List<T>> futureTask) {
|
||||
super(futureTask);
|
||||
this.query = query;
|
||||
}
|
||||
|
||||
public Query<T> getQuery() {
|
||||
return query;
|
||||
}
|
||||
|
||||
public boolean cancel(boolean mayInterruptIfRunning) {
|
||||
query.cancel();
|
||||
return super.cancel(mayInterruptIfRunning);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.concurrent.FutureTask;
|
||||
|
||||
import com.avaje.ebean.FutureRowCount;
|
||||
import com.avaje.ebean.Query;
|
||||
|
||||
/**
|
||||
* Future implementation for the row count query.
|
||||
*/
|
||||
public class QueryFutureRowCount<T> extends BaseFuture<Integer> implements FutureRowCount<T> {
|
||||
|
||||
private final Query<T> query;
|
||||
|
||||
public QueryFutureRowCount(Query<T> query, FutureTask<Integer> futureTask) {
|
||||
super(futureTask);
|
||||
this.query = query;
|
||||
}
|
||||
|
||||
public Query<T> getQuery() {
|
||||
return query;
|
||||
}
|
||||
|
||||
public boolean cancel(boolean mayInterruptIfRunning) {
|
||||
query.cancel();
|
||||
return super.cancel(mayInterruptIfRunning);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
|
||||
import com.avaje.ebean.config.dbplatform.SqlLimitResponse;
|
||||
import com.avaje.ebean.config.dbplatform.SqlLimiter;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.DRawSqlSelect;
|
||||
import com.avaje.ebeaninternal.server.deploy.DeployNamedQuery;
|
||||
import com.avaje.ebeaninternal.server.deploy.DeployParser;
|
||||
import com.avaje.ebeaninternal.server.persist.Binder;
|
||||
import com.avaje.ebeaninternal.server.querydefn.OrmQueryLimitRequest;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Factory for SqlSelectClause based on raw sql.
|
||||
* <p>
|
||||
* Its job is to execute the sql, read the meta data to determine the columns to
|
||||
* bean property mapping.
|
||||
* </p>
|
||||
*/
|
||||
public class RawSqlSelectClauseBuilder {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(RawSqlSelectClauseBuilder.class.getName());
|
||||
|
||||
private final Binder binder;
|
||||
|
||||
private final SqlLimiter dbQueryLimiter;
|
||||
private final DatabasePlatform dbPlatform;
|
||||
|
||||
public RawSqlSelectClauseBuilder(DatabasePlatform dbPlatform, Binder binder) {
|
||||
|
||||
this.binder = binder;
|
||||
this.dbQueryLimiter = dbPlatform.getSqlLimiter();
|
||||
this.dbPlatform = dbPlatform;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build based on the includes and using the BeanJoinTree.
|
||||
*/
|
||||
public <T> CQuery<T> build(OrmQueryRequest<T> request) throws PersistenceException {
|
||||
|
||||
SpiQuery<T> query = request.getQuery();
|
||||
BeanDescriptor<T> desc = request.getBeanDescriptor();
|
||||
|
||||
DeployNamedQuery namedQuery = desc.getNamedQuery(query.getName());
|
||||
DRawSqlSelect sqlSelect = namedQuery.getSqlSelect();
|
||||
|
||||
// create a parser for this specific SqlSelect... has to be really
|
||||
// as each SqlSelect could have different table alias etc
|
||||
DeployParser parser = sqlSelect.createDeployPropertyParser();
|
||||
|
||||
CQueryPredicates predicates = new CQueryPredicates(binder, request);
|
||||
// prepare and convert logical property names to dbColumns etc
|
||||
predicates.prepareRawSql(parser);
|
||||
|
||||
SqlTreeAlias alias = new SqlTreeAlias(sqlSelect.getTableAlias());
|
||||
predicates.parseTableAlias(alias);
|
||||
|
||||
String sql = null;
|
||||
try {
|
||||
|
||||
boolean includeRowNumColumn = false;
|
||||
String orderBy = sqlSelect.getOrderBy(predicates);
|
||||
|
||||
// build the actual sql String
|
||||
sql = sqlSelect.buildSql(orderBy, predicates, request);
|
||||
if (query.hasMaxRowsOrFirstRow() && dbQueryLimiter != null) {
|
||||
// wrap with a limit offset or ROW_NUMBER() etc
|
||||
SqlLimitResponse limitSql = dbQueryLimiter.limit(new OrmQueryLimitRequest(sql, orderBy, query, dbPlatform));
|
||||
includeRowNumColumn = limitSql.isIncludesRowNumberColumn();
|
||||
|
||||
sql = limitSql.getSql();
|
||||
} else {
|
||||
// add back select keyword
|
||||
// ... was removed to support dbQueryLimiter
|
||||
sql = "select " + sql;
|
||||
}
|
||||
|
||||
SqlTree sqlTree = sqlSelect.getSqlTree();
|
||||
|
||||
CQueryPlan queryPlan = new CQueryPlan(sql, sqlTree, true, includeRowNumColumn, "");
|
||||
CQuery<T> compiledQuery = new CQuery<T>(request, predicates, queryPlan);
|
||||
|
||||
return compiledQuery;
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
String msg = "Error with " + desc.getFullName() + " query:\r" + sql;
|
||||
logger.log(Level.SEVERE, msg);
|
||||
throw new PersistenceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
public class SplitName {
|
||||
|
||||
public static String add(String prefix, String name){
|
||||
if (prefix != null){
|
||||
return prefix+"."+name;
|
||||
} else {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the number of occurrences of char in name.
|
||||
*/
|
||||
public static int count(char c, String name){
|
||||
|
||||
int count = 0;
|
||||
for (int i = 0; i < name.length(); i++) {
|
||||
if (c == name.charAt(i)){
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the parent part of the path.
|
||||
*/
|
||||
public static String parent(String name) {
|
||||
if (name == null){
|
||||
return null;
|
||||
} else {
|
||||
String[] s = split(name, true);
|
||||
return s[0];
|
||||
}
|
||||
}
|
||||
|
||||
public static String[] split(String name){
|
||||
return split(name, true);
|
||||
}
|
||||
|
||||
public static String[] splitBegin(String name){
|
||||
return split(name, false);
|
||||
}
|
||||
|
||||
private static String[] split(String name, boolean last){
|
||||
|
||||
int pos = last ? name.lastIndexOf('.') : name.indexOf('.');
|
||||
if (pos == -1){
|
||||
if (last){
|
||||
return new String[]{null, name};
|
||||
} else {
|
||||
return new String[]{name, null};
|
||||
}
|
||||
} else {
|
||||
String s0 = name.substring(0, pos);
|
||||
String s1 = name.substring(pos+1);
|
||||
return new String[]{s0,s1};
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
import com.avaje.ebean.bean.EntityBeanIntercept;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery.Mode;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
|
||||
|
||||
/**
|
||||
* Controls the loading of property data into a bean.
|
||||
* <p>
|
||||
* Takes into account the differences of lazy loading and
|
||||
* partial objects.
|
||||
* </p>
|
||||
*/
|
||||
public class SqlBeanLoad {
|
||||
|
||||
private final DbReadContext ctx;
|
||||
private final Object bean;
|
||||
private final Class<?> type;
|
||||
private final Object originalOldValues;
|
||||
private final boolean isLazyLoad;
|
||||
|
||||
// set of properties to exclude from the refresh because it is
|
||||
// not a refresh but rather a lazyLoading event.
|
||||
private final Set<String> excludes;
|
||||
private final boolean setOriginalOldValues;
|
||||
|
||||
private final boolean rawSql;
|
||||
|
||||
public SqlBeanLoad(DbReadContext ctx, Class<?> type, Object bean, Mode queryMode) {
|
||||
|
||||
this.ctx = ctx;
|
||||
this.rawSql = ctx.isRawSql();
|
||||
this.type = type;
|
||||
this.isLazyLoad = queryMode.equals(Mode.LAZYLOAD_BEAN);
|
||||
this.bean = bean;
|
||||
|
||||
if (bean instanceof EntityBean) {
|
||||
EntityBeanIntercept ebi = ((EntityBean) bean)._ebean_getIntercept();
|
||||
|
||||
this.excludes = isLazyLoad ? ebi.getLoadedProps() : null;
|
||||
if (excludes != null) {
|
||||
// lazy loading a "Partial Object"... which already
|
||||
// contains some properties and perhaps some oldValues
|
||||
// and these will need to be maintained...
|
||||
originalOldValues = ebi.getOldValues();
|
||||
} else {
|
||||
originalOldValues = null;
|
||||
}
|
||||
this.setOriginalOldValues = originalOldValues != null;
|
||||
} else {
|
||||
this.excludes = null;
|
||||
this.originalOldValues = null;
|
||||
this.setOriginalOldValues = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this is a lazy loading.
|
||||
*/
|
||||
public boolean isLazyLoad() {
|
||||
return isLazyLoad;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment the resultSet index 1.
|
||||
*/
|
||||
public void loadIgnore(int increment) {
|
||||
ctx.getDataReader().incrementPos(increment);
|
||||
}
|
||||
|
||||
public Object load(BeanProperty prop) throws SQLException {
|
||||
|
||||
if (!rawSql && prop.isTransient()){
|
||||
return null;
|
||||
}
|
||||
|
||||
if ((bean == null)
|
||||
|| (excludes != null && excludes.contains(prop.getName()))
|
||||
|| (type != null && !prop.isAssignableFrom(type))){
|
||||
|
||||
// ignore this property
|
||||
// ... null: bean already in persistence context
|
||||
// ... excludes: partial bean that is lazy loading
|
||||
// ... type: inheritance and not assignable to this instance
|
||||
|
||||
prop.loadIgnore(ctx);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
Object dbVal = prop.read(ctx);
|
||||
if (isLazyLoad){
|
||||
prop.setValue(bean, dbVal);
|
||||
} else {
|
||||
prop.setValueIntercept(bean, dbVal);
|
||||
}
|
||||
if (setOriginalOldValues){
|
||||
// maintain original oldValues for partially loaded bean
|
||||
prop.setValue(originalOldValues, dbVal);
|
||||
}
|
||||
return dbVal;
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = "Error loading on " + prop.getFullBeanName();
|
||||
throw new PersistenceException(msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
public void loadAssocMany(BeanPropertyAssocMany<?> prop) {
|
||||
|
||||
// do nothing, as a lazy loading BeanCollection 'reference'
|
||||
// is created and registered with the loading context
|
||||
// in SqlTreeNodeBean.createListProxies()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.FutureTask;
|
||||
|
||||
import com.avaje.ebean.SqlFutureList;
|
||||
import com.avaje.ebean.SqlQuery;
|
||||
import com.avaje.ebean.SqlRow;
|
||||
|
||||
/**
|
||||
* Default implementation of SqlFutureList.
|
||||
*
|
||||
* @author rbygrave
|
||||
*/
|
||||
public class SqlQueryFutureList extends BaseFuture<List<SqlRow>> implements SqlFutureList {
|
||||
|
||||
private final SqlQuery query;
|
||||
|
||||
public SqlQueryFutureList(SqlQuery query, FutureTask<List<SqlRow>> futureTask) {
|
||||
super(futureTask);
|
||||
this.query = query;
|
||||
}
|
||||
|
||||
public SqlQuery getQuery() {
|
||||
return query;
|
||||
}
|
||||
|
||||
public boolean cancel(boolean mayInterruptIfRunning) {
|
||||
query.cancel();
|
||||
return super.cancel(mayInterruptIfRunning);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
|
||||
|
||||
/**
|
||||
* Represents the SELECT clause part of the SQL query.
|
||||
*/
|
||||
public class SqlTree {
|
||||
|
||||
private SqlTreeNode rootNode;
|
||||
|
||||
|
||||
/**
|
||||
* Property if resultSet contains master and detail rows.
|
||||
*/
|
||||
private BeanPropertyAssocMany<?> manyProperty;
|
||||
private String manyPropertyName;
|
||||
private ElPropertyValue manyPropEl;
|
||||
|
||||
private Set<String> includes;
|
||||
|
||||
/**
|
||||
* Summary of the select being generated.
|
||||
*/
|
||||
private String summary;
|
||||
|
||||
private String selectSql;
|
||||
|
||||
private String fromSql;
|
||||
|
||||
/**
|
||||
* Encrypted Properties require additional binding.
|
||||
*/
|
||||
private BeanProperty[] encryptedProps;
|
||||
|
||||
/**
|
||||
* Where clause for inheritance.
|
||||
*/
|
||||
private String inheritanceWhereSql;
|
||||
|
||||
|
||||
/**
|
||||
* Create the SqlSelectClause.
|
||||
*/
|
||||
public SqlTree() {
|
||||
}
|
||||
|
||||
public List<String> buildSelectExpressionChain() {
|
||||
ArrayList<String> list = new ArrayList<String>();
|
||||
rootNode.buildSelectExpressionChain(list);
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the includes. Associated beans lists etc.
|
||||
*/
|
||||
public Set<String> getIncludes() {
|
||||
return includes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the association includes (Ones and Many's).
|
||||
*/
|
||||
public void setIncludes(Set<String> includes) {
|
||||
this.includes = includes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the manyProperty used for this query.
|
||||
*/
|
||||
public void setManyProperty(BeanPropertyAssocMany<?> manyProperty, String manyPropertyName, ElPropertyValue manyPropEl) {
|
||||
this.manyProperty = manyProperty;
|
||||
this.manyPropertyName = manyPropertyName;
|
||||
this.manyPropEl = manyPropEl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the String for the actual SQL.
|
||||
*/
|
||||
public String getSelectSql() {
|
||||
return selectSql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the select sql clause.
|
||||
*/
|
||||
public void setSelectSql(String selectSql) {
|
||||
this.selectSql = selectSql;
|
||||
}
|
||||
|
||||
|
||||
public String getFromSql() {
|
||||
return fromSql;
|
||||
}
|
||||
|
||||
public void setFromSql(String fromSql) {
|
||||
this.fromSql = fromSql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the where clause for inheritance.
|
||||
*/
|
||||
public String getInheritanceWhereSql() {
|
||||
return inheritanceWhereSql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set where clause(s) for inheritance.
|
||||
*/
|
||||
public void setInheritanceWhereSql(String whereSql) {
|
||||
this.inheritanceWhereSql = whereSql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the summary description of the query.
|
||||
*/
|
||||
public void setSummary(String summary) {
|
||||
this.summary = summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a summary of the select clause.
|
||||
*/
|
||||
public String getSummary() {
|
||||
return summary;
|
||||
}
|
||||
|
||||
public SqlTreeNode getRootNode() {
|
||||
return rootNode;
|
||||
}
|
||||
|
||||
public void setRootNode(SqlTreeNode rootNode) {
|
||||
this.rootNode = rootNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the property that is associated with the many. There can only be
|
||||
* one per SqlSelect. This can be null.
|
||||
*/
|
||||
public BeanPropertyAssocMany<?> getManyProperty() {
|
||||
return manyProperty;
|
||||
}
|
||||
|
||||
public String getManyPropertyName() {
|
||||
return manyPropertyName;
|
||||
}
|
||||
|
||||
public ElPropertyValue getManyPropertyEl() {
|
||||
return manyPropEl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this query includes a Many association.
|
||||
*/
|
||||
public boolean isManyIncluded() {
|
||||
return (manyProperty != null);
|
||||
}
|
||||
|
||||
public BeanProperty[] getEncryptedProps() {
|
||||
return encryptedProps;
|
||||
}
|
||||
|
||||
public void setEncryptedProps(BeanProperty[] encryptedProps) {
|
||||
this.encryptedProps = encryptedProps;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.el.ElPropertyDeploy;
|
||||
|
||||
/**
|
||||
* Special Map of the logical property joins to table alias.
|
||||
*
|
||||
* @author rbygrave
|
||||
*/
|
||||
public class SqlTreeAlias {
|
||||
|
||||
private int counter;
|
||||
|
||||
private int manyWhereCounter;
|
||||
|
||||
private TreeSet<String> joinProps = new TreeSet<String>();
|
||||
|
||||
private HashSet<String> embeddedPropertyJoins;
|
||||
|
||||
private TreeSet<String> manyWhereJoinProps = new TreeSet<String>();
|
||||
|
||||
private HashMap<String,String> aliasMap = new HashMap<String,String>();
|
||||
|
||||
private HashMap<String, String> manyWhereAliasMap = new HashMap<String, String>();
|
||||
|
||||
private final String rootTableAlias;
|
||||
|
||||
public SqlTreeAlias(String rootTableAlias) {
|
||||
this.rootTableAlias = rootTableAlias;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add joins to support where predicates
|
||||
* @param manyWhereJoins
|
||||
*/
|
||||
public void addManyWhereJoins(Set<String> manyWhereJoins) {
|
||||
if (manyWhereJoins != null){
|
||||
for (String include : manyWhereJoins) {
|
||||
addPropertyJoin(include, manyWhereJoinProps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void addEmbeddedPropertyJoin(String embProp){
|
||||
if (embeddedPropertyJoins == null){
|
||||
embeddedPropertyJoins = new HashSet<String>();
|
||||
}
|
||||
embeddedPropertyJoins.add(embProp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add joins.
|
||||
*/
|
||||
public void addJoin(Set<String> propJoins, BeanDescriptor<?> desc) {
|
||||
if (propJoins != null){
|
||||
for (String propJoin : propJoins) {
|
||||
ElPropertyDeploy elProp = desc.getElPropertyDeploy(propJoin);
|
||||
if (elProp != null && elProp.getBeanProperty().isEmbedded()) {
|
||||
String[] split = SplitName.split(propJoin);
|
||||
addPropertyJoin(split[0], joinProps);
|
||||
addEmbeddedPropertyJoin(propJoin);
|
||||
|
||||
} else {
|
||||
addPropertyJoin(propJoin, joinProps);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void addPropertyJoin(String include, TreeSet<String> set){
|
||||
if (set.add(include)) {
|
||||
String[] split = SplitName.split(include);
|
||||
if (split[0] != null){
|
||||
addPropertyJoin(split[0], set);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a set of table alias for the given bean and fetch
|
||||
* joined properties.
|
||||
*/
|
||||
public void buildAlias() {
|
||||
|
||||
Iterator<String> i = joinProps.iterator();
|
||||
while (i.hasNext()) {
|
||||
calcAlias(i.next());
|
||||
}
|
||||
|
||||
i = manyWhereJoinProps.iterator();
|
||||
while (i.hasNext()) {
|
||||
calcAliasManyWhere(i.next());
|
||||
}
|
||||
|
||||
mapEmbeddedPropertyAlias();
|
||||
}
|
||||
|
||||
private void mapEmbeddedPropertyAlias() {
|
||||
if (embeddedPropertyJoins != null){
|
||||
for (String propJoin : embeddedPropertyJoins) {
|
||||
String[] split = SplitName.split(propJoin);
|
||||
// the table alias of the parent path
|
||||
String alias = getTableAlias(split[0]);
|
||||
aliasMap.put(propJoin, alias);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String calcAlias(String prefix) {
|
||||
|
||||
String alias = nextTableAlias();
|
||||
aliasMap.put(prefix, alias);
|
||||
return alias;
|
||||
}
|
||||
|
||||
private String calcAliasManyWhere(String prefix) {
|
||||
|
||||
String alias = nextManyWhereTableAlias();
|
||||
manyWhereAliasMap.put(prefix, alias);
|
||||
return alias;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the table alias for a given property name.
|
||||
*/
|
||||
public String getTableAlias(String prefix){
|
||||
if (prefix == null){
|
||||
return rootTableAlias;
|
||||
} else {
|
||||
String s = aliasMap.get(prefix);
|
||||
if (s == null){
|
||||
return calcAlias(prefix);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an alias using "Many where joins".
|
||||
*/
|
||||
public String getTableAliasManyWhere(String prefix) {
|
||||
if (prefix == null){
|
||||
return rootTableAlias;
|
||||
}
|
||||
String s = manyWhereAliasMap.get(prefix);
|
||||
if (s == null){
|
||||
s = aliasMap.get(prefix);
|
||||
}
|
||||
if (s == null) {
|
||||
String msg = "Could not determine table alias for [" + prefix + "] manyMap["
|
||||
+ manyWhereAliasMap + "] aliasMap[" + aliasMap + "]";
|
||||
throw new RuntimeException(msg);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse for where clauses that uses "Many where joins"
|
||||
*/
|
||||
public String parseWhere(String clause) {
|
||||
clause = parseRootAlias(clause);
|
||||
clause = parseAliasMap(clause, manyWhereAliasMap);
|
||||
return parseAliasMap(clause, aliasMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse without using any extra "Many where joins".
|
||||
*/
|
||||
public String parse(String clause) {
|
||||
clause = parseRootAlias(clause);
|
||||
return parseAliasMap(clause, aliasMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the clause replacing the table alias place holders.
|
||||
*/
|
||||
private String parseRootAlias(String clause) {
|
||||
|
||||
if (rootTableAlias == null){
|
||||
return clause.replace("${}", "");
|
||||
} else {
|
||||
return clause.replace("${}", rootTableAlias+".");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the clause replacing the table alias place holders.
|
||||
*/
|
||||
private String parseAliasMap(String clause, HashMap<String,String> parseAliasMap) {
|
||||
|
||||
Iterator<Entry<String, String>> i = parseAliasMap.entrySet().iterator();
|
||||
while (i.hasNext()) {
|
||||
Map.Entry<String,String> e = i.next();
|
||||
String k = "${"+e.getKey()+"}";
|
||||
clause = clause.replace(k, e.getValue()+".");
|
||||
}
|
||||
|
||||
return clause;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Return the next valid table alias given the preferred table alias.
|
||||
*/
|
||||
private String nextTableAlias() {
|
||||
return "t"+(++counter);
|
||||
}
|
||||
|
||||
private String nextManyWhereTableAlias() {
|
||||
return "u"+(++manyWhereCounter);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,683 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.avaje.ebeaninternal.api.ManyWhereJoins;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery.Type;
|
||||
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssoc;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
import com.avaje.ebeaninternal.server.deploy.InheritInfo;
|
||||
import com.avaje.ebeaninternal.server.deploy.TableJoin;
|
||||
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
|
||||
import com.avaje.ebeaninternal.server.querydefn.OrmQueryDetail;
|
||||
import com.avaje.ebeaninternal.server.querydefn.OrmQueryProperties;
|
||||
|
||||
/**
|
||||
* Factory for SqlTree.
|
||||
*/
|
||||
public class SqlTreeBuilder {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(SqlTreeBuilder.class.getName());
|
||||
|
||||
private final SpiQuery<?> query;
|
||||
|
||||
private final BeanDescriptor<?> desc;
|
||||
|
||||
private final OrmQueryDetail queryDetail;
|
||||
|
||||
private final StringBuilder summary = new StringBuilder();
|
||||
|
||||
private final CQueryPredicates predicates;
|
||||
|
||||
private final boolean subQuery;
|
||||
|
||||
/**
|
||||
* Property if resultSet contains master and detail rows.
|
||||
*/
|
||||
private BeanPropertyAssocMany<?> manyProperty;
|
||||
|
||||
private String manyPropertyName;
|
||||
|
||||
private final SqlTreeAlias alias;
|
||||
|
||||
private final DefaultDbSqlContext ctx;
|
||||
|
||||
private final HashSet<String> selectIncludes = new HashSet<String>();
|
||||
|
||||
private final ManyWhereJoins manyWhereJoins;
|
||||
|
||||
private final TableJoin includeJoin;
|
||||
|
||||
private final boolean rawSql;
|
||||
|
||||
/**
|
||||
* Construct for RawSql query.
|
||||
*/
|
||||
public SqlTreeBuilder(OrmQueryRequest<?> request, CQueryPredicates predicates, OrmQueryDetail queryDetail) {
|
||||
|
||||
this.rawSql = true;
|
||||
this.desc = request.getBeanDescriptor();
|
||||
this.query = null;
|
||||
this.subQuery = false;
|
||||
this.queryDetail = queryDetail;
|
||||
this.predicates = predicates;
|
||||
|
||||
this.includeJoin = null;
|
||||
this.manyWhereJoins = null;
|
||||
this.alias = null;
|
||||
this.ctx = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The predicates are used to determine if 'extra' joins are required to
|
||||
* support the where and/or order by clause. If so these extra joins are
|
||||
* added to the root node.
|
||||
*/
|
||||
public SqlTreeBuilder(String tableAliasPlaceHolder, String columnAliasPrefix, OrmQueryRequest<?> request, CQueryPredicates predicates) {
|
||||
|
||||
this.rawSql = false;
|
||||
this.desc = request.getBeanDescriptor();
|
||||
this.query = request.getQuery();
|
||||
|
||||
this.subQuery = Type.SUBQUERY.equals(query.getType());
|
||||
this.includeJoin = query.getIncludeTableJoin();
|
||||
this.manyWhereJoins = query.getManyWhereJoins();
|
||||
this.queryDetail = query.getDetail();
|
||||
|
||||
this.predicates = predicates;
|
||||
this.alias = new SqlTreeAlias(request.getBeanDescriptor().getBaseTableAlias());
|
||||
this.ctx = new DefaultDbSqlContext(alias, tableAliasPlaceHolder, columnAliasPrefix, !subQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build based on the includes and using the BeanJoinTree.
|
||||
*/
|
||||
public SqlTree build() {
|
||||
|
||||
SqlTree sqlTree = new SqlTree();
|
||||
|
||||
summary.append(desc.getName());
|
||||
|
||||
// build the appropriate chain of SelectAdapter's
|
||||
buildRoot(desc, sqlTree);
|
||||
|
||||
// build the actual String
|
||||
SqlTreeNode rootNode = sqlTree.getRootNode();
|
||||
|
||||
if (!rawSql){
|
||||
sqlTree.setSelectSql(buildSelectClause(rootNode));
|
||||
sqlTree.setFromSql(buildFromClause(rootNode));
|
||||
sqlTree.setInheritanceWhereSql(buildWhereClause(rootNode));
|
||||
sqlTree.setEncryptedProps(ctx.getEncryptedProps());
|
||||
}
|
||||
sqlTree.setIncludes(queryDetail.getIncludes());
|
||||
sqlTree.setSummary(summary.toString());
|
||||
|
||||
if (manyPropertyName != null){
|
||||
ElPropertyValue manyPropEl = desc.getElGetValue(manyPropertyName);
|
||||
sqlTree.setManyProperty(manyProperty, manyPropertyName, manyPropEl);
|
||||
}
|
||||
|
||||
return sqlTree;
|
||||
}
|
||||
|
||||
private String buildSelectClause(SqlTreeNode rootNode) {
|
||||
|
||||
if (rawSql){
|
||||
return "Not Used";
|
||||
}
|
||||
rootNode.appendSelect(ctx, subQuery);
|
||||
|
||||
String selectSql = ctx.getContent();
|
||||
|
||||
// trim off the first comma
|
||||
if (selectSql.length() >= SqlTreeNode.COMMA.length()) {
|
||||
selectSql = selectSql.substring(SqlTreeNode.COMMA.length());
|
||||
}
|
||||
|
||||
return selectSql;
|
||||
}
|
||||
|
||||
private String buildWhereClause(SqlTreeNode rootNode) {
|
||||
|
||||
if (rawSql){
|
||||
return "Not Used";
|
||||
}
|
||||
rootNode.appendWhere(ctx);
|
||||
return ctx.getContent();
|
||||
}
|
||||
|
||||
private String buildFromClause(SqlTreeNode rootNode) {
|
||||
|
||||
if (rawSql){
|
||||
return "Not Used";
|
||||
}
|
||||
rootNode.appendFrom(ctx, false);
|
||||
return ctx.getContent();
|
||||
}
|
||||
|
||||
private void buildRoot(BeanDescriptor<?> desc, SqlTree sqlTree) {
|
||||
|
||||
SqlTreeNode selectRoot = buildSelectChain(null, null, desc, null);
|
||||
sqlTree.setRootNode(selectRoot);
|
||||
|
||||
if (!rawSql){
|
||||
alias.addJoin(queryDetail.getIncludes(), desc);
|
||||
alias.addJoin(predicates.getPredicateIncludes(), desc);
|
||||
alias.addManyWhereJoins(manyWhereJoins.getJoins());
|
||||
|
||||
// build set of table alias
|
||||
alias.buildAlias();
|
||||
|
||||
predicates.parseTableAlias(alias);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively build the query tree depending on what leaves in the tree
|
||||
* should be included.
|
||||
*/
|
||||
private SqlTreeNode buildSelectChain(String prefix, BeanPropertyAssoc<?> prop, BeanDescriptor<?> desc, List<SqlTreeNode> joinList) {
|
||||
|
||||
List<SqlTreeNode> myJoinList = new ArrayList<SqlTreeNode>();
|
||||
|
||||
BeanPropertyAssocOne<?>[] ones = desc.propertiesOne();
|
||||
for (int i = 0; i < ones.length; i++) {
|
||||
String propPrefix = SplitName.add(prefix, ones[i].getName());
|
||||
if (isIncludeBean(propPrefix, ones[i])) {
|
||||
selectIncludes.add(propPrefix);
|
||||
buildSelectChain(propPrefix, ones[i], ones[i].getTargetDescriptor(), myJoinList);
|
||||
}
|
||||
}
|
||||
|
||||
BeanPropertyAssocMany<?>[] manys = desc.propertiesMany();
|
||||
for (int i = 0; i < manys.length; i++) {
|
||||
String propPrefix = SplitName.add(prefix, manys[i].getName());
|
||||
if (isIncludeMany(prefix, propPrefix, manys[i])) {
|
||||
selectIncludes.add(propPrefix);
|
||||
buildSelectChain(propPrefix, manys[i], manys[i].getTargetDescriptor(), myJoinList);
|
||||
}
|
||||
}
|
||||
|
||||
if (prefix == null && !rawSql) {
|
||||
addManyWhereJoins(myJoinList);
|
||||
}
|
||||
|
||||
SqlTreeNode selectNode = buildNode(prefix, prop, desc, myJoinList);
|
||||
if (joinList != null) {
|
||||
joinList.add(selectNode);
|
||||
}
|
||||
return selectNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add joins used to support where clause predicates on 'many' properties.
|
||||
* <p>
|
||||
* These joins are effectively independent of any fetch joins on 'many' properties.
|
||||
* </p>
|
||||
*/
|
||||
private void addManyWhereJoins(List<SqlTreeNode> myJoinList) {
|
||||
|
||||
Set<String> includes = manyWhereJoins.getJoins();
|
||||
for (String joinProp : includes) {
|
||||
|
||||
BeanPropertyAssoc<?> beanProperty = (BeanPropertyAssoc<?>) desc.getBeanPropertyFromPath(joinProp);
|
||||
SqlTreeNodeManyWhereJoin nodeJoin = new SqlTreeNodeManyWhereJoin(joinProp, beanProperty);
|
||||
myJoinList.add(nodeJoin);
|
||||
}
|
||||
}
|
||||
|
||||
private SqlTreeNode buildNode(String prefix, BeanPropertyAssoc<?> prop, BeanDescriptor<?> desc, List<SqlTreeNode> myList) {
|
||||
|
||||
OrmQueryProperties queryProps = queryDetail.getChunk(prefix, false);
|
||||
|
||||
SqlTreeProperties props = getBaseSelect(desc, queryProps);
|
||||
|
||||
if (prefix == null) {
|
||||
buildExtraJoins(desc, myList);
|
||||
return new SqlTreeNodeRoot(desc, props, myList, !subQuery, includeJoin);
|
||||
|
||||
} else if (prop instanceof BeanPropertyAssocMany<?>) {
|
||||
return new SqlTreeNodeManyRoot(prefix, (BeanPropertyAssocMany<?>) prop, props, myList);
|
||||
|
||||
} else {
|
||||
return new SqlTreeNodeBean(prefix, prop, props, myList, true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build extra joins to support properties used in where clause but not
|
||||
* already in select clause.
|
||||
*/
|
||||
private void buildExtraJoins(BeanDescriptor<?> desc, List<SqlTreeNode> myList) {
|
||||
|
||||
if (rawSql){
|
||||
return;
|
||||
}
|
||||
|
||||
Set<String> predicateIncludes = predicates.getPredicateIncludes();
|
||||
|
||||
if (predicateIncludes == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Note includes - basically means joins.
|
||||
// The selectIncludes is the set of joins that are required to support
|
||||
// the 'select' part of the query. We may need to add other joins to
|
||||
// support the predicates or order by clauses.
|
||||
|
||||
// remove ManyWhereJoins from the predicateIncludes
|
||||
predicateIncludes.removeAll(manyWhereJoins.getJoins());
|
||||
|
||||
// look for predicateIncludes that are not in selectIncludes and add
|
||||
// them as extra joins to the query
|
||||
IncludesDistiller extraJoinDistill = new IncludesDistiller(desc, selectIncludes, predicateIncludes);
|
||||
|
||||
Collection<SqlTreeNodeExtraJoin> extraJoins = extraJoinDistill.getExtraJoinRootNodes();
|
||||
if (extraJoins.isEmpty()) {
|
||||
return;
|
||||
|
||||
} else {
|
||||
// add extra joins required to support predicates
|
||||
// and/or order by clause
|
||||
Iterator<SqlTreeNodeExtraJoin> it = extraJoins.iterator();
|
||||
while (it.hasNext()) {
|
||||
SqlTreeNodeExtraJoin extraJoin = it.next();
|
||||
myList.add(extraJoin);
|
||||
|
||||
if (extraJoin.isManyJoin()) {
|
||||
// as we are now going to join to the many then we need
|
||||
// to add the distinct to the sql query to stop duplicate
|
||||
// rows...
|
||||
query.setDistinct(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A subQuery has slightly different rules in that it just generates SQL
|
||||
* (into the where clause) and its properties are not required to read the
|
||||
* resultSet etc.
|
||||
* <p>
|
||||
* This means it can included individual properties of an embedded bean.
|
||||
* </p>
|
||||
*/
|
||||
private void addPropertyToSubQuery(SqlTreeProperties selectProps, BeanDescriptor<?> desc, OrmQueryProperties queryProps, String propName) {
|
||||
|
||||
BeanProperty p = desc.findBeanProperty(propName);
|
||||
if (p == null) {
|
||||
logger.log(Level.SEVERE, "property [" + propName + "]not found on " + desc + " for query - excluding it.");
|
||||
|
||||
}
|
||||
else if (p instanceof BeanPropertyAssoc<?> && p.isEmbedded()) {
|
||||
// if the property is embedded we need to lookup the real column name
|
||||
int pos = propName.indexOf(".");
|
||||
if (pos > -1) {
|
||||
String name = propName.substring(pos + 1);
|
||||
p = ((BeanPropertyAssoc<?>) p).getTargetDescriptor().findBeanProperty(name);
|
||||
}
|
||||
}
|
||||
|
||||
selectProps.add(p);
|
||||
}
|
||||
|
||||
private void addProperty(SqlTreeProperties selectProps, BeanDescriptor<?> desc, OrmQueryProperties queryProps, String propName) {
|
||||
|
||||
if (subQuery) {
|
||||
addPropertyToSubQuery(selectProps, desc, queryProps, propName);
|
||||
return;
|
||||
}
|
||||
|
||||
int basePos = propName.indexOf('.');
|
||||
if (basePos > -1) {
|
||||
// property on an embedded bean. Embedded beans do not yet
|
||||
// support being partially populated so we include the
|
||||
// 'base' property and make sure we only do that once
|
||||
String baseName = propName.substring(0, basePos);
|
||||
|
||||
// make sure we only included the base/embedded bean once
|
||||
if (!selectProps.containsProperty(baseName)) {
|
||||
BeanProperty p = desc.findBeanProperty(baseName);
|
||||
if (p == null) {
|
||||
String m = "property [" + propName + "] not found on " + desc + " for query - excluding it.";
|
||||
logger.log(Level.SEVERE, m);
|
||||
|
||||
} else if (p.isEmbedded()) {
|
||||
// add the embedded bean (and effectively
|
||||
// all its properties)
|
||||
selectProps.add(p);
|
||||
// also make sure it is added to included properties
|
||||
// to avoid unnecessary lazy loading
|
||||
selectProps.getIncludedProperties().add(baseName);
|
||||
|
||||
} else {
|
||||
String m = "property [" + p.getFullBeanName()
|
||||
+ "] expected to be an embedded bean for query - excluding it.";
|
||||
logger.log(Level.SEVERE, m);
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
// find the property including searching the
|
||||
// sub class hierarchy if required
|
||||
BeanProperty p = desc.findBeanProperty(propName);
|
||||
if (p == null) {
|
||||
logger.log(Level.SEVERE, "property [" + propName + "] not found on " + desc
|
||||
+ " for query - excluding it.");
|
||||
|
||||
} else if (p.isId()) {
|
||||
// do not bother to include id for normal queries as the
|
||||
// id is always added (except for subQueries)
|
||||
|
||||
} else if (p instanceof BeanPropertyAssoc<?>) {
|
||||
// need to check if this property should be
|
||||
// excluded. This occurs when this property is
|
||||
// included as a bean join. With a bean join
|
||||
// the property should be excluded as the bean
|
||||
// join has its own node in the SqlTree.
|
||||
if (!queryProps.isIncludedBeanJoin(p.getName())) {
|
||||
// include the property... which basically
|
||||
// means include the foreign key column(s)
|
||||
selectProps.add(p);
|
||||
}
|
||||
} else {
|
||||
selectProps.add(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private SqlTreeProperties getBaseSelectPartial(BeanDescriptor<?> desc, OrmQueryProperties queryProps) {
|
||||
|
||||
SqlTreeProperties selectProps = new SqlTreeProperties();
|
||||
selectProps.setReadOnly(queryProps.isReadOnly());
|
||||
selectProps.setIncludedProperties(queryProps.getAllIncludedProperties());
|
||||
|
||||
// add properties in the order in which they appear
|
||||
// in the query. Gives predictable sql/properties for
|
||||
// use with SqlSelect type queries.
|
||||
|
||||
// Also note that this can include transient properties.
|
||||
// This makes sense for transient properties used to
|
||||
// hold sum() count() type values (with SqlSelect)
|
||||
Iterator<String> it = queryProps.getSelectProperties();
|
||||
while (it.hasNext()) {
|
||||
String propName = it.next();
|
||||
if (propName.length() > 0) {
|
||||
addProperty(selectProps, desc, queryProps, propName);
|
||||
}
|
||||
}
|
||||
|
||||
return selectProps;
|
||||
}
|
||||
|
||||
private SqlTreeProperties getBaseSelect(BeanDescriptor<?> desc, OrmQueryProperties queryProps) {
|
||||
|
||||
boolean partial = queryProps != null && !queryProps.allProperties();
|
||||
if (partial) {
|
||||
return getBaseSelectPartial(desc, queryProps);
|
||||
}
|
||||
|
||||
SqlTreeProperties selectProps = new SqlTreeProperties();
|
||||
|
||||
// normal simple properties of the bean
|
||||
selectProps.add(desc.propertiesBaseScalar());
|
||||
selectProps.add(desc.propertiesBaseCompound());
|
||||
selectProps.add(desc.propertiesEmbedded());
|
||||
|
||||
BeanPropertyAssocOne<?>[] propertiesOne = desc.propertiesOne();
|
||||
for (int i = 0; i < propertiesOne.length; i++) {
|
||||
if (queryProps != null && queryProps.isIncludedBeanJoin(propertiesOne[i].getName())) {
|
||||
// if it is a joined bean... then don't add the property
|
||||
// as it will have its own entire Node in the SqlTree
|
||||
} else {
|
||||
selectProps.add(propertiesOne[i]);
|
||||
}
|
||||
}
|
||||
|
||||
selectProps.setTableJoins(desc.tableJoins());
|
||||
|
||||
InheritInfo inheritInfo = desc.getInheritInfo();
|
||||
if (inheritInfo != null) {
|
||||
// add sub type properties
|
||||
inheritInfo.addChildrenProperties(selectProps);
|
||||
|
||||
}
|
||||
return selectProps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this many node should be included in the query.
|
||||
*/
|
||||
private boolean isIncludeMany(String prefix, String propName, BeanPropertyAssocMany<?> manyProp) {
|
||||
|
||||
if (queryDetail.isJoinsEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (queryDetail.includes(propName)) {
|
||||
|
||||
if (manyProperty != null) {
|
||||
// only one many associated allowed to be included in fetch
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
String msg = "Not joining [" + propName + "] as already joined to a Many[" + manyProperty + "].";
|
||||
logger.fine(msg);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
manyProperty = manyProp;
|
||||
manyPropertyName = propName;
|
||||
summary.append(" +many:").append(propName);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to see if we are including this node into the query.
|
||||
* <p>
|
||||
* Return true if this node is FULLY included resulting in table join. If
|
||||
* the node is not included but its parent has been included then a "bean
|
||||
* proxy" is added and false is returned.
|
||||
* </p>
|
||||
*/
|
||||
private boolean isIncludeBean(String prefix, BeanPropertyAssocOne<?> prop) {
|
||||
|
||||
if (queryDetail.includes(prefix)) {
|
||||
// explicitly included
|
||||
summary.append(", ").append(prefix);
|
||||
String[] splitNames = SplitName.split(prefix);
|
||||
queryDetail.includeBeanJoin(splitNames[0], splitNames[1]);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes the select includes and the predicates includes and determines the
|
||||
* extra joins required to support the predicates (that are not already
|
||||
* supported by the select includes).
|
||||
* <p>
|
||||
* This returns ONLY the leaves. The joins for the leaves
|
||||
* </p>
|
||||
*/
|
||||
private static class IncludesDistiller {
|
||||
|
||||
private final Set<String> selectIncludes;
|
||||
private final Set<String> predicateIncludes;
|
||||
|
||||
/**
|
||||
* Contains the 'root' extra joins. We only return the roots back.
|
||||
*/
|
||||
private final Map<String, SqlTreeNodeExtraJoin> joinRegister = new HashMap<String, SqlTreeNodeExtraJoin>();
|
||||
|
||||
/**
|
||||
* Register of all the extra join nodes.
|
||||
*/
|
||||
private final Map<String, SqlTreeNodeExtraJoin> rootRegister = new HashMap<String, SqlTreeNodeExtraJoin>();
|
||||
|
||||
private final BeanDescriptor<?> desc;
|
||||
|
||||
private IncludesDistiller(BeanDescriptor<?> desc, Set<String> selectIncludes, Set<String> predicateIncludes) {
|
||||
this.desc = desc;
|
||||
this.selectIncludes = selectIncludes;
|
||||
this.predicateIncludes = predicateIncludes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the collection of extra joins returning just the roots.
|
||||
* <p>
|
||||
* each root returned here could contain a little tree of joins. This
|
||||
* follows the more natural pattern and allows for forcing outer joins
|
||||
* from a join to a 'many' down through the rest of its tree.
|
||||
* </p>
|
||||
*/
|
||||
private Collection<SqlTreeNodeExtraJoin> getExtraJoinRootNodes() {
|
||||
|
||||
String[] extras = findExtras();
|
||||
if (extras.length == 0) {
|
||||
return rootRegister.values();
|
||||
}
|
||||
|
||||
// sort so we process only getting the leaves
|
||||
// excluding nodes between root and the leaf
|
||||
Arrays.sort(extras);
|
||||
|
||||
// reverse order so get the leaves first...
|
||||
for (int i = 0; i < extras.length; i++) {
|
||||
createExtraJoin(extras[i]);
|
||||
}
|
||||
|
||||
return rootRegister.values();
|
||||
}
|
||||
|
||||
private void createExtraJoin(String includeProp) {
|
||||
|
||||
SqlTreeNodeExtraJoin extraJoin = createJoinLeaf(includeProp);
|
||||
if (extraJoin != null) {
|
||||
// add the extra join...
|
||||
|
||||
// find root of this extra join... linking back to the
|
||||
// parents (creating the tree) as it goes.
|
||||
SqlTreeNodeExtraJoin root = findExtraJoinRoot(includeProp, extraJoin);
|
||||
|
||||
// register the root because these are the only ones we
|
||||
// return back.
|
||||
rootRegister.put(root.getName(), root);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a SqlTreeNodeExtraJoin, register and return it.
|
||||
*/
|
||||
private SqlTreeNodeExtraJoin createJoinLeaf(String propertyName) {
|
||||
|
||||
ElPropertyValue elGetValue = desc.getElGetValue(propertyName);
|
||||
|
||||
if (elGetValue == null) {
|
||||
// this can occur for master detail queries
|
||||
// with concatenated keys (so not an error now)
|
||||
return null;
|
||||
}
|
||||
BeanProperty beanProperty = elGetValue.getBeanProperty();
|
||||
if (beanProperty instanceof BeanPropertyAssoc<?>) {
|
||||
BeanPropertyAssoc<?> assocProp = (BeanPropertyAssoc<?>) beanProperty;
|
||||
if (assocProp.isEmbedded()) {
|
||||
// no extra join required for embedded beans
|
||||
return null;
|
||||
}
|
||||
SqlTreeNodeExtraJoin extraJoin = new SqlTreeNodeExtraJoin(propertyName, assocProp);
|
||||
joinRegister.put(propertyName, extraJoin);
|
||||
return extraJoin;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the root the this extra join tree.
|
||||
* <p>
|
||||
* This may need to create a parent join implicitly if a predicate join
|
||||
* 'skips' a level. e.g. where details.user.id = 1 (maybe join to
|
||||
* details is not specified and is implicitly created.
|
||||
* </p>
|
||||
*/
|
||||
private SqlTreeNodeExtraJoin findExtraJoinRoot(String includeProp, SqlTreeNodeExtraJoin childJoin) {
|
||||
|
||||
int dotPos = includeProp.lastIndexOf('.');
|
||||
if (dotPos == -1) {
|
||||
// no parent possible(parent is root)
|
||||
return childJoin;
|
||||
|
||||
} else {
|
||||
// look in register ...
|
||||
String parentPropertyName = includeProp.substring(0, dotPos);
|
||||
if (selectIncludes.contains(parentPropertyName)) {
|
||||
// parent already handled by select
|
||||
return childJoin;
|
||||
}
|
||||
|
||||
SqlTreeNodeExtraJoin parentJoin = joinRegister.get(parentPropertyName);
|
||||
if (parentJoin == null) {
|
||||
// we need to create this the parent implicitly...
|
||||
parentJoin = createJoinLeaf(parentPropertyName);
|
||||
}
|
||||
|
||||
parentJoin.addChild(childJoin);
|
||||
return findExtraJoinRoot(parentPropertyName, parentJoin);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the extra joins required by predicates and not already taken
|
||||
* care of by the select.
|
||||
*/
|
||||
private String[] findExtras() {
|
||||
|
||||
List<String> extras = new ArrayList<String>();
|
||||
|
||||
for (String predProp : predicateIncludes) {
|
||||
if (!selectIncludes.contains(predProp)) {
|
||||
extras.add(predProp);
|
||||
}
|
||||
}
|
||||
return extras.toArray(new String[extras.size()]);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
|
||||
|
||||
public interface SqlTreeNode {
|
||||
|
||||
/**
|
||||
* the new line character used.
|
||||
* <p>
|
||||
* Note that this is removed for logging sql to the transaction log.
|
||||
* </p>
|
||||
*/
|
||||
public static final char NEW_LINE = '\n';
|
||||
|
||||
public static final String PERIOD = ".";
|
||||
|
||||
public static final String COMMA = ", ";
|
||||
|
||||
public static final int NORMAL = 0;
|
||||
public static final int SHARED = 1;
|
||||
public static final int READONLY = 2;
|
||||
|
||||
public void buildSelectExpressionChain(List<String> selectChain);
|
||||
|
||||
/**
|
||||
* Append the required column information to the SELECT part of the sql
|
||||
* statement.
|
||||
*/
|
||||
public void appendSelect(DbSqlContext ctx, boolean subQuery);
|
||||
|
||||
/**
|
||||
* Append to the FROM part of the sql.
|
||||
*/
|
||||
public void appendFrom(DbSqlContext ctx, boolean forceOuterJoin);
|
||||
|
||||
/**
|
||||
* Append any where predicates for inheritance.
|
||||
*/
|
||||
public void appendWhere(DbSqlContext ctx);
|
||||
|
||||
/**
|
||||
* Load the appropriate information from the SqlSelectReader.
|
||||
* <p>
|
||||
* At a high level this actually controls the reading of the data from the
|
||||
* jdbc resultSet and putting it into the bean etc.
|
||||
* </p>
|
||||
*
|
||||
*/
|
||||
public void load(DbReadContext ctx, Object parentBean) throws SQLException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import com.avaje.ebean.bean.BeanCollection;
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
import com.avaje.ebean.bean.EntityBeanIntercept;
|
||||
import com.avaje.ebean.bean.PersistenceContext;
|
||||
import com.avaje.ebeaninternal.api.SpiQuery.Mode;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssoc;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
|
||||
import com.avaje.ebeaninternal.server.deploy.InheritInfo;
|
||||
import com.avaje.ebeaninternal.server.deploy.TableJoin;
|
||||
import com.avaje.ebeaninternal.server.deploy.id.IdBinder;
|
||||
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Normal bean included in the query.
|
||||
*/
|
||||
public class SqlTreeNodeBean implements SqlTreeNode {
|
||||
|
||||
private static final SqlTreeNode[] NO_CHILDREN = new SqlTreeNode[0];
|
||||
|
||||
final BeanDescriptor<?> desc;
|
||||
|
||||
final IdBinder idBinder;
|
||||
|
||||
/**
|
||||
* The children which will be other SelectBean or SelectProxyBean.
|
||||
*/
|
||||
final SqlTreeNode[] children;
|
||||
|
||||
final boolean readOnlyLeaf;
|
||||
|
||||
/**
|
||||
* Set to true if this is a partial object fetch.
|
||||
*/
|
||||
final boolean partialObject;
|
||||
|
||||
/**
|
||||
* The set of properties explicitly included in the query.
|
||||
* We actually add the manyProp names to this as they are
|
||||
* references/proxies we add via createListProxies().
|
||||
*/
|
||||
final Set<String> partialProps;
|
||||
|
||||
/**
|
||||
* The hash of the partialProps (calculate once).
|
||||
*/
|
||||
final int partialHash;
|
||||
|
||||
final BeanProperty[] properties;
|
||||
|
||||
/**
|
||||
* Extra where clause added by Where annotation on associated many.
|
||||
*/
|
||||
final String extraWhere;
|
||||
|
||||
final BeanPropertyAssoc<?> nodeBeanProp;
|
||||
|
||||
final TableJoin[] tableJoins;
|
||||
|
||||
/**
|
||||
* False if report bean and has no id property.
|
||||
*/
|
||||
final boolean readId;
|
||||
|
||||
final boolean disableLazyLoad;
|
||||
|
||||
final InheritInfo inheritInfo;
|
||||
|
||||
final String prefix;
|
||||
|
||||
final Set<String> includedProps;
|
||||
|
||||
final Map<String,String> pathMap;
|
||||
|
||||
public SqlTreeNodeBean(String prefix, BeanPropertyAssoc<?> beanProp,
|
||||
SqlTreeProperties props, List<SqlTreeNode> myChildren, boolean withId) {
|
||||
|
||||
this(prefix, beanProp, beanProp.getTargetDescriptor(),props, myChildren, withId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create with the appropriate node.
|
||||
*/
|
||||
public SqlTreeNodeBean(String prefix, BeanPropertyAssoc<?> beanProp, BeanDescriptor<?> desc,
|
||||
SqlTreeProperties props, List<SqlTreeNode> myChildren, boolean withId) {
|
||||
|
||||
this.prefix = prefix;
|
||||
this.nodeBeanProp = beanProp;
|
||||
this.desc = desc;
|
||||
this.inheritInfo = desc.getInheritInfo();
|
||||
this.extraWhere = (beanProp == null) ? null : beanProp.getExtraWhere();
|
||||
|
||||
this.idBinder = desc.getIdBinder();
|
||||
|
||||
// the bean has an Id property and we want to use it
|
||||
this.readId = withId && (desc.propertiesId().length > 0);
|
||||
this.disableLazyLoad = !readId || desc.isSqlSelectBased();
|
||||
|
||||
this.tableJoins = props.getTableJoins();
|
||||
|
||||
this.partialObject = props.isPartialObject();
|
||||
this.partialProps = props.getIncludedProperties();
|
||||
this.partialHash = partialObject ? partialProps.hashCode() : 0;
|
||||
|
||||
this.readOnlyLeaf = props.isReadOnly();
|
||||
|
||||
this.properties = props.getProps();
|
||||
|
||||
if (partialObject){
|
||||
// merge the explicit partialProps with the implicitly added
|
||||
// list proxies (that are added by createListProxies()) to get
|
||||
// the full set of 'loaded' properties for this bean.
|
||||
includedProps = LoadedPropertiesCache.get(partialHash, partialProps, desc);
|
||||
} else {
|
||||
includedProps = null;
|
||||
}
|
||||
|
||||
if (myChildren == null) {
|
||||
children = NO_CHILDREN;
|
||||
} else {
|
||||
children = myChildren.toArray(new SqlTreeNode[myChildren.size()]);
|
||||
}
|
||||
|
||||
pathMap = createPathMap(prefix, desc);
|
||||
}
|
||||
|
||||
private Map<String,String> createPathMap(String prefix, BeanDescriptor<?> desc) {
|
||||
|
||||
BeanPropertyAssocMany<?>[] manys = desc.propertiesMany();
|
||||
|
||||
HashMap<String,String> m = new HashMap<String,String>();
|
||||
for (int i = 0; i < manys.length; i++) {
|
||||
String name = manys[i].getName();
|
||||
m.put(name, getPath(prefix, name));
|
||||
}
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
private String getPath(String prefix, String propertyName){
|
||||
if (prefix == null){
|
||||
return propertyName;
|
||||
} else {
|
||||
return prefix+"."+propertyName;
|
||||
}
|
||||
}
|
||||
|
||||
protected void postLoad(DbReadContext cquery, Object loadedBean, Object id) {
|
||||
}
|
||||
|
||||
public void buildSelectExpressionChain(List<String> selectChain){
|
||||
if (readId){
|
||||
idBinder.buildSelectExpressionChain(prefix, selectChain);
|
||||
}
|
||||
for (int i = 0, x = properties.length; i < x; i++) {
|
||||
properties[i].buildSelectExpressionChain(prefix, selectChain);
|
||||
}
|
||||
// recursively continue reading...
|
||||
for (int i = 0; i < children.length; i++) {
|
||||
// read each child... and let them set their
|
||||
// values back to this localBean
|
||||
children[i].buildSelectExpressionChain(selectChain);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* read the properties from the resultSet.
|
||||
*/
|
||||
public void load(DbReadContext ctx, Object parentBean) throws SQLException {
|
||||
|
||||
// bean already existing in the persistence context
|
||||
Object contextBean = null;
|
||||
|
||||
Class<?> localType;
|
||||
BeanDescriptor<?> localDesc;
|
||||
IdBinder localIdBinder;
|
||||
Object localBean;
|
||||
|
||||
if (inheritInfo != null){
|
||||
InheritInfo localInfo = inheritInfo.readType(ctx);
|
||||
if (localInfo == null){
|
||||
// the bean must be null
|
||||
localIdBinder = idBinder;
|
||||
localBean = null;
|
||||
localType = null;
|
||||
localDesc = desc;
|
||||
} else {
|
||||
localBean = localInfo.createBean(ctx.isVanillaMode());
|
||||
localType = localInfo.getType();
|
||||
localIdBinder = localInfo.getIdBinder();
|
||||
localDesc = localInfo.getBeanDescriptor();
|
||||
}
|
||||
|
||||
} else {
|
||||
localType = null;
|
||||
localDesc = desc;
|
||||
localBean = desc.createBean(ctx.isVanillaMode());
|
||||
localIdBinder = idBinder;
|
||||
}
|
||||
|
||||
Mode queryMode = ctx.getQueryMode();
|
||||
|
||||
PersistenceContext persistenceContext = ctx.getPersistenceContext();
|
||||
|
||||
Object id = null;
|
||||
if (!readId){
|
||||
// report type bean... or perhaps excluding the id for SqlSelect?
|
||||
|
||||
} else {
|
||||
id = localIdBinder.readSet(ctx, localBean);
|
||||
if (id == null){
|
||||
// bean must be null...
|
||||
localBean = null;
|
||||
} else {
|
||||
// check the PersistenceContext to see if the bean already exists
|
||||
contextBean = persistenceContext.putIfAbsent(id, localBean);
|
||||
if (contextBean == null){
|
||||
// bean just added to the persistenceContext
|
||||
contextBean = localBean;
|
||||
} else {
|
||||
// bean already exists in persistenceContext
|
||||
if (queryMode.isLoadContextBean()){
|
||||
// refresh it anyway (lazy loading for example)
|
||||
localBean = contextBean;
|
||||
if (localBean instanceof EntityBean){
|
||||
// temporarily turn off interception during load
|
||||
((EntityBean)localBean)._ebean_getIntercept().setIntercepting(false);
|
||||
}
|
||||
} else {
|
||||
// ignore the DB data...
|
||||
localBean = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ctx.setCurrentPrefix(prefix, pathMap);
|
||||
|
||||
ctx.propagateState(localBean);
|
||||
|
||||
SqlBeanLoad sqlBeanLoad = new SqlBeanLoad(ctx, localType, localBean, queryMode);
|
||||
|
||||
if (inheritInfo == null){
|
||||
// normal behaviour with no inheritance
|
||||
for (int i = 0, x = properties.length; i < x; i++) {
|
||||
properties[i].load(sqlBeanLoad);
|
||||
}
|
||||
|
||||
} else {
|
||||
// take account of inheritance and due to subclassing approach
|
||||
// need to get a 'local' version of the property
|
||||
for (int i = 0, x = properties.length; i < x; i++) {
|
||||
// get a local version of the BeanProperty
|
||||
BeanProperty p = localDesc.getBeanProperty(properties[i].getName());
|
||||
if (p != null){
|
||||
p.load(sqlBeanLoad);
|
||||
} else {
|
||||
properties[i].loadIgnore(ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0, x = tableJoins.length; i < x; i++) {
|
||||
tableJoins[i].load(sqlBeanLoad);
|
||||
}
|
||||
|
||||
boolean lazyLoadMany = false;
|
||||
if (localBean == null && queryMode.equals(Mode.LAZYLOAD_MANY)){
|
||||
// batch lazy load many into existing contextBean
|
||||
localBean = contextBean;
|
||||
lazyLoadMany = true;
|
||||
}
|
||||
|
||||
// recursively continue reading...
|
||||
for (int i = 0; i < children.length; i++) {
|
||||
// read each child... and let them set their
|
||||
// values back to this localBean
|
||||
children[i].load(ctx, localBean);
|
||||
}
|
||||
|
||||
if (lazyLoadMany){
|
||||
// special case where we load children
|
||||
|
||||
} else if (localBean != null) {
|
||||
|
||||
ctx.setCurrentPrefix(prefix, pathMap);
|
||||
if (!ctx.isVanillaMode()){
|
||||
// only create lazy loading collection proxies
|
||||
// when not in vanilla mode
|
||||
createListProxies(localDesc, ctx, localBean);
|
||||
}
|
||||
|
||||
localDesc.postLoad(localBean, includedProps);
|
||||
|
||||
if (localBean instanceof EntityBean) {
|
||||
EntityBeanIntercept ebi = ((EntityBean)localBean)._ebean_getIntercept();
|
||||
ebi.setPersistenceContext(persistenceContext);
|
||||
ebi.setLoadedProps(includedProps);
|
||||
if (Mode.LAZYLOAD_BEAN.equals(queryMode)) {
|
||||
// Lazy Load does not reset the dirty state
|
||||
ebi.setLoadedLazy();
|
||||
} else {
|
||||
// normal bean loading
|
||||
ebi.setLoaded();
|
||||
}
|
||||
|
||||
if (partialObject) {
|
||||
ctx.register(null, ebi);
|
||||
}
|
||||
|
||||
if (disableLazyLoad) {
|
||||
// bean does not have an Id or is SqlSelect based
|
||||
ebi.setDisableLazyLoad(true);
|
||||
}
|
||||
if (ctx.isAutoFetchProfiling()) {
|
||||
// collect autofetch profiling for this bean...
|
||||
ctx.profileBean(ebi, prefix);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if (parentBean != null && contextBean != null) {
|
||||
// set this back to the parentBean
|
||||
nodeBeanProp.setValue(parentBean, contextBean);
|
||||
}
|
||||
|
||||
if (!readId){
|
||||
// a bean with no Id (never found in context)
|
||||
postLoad(ctx, localBean, id);
|
||||
|
||||
} else {
|
||||
// return the contextBean which is either the localBean
|
||||
// read from the resultSet and put into the context OR
|
||||
// the 'matching' bean that already existed in the context
|
||||
postLoad(ctx, contextBean, id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create lazy loading proxies for the Many's except for the one that is
|
||||
* included in the actual query.
|
||||
*/
|
||||
private void createListProxies(BeanDescriptor<?> localDesc, DbReadContext ctx, Object localBean) {
|
||||
|
||||
BeanPropertyAssocMany<?> fetchedMany = ctx.getManyProperty();
|
||||
|
||||
// load the List/Set/Map proxy objects (deferred fetching of lists)
|
||||
BeanPropertyAssocMany<?>[] manys = localDesc.propertiesMany();
|
||||
for (int i = 0; i < manys.length; i++) {
|
||||
|
||||
if (fetchedMany != null && fetchedMany.equals(manys[i])) {
|
||||
// this many property is included in the query...
|
||||
// it is being loaded with real row data (result[1])
|
||||
} else {
|
||||
// create a proxy for the many (deferred fetching)
|
||||
BeanCollection<?> ref = manys[i].createReferenceIfNull(localBean);
|
||||
if (ref != null){
|
||||
ctx.register(manys[i].getName(), ref);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Append the property columns to the buffer.
|
||||
*/
|
||||
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
|
||||
|
||||
ctx.pushJoin(prefix);
|
||||
ctx.pushTableAlias(prefix);
|
||||
|
||||
if (nodeBeanProp != null) {
|
||||
ctx.append(NEW_LINE).append(" ");
|
||||
}
|
||||
|
||||
if (!subQuery && inheritInfo != null){
|
||||
ctx.appendColumn(inheritInfo.getDiscriminatorColumn());
|
||||
}
|
||||
|
||||
if (readId) {
|
||||
appendSelect(ctx, false, idBinder.getProperties());
|
||||
}
|
||||
appendSelect(ctx, subQuery, properties);
|
||||
appendSelectTableJoins(ctx);
|
||||
|
||||
for (int i = 0; i < children.length; i++) {
|
||||
// read each child... and let them set their
|
||||
// values back to this localBean
|
||||
children[i].appendSelect(ctx, subQuery);
|
||||
}
|
||||
|
||||
ctx.popTableAlias();
|
||||
ctx.popJoin();
|
||||
}
|
||||
|
||||
private void appendSelectTableJoins(DbSqlContext ctx) {
|
||||
|
||||
String baseAlias = ctx.getTableAlias(prefix);
|
||||
|
||||
for (int i = 0; i < tableJoins.length; i++) {
|
||||
TableJoin join = tableJoins[i];
|
||||
|
||||
String alias = baseAlias+i;
|
||||
|
||||
ctx.pushSecondaryTableAlias(alias);
|
||||
join.appendSelect(ctx, false);
|
||||
ctx.popTableAlias();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Append the properties to the buffer.
|
||||
*/
|
||||
private void appendSelect(DbSqlContext ctx, boolean subQuery, BeanProperty[] props) {
|
||||
|
||||
for (int i = 0; i < props.length; i++) {
|
||||
props[i].appendSelect(ctx, subQuery);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void appendWhere(DbSqlContext ctx) {
|
||||
|
||||
if (inheritInfo != null) {
|
||||
if (inheritInfo.isRoot()) {
|
||||
// at root of hierarchy so don't bother
|
||||
// adding a where clause because we want
|
||||
// all the types...
|
||||
} else {
|
||||
// restrict to this type and
|
||||
// sub types of this type.
|
||||
if (ctx.length() > 0){
|
||||
ctx.append(" and");
|
||||
}
|
||||
ctx.append(" ").append(ctx.getTableAlias(prefix)).append(".");//tableAlias
|
||||
ctx.append(inheritInfo.getWhere()).append(" ");
|
||||
}
|
||||
}
|
||||
if (extraWhere != null){
|
||||
if (ctx.length() > 0){
|
||||
ctx.append(" and");
|
||||
}
|
||||
String ta = ctx.getTableAlias(prefix);
|
||||
String ew = StringHelper.replaceString(extraWhere, "${ta}", ta);
|
||||
ctx.append(" ").append(ew).append(" ");
|
||||
}
|
||||
|
||||
for (int i = 0; i < children.length; i++) {
|
||||
// recursively add to the where clause any
|
||||
// fixed predicates (extraWhere etc)
|
||||
children[i].appendWhere(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Append to the FROM clause for this node.
|
||||
*/
|
||||
public void appendFrom(DbSqlContext ctx, boolean forceOuterJoin) {
|
||||
|
||||
ctx.pushJoin(prefix);
|
||||
ctx.pushTableAlias(prefix);
|
||||
|
||||
forceOuterJoin = appendFromBaseTable(ctx, forceOuterJoin);
|
||||
|
||||
for (int i = 0; i < properties.length; i++) {
|
||||
// usually nothing... except for 1-1 Exported
|
||||
properties[i].appendFrom(ctx, forceOuterJoin);
|
||||
}
|
||||
|
||||
for (int i = 0; i < children.length; i++) {
|
||||
children[i].appendFrom(ctx, forceOuterJoin);
|
||||
}
|
||||
|
||||
ctx.popTableAlias();
|
||||
ctx.popJoin();
|
||||
}
|
||||
|
||||
/**
|
||||
* Join to base table for this node. This includes a join to
|
||||
* the intersection table if this is a ManyToMany node.
|
||||
*/
|
||||
public boolean appendFromBaseTable(DbSqlContext ctx, boolean forceOuterJoin) {
|
||||
|
||||
if (nodeBeanProp instanceof BeanPropertyAssocMany<?>){
|
||||
BeanPropertyAssocMany<?> manyProp = (BeanPropertyAssocMany<?>)nodeBeanProp;
|
||||
if (manyProp.isManyToMany()){
|
||||
|
||||
String alias = ctx.getTableAlias(prefix);
|
||||
String[] split = SplitName.split(prefix);
|
||||
String parentAlias = ctx.getTableAlias(split[0]);
|
||||
String alias2 = alias+"z_";
|
||||
|
||||
TableJoin manyToManyJoin = manyProp.getIntersectionTableJoin();
|
||||
manyToManyJoin.addJoin(forceOuterJoin, parentAlias, alias2, ctx);
|
||||
|
||||
return nodeBeanProp.addJoin(forceOuterJoin, alias2, alias, ctx);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return nodeBeanProp.addJoin(forceOuterJoin, prefix, ctx);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Summary description.
|
||||
*/
|
||||
public String toString() {
|
||||
return "SqlTreeNodeBean: " + desc;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssoc;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
|
||||
import com.avaje.ebeaninternal.server.deploy.TableJoin;
|
||||
|
||||
/**
|
||||
* The purpose is to add an extra join to the query.
|
||||
* <p>
|
||||
* This is used to support the where clause or order by clause that refers
|
||||
* to properties that are NOT included in the select. To support the where clause
|
||||
* etc in this case we must add an extra join.
|
||||
* </p>
|
||||
*/
|
||||
public class SqlTreeNodeExtraJoin implements SqlTreeNode {
|
||||
|
||||
|
||||
final BeanPropertyAssoc<?> assocBeanProperty;
|
||||
|
||||
final String prefix;
|
||||
|
||||
final boolean manyJoin;
|
||||
|
||||
List<SqlTreeNodeExtraJoin> children;
|
||||
|
||||
public SqlTreeNodeExtraJoin(String prefix, BeanPropertyAssoc<?> assocBeanProperty) {
|
||||
this.prefix = prefix;
|
||||
this.assocBeanProperty = assocBeanProperty;
|
||||
this.manyJoin = assocBeanProperty instanceof BeanPropertyAssocMany<?>;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void buildSelectExpressionChain(List<String> selectChain) {
|
||||
// nothing to add
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Return true if the extra join is a many join.
|
||||
* <p>
|
||||
* This means we need to add distinct to the sql query.
|
||||
* </p>
|
||||
*/
|
||||
public boolean isManyJoin() {
|
||||
return manyJoin;
|
||||
}
|
||||
|
||||
|
||||
public String getName() {
|
||||
return prefix;
|
||||
}
|
||||
|
||||
public void addChild(SqlTreeNodeExtraJoin child){
|
||||
if (children == null){
|
||||
children = new ArrayList<SqlTreeNodeExtraJoin>();
|
||||
}
|
||||
children.add(child);
|
||||
}
|
||||
|
||||
public void appendFrom(DbSqlContext ctx, boolean forceOuterJoin) {
|
||||
|
||||
boolean manyToMany = false;
|
||||
|
||||
if (assocBeanProperty instanceof BeanPropertyAssocMany<?>){
|
||||
BeanPropertyAssocMany<?> manyProp = (BeanPropertyAssocMany<?>)assocBeanProperty;
|
||||
if (manyProp.isManyToMany()){
|
||||
|
||||
manyToMany = true;
|
||||
|
||||
String alias = ctx.getTableAlias(prefix);
|
||||
String[] split = SplitName.split(prefix);
|
||||
String parentAlias = ctx.getTableAlias(split[0]);
|
||||
String alias2 = alias+"z_";
|
||||
|
||||
TableJoin manyToManyJoin = manyProp.getIntersectionTableJoin();
|
||||
manyToManyJoin.addJoin(forceOuterJoin, parentAlias, alias2, ctx);
|
||||
|
||||
assocBeanProperty.addJoin(forceOuterJoin, alias2, alias, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
if (!manyToMany){
|
||||
assocBeanProperty.addJoin(forceOuterJoin, prefix, ctx);
|
||||
}
|
||||
|
||||
if (children != null){
|
||||
|
||||
if (manyJoin){
|
||||
// make sure all decendants use OUTER JOIN
|
||||
forceOuterJoin = true;
|
||||
}
|
||||
|
||||
for (int i = 0; i < children.size(); i++) {
|
||||
SqlTreeNodeExtraJoin child = children.get(i);
|
||||
child.appendFrom(ctx, forceOuterJoin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Does nothing.
|
||||
*/
|
||||
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Does nothing.
|
||||
*/
|
||||
public void appendWhere(DbSqlContext ctx) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Does nothing.
|
||||
*/
|
||||
public void load(DbReadContext ctx, Object parentBean) throws SQLException {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
|
||||
|
||||
public final class SqlTreeNodeManyRoot extends SqlTreeNodeBean {
|
||||
|
||||
public SqlTreeNodeManyRoot(String prefix, BeanPropertyAssocMany<?> prop, SqlTreeProperties props, List<SqlTreeNode> myList) {
|
||||
super(prefix, prop, prop.getTargetDescriptor(), props, myList, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void postLoad(DbReadContext cquery, Object loadedBean, Object id) {
|
||||
|
||||
// put the localBean into the manyValue so that it
|
||||
// is added to the collection/map
|
||||
cquery.setLoadedManyBean(loadedBean);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(DbReadContext cquery, Object parentBean) throws SQLException {
|
||||
// pass in null for parentBean because the localBean
|
||||
// that is built is added to a collection rather than
|
||||
// being set to the parentBean directly
|
||||
super.load(cquery, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Force outer join for everything after the many property.
|
||||
*/
|
||||
@Override
|
||||
public void appendFrom(DbSqlContext ctx, boolean forceOuterJoin) {
|
||||
super.appendFrom(ctx, true);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssoc;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
|
||||
import com.avaje.ebeaninternal.server.deploy.TableJoin;
|
||||
|
||||
/**
|
||||
* Join to Many (or child of a many) to support where clause predicates on many properties.
|
||||
*
|
||||
* @author rbygrave
|
||||
*/
|
||||
public class SqlTreeNodeManyWhereJoin implements SqlTreeNode {
|
||||
|
||||
private final String parentPrefix;
|
||||
private final String prefix;
|
||||
private final BeanPropertyAssoc<?> nodeBeanProp;
|
||||
private final SqlTreeNode[] children;
|
||||
|
||||
public SqlTreeNodeManyWhereJoin(String prefix, BeanPropertyAssoc<?> prop) {
|
||||
|
||||
this.nodeBeanProp = prop;
|
||||
this.prefix = prefix;
|
||||
|
||||
String[] split = SplitName.split(prefix);
|
||||
this.parentPrefix = split[0];
|
||||
|
||||
List<SqlTreeNode> childrenList = new ArrayList<SqlTreeNode>(0);
|
||||
this.children = childrenList.toArray(new SqlTreeNode[childrenList.size()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Append to the FROM clause for this node.
|
||||
*/
|
||||
public void appendFrom(DbSqlContext ctx, boolean forceOuterJoin) {
|
||||
|
||||
appendFromBaseTable(ctx, forceOuterJoin);
|
||||
|
||||
for (int i = 0; i < children.length; i++) {
|
||||
children[i].appendFrom(ctx, forceOuterJoin);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Join to base table for this node. This includes a join to the
|
||||
* intersection table if this is a ManyToMany node.
|
||||
*/
|
||||
public void appendFromBaseTable(DbSqlContext ctx, boolean forceOuterJoin) {
|
||||
|
||||
String alias = ctx.getTableAliasManyWhere(prefix);
|
||||
String parentAlias = ctx.getTableAliasManyWhere(parentPrefix);
|
||||
|
||||
if (nodeBeanProp instanceof BeanPropertyAssocOne<?>){
|
||||
nodeBeanProp.addInnerJoin(parentAlias, alias, ctx);
|
||||
|
||||
} else {
|
||||
BeanPropertyAssocMany<?> manyProp = (BeanPropertyAssocMany<?>)nodeBeanProp;
|
||||
if (!manyProp.isManyToMany()) {
|
||||
manyProp.addInnerJoin(parentAlias, alias, ctx);
|
||||
|
||||
} else {
|
||||
String alias2 = alias + "z_";
|
||||
|
||||
TableJoin manyToManyJoin = manyProp.getIntersectionTableJoin();
|
||||
manyToManyJoin.addInnerJoin(parentAlias, alias2, ctx);
|
||||
manyProp.addInnerJoin(alias2, alias, ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void buildSelectExpressionChain(List<String> selectChain) {
|
||||
// nothing to add
|
||||
}
|
||||
|
||||
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
|
||||
// nothing to do here
|
||||
}
|
||||
|
||||
public void appendWhere(DbSqlContext ctx) {
|
||||
// nothing to do here
|
||||
}
|
||||
|
||||
public void load(DbReadContext ctx, Object parentBean) throws SQLException {
|
||||
// nothing to do here
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
|
||||
import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
|
||||
import com.avaje.ebeaninternal.server.deploy.TableJoin;
|
||||
|
||||
/**
|
||||
* Represents the root node of the Sql Tree.
|
||||
*/
|
||||
public final class SqlTreeNodeRoot extends SqlTreeNodeBean {
|
||||
|
||||
private final TableJoin includeJoin;
|
||||
|
||||
/**
|
||||
* Specify for SqlSelect to include an Id property or not.
|
||||
*/
|
||||
public SqlTreeNodeRoot(BeanDescriptor<?> desc, SqlTreeProperties props, List<SqlTreeNode> myList, boolean withId, TableJoin includeJoin){
|
||||
super(null, null, desc, props, myList, withId);
|
||||
this.includeJoin = includeJoin;
|
||||
}
|
||||
|
||||
public SqlTreeNodeRoot(BeanDescriptor<?> desc, SqlTreeProperties props, List<SqlTreeNode> myList, boolean withId) {
|
||||
super(null, null, desc, props, myList, withId);
|
||||
this.includeJoin = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void postLoad(DbReadContext cquery, Object loadedBean, Object id) {
|
||||
|
||||
// set the current bean with id...
|
||||
cquery.setLoadedBean(loadedBean, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* For the root node there is no join type or on clause etc.
|
||||
*/
|
||||
@Override
|
||||
public boolean appendFromBaseTable(DbSqlContext ctx, boolean forceOuterJoin) {
|
||||
|
||||
ctx.append(desc.getBaseTable());
|
||||
ctx.append(" ").append(ctx.getTableAlias(null));
|
||||
|
||||
if (includeJoin != null){
|
||||
String a1 = ctx.getTableAlias(null);
|
||||
String a2 = "int_"; // unique alias for intersection join
|
||||
includeJoin.addJoin(forceOuterJoin, a1, a2, ctx);
|
||||
}
|
||||
|
||||
return forceOuterJoin;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
import com.avaje.ebeaninternal.server.deploy.TableJoin;
|
||||
|
||||
/**
|
||||
* The select properties for a node in the SqlTree.
|
||||
*/
|
||||
public class SqlTreeProperties {
|
||||
|
||||
/**
|
||||
* The included Properties that will be used by EntityBeanIntercept
|
||||
* to determine lazy loading on partial objects.
|
||||
*/
|
||||
Set<String> includedProps;
|
||||
|
||||
/**
|
||||
* True if this node of the tree should have read only entity beans.
|
||||
*/
|
||||
boolean readOnly;
|
||||
|
||||
/**
|
||||
* set to false if the id field is not included.
|
||||
*/
|
||||
boolean includeId = true;
|
||||
|
||||
TableJoin[] tableJoins = new TableJoin[0];
|
||||
|
||||
/**
|
||||
* The bean properties in order.
|
||||
*/
|
||||
List<BeanProperty> propsList = new ArrayList<BeanProperty>();
|
||||
|
||||
/**
|
||||
* Maintain a list of property names to detect embedded bean additions.
|
||||
*/
|
||||
LinkedHashSet<String> propNames = new LinkedHashSet<String>();
|
||||
|
||||
public SqlTreeProperties() {
|
||||
|
||||
}
|
||||
|
||||
public boolean containsProperty(String propName){
|
||||
return propNames.contains(propName);
|
||||
}
|
||||
|
||||
public void add(BeanProperty[] props) {
|
||||
for (BeanProperty beanProperty : props) {
|
||||
propsList.add(beanProperty);
|
||||
}
|
||||
}
|
||||
|
||||
public void add(BeanProperty prop) {
|
||||
propsList.add(prop);
|
||||
propNames.add(prop.getName());
|
||||
|
||||
}
|
||||
|
||||
public BeanProperty[] getProps() {
|
||||
return propsList.toArray(new BeanProperty[propsList.size()]);
|
||||
}
|
||||
|
||||
public boolean isIncludeId() {
|
||||
return includeId;
|
||||
}
|
||||
|
||||
public void setIncludeId(boolean includeId) {
|
||||
this.includeId = includeId;
|
||||
}
|
||||
|
||||
public boolean isPartialObject() {
|
||||
return includedProps != null;
|
||||
}
|
||||
|
||||
public Set<String> getIncludedProperties() {
|
||||
return includedProps;
|
||||
}
|
||||
|
||||
public void setIncludedProperties(Set<String> includedProps) {
|
||||
this.includedProps = includedProps;
|
||||
}
|
||||
|
||||
public boolean isReadOnly() {
|
||||
return readOnly;
|
||||
}
|
||||
|
||||
public void setReadOnly(boolean readOnly) {
|
||||
this.readOnly = readOnly;
|
||||
}
|
||||
|
||||
public TableJoin[] getTableJoins() {
|
||||
return tableJoins;
|
||||
}
|
||||
|
||||
public void setTableJoins(TableJoin[] tableJoins) {
|
||||
this.tableJoins = tableJoins;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* Controls execution of the Orm and Raw Sql queries.
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.query;
|
||||
Reference in new issue
Block a user