No effective change - format only

This commit is contained in:
Robin Bygrave committed 2015-08-01 08:54:49 +12:00
1 parent f50b18556e
commit 4f2d669897
34 files changed
+1283 -1291

No files matched your search

@@ -8,39 +8,38 @@ import java.util.concurrent.TimeoutException;
/**
* A base object for query Future objects.
*
* @author rbygrave
*
* @param <T> the entity bean type
* @author rbygrave
*/
public abstract class BaseFuture<T> implements Future<T> {
protected 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();
}
protected final FutureTask<T> futureTask;
public T get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return futureTask.get(timeout, unit);
}
public BaseFuture(FutureTask<T> futureTask) {
this.futureTask = futureTask;
}
public boolean isCancelled() {
return futureTask.isCancelled();
}
public boolean cancel(boolean mayInterruptIfRunning) {
return futureTask.cancel(mayInterruptIfRunning);
}
public boolean isDone() {
return futureTask.isDone();
}
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();
}
}
@@ -19,147 +19,145 @@ import java.util.Map;
*/
public final class BeanCollectionWrapper {
/**
* Flag set if this builds a Map rather than a Collection.
*/
private final boolean isMap;
/**
* Flag set if this builds a Map rather than a Collection.
*/
private final boolean isMap;
/**
* The type.
*/
private final SpiQuery.Type queryType;
/**
* The type.
*/
private final SpiQuery.Type queryType;
/**
* A property name used as key for a Map.
*/
private final String mapKey;
/**
* A property name used as key for a Map.
*/
private final String mapKey;
/**
* The actual BeanCollection.
*/
private final BeanCollection<?> beanCollection;
/**
* The actual BeanCollection.
*/
private final BeanCollection<?> beanCollection;
/**
* Collection type of BeanCollection.
*/
private final Collection<Object> collection;
/**
* Collection type of BeanCollection.
*/
private final Collection<Object> collection;
/**
* Map type of BeanCollection.
*/
private final Map<Object,Object> map;
/**
* Map type of BeanCollection.
*/
private final Map<Object, Object> map;
/**
* The associated BeanDescriptor.
*/
private final BeanDescriptor<?> desc;
/**
* The associated BeanDescriptor.
*/
private final BeanDescriptor<?> desc;
/**
* The number of rows added.
*/
private int rowCount;
public BeanCollectionWrapper(RelationalQueryRequest request) {
/**
* The number of rows added.
*/
private int rowCount;
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);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Map<Object,Object> getMap(boolean isMap) {
return isMap ? (Map)beanCollection : null;
}
public BeanCollectionWrapper(RelationalQueryRequest request) {
@SuppressWarnings("unchecked")
private Collection<Object> getCollection(boolean isMap) {
return isMap ? null : (Collection<Object>)beanCollection ;
}
this.desc = null;
this.queryType = request.getQueryType();
this.mapKey = request.getQuery().getMapKey();
this.isMap = SpiQuery.Type.MAP.equals(queryType);
/**
* Return the underlying BeanCollection.
*/
public BeanCollection<?> getBeanCollection() {
return beanCollection;
}
this.beanCollection = createBeanCollection(queryType);
this.collection = getCollection(isMap);
this.map = getMap(isMap);
}
/**
* Create a BeanCollection of the correct type.
*/
private BeanCollection<?> createBeanCollection(SpiQuery.Type manyType) {
BeanCollectionParams p = new BeanCollectionParams(manyType);
return BeanCollectionFactory.create(p);
}
@SuppressWarnings({"unchecked", "rawtypes"})
private Map<Object, Object> getMap(boolean isMap) {
return isMap ? (Map) beanCollection : null;
}
/**
* Return true if this wraps a Map rather than a set or list.
*/
public boolean isMap() {
return isMap;
}
@SuppressWarnings("unchecked")
private Collection<Object> getCollection(boolean isMap) {
return isMap ? null : (Collection<Object>) beanCollection;
}
/**
* Return the number of rows added to this wrapper.
*/
public int size() {
return rowCount;
}
/**
* Return the underlying BeanCollection.
*/
public BeanCollection<?> getBeanCollection() {
return beanCollection;
}
/**
* Add the bean to the collection held in this wrapper.
*/
public void add(EntityBean bean) {
add(bean, beanCollection);
}
/**
* Create a BeanCollection of the correct type.
*/
private BeanCollection<?> createBeanCollection(SpiQuery.Type manyType) {
BeanCollectionParams p = new BeanCollectionParams(manyType);
return BeanCollectionFactory.create(p);
}
/**
* 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(EntityBean bean, Object collection) {
if (bean == null) {
return;
}
rowCount++;
if (isMap) {
Object keyValue;
if (mapKey != null) {
// use the value for the property
keyValue = desc.getValue(bean, mapKey);
} else {
// use the uniqueId for this
keyValue = desc.getId(bean);
}
/**
* Return true if this wraps a Map rather than a set or list.
*/
public boolean isMap() {
return isMap;
}
Map mapColl = (Map) collection;
mapColl.put(keyValue, bean);
} else {
((Collection) collection).add(bean);
}
}
/**
* Return the number of rows added to this wrapper.
*/
public int size() {
return rowCount;
}
/**
* Specifically add to a Collection.
*/
public void addToCollection(Object bean) {
collection.add(bean);
}
/**
* Add the bean to the collection held in this wrapper.
*/
public void add(EntityBean bean) {
add(bean, beanCollection);
}
/**
* Specifically add to this as a Map with a known key.
*/
public void addToMap(Object bean, Object key) {
map.put(key, bean);
}
/**
* 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(EntityBean bean, Object collection) {
if (bean == null) {
return;
}
rowCount++;
if (isMap) {
Object keyValue;
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);
}
}
@@ -135,7 +135,7 @@ public class CQueryBuilder {
query.setMaxRows(0);
ManyWhereJoins manyWhereJoins = query.getManyWhereJoins();
boolean hasMany = manyWhereJoins.isHasMany();
if (manyWhereJoins.isSelectId()) {
// just select the id property
@@ -271,7 +271,7 @@ public class CQueryBuilder {
ElPropertyValue el = descriptor.getElGetValue(propertyName);
if (el == null) {
throw new PersistenceException("Property [" + propertyName + "] not found on " + descriptor.getFullName());
throw new PersistenceException("Property [" + propertyName + "] not found on " + descriptor.getFullName());
} else {
BeanProperty beanProperty = el.getBeanProperty();
if (beanProperty.isId() || beanProperty.isDiscriminator()) {
@@ -326,7 +326,7 @@ public class CQueryBuilder {
StringBuilder sb = new StringBuilder(500);
String dbOrderBy = predicates.getDbOrderBy();
if (selectClause != null) {
sb.append(selectClause);
@@ -442,7 +442,7 @@ public class CQueryBuilder {
// just remove the ASC and DESC keywords
return dbOrderBy.replaceAll("(?i)\\b asc\\b|\\b desc\\b", "");
}
private boolean isEmpty(String s) {
return s == null || s.length() == 0;
}
@@ -13,136 +13,136 @@ import com.avaje.ebeaninternal.server.util.BindParamsParser;
public class CQueryBuilderRawSql {
private final SqlLimiter sqlLimiter;
private final DatabasePlatform dbPlatform;
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 == null) {
// this is a ResultSet based RawSql query - just use some placeholder for the SQL
return new SqlLimitResponse("--ResultSetBasedRawSql", false);
}
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);
}
CQueryBuilderRawSql(SqlLimiter sqlLimiter, DatabasePlatform dbPlatform) {
this.sqlLimiter = sqlLimiter;
this.dbPlatform = dbPlatform;
}
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(" ");
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(" ");
/**
* Build the full SQL Select statement for the request.
*/
public SqlLimitResponse buildSql(OrmQueryRequest<?> request, CQueryPredicates predicates, RawSql.Sql rsql) {
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)) {
if (sql.isAndWhereExpr()) {
sb.append(" and ");
} else {
sb.append(" where ");
}
sb.append(dynamicWhere);
sb.append(" ");
}
String preHaving = sql.getPreHaving();
if (!isEmpty(preHaving)) {
sb.append(preHaving);
sb.append(" ");
}
String dbHaving = predicates.getDbHaving();
if (!isEmpty(dbHaving)) {
sb.append(" ");
if (sql.isAndHavingExpr()) {
sb.append("and ");
} else {
sb.append("having ");
}
sb.append(dbHaving);
sb.append(" ");
}
if (!isEmpty(orderBy)) {
sb.append(" ").append(sql.getOrderByPrefix()).append(" ").append(orderBy);
}
return sb.toString().trim();
}
private boolean isEmpty(String s) {
return s == null || s.length() == 0;
if (rsql == null) {
// this is a ResultSet based RawSql query - just use some placeholder for the SQL
return new SqlLimitResponse("--ResultSetBasedRawSql", false);
}
private String getOrderBy(CQueryPredicates predicates, RawSql.Sql sql) {
String orderBy = predicates.getDbOrderBy();
if (orderBy != null) {
return orderBy;
} else {
return sql.getOrderBy();
}
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(" ");
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)) {
if (sql.isAndWhereExpr()) {
sb.append(" and ");
} else {
sb.append(" where ");
}
sb.append(dynamicWhere);
sb.append(" ");
}
String preHaving = sql.getPreHaving();
if (!isEmpty(preHaving)) {
sb.append(preHaving);
sb.append(" ");
}
String dbHaving = predicates.getDbHaving();
if (!isEmpty(dbHaving)) {
sb.append(" ");
if (sql.isAndHavingExpr()) {
sb.append("and ");
} else {
sb.append("having ");
}
sb.append(dbHaving);
sb.append(" ");
}
if (!isEmpty(orderBy)) {
sb.append(" ").append(sql.getOrderByPrefix()).append(" ").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();
}
}
}
@@ -43,7 +43,7 @@ public class CQueryEngine {
private final CQueryHistorySupport historySupport;
public CQueryEngine(DatabasePlatform dbPlatform, Binder binder, Map<String,String> asOfTableMapping, String asOfSysPeriod) {
public CQueryEngine(DatabasePlatform dbPlatform, Binder binder, Map<String, String> asOfTableMapping, String asOfSysPeriod) {
this.forwardOnlyHintOnFindIterate = dbPlatform.isForwardOnlyHintOnFindIterate();
this.historySupport = new CQueryHistorySupport(dbPlatform.getHistorySupport(), asOfTableMapping, asOfSysPeriod);
this.queryBuilder = new CQueryBuilder(dbPlatform, binder, historySupport);
@@ -17,7 +17,7 @@ public class CQueryHistorySupport {
/**
* The mapping of base tables to their matching 'with history' views.
*/
private final Map<String,String> asOfTableMap;
private final Map<String, String> asOfTableMap;
/**
* The sys period column.
@@ -16,62 +16,62 @@ import com.avaje.ebeaninternal.server.el.ElPropertyValue;
*/
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();
private final BeanDescriptor<?> desc;
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 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;
}
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();
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();
}
}
@@ -37,33 +37,33 @@ import com.avaje.ebeaninternal.server.type.RsetDataReader;
public class CQueryPlan {
private final SpiEbeanServer server;
private final boolean autofetchTuned;
private final HashQueryPlan hash;
private final boolean rawSql;
private final boolean rowNumberIncluded;
private final boolean autofetchTuned;
private final String sql;
private final HashQueryPlan hash;
private final String logWhereSql;
private final boolean rawSql;
private final SqlTree sqlTree;
private final boolean rowNumberIncluded;
/**
* Encrypted properties required additional binding.
*/
private final BeanProperty[] encryptedProps;
private final CQueryPlanStats stats;
private final String sql;
private final String logWhereSql;
private final SqlTree sqlTree;
/**
* Encrypted properties required additional binding.
*/
private final BeanProperty[] encryptedProps;
private final CQueryPlanStats stats;
private final Class<?> beanType;
/**
* Create a query plan based on a OrmQueryRequest.
*/
/**
* Create a query plan based on a OrmQueryRequest.
*/
public CQueryPlan(OrmQueryRequest<?> request, SqlLimitResponse sqlRes, SqlTree sqlTree, boolean rawSql, String logWhereSql) {
this.server = request.getServer();
@@ -84,38 +84,38 @@ public class CQueryPlan {
this.encryptedProps = sqlTree.getEncryptedProps();
}
/**
* Create a query plan for a raw sql query.
*/
public CQueryPlan(OrmQueryRequest<?> request, String sql, SqlTree sqlTree,
boolean rawSql, boolean rowNumberIncluded, String logWhereSql) {
this.server = request.getServer();
this.beanType = request.getBeanDescriptor().getBeanType();
this.stats = new CQueryPlanStats(this, server.isCollectQueryOrigins());
this.hash = buildHash(sql, rawSql, rowNumberIncluded, logWhereSql);
this.autofetchTuned = false;
this.sql = sql;
this.sqlTree = sqlTree;
this.rawSql = rawSql;
this.rowNumberIncluded = rowNumberIncluded;
this.logWhereSql = logWhereSql;
this.encryptedProps = sqlTree.getEncryptedProps();
}
/**
* Create a query plan for a raw sql query.
*/
public CQueryPlan(OrmQueryRequest<?> request, String sql, SqlTree sqlTree,
boolean rawSql, boolean rowNumberIncluded, String logWhereSql) {
this.server = request.getServer();
this.beanType = request.getBeanDescriptor().getBeanType();
this.stats = new CQueryPlanStats(this, server.isCollectQueryOrigins());
this.hash = buildHash(sql, rawSql, rowNumberIncluded, logWhereSql);
this.autofetchTuned = false;
this.sql = sql;
this.sqlTree = sqlTree;
this.rawSql = rawSql;
this.rowNumberIncluded = rowNumberIncluded;
this.logWhereSql = logWhereSql;
this.encryptedProps = sqlTree.getEncryptedProps();
}
private HashQueryPlan buildHash(String sql, boolean rawSql, boolean rowNumberIncluded, String logWhereSql) {
HashQueryPlanBuilder builder = new HashQueryPlanBuilder();
builder.add(sql).add(rawSql).add(rowNumberIncluded).add(logWhereSql);
builder.addRawSql(sql);
return builder.build();
}
HashQueryPlanBuilder builder = new HashQueryPlanBuilder();
builder.add(sql).add(rawSql).add(rowNumberIncluded).add(logWhereSql);
builder.addRawSql(sql);
return builder.build();
}
public String toString() {
return beanType+" hash:"+hash;
}
public Class<?> getBeanType() {
public String toString() {
return beanType + " hash:" + hash;
}
public Class<?> getBeanType() {
return beanType;
}
@@ -132,70 +132,70 @@ public class CQueryPlan {
}
}
}
public boolean isAutofetchTuned() {
return autofetchTuned;
}
public HashQueryPlan getHash() {
return hash;
}
public boolean isAutofetchTuned() {
return autofetchTuned;
}
public String getSql() {
return sql;
}
public HashQueryPlan getHash() {
return hash;
}
public SqlTree getSqlTree() {
return sqlTree;
}
public String getSql() {
return sql;
}
public boolean isRawSql() {
return rawSql;
}
public SqlTree getSqlTree() {
return sqlTree;
}
public boolean isRowNumberIncluded() {
return rowNumberIncluded;
}
public boolean isRawSql() {
return rawSql;
}
public String getLogWhereSql() {
return logWhereSql;
}
public boolean isRowNumberIncluded() {
return rowNumberIncluded;
}
/**
* Reset the query statistics.
*/
public void resetStatistics() {
stats.reset();
}
/**
* Register an execution time against this query plan;
*/
public void executionTime(long loadedBeanCount, long timeMicros, ObjectGraphNode objectGraphNode) {
public String getLogWhereSql() {
return logWhereSql;
}
stats.add(loadedBeanCount, timeMicros, objectGraphNode);
if (objectGraphNode != null) {
// collect stats based on objectGraphNode for lazy loading reporting
server.collectQueryStats(objectGraphNode, loadedBeanCount, timeMicros);
}
}
/**
* Reset the query statistics.
*/
public void resetStatistics() {
stats.reset();
}
/**
* Register an execution time against this query plan;
*/
public void executionTime(long loadedBeanCount, long timeMicros, ObjectGraphNode objectGraphNode) {
stats.add(loadedBeanCount, timeMicros, objectGraphNode);
if (objectGraphNode != null) {
// collect stats based on objectGraphNode for lazy loading reporting
server.collectQueryStats(objectGraphNode, loadedBeanCount, timeMicros);
}
}
public Snapshot getSnapshot(boolean reset) {
return stats.getSnapshot(reset);
}
/**
* Return the current query statistics.
*/
public CQueryPlanStats getQueryStats() {
return stats;
}
/**
* Return the time this query plan was last used.
*/
public long getLastQueryTime(){
return stats.getLastQueryTime();
}
/**
* Return the current query statistics.
*/
public CQueryPlanStats getQueryStats() {
return stats;
}
/**
* Return the time this query plan was last used.
*/
public long getLastQueryTime() {
return stats.getLastQueryTime();
}
}
@@ -55,11 +55,11 @@ public class CQueryPlanRawSql extends CQueryPlan {
// check and handle the case where a discriminator column for
// an associated bean is in the raw SQL but is mapped columnIgnore
for (int i = 0; i <indexPositions.length ; i++) {
for (int i = 0; i < indexPositions.length; i++) {
if (indexPositions[i] == 0) {
if (i < indexPositions.length) {
// expect discriminator column to immediately proceed id column
indexPositions[i] = indexPositions[i+1] - 1;
indexPositions[i] = indexPositions[i + 1] - 1;
}
}
}
@@ -14,12 +14,12 @@ import com.avaje.ebeaninternal.server.util.LongAdder;
import com.avaje.ebeaninternal.server.util.LongMaxUpdater;
/**
* Statistics for a specific query plan that can accumulate.
* Statistics for a specific query plan that can accumulate.
*/
public final class CQueryPlanStats {
private final CQueryPlan queryPlan;
private final LongAdder count = new LongAdder();
private final LongAdder totalTime = new LongAdder();
@@ -37,25 +37,25 @@ public final class CQueryPlanStats {
/**
* Construct for a given query plan.
*/
public CQueryPlanStats(CQueryPlan queryPlan, boolean collectQueryOrigins) {
this.queryPlan = queryPlan;
this.origins = !collectQueryOrigins ? null : new ConcurrentHashMap<ObjectGraphNode, LongAdder>();
}
public CQueryPlanStats(CQueryPlan queryPlan, boolean collectQueryOrigins) {
/**
* Add a query execution to the statistics.
*/
public void add(long loadedBeanCount, long timeMicros, ObjectGraphNode objectGraphNode) {
count.increment();
totalBeans.add(loadedBeanCount);
totalTime.add(timeMicros);
maxTime.update(timeMicros);
this.queryPlan = queryPlan;
this.origins = !collectQueryOrigins ? null : new ConcurrentHashMap<ObjectGraphNode, LongAdder>();
}
// not safe but should be atomic
/**
* Add a query execution to the statistics.
*/
public void add(long loadedBeanCount, long timeMicros, ObjectGraphNode objectGraphNode) {
count.increment();
totalBeans.add(loadedBeanCount);
totalTime.add(timeMicros);
maxTime.update(timeMicros);
// not safe but should be atomic
lastQueryTime = System.currentTimeMillis();
if (origins != null && objectGraphNode != null) {
// Maintain the origin points this query fires from
// with a simple counter
@@ -65,88 +65,88 @@ public final class CQueryPlanStats {
// to live with that. Don't want to lock/synchronize etc
counter = new LongAdder();
origins.put(objectGraphNode, counter);
}
}
counter.increment();
}
}
/**
* Reset the internal statistics counters.
*/
public void reset() {
// Racey but near enough for our purposes as we don't want locks
count.reset();
totalBeans.reset();
totalTime.reset();
maxTime.reset();
startTime.set(System.currentTimeMillis());
if (origins != null) {
for (LongAdder counter : origins.values()) {
}
/**
* Reset the internal statistics counters.
*/
public void reset() {
// Racey but near enough for our purposes as we don't want locks
count.reset();
totalBeans.reset();
totalTime.reset();
maxTime.reset();
startTime.set(System.currentTimeMillis());
if (origins != null) {
for (LongAdder counter : origins.values()) {
counter.reset();
}
}
}
/**
* Return the last time this query was executed.
*/
public long getLastQueryTime() {
return lastQueryTime;
}
/**
* Return a Snapshot of the query execution statistics potentially resetting the internal counters.
*/
public Snapshot getSnapshot(boolean reset) {
List<MetaQueryPlanOriginCount> origins = getOrigins(reset);
// not guaranteed to be consistent due to time gaps between getting each value out of LongAdders but can live with that
// relative to the cost of making sure count and totalTime etc are all guaranteed to be consistent
if (reset) {
return new Snapshot(queryPlan, count.sumThenReset(), totalTime.sumThenReset(), totalBeans.sumThenReset(), maxTime.maxThenReset(), startTime.getAndSet(System.currentTimeMillis()), lastQueryTime, origins);
}
return new Snapshot(queryPlan, count.sum(), totalTime.sum(), totalBeans.sum(), maxTime.max(), startTime.get(), lastQueryTime, origins);
}
/**
* Return the list/snapshot of the origins and their counter value.
*/
private List<MetaQueryPlanOriginCount> getOrigins(boolean reset) {
if (origins == null) {
return Collections.emptyList();
}
List<MetaQueryPlanOriginCount> list = new ArrayList<MetaQueryPlanOriginCount>();
for (Entry<ObjectGraphNode, LongAdder> entry : origins.entrySet()) {
if (reset) {
list.add(new OriginSnapshot(entry.getKey(), entry.getValue().sumThenReset()));
} else {
list.add(new OriginSnapshot(entry.getKey(), entry.getValue().sum()));
}
}
return list;
}
/**
* Snapshot of the origin ObjectGraphNode and counter value.
*/
private static class OriginSnapshot implements MetaQueryPlanOriginCount {
private final ObjectGraphNode objectGraphNode;
private final long count;
}
/**
* Return the last time this query was executed.
*/
public long getLastQueryTime() {
return lastQueryTime;
}
/**
* Return a Snapshot of the query execution statistics potentially resetting the internal counters.
*/
public Snapshot getSnapshot(boolean reset) {
List<MetaQueryPlanOriginCount> origins = getOrigins(reset);
// not guaranteed to be consistent due to time gaps between getting each value out of LongAdders but can live with that
// relative to the cost of making sure count and totalTime etc are all guaranteed to be consistent
if (reset) {
return new Snapshot(queryPlan, count.sumThenReset(), totalTime.sumThenReset(), totalBeans.sumThenReset(), maxTime.maxThenReset(), startTime.getAndSet(System.currentTimeMillis()), lastQueryTime, origins);
}
return new Snapshot(queryPlan, count.sum(), totalTime.sum(), totalBeans.sum(), maxTime.max(), startTime.get(), lastQueryTime, origins);
}
/**
* Return the list/snapshot of the origins and their counter value.
*/
private List<MetaQueryPlanOriginCount> getOrigins(boolean reset) {
if (origins == null) {
return Collections.emptyList();
}
List<MetaQueryPlanOriginCount> list = new ArrayList<MetaQueryPlanOriginCount>();
for (Entry<ObjectGraphNode, LongAdder> entry : origins.entrySet()) {
if (reset) {
list.add(new OriginSnapshot(entry.getKey(), entry.getValue().sumThenReset()));
} else {
list.add(new OriginSnapshot(entry.getKey(), entry.getValue().sum()));
}
}
return list;
}
/**
* Snapshot of the origin ObjectGraphNode and counter value.
*/
private static class OriginSnapshot implements MetaQueryPlanOriginCount {
private final ObjectGraphNode objectGraphNode;
private final long count;
public OriginSnapshot(ObjectGraphNode objectGraphNode, long count) {
this.objectGraphNode = objectGraphNode;
this.count = count;
}
public String toString() {
return "node["+objectGraphNode+"] count["+count+"]";
return "node[" + objectGraphNode + "] count[" + count + "]";
}
@Override
public ObjectGraphNode getObjectGraphNode() {
return objectGraphNode;
@@ -155,26 +155,26 @@ public final class CQueryPlanStats {
@Override
public long getCount() {
return count;
}
}
/**
* A snapshot of the current statistics for a query plan.
*/
public static class Snapshot implements MetaQueryPlanStatistic {
private final CQueryPlan queryPlan;
private final long count;
private final long totalTime;
private final long totalBeans;
private final long maxTime;
private final long startTime;
private final long lastQueryTime;
}
}
/**
* A snapshot of the current statistics for a query plan.
*/
public static class Snapshot implements MetaQueryPlanStatistic {
private final CQueryPlan queryPlan;
private final long count;
private final long totalTime;
private final long totalBeans;
private final long maxTime;
private final long startTime;
private final long lastQueryTime;
private final List<MetaQueryPlanOriginCount> origins;
public Snapshot(CQueryPlan queryPlan, long count, long totalTime, long totalBeans, long maxTime, long startTime, long lastQueryTime,
List<MetaQueryPlanOriginCount> origins) {
public Snapshot(CQueryPlan queryPlan, long count, long totalTime, long totalBeans, long maxTime, long startTime, long lastQueryTime,
List<MetaQueryPlanOriginCount> origins) {
this.queryPlan = queryPlan;
this.count = count;
this.totalTime = totalTime;
@@ -184,17 +184,17 @@ public final class CQueryPlanStats {
this.lastQueryTime = lastQueryTime;
this.origins = origins;
}
public String toString() {
return queryPlan + " count:" + count + " time:" + totalTime + " maxTime:" + maxTime + " beans:" + totalBeans
+ " start:" + startTime + " lastQuery:" + lastQueryTime + " origins:" + origins;
}
@Override
public Class<?> getBeanType() {
return queryPlan.getBeanType();
}
@Override
public long getExecutionCount() {
return count;
@@ -250,12 +250,12 @@ public final class CQueryPlanStats {
public long getAvgLoadedBeans() {
return count < 1 ? 0 : totalBeans / count;
}
@Override
public List<MetaQueryPlanOriginCount> getOrigins() {
return origins;
}
}
}
}
@@ -116,7 +116,7 @@ public class CQueryPredicates {
* Includes from where and order by clauses.
*/
private Set<String> predicateIncludes;
private Set<String> orderByIncludes;
public CQueryPredicates(Binder binder, OrmQueryRequest<?> request) {
@@ -330,7 +330,7 @@ public class CQueryPredicates {
if (logicalOrderBy != null) {
dbOrderBy = deployParser.parse(logicalOrderBy);
}
// create a copy of the includes required to support the orderBy
orderByIncludes = new HashSet<String>(deployParser.getIncludes());
@@ -19,147 +19,147 @@ import java.sql.SQLException;
*/
public class CQueryRowCount {
private static final Logger logger = LoggerFactory.getLogger(CQueryRowCount.class);
private static final Logger logger = LoggerFactory.getLogger(CQueryRowCount.class);
/**
* The overall find request wrapper object.
*/
private final OrmQueryRequest<?> request;
/**
* The overall find request wrapper object.
*/
private final OrmQueryRequest<?> request;
private final BeanDescriptor<?> desc;
private final BeanDescriptor<?> desc;
private final SpiQuery<?> query;
private final SpiQuery<?> query;
/**
* Where clause predicates.
*/
private final CQueryPredicates predicates;
/**
* Where clause predicates.
*/
private final CQueryPredicates predicates;
/**
* The final sql that is generated.
*/
private final String sql;
/**
* The final sql that is generated.
*/
private final String sql;
/**
* The resultSet that is read and converted to objects.
*/
private ResultSet rset;
/**
* The resultSet that is read and converted to objects.
*/
private ResultSet rset;
/**
* The statement used to create the resultSet.
*/
private PreparedStatement pstmt;
/**
* The statement used to create the resultSet.
*/
private PreparedStatement pstmt;
private String bindLog;
private String bindLog;
private int executionTimeMicros;
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;
private int rowCount;
query.setGeneratedSql(sql);
/**
* 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;
this.desc = request.getBeanDescriptor();
this.predicates = predicates;
query.setGeneratedSql(sql);
}
/**
* Return a summary description of this query.
*/
public String getSummary() {
StringBuilder sb = new StringBuilder(80);
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();
}
this.desc = request.getBeanDescriptor();
this.predicates = predicates;
/**
* Return the bind log.
*/
public String getBindLog() {
return bindLog;
}
/**
* Return a summary description of this query.
*/
public String getSummary() {
StringBuilder sb = new StringBuilder(80);
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;
}
/**
* Execute the query returning the row count.
*/
public int findRowCount() throws SQLException {
long 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();
}
}
/**
* Return the generated sql.
*/
public String getGeneratedSql() {
return sql;
}
/**
* 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.error(null, e);
}
try {
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
} catch (SQLException e) {
logger.error(null, e);
}
}
/**
* Execute the query returning the row count.
*/
public int findRowCount() throws SQLException {
long 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.error(null, e);
}
try {
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
} catch (SQLException e) {
logger.error(null, e);
}
}
}
@@ -6,24 +6,23 @@ import com.avaje.ebeaninternal.api.SpiQuery;
/**
* Base object for making query execution into Callable's.
*
* @author rbygrave
*
* @param <T> the entity bean type
* @author rbygrave
*/
public abstract class CallableQuery<T> {
protected final SpiQuery<T> query;
protected final SpiEbeanServer server;
protected final Transaction transaction;
public CallableQuery(SpiEbeanServer server, SpiQuery<T> query, Transaction t) {
this.server = server;
this.query = query;
this.transaction = t;
}
protected final SpiQuery<T> query;
protected final SpiEbeanServer server;
protected final Transaction transaction;
public CallableQuery(SpiEbeanServer server, SpiQuery<T> query, Transaction t) {
this.server = server;
this.query = query;
this.transaction = t;
}
public SpiQuery<T> getQuery() {
return query;
@@ -32,5 +31,5 @@ public abstract class CallableQuery<T> {
public Transaction getTransaction() {
return transaction;
}
}
@@ -14,23 +14,23 @@ import com.avaje.ebeaninternal.api.SpiQuery;
*/
public class CallableQueryIds<T> extends CallableQuery<T> implements Callable<List<Object>> {
public CallableQueryIds(SpiEbeanServer server, SpiQuery<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)
try {
return server.findIdsWithCopy(query, transaction);
} finally {
transaction.end();
}
}
public CallableQueryIds(SpiEbeanServer server, SpiQuery<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)
try {
return server.findIdsWithCopy(query, transaction);
} finally {
transaction.end();
}
}
}
@@ -14,23 +14,22 @@ import com.avaje.ebeaninternal.api.SpiQuery;
*/
public class CallableQueryList<T> extends CallableQuery<T> implements Callable<List<T>> {
public CallableQueryList(SpiEbeanServer server, SpiQuery<T> query, Transaction t) {
super(server, query, t);
}
/**
* Execute the query returning the resulting List.
*/
public List<T> call() throws Exception {
try {
return server.findList(query, transaction);
} finally {
// cleanup the underlying connection
transaction.end();
}
}
public CallableQueryList(SpiEbeanServer server, SpiQuery<T> query, Transaction t) {
super(server, query, t);
}
/**
* Execute the query returning the resulting List.
*/
public List<T> call() throws Exception {
try {
return server.findList(query, transaction);
} finally {
// cleanup the underlying connection
transaction.end();
}
}
}
@@ -8,9 +8,8 @@ import com.avaje.ebeaninternal.api.SpiQuery;
/**
* Represent the findRowCount query as a Callable.
*
* @param <T>
* the entity bean type
*
* @param <T> the entity bean type
*/
public class CallableQueryRowCount<T> extends CallableQuery<T> implements Callable<Integer> {
@@ -13,29 +13,28 @@ import com.avaje.ebean.Transaction;
*/
public class CallableSqlQueryList implements Callable<List<SqlRow>> {
private final SqlQuery query;
private final EbeanServer server;
private final Transaction transaction;
public CallableSqlQueryList(EbeanServer server, SqlQuery query, Transaction t) {
this.server = server;
this.query = query;
this.transaction = t;
}
private final SqlQuery query;
private final EbeanServer server;
private final Transaction transaction;
public CallableSqlQueryList(EbeanServer server, SqlQuery query, Transaction t) {
this.server = server;
this.query = query;
this.transaction = t;
}
/**
* Execute the query returning the resulting list.
*/
public List<SqlRow> call() throws Exception {
try {
return server.findList(query, transaction);
} finally {
transaction.end();
}
}
/**
* Execute the query returning the resulting list.
*/
public List<SqlRow> call() throws Exception {
try {
return server.findList(query, transaction);
} finally {
transaction.end();
}
}
}
@@ -9,11 +9,11 @@ package com.avaje.ebeaninternal.server.query;
*/
public interface CancelableQuery {
/**
* Cancel the query.
* <p>
* For JDBC this translates to calling cancel on the PreparedStatement.
* </p>
*/
void cancel();
/**
* Cancel the query.
* <p>
* For JDBC this translates to calling cancel on the PreparedStatement.
* </p>
*/
void cancel();
}
@@ -53,7 +53,7 @@ public class DefaultDbSqlContext implements DbSqlContext {
* Construct for SELECT clause (with column alias settings).
*/
public DefaultDbSqlContext(SqlTreeAlias alias, String tableAliasPlaceHolder,
String columnAliasPrefix, boolean alwaysUseColumnAlias, CQueryHistorySupport historySupport) {
String columnAliasPrefix, boolean alwaysUseColumnAlias, CQueryHistorySupport historySupport) {
this.alias = alias;
this.tableAliasPlaceHolder = tableAliasPlaceHolder;
@@ -139,11 +139,11 @@ public class DefaultDbSqlContext implements DbSqlContext {
// add on any inheritance where clause
if (inheritance != null && inheritance.length() > 0){
sb.append(" and ");
sb.append(a2);
sb.append(".");
sb.append(inheritance);
if (inheritance != null && inheritance.length() > 0) {
sb.append(" and ");
sb.append(a2);
sb.append(".");
sb.append(inheritance);
}
sb.append(" ");
@@ -89,7 +89,7 @@ public class DefaultOrmQueryEngine implements OrmQueryEngine {
}
SpiQuery<T> query = request.getQuery();
if (query.isLoadBeanCache()) {
// load the individual beans into the bean cache
BeanDescriptor<T> descriptor = request.getBeanDescriptor();
@@ -26,206 +26,206 @@ import java.util.ArrayList;
*/
public class DefaultRelationalQueryEngine implements RelationalQueryEngine {
private static final Logger logger = LoggerFactory.getLogger(DefaultRelationalQueryEngine.class);
private static final Logger logger = LoggerFactory.getLogger(DefaultRelationalQueryEngine.class);
private static final int GLOBAL_ROW_LIMIT = Integer.valueOf(System.getProperty("ebean.query.globallimit","1000000"));
private static final int GLOBAL_ROW_LIMIT = Integer.valueOf(System.getProperty("ebean.query.globallimit", "1000000"));
private final Binder binder;
private final String dbTrueValue;
private final Binder binder;
public DefaultRelationalQueryEngine(Binder binder, String dbTrueValue) {
this.binder = binder;
this.dbTrueValue = dbTrueValue == null ? "true" : dbTrueValue;
}
private final String dbTrueValue;
public Object findMany(RelationalQueryRequest request) {
public DefaultRelationalQueryEngine(Binder binder, String dbTrueValue) {
this.binder = binder;
this.dbTrueValue = dbTrueValue == null ? "true" : dbTrueValue;
}
SpiSqlQuery query = request.getQuery();
public Object findMany(RelationalQueryRequest request) {
long startTime = System.currentTimeMillis();
SpiSqlQuery query = request.getQuery();
SpiTransaction t = request.getTransaction();
Connection conn = t.getInternalConnection();
ResultSet rset = null;
PreparedStatement pstmt = null;
long startTime = System.currentTimeMillis();
String sql = query.getQuery();
SpiTransaction t = request.getTransaction();
Connection conn = t.getInternalConnection();
ResultSet rset = null;
PreparedStatement pstmt = null;
BindParams bindParams = query.getBindParams();
String sql = query.getQuery();
if (!bindParams.isEmpty()) {
// convert any named parameters if required
sql = BindParamsParser.parse(bindParams, sql);
}
BindParams bindParams = query.getBindParams();
try {
if (!bindParams.isEmpty()) {
// convert any named parameters if required
sql = BindParamsParser.parse(bindParams, sql);
}
String bindLog = "";
String[] propNames;
synchronized (query) {
if (query.isCancelled()){
logger.trace("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 logSql = sql;
if (TransactionManager.SQL_LOGGER.isTraceEnabled()) {
logSql = Str.add(logSql, "; --bind(", bindLog, ")");
}
t.logSql(logSql);
}
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;
try {
// determine the maxRows limit
int maxRows = GLOBAL_ROW_LIMIT;
if (query.getMaxRows() >= 1) {
maxRows = query.getMaxRows();
}
String bindLog = "";
String[] propNames;
int loadRowCount = 0;
synchronized (query) {
if (query.isCancelled()) {
logger.trace("Query already cancelled");
return null;
}
SqlQueryListener listener = query.getListener();
// synchronise for query.cancel() support
pstmt = conn.prepareStatement(sql);
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(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...
break;
}
}
}
if (query.getTimeout() > 0) {
pstmt.setQueryTimeout(query.getTimeout());
}
if (query.getBufferFetchSizeHint() > 0) {
pstmt.setFetchSize(query.getBufferFetchSizeHint());
}
BeanCollection<?> beanColl = wrapper.getBeanCollection();
if (!bindParams.isEmpty()) {
bindLog = binder.bind(bindParams, new DataBind(pstmt));
}
if (request.isLogSummary()) {
long exeTime = System.currentTimeMillis() - startTime;
String msg = "SqlQuery rows[" + loadRowCount + "] time[" + exeTime + "] bind[" + bindLog + "]";
t.logSummary(msg);
}
if (query.isCancelled()){
logger.debug("Query was cancelled during execution rows:"+loadRowCount);
}
return beanColl;
if (request.isLogSql()) {
String logSql = sql;
if (TransactionManager.SQL_LOGGER.isTraceEnabled()) {
logSql = Str.add(logSql, "; --bind(", bindLog, ")");
}
t.logSql(logSql);
}
} catch (Exception e) {
String m = Message.msg("fetch.error", e.getMessage(), sql);
throw new PersistenceException(m, e);
rset = pstmt.executeQuery();
} finally {
try {
if (rset != null) {
rset.close();
}
} catch (SQLException e) {
logger.error(null, e);
}
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
logger.error(null, e);
}
}
}
propNames = getPropertyNames(rset);
}
/**
* Build the list of property names.
*/
protected String[] getPropertyNames(ResultSet rset) throws SQLException {
// 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;
ArrayList<String> propNames = new ArrayList<String>();
// determine the maxRows limit
int maxRows = GLOBAL_ROW_LIMIT;
if (query.getMaxRows() >= 1) {
maxRows = query.getMaxRows();
}
ResultSetMetaData rsmd = rset.getMetaData();
int loadRowCount = 0;
int columnsPlusOne = rsmd.getColumnCount()+1;
SqlQueryListener listener = query.getListener();
for (int i = 1; i < columnsPlusOne; i++) {
String columnName = rsmd.getColumnLabel(i);
// will convert columnName to lower case
propNames.add(columnName);
}
BeanCollectionWrapper wrapper = new BeanCollectionWrapper(request);
boolean isMap = wrapper.isMap();
String mapKey = query.getMapKey();
return propNames.toArray(new String[propNames.size()]);
}
SqlRow bean = null;
/**
* Read the row from the ResultSet and return as a MapBean.
*/
protected SqlRow readRow(ResultSet rset, String[] propNames, int initialCapacity) throws SQLException {
while (rset.next()) {
synchronized (query) {
// synchronise for query.cancel() support
if (!query.isCancelled()) {
bean = readRow(rset, propNames, estimateCapacity);
}
}
if (bean != null) {
// bean can be null if query cancelled
if (listener != null) {
listener.process(bean);
// 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;
} else {
if (isMap) {
Object keyValue = bean.get(mapKey);
wrapper.addToMap(bean, keyValue);
} else {
wrapper.addToCollection(bean);
}
}
for (int i = 0; i < propNames.length; i++) {
index++;
Object value = rset.getObject(index);
bean.set(propNames[i], value);
}
loadRowCount++;
return bean;
if (loadRowCount == maxRows) {
// break, as we have hit the max rows to fetch...
break;
}
}
}
}
BeanCollection<?> beanColl = wrapper.getBeanCollection();
if (request.isLogSummary()) {
long exeTime = System.currentTimeMillis() - startTime;
String msg = "SqlQuery rows[" + loadRowCount + "] time[" + exeTime + "] bind[" + bindLog + "]";
t.logSummary(msg);
}
if (query.isCancelled()) {
logger.debug("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 {
try {
if (rset != null) {
rset.close();
}
} catch (SQLException e) {
logger.error(null, e);
}
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
logger.error(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 propNames.toArray(new String[propNames.size()]);
}
/**
* Read the row from the ResultSet and return as a MapBean.
*/
protected SqlRow readRow(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;
}
}
@@ -31,157 +31,157 @@ import com.avaje.ebeaninternal.server.core.BasicTypeConverter;
*/
public class DefaultSqlRow implements SqlRow {
static final long serialVersionUID = -3120927797041336242L;
static final long serialVersionUID = -3120927797041336242L;
private final String dbTrueValue;
/**
* The underlying map of property data.
*/
final Map<String, Object> map;
private final String 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;
}
/**
* The underlying map of property data.
*/
final Map<String, Object> map;
public Iterator<String> keys() {
return map.keySet().iterator();
}
/**
* 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 Object remove(Object name) {
name = ((String) name).toLowerCase();
return map.remove(name);
}
public Iterator<String> keys() {
return map.keySet().iterator();
}
public Object get(Object name) {
name = ((String) name).toLowerCase();
return map.get(name);
}
public Object remove(Object name) {
name = ((String) name).toLowerCase();
return map.remove(name);
}
public Object put(String name, Object value) {
return setInternal(name, value);
}
public Object get(Object name) {
name = ((String) name).toLowerCase();
return map.get(name);
}
public Object set(String name, Object value) {
return setInternal(name, value);
}
public Object put(String name, Object value) {
return setInternal(name, value);
}
private Object setInternal(String name, Object newValue) {
// MapBean properties are always lowercase
name = name.toLowerCase();
public Object set(String name, Object value) {
return setInternal(name, value);
}
// valueList = null;
return map.put(name, newValue);
}
private Object setInternal(String name, Object newValue) {
// MapBean properties are always lowercase
name = name.toLowerCase();
public UUID getUUID(String name) {
Object val = get(name);
return BasicTypeConverter.toUUID(val);
}
// valueList = null;
return map.put(name, newValue);
}
public Boolean getBoolean(String name) {
Object val = get(name);
return BasicTypeConverter.toBoolean(val, dbTrueValue);
}
public UUID getUUID(String name) {
Object val = get(name);
return BasicTypeConverter.toUUID(val);
}
public Integer getInteger(String name) {
Object val = get(name);
return BasicTypeConverter.toInteger(val);
}
public Boolean getBoolean(String name) {
Object val = get(name);
return BasicTypeConverter.toBoolean(val, dbTrueValue);
}
public BigDecimal getBigDecimal(String name) {
Object val = get(name);
return BasicTypeConverter.toBigDecimal(val);
}
public Integer getInteger(String name) {
Object val = get(name);
return BasicTypeConverter.toInteger(val);
}
public Long getLong(String name) {
Object val = get(name);
return BasicTypeConverter.toLong(val);
}
public BigDecimal getBigDecimal(String name) {
Object val = get(name);
return BasicTypeConverter.toBigDecimal(val);
}
public Double getDouble(String name) {
Object val = get(name);
return BasicTypeConverter.toDouble(val);
}
public Long getLong(String name) {
Object val = get(name);
return BasicTypeConverter.toLong(val);
}
public Float getFloat(String name) {
Object val = get(name);
return BasicTypeConverter.toFloat(val);
}
public Double getDouble(String name) {
Object val = get(name);
return BasicTypeConverter.toDouble(val);
}
public String getString(String name) {
Object val = get(name);
return BasicTypeConverter.toString(val);
}
public Float getFloat(String name) {
Object val = get(name);
return BasicTypeConverter.toFloat(val);
}
public java.util.Date getUtilDate(String name) {
Object val = get(name);
return BasicTypeConverter.toUtilDate(val);
}
public String getString(String name) {
Object val = get(name);
return BasicTypeConverter.toString(val);
}
public Date getDate(String name) {
Object val = get(name);
return BasicTypeConverter.toDate(val);
}
public java.util.Date getUtilDate(String name) {
Object val = get(name);
return BasicTypeConverter.toUtilDate(val);
}
public Timestamp getTimestamp(String name) {
Object val = get(name);
return BasicTypeConverter.toTimestamp(val);
}
public Date getDate(String name) {
Object val = get(name);
return BasicTypeConverter.toDate(val);
}
public String toString() {
return map.toString();
}
public Timestamp getTimestamp(String name) {
Object val = get(name);
return BasicTypeConverter.toTimestamp(val);
}
// ------------------------------------
// Normal map methods...
public String toString() {
return map.toString();
}
public void clear() {
map.clear();
}
// ------------------------------------
// Normal map methods...
public boolean containsKey(Object key) {
key = ((String) key).toLowerCase();
return map.containsKey(key);
}
public void clear() {
map.clear();
}
public boolean containsValue(Object value) {
return map.containsValue(value);
}
public boolean containsKey(Object key) {
key = ((String) key).toLowerCase();
return map.containsKey(key);
}
public Set<Map.Entry<String, Object>> entrySet() {
return map.entrySet();
}
public boolean containsValue(Object value) {
return map.containsValue(value);
}
public boolean isEmpty() {
return map.isEmpty();
}
public Set<Map.Entry<String, Object>> entrySet() {
return map.entrySet();
}
public Set<String> keySet() {
return map.keySet();
}
public boolean isEmpty() {
return map.isEmpty();
}
public void putAll(Map<? extends String, ?> t) {
map.putAll(t);
}
public Set<String> keySet() {
return map.keySet();
}
public int size() {
return map.size();
}
public void putAll(Map<? extends String, ?> t) {
map.putAll(t);
}
public Collection<Object> values() {
return map.values();
}
public int size() {
return map.size();
}
public Collection<Object> values() {
return map.values();
}
}
@@ -12,9 +12,8 @@ import com.avaje.ebeaninternal.api.SpiQuery;
/**
* PagedList implementation based on limit offset types of queries.
*
* @param <T>
* the entity bean type
*
* @param <T> the entity bean type
*/
public class LimitOffsetPagedList<T> implements PagedList<T> {
@@ -44,7 +43,7 @@ public class LimitOffsetPagedList<T> implements PagedList<T> {
public void loadRowCount() {
getFutureRowCount();
}
public Future<Integer> getFutureRowCount() {
synchronized (monitor) {
if (futureRowCount == null) {
@@ -12,32 +12,32 @@ import com.avaje.ebean.Transaction;
*/
public class QueryFutureIds<T> extends BaseFuture<List<Object>> implements FutureIds<T> {
private final CallableQueryIds<T> call;
public QueryFutureIds(CallableQueryIds<T> call ) {
super(new FutureTask<List<Object>>(call));
this.call = call;
}
public FutureTask<List<Object>> getFutureTask() {
return futureTask;
}
public Transaction getTransaction() {
return call.transaction;
}
public Query<T> getQuery() {
return call.query;
}
public List<Object> getPartialIds() {
return call.query.getIdList();
}
private final CallableQueryIds<T> call;
public boolean cancel(boolean mayInterruptIfRunning) {
call.query.cancel();
return super.cancel(mayInterruptIfRunning);
}
public QueryFutureIds(CallableQueryIds<T> call) {
super(new FutureTask<List<Object>>(call));
this.call = call;
}
public FutureTask<List<Object>> getFutureTask() {
return futureTask;
}
public Transaction getTransaction() {
return call.transaction;
}
public Query<T> getQuery() {
return call.query;
}
public List<Object> getPartialIds() {
return call.query.getIdList();
}
public boolean cancel(boolean mayInterruptIfRunning) {
call.query.cancel();
return super.cancel(mayInterruptIfRunning);
}
}
@@ -17,34 +17,34 @@ import javax.persistence.PersistenceException;
*/
public class QueryFutureList<T> extends BaseFuture<List<T>> implements FutureList<T> {
private final CallableQueryList<T> call;
public QueryFutureList(CallableQueryList<T> call) {
super(new FutureTask<List<T>>(call));
this.call = call;
}
public FutureTask<List<T>> getFutureTask() {
return futureTask;
}
public Transaction getTransaction() {
return call.transaction;
}
private final CallableQueryList<T> call;
public QueryFutureList(CallableQueryList<T> call) {
super(new FutureTask<List<T>>(call));
this.call = call;
}
public FutureTask<List<T>> getFutureTask() {
return futureTask;
}
public Transaction getTransaction() {
return call.transaction;
}
@Override
public Query<T> getQuery() {
return call.query;
}
public Query<T> getQuery() {
return call.query;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
call.query.cancel();
return super.cancel(mayInterruptIfRunning);
}
public boolean cancel(boolean mayInterruptIfRunning) {
call.query.cancel();
return super.cancel(mayInterruptIfRunning);
}
@Override
public List<T> getUnchecked() {
public List<T> getUnchecked() {
try {
return get();
} catch (InterruptedException e) {
@@ -64,5 +64,5 @@ public class QueryFutureList<T> extends BaseFuture<List<T>> implements FutureLis
throw new PersistenceException(e);
}
}
}
@@ -12,28 +12,28 @@ import com.avaje.ebean.Transaction;
public class QueryFutureRowCount<T> extends BaseFuture<Integer> implements FutureRowCount<T> {
private final CallableQueryRowCount<T> call;
public QueryFutureRowCount(CallableQueryRowCount<T> call ) {
super(new FutureTask<Integer>(call));
this.call = call;
}
public FutureTask<Integer> getFutureTask() {
return futureTask;
}
public Transaction getTransaction() {
return call.transaction;
}
public Query<T> getQuery() {
return call.query;
}
public boolean cancel(boolean mayInterruptIfRunning) {
call.query.cancel();
return super.cancel(mayInterruptIfRunning);
}
public QueryFutureRowCount(CallableQueryRowCount<T> call) {
super(new FutureTask<Integer>(call));
this.call = call;
}
public FutureTask<Integer> getFutureTask() {
return futureTask;
}
public Transaction getTransaction() {
return call.transaction;
}
public Query<T> getQuery() {
return call.query;
}
public boolean cancel(boolean mayInterruptIfRunning) {
call.query.cancel();
return super.cancel(mayInterruptIfRunning);
}
}
@@ -25,73 +25,73 @@ import org.slf4j.LoggerFactory;
*/
public class RawSqlSelectClauseBuilder {
private static final Logger logger = LoggerFactory.getLogger(RawSqlSelectClauseBuilder.class);
private static final Logger logger = LoggerFactory.getLogger(RawSqlSelectClauseBuilder.class);
private final Binder binder;
private final Binder binder;
private final SqlLimiter dbQueryLimiter;
private final DatabasePlatform dbPlatform;
private final SqlLimiter dbQueryLimiter;
private final DatabasePlatform dbPlatform;
public RawSqlSelectClauseBuilder(DatabasePlatform dbPlatform, Binder binder) {
public RawSqlSelectClauseBuilder(DatabasePlatform dbPlatform, Binder binder) {
this.binder = binder;
this.dbQueryLimiter = dbPlatform.getSqlLimiter();
this.dbPlatform = dbPlatform;
}
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 {
/**
* 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();
SpiQuery<T> query = request.getQuery();
BeanDescriptor<T> desc = request.getBeanDescriptor();
DeployNamedQuery namedQuery = desc.getNamedQuery(query.getName());
DRawSqlSelect sqlSelect = namedQuery.getSqlSelect();
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();
// 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);
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);
SqlTreeAlias alias = new SqlTreeAlias(sqlSelect.getTableAlias());
predicates.parseTableAlias(alias);
String sql = null;
try {
String sql = null;
try {
boolean includeRowNumColumn = false;
String orderBy = sqlSelect.getOrderBy(predicates);
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();
// 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;
}
sql = limitSql.getSql();
} else {
// add back select keyword
// ... was removed to support dbQueryLimiter
sql = "select " + sql;
}
SqlTree sqlTree = sqlSelect.getSqlTree();
SqlTree sqlTree = sqlSelect.getSqlTree();
CQueryPlan queryPlan = new CQueryPlan(request, sql, sqlTree, true, includeRowNumColumn, "");
return new CQuery<T>(request, predicates, queryPlan);
CQueryPlan queryPlan = new CQueryPlan(request, sql, sqlTree, true, includeRowNumColumn, "");
return new CQuery<T>(request, predicates, queryPlan);
} catch (Exception e) {
} catch (Exception e) {
String msg = "Error with " + desc.getFullName() + " query:\r" + sql;
logger.error(msg);
throw new PersistenceException(e);
}
String msg = "Error with " + desc.getFullName() + " query:\r" + sql;
logger.error(msg);
throw new PersistenceException(e);
}
}
}
@@ -2,62 +2,62 @@ 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 add(String prefix, String name) {
if (prefix != null) {
return prefix + "." + name;
} else {
return name;
}
}
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};
}
}
/**
* 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};
}
}
}
@@ -17,15 +17,15 @@ import javax.persistence.PersistenceException;
*/
public class SqlBeanLoad {
private final DbReadContext ctx;
private final EntityBean bean;
private final EntityBeanIntercept ebi;
private final Class<?> type;
private final boolean lazyLoading;
private final boolean refreshLoading;
private final DbReadContext ctx;
private final EntityBean bean;
private final EntityBeanIntercept ebi;
private final Class<?> type;
private final boolean lazyLoading;
private final boolean refreshLoading;
private final boolean rawSql;
public SqlBeanLoad(DbReadContext ctx, Class<?> type, EntityBean bean, Mode queryMode) {
this.ctx = ctx;
@@ -36,7 +36,7 @@ public class SqlBeanLoad {
this.bean = bean;
this.ebi = bean == null ? null : bean._ebean_getIntercept();
}
/**
* Return true if this is a lazy loading.
*/
@@ -57,7 +57,7 @@ public class SqlBeanLoad {
return null;
}
if ((bean == null)
if ((bean == null)
|| (lazyLoading && ebi.isLoadedProperty(prop.getPropertyIndex()))
|| (type != null && !prop.isAssignableFrom(type))) {
@@ -4,17 +4,17 @@ package com.avaje.ebeaninternal.server.query;
* Inner join, Outer join or automatic determination based on cardinality and optionality.
*/
public enum SqlJoinType {
/**
* It is an inner join.
*/
INNER("join"),
/**
* It is an outer join.
*/
OUTER("left outer join"),
/**
* It is automatically determined based on cardinality and optionality.
*/
@@ -43,7 +43,7 @@ public enum SqlJoinType {
}
return this.getLiteral();
}
/**
* If this is an AUTO join set it to OUTER as we are joining to a Many.
*/
@@ -54,7 +54,7 @@ public enum SqlJoinType {
return this;
}
}
/**
* If join is AUTO but deploymentJoinType is OUTER then go into OUTER join mode.
*/
@@ -9,26 +9,26 @@ 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;
}
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);
}
public boolean cancel(boolean mayInterruptIfRunning) {
query.cancel();
return super.cancel(mayInterruptIfRunning);
}
}
@@ -11,7 +11,7 @@ import com.avaje.ebeaninternal.server.el.ElPropertyDeploy;
/**
* Special Map of the logical property joins to table alias.
*
*
* @author rbygrave
*/
public class SqlTreeAlias {
@@ -147,7 +147,7 @@ public class SqlTreeAlias {
s = aliasMap.get(prefix);
}
if (s == null) {
String msg = "Could not determine table alias for [" + prefix + "] manyMap[" + manyWhereAliasMap + "] aliasMap["+ aliasMap + "]";
String msg = "Could not determine table alias for [" + prefix + "] manyMap[" + manyWhereAliasMap + "] aliasMap[" + aliasMap + "]";
throw new RuntimeException(msg);
}
return s;
@@ -99,7 +99,7 @@ public class SqlTreeBuilder {
* to the root node.
*/
public SqlTreeBuilder(String tableAliasPlaceHolder, String columnAliasPrefix,
OrmQueryRequest<?> request, CQueryPredicates predicates, CQueryHistorySupport historySupport) {
OrmQueryRequest<?> request, CQueryPredicates predicates, CQueryHistorySupport historySupport) {
this.rawSql = false;
this.rawNoId = false;
@@ -112,7 +112,7 @@ public class SqlTreeBuilder {
this.queryDetail = query.getDetail();
this.predicates = predicates;
this.alias = new SqlTreeAlias(request.getQuery().getAlias()==null?request.getBeanDescriptor().getBaseTableAlias():request.getQuery().getAlias());
this.alias = new SqlTreeAlias(request.getQuery().getAlias() == null ? request.getBeanDescriptor().getBaseTableAlias() : request.getQuery().getAlias());
this.ctx = new DefaultDbSqlContext(alias, tableAliasPlaceHolder, columnAliasPrefix, !subQuery, historySupport);
}
@@ -139,7 +139,7 @@ public class SqlTreeBuilder {
}
return new SqlTree(summary.toString(), rootNode, selectSql, fromSql, inheritanceWhereSql, encryptedProps,
manyProperty, queryDetail.getIncludes());
manyProperty, queryDetail.getIncludes());
}
private String buildSelectClause() {
@@ -198,7 +198,7 @@ public class SqlTreeBuilder {
* should be included.
*/
private SqlTreeNode buildSelectChain(String prefix, BeanPropertyAssoc<?> prop,
BeanDescriptor<?> desc, List<SqlTreeNode> joinList) {
BeanDescriptor<?> desc, List<SqlTreeNode> joinList) {
List<SqlTreeNode> myJoinList = new ArrayList<SqlTreeNode>();
@@ -303,7 +303,7 @@ public class SqlTreeBuilder {
if (!extraJoins.isEmpty()) {
// add extra joins required to support predicates
// and/or order by clause
for (SqlTreeNodeExtraJoin extraJoin: extraJoins) {
for (SqlTreeNodeExtraJoin extraJoin : extraJoins) {
myList.add(extraJoin);
if (extraJoin.isManyJoin()) {
// as we are now going to join to the many then we need
@@ -342,7 +342,7 @@ public class SqlTreeBuilder {
}
private void addProperty(SqlTreeProperties selectProps, BeanDescriptor<?> desc,
OrmQueryProperties queryProps, String propName) {
OrmQueryProperties queryProps, String propName) {
if (subQuery) {
addPropertyToSubQuery(selectProps, desc, propName);
@@ -379,7 +379,7 @@ public class SqlTreeBuilder {
BeanProperty p = desc.findBeanProperty(propName);
if (p == null) {
logger.error("property [" + propName + "] not found on " + desc + " for query - excluding it.");
p = desc.findBeanProperty("id");
p = desc.findBeanProperty("id");
selectProps.add(p);
} else if (p.isId()) {
@@ -533,7 +533,7 @@ public class SqlTreeBuilder {
private final BeanDescriptor<?> desc;
private IncludesDistiller(BeanDescriptor<?> desc, Set<String> selectIncludes,
Set<String> predicateIncludes) {
Set<String> predicateIncludes) {
this.desc = desc;
this.selectIncludes = selectIncludes;
this.predicateIncludes = predicateIncludes;
@@ -617,7 +617,7 @@ public class SqlTreeBuilder {
* </p>
*/
private SqlTreeNodeExtraJoin findExtraJoinRoot(String includeProp,
SqlTreeNodeExtraJoin childJoin) {
SqlTreeNodeExtraJoin childJoin) {
int dotPos = includeProp.lastIndexOf('.');
if (dotPos == -1) {
@@ -70,7 +70,7 @@ public class SqlTreeNodeBean implements SqlTreeNode {
protected final String prefix;
protected final Map<String, String> pathMap;
protected final BeanPropertyAssocMany<?> lazyLoadParent;
protected final SpiQuery.TemporalMode temporalMode;
@@ -98,7 +98,7 @@ public class SqlTreeNodeBean implements SqlTreeNode {
* Construct for leaf node.
*/
public SqlTreeNodeBean(String prefix, BeanPropertyAssoc<?> beanProp, SqlTreeProperties props,
List<SqlTreeNode> myChildren, boolean withId, boolean disableLazyLoad) {
List<SqlTreeNode> myChildren, boolean withId, boolean disableLazyLoad) {
this(prefix, beanProp, beanProp.getTargetDescriptor(), props, myChildren, withId, null, SpiQuery.TemporalMode.CURRENT, disableLazyLoad);
}
@@ -115,7 +115,7 @@ public class SqlTreeNodeBean implements SqlTreeNode {
* Create with the appropriate node.
*/
private SqlTreeNodeBean(String prefix, BeanPropertyAssoc<?> beanProp, BeanDescriptor<?> desc, SqlTreeProperties props,
List<SqlTreeNode> myChildren, boolean withId, BeanPropertyAssocMany<?> lazyLoadParent,
List<SqlTreeNode> myChildren, boolean withId, BeanPropertyAssocMany<?> lazyLoadParent,
SpiQuery.TemporalMode temporalMode, boolean disableLazyLoad) {
this.lazyLoadParent = lazyLoadParent;
@@ -189,7 +189,7 @@ public class SqlTreeNodeBean implements SqlTreeNode {
// these are always the first 2 columns in the resultSet
Timestamp start = ctx.getDataReader().getTimestamp();
Timestamp end = ctx.getDataReader().getTimestamp();
T bean = (T)load(ctx, null, null);
T bean = (T) load(ctx, null, null);
return new Version<T>(bean, start, end);
}
@@ -203,7 +203,7 @@ public class SqlTreeNodeBean implements SqlTreeNode {
if (lazyLoadParentIdBinder != null) {
lazyLoadParentId = lazyLoadParentIdBinder.read(ctx);
}
// bean already existing in the persistence context
EntityBean contextBean = null;
@@ -245,13 +245,13 @@ public class SqlTreeNodeBean implements SqlTreeNode {
localBean = null;
} else if (!temporalVersions) {
// check the PersistenceContext to see if the bean already exists
contextBean = (EntityBean)persistenceContext.putIfAbsent(id, localBean);
contextBean = (EntityBean) persistenceContext.putIfAbsent(id, localBean);
if (contextBean == null) {
// bean just added to the persistenceContext
contextBean = localBean;
} else {
// bean already exists in persistenceContext
if (isLoadContextBeanNeeded(queryMode, contextBean)){
if (isLoadContextBeanNeeded(queryMode, contextBean)) {
// refresh it anyway (lazy loading for example)
localBean = contextBean;
} else {
@@ -537,7 +537,7 @@ public class SqlTreeNodeBean implements SqlTreeNode {
public String toString() {
return "SqlTreeNodeBean: " + desc;
}
private boolean isLoadContextBeanNeeded(Mode queryMode, EntityBean contextBean) {
// if explicitly set loadContextBean to true, then reload
if (queryMode.isLoadContextBean()) {
@@ -552,5 +552,5 @@ public class SqlTreeNodeBean implements SqlTreeNode {
// return true by default
return true;
}
}