Refactor transaction logging to simple SLF4J use

This commit is contained in:
Robin Bygrave committed 2013-04-15 23:16:08 +12:00
1 parent b5ef07bab9
commit cbd7b5e912
60 files changed
+2976 -4529

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -319,8 +319,7 @@ public class CQueryBuilder implements Constants {
sb.append(select.getSelectSql());
}
sb.append(" ").append(NEW_LINE);
sb.append("from ");
sb.append(" from ");
// build the from clause potentially with joins
// required only for the predicates
@@ -330,7 +329,7 @@ public class CQueryBuilder implements Constants {
boolean hasWhere = false;
if (inheritanceWhere.length() > 0) {
sb.append(" ").append(NEW_LINE).append("where");
sb.append(" where");
sb.append(inheritanceWhere);
hasWhere = true;
}
@@ -339,7 +338,7 @@ public class CQueryBuilder implements Constants {
if (hasWhere) {
sb.append(" and ");
} else {
sb.append(NEW_LINE).append("where ");
sb.append(" where ");
}
BeanDescriptor<?> desc = request.getBeanDescriptor();
@@ -356,9 +355,9 @@ public class CQueryBuilder implements Constants {
if (!isEmpty(dbWhere)) {
if (!hasWhere) {
hasWhere = true;
sb.append(" ").append(NEW_LINE).append("where ");
sb.append(" where ");
} else {
sb.append("and ");
sb.append(" and ");
}
sb.append(dbWhere);
}
@@ -366,7 +365,7 @@ public class CQueryBuilder implements Constants {
String dbFilterMany = predicates.getDbFilterMany();
if (!isEmpty(dbFilterMany)) {
if (!hasWhere) {
sb.append(" ").append(NEW_LINE).append("where ");
sb.append(" where ");
} else {
sb.append("and ");
}
@@ -375,8 +374,7 @@ public class CQueryBuilder implements Constants {
String dbOrderBy = predicates.getDbOrderBy();
if (dbOrderBy != null) {
sb.append(" ").append(NEW_LINE);
sb.append("order by ").append(dbOrderBy);
sb.append(" order by ").append(dbOrderBy);
}
if (useSqlLimiter) {
@@ -60,7 +60,6 @@ public class CQueryBuilderRawSql implements Constants {
StringBuilder sb = new StringBuilder();
sb.append(sql.getPreFrom());
sb.append(" ");
sb.append(NEW_LINE);
String s = sql.getPreWhere();
BindParams bindParams = request.getQuery().getBindParams();
@@ -95,11 +94,10 @@ public class CQueryBuilderRawSql implements Constants {
}
if (!isEmpty(dynamicWhere)) {
sb.append(NEW_LINE);
if (sql.isAndWhereExpr()) {
sb.append("and ");
sb.append(" and ");
} else {
sb.append("where ");
sb.append(" where ");
}
sb.append(dynamicWhere);
sb.append(" ");
@@ -107,7 +105,6 @@ public class CQueryBuilderRawSql implements Constants {
String preHaving = sql.getPreHaving();
if (!isEmpty(preHaving)) {
sb.append(NEW_LINE);
sb.append(preHaving);
sb.append(" ");
}
@@ -115,7 +112,6 @@ public class CQueryBuilderRawSql implements Constants {
String dbHaving = predicates.getDbHaving();
if (!isEmpty(dbHaving)) {
sb.append(" ");
sb.append(NEW_LINE);
if (sql.isAndHavingExpr()) {
sb.append("and ");
} else {
@@ -126,7 +122,6 @@ public class CQueryBuilderRawSql implements Constants {
}
if (!isEmpty(orderBy)) {
sb.append(NEW_LINE);
sb.append(" order by ").append(orderBy);
}
@@ -3,6 +3,9 @@ package com.avaje.ebeaninternal.server.query;
import java.sql.SQLException;
import java.util.concurrent.FutureTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.BackgroundExecutor;
import com.avaje.ebean.QueryIterator;
import com.avaje.ebean.bean.BeanCollection;
@@ -12,10 +15,8 @@ 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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebeaninternal.server.transaction.TransactionManager;
/**
* Handles the Object Relational fetching.
@@ -26,15 +27,12 @@ public class CQueryEngine {
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) {
public CQueryEngine(DatabasePlatform dbPlatform, Binder binder, BackgroundExecutor backgroundExecutor) {
this.logControl = logControl;
this.backgroundExecutor = backgroundExecutor;
this.queryBuilder = new CQueryBuilder(backgroundExecutor, dbPlatform, binder);
}
@@ -51,18 +49,19 @@ public class CQueryEngine {
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.isLogSql()) {
String logSql = rcQuery.getGeneratedSql();
if (TransactionManager.SQL_LOGGER.isTraceEnabled()) {
logSql += "; --bind("+rcQuery.getBindLog()+")";
}
request.logSql(logSql);
}
if (request.isLogSummary()) {
request.getTransaction().logInternal(rcQuery.getSummary());
request.getTransaction().logSummary(rcQuery.getSummary());
}
if (!list.isFetchingInBackground() && request.getQuery().isFutureFetch()) {
@@ -85,19 +84,19 @@ public class CQueryEngine {
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.isLogSql()) {
String logSql = rcQuery.getGeneratedSql();
if (TransactionManager.SQL_LOGGER.isTraceEnabled()) {
logSql += "; --bind("+rcQuery.getBindLog()+")";
}
request.logSql(logSql);
}
if (request.isLogSummary()) {
request.getTransaction().logInternal(rcQuery.getSummary());
request.getTransaction().logSummary(rcQuery.getSummary());
}
if (request.getQuery().isFutureFetch()) {
@@ -123,20 +122,16 @@ public class CQueryEngine {
try {
if (logControl.isDebugGeneratedSql()) {
logSqlToConsole(cquery);
}
if (request.isLogSql()) {
logSql(cquery);
}
if (!cquery.prepareBindExecuteQuery()) {
// query has been cancelled already
logger.trace("Future fetch already cancelled");
return null;
}
if (request.isLogSql()) {
logSql(cquery);
}
int iterateBufferSize = request.getSecondaryQueriesMinBatchSize(defaultSecondaryQueryBatchSize);
QueryIterator<T> readIterate = cquery.readIterate(iterateBufferSize, request);
@@ -164,19 +159,15 @@ public class CQueryEngine {
request.setCancelableQuery(cquery);
try {
if (logControl.isDebugGeneratedSql()) {
logSqlToConsole(cquery);
}
if (request.isLogSql()) {
logSql(cquery);
}
if (!cquery.prepareBindExecuteQuery()) {
// query has been cancelled already
logger.trace("Future fetch already cancelled");
return null;
}
if (request.isLogSql()) {
logSql(cquery);
}
BeanCollection<T> beanCollection = cquery.readCollection();
@@ -208,10 +199,8 @@ public class CQueryEngine {
return beanCollection;
} catch (SQLException e) {
throw cquery.createPersistenceException(e);// request, e,
// cquery.getBindLog(),
// cquery.getGeneratedSql());
throw cquery.createPersistenceException(e);
} finally {
if (useBackgroundToContinueFetch) {
// left closing resources to BackgroundFetch...
@@ -239,15 +228,12 @@ public class CQueryEngine {
CQuery<T> cquery = queryBuilder.buildQuery(request);
try {
if (logControl.isDebugGeneratedSql()) {
logSqlToConsole(cquery);
}
cquery.prepareBindExecuteQuery();
if (request.isLogSql()) {
logSql(cquery);
}
cquery.prepareBindExecuteQuery();
if (cquery.readBean()) {
bean = cquery.getLoadedBean();
}
@@ -268,46 +254,16 @@ public class CQueryEngine {
}
}
/**
* 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);
if (TransactionManager.SQL_LOGGER.isTraceEnabled()) {
sql += "; --bind("+query.getBindLog()+")";
}
query.getTransaction().logSql(sql);
}
/**
@@ -349,7 +305,7 @@ public class CQueryEngine {
msg.append("] rows[").append(q.getLoadedRowDetail());
msg.append("] bind[").append(q.getBindLog()).append("]");
q.getTransaction().logInternal(msg.toString());
q.getTransaction().logSummary(msg.toString());
}
/**
@@ -394,6 +350,6 @@ public class CQueryEngine {
msg.append("] predicates[").append(q.getLogWhereSql());
msg.append("] bind[").append(q.getBindLog()).append("]");
q.getTransaction().logInternal(msg.toString());
q.getTransaction().logSummary(msg.toString());
}
}
@@ -151,7 +151,7 @@ public class CQueryPredicates {
Object bindValue = whereExprBindValues.get(i);
binder.bindObject(dataBind, bindValue);
if (i > 0 || idValue != null) {
bindLog.append(", ");
bindLog.append(",");
}
bindLog.append(bindValue);
}
@@ -163,7 +163,7 @@ public class CQueryPredicates {
Object bindValue = filterManyExprBindValues.get(i);
binder.bindObject(dataBind, bindValue);
if (i > 0 || idValue != null) {
bindLog.append(", ");
bindLog.append(",");
}
bindLog.append(bindValue);
}
@@ -182,7 +182,7 @@ public class CQueryPredicates {
Object bindValue = havingExprBindValues.get(i);
binder.bindObject(dataBind, bindValue);
if (i > 0) {
bindLog.append(", ");
bindLog.append(",");
}
bindLog.append(bindValue);
}
@@ -215,10 +215,8 @@ public class CQueryPredicates {
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
// 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);
@@ -259,7 +257,6 @@ public class CQueryPredicates {
public void prepare(boolean buildSql) {
DeployParser deployParser = request.createDeployParser();
prepare(buildSql, true, deployParser);
}
@@ -5,19 +5,6 @@ package com.avaje.ebeaninternal.server.query;
*/
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.
*/
@@ -11,264 +11,261 @@ 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 COMMA = ", ";
private static final String PERIOD = ".";
private static final String PERIOD = ".";
private final String tableAliasPlaceHolder;
private final String tableAliasPlaceHolder;
private final String columnAliasPrefix;
private final String columnAliasPrefix;
private final ArrayStack<String> tableAliasStack = new ArrayStack<String>();
private final ArrayStack<String> tableAliasStack = new ArrayStack<String>();
private final ArrayStack<String> joinStack = new ArrayStack<String>();
private final ArrayStack<String> joinStack = new ArrayStack<String>();
private final ArrayStack<String> prefixStack = new ArrayStack<String>();
private final ArrayStack<String> prefixStack = new ArrayStack<String>();
private final boolean useColumnAlias;
private final boolean useColumnAlias;
private int columnIndex;
private int columnIndex;
private StringBuilder sb = new StringBuilder(140);
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;
/**
* A Set used to make sure formula joins are only added once to a query.
*/
private HashSet<String> formulaJoins;
private HashSet<String> tableJoins;
private HashSet<String> tableJoins;
private SqlTreeAlias alias;
private SqlTreeAlias alias;
private String currentPrefix;
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;
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;
}
/**
* 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;
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>();
}
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()]);
String joinKey = table + "-" + a1 + "-" + a2;
if (tableJoins.contains(joinKey)) {
return;
}
public String peekJoin() {
return joinStack.peek();
tableJoins.add(joinKey);
sb.append(" ");
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());
}
public void popJoin() {
joinStack.pop();
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;
}
public void pushJoin(String node) {
joinStack.push(node);
// we only want to add this join once
formulaJoins.add(converted);
sb.append(" ");
if (forceOuterJoin) {
if ("join".equals(sqlFormulaJoin.substring(0, 4).toLowerCase())) {
// prepend left outer as we are in the 'many' part
append(" left outer ");
}
}
public void addJoin(String type, String table, TableJoinColumn[] cols, String a1, String a2) {
sb.append(converted);
sb.append(" ");
}
if (tableJoins == null) {
tableJoins = new HashSet<String>();
}
public void appendFormulaSelect(String sqlFormulaSelect) {
String joinKey = table + "-" + a1 + "-" + a2;
if (tableJoins.contains(joinKey)) {
return;
}
String tableAlias = tableAliasStack.peek();
String converted = StringHelper.replaceString(sqlFormulaSelect, tableAliasPlaceHolder,
tableAlias);
tableJoins.add(joinKey);
sb.append(COMMA);
sb.append(converted);
}
sb.append(NEW_LINE);
sb.append(type);
public void appendColumn(String column) {
appendColumn(tableAliasStack.peek(), column);
}
sb.append(" ").append(table).append(" ");
sb.append(a2);
public void appendColumn(String tableAlias, String column) {
sb.append(COMMA);
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(" ");
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);
}
public String getTableAlias(String prefix) {
return alias.getTableAlias(prefix);
if (useColumnAlias) {
sb.append(" ");
sb.append(columnAliasPrefix);
sb.append(columnIndex);
}
columnIndex++;
}
public String getTableAliasManyWhere(String prefix) {
return alias.getTableAliasManyWhere(prefix);
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 void pushSecondaryTableAlias(String alias) {
tableAliasStack.push(alias);
}
public int length() {
return sb.length();
}
public String getRelativePrefix(String propName) {
public String getContent() {
String s = sb.toString();
sb = new StringBuilder();
return s;
}
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();
}
public String toString() {
return "DefaultDbSqlContext: " + sb.toString();
}
}
@@ -9,6 +9,9 @@ import java.util.ArrayList;
import javax.persistence.PersistenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.SqlQueryListener;
import com.avaje.ebean.SqlRow;
import com.avaje.ebean.bean.BeanCollection;
@@ -19,12 +22,10 @@ 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.transaction.TransactionManager;
import com.avaje.ebeaninternal.server.type.DataBind;
import com.avaje.ebeaninternal.server.util.BindParamsParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Perform native sql fetches.
@@ -39,7 +40,7 @@ public class DefaultRelationalQueryEngine implements RelationalQueryEngine {
private final String dbTrueValue;
public DefaultRelationalQueryEngine(MAdminLogging logControl, Binder binder, String dbTrueValue) {
public DefaultRelationalQueryEngine(Binder binder, String dbTrueValue) {
this.binder = binder;
this.defaultMaxRows = GlobalProperties.getInt("nativesql.defaultmaxrows",100000);
this.dbTrueValue = dbTrueValue == null ? "true" : dbTrueValue;
@@ -94,9 +95,11 @@ public class DefaultRelationalQueryEngine implements RelationalQueryEngine {
}
if (request.isLogSql()) {
String sOut = sql.replace(Constants.NEW_LINE, ' ');
sOut = sOut.replace(Constants.CARRIAGE_RETURN, ' ');
t.logInternal(sOut);
String logSql = sql;
if (TransactionManager.SQL_LOGGER.isTraceEnabled()) {
logSql += "; --bind("+bindLog+")";
}
t.logSql(logSql);
}
rset = pstmt.executeQuery();
@@ -178,7 +181,7 @@ public class DefaultRelationalQueryEngine implements RelationalQueryEngine {
String msg = "SqlQuery rows[" + loadRowCount + "] time[" + exeTime + "] bind["
+ bindLog + "] finished[" + beanColl.isFinishedFetch() + "]";
t.logInternal(msg);
t.logSummary(msg);
}
if (query.isCancelled()){
@@ -13,160 +13,158 @@ import com.avaje.ebeaninternal.server.el.ElPropertyValue;
*/
public class SqlTree {
private SqlTreeNode rootNode;
private SqlTreeNode rootNode;
/**
* Property if resultSet contains master and detail rows.
*/
private BeanPropertyAssocMany<?> manyProperty;
private String manyPropertyName;
private ElPropertyValue manyPropEl;
/**
* Property if resultSet contains master and detail rows.
*/
private BeanPropertyAssocMany<?> manyProperty;
private String manyPropertyName;
private ElPropertyValue manyPropEl;
private Set<String> includes;
private Set<String> includes;
/**
* Summary of the select being generated.
*/
private String summary;
/**
* Summary of the select being generated.
*/
private String summary;
private String selectSql;
private String selectSql;
private String fromSql;
private String fromSql;
/**
* Encrypted Properties require additional binding.
*/
private BeanProperty[] encryptedProps;
/**
* Where clause for inheritance.
*/
private String inheritanceWhereSql;
/**
* Encrypted Properties require additional binding.
*/
private BeanProperty[] encryptedProps;
/**
* 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;
}
/**
* Where clause for inheritance.
*/
private String inheritanceWhereSql;
/**
* Return the String for the actual SQL.
*/
public String getSelectSql() {
return selectSql;
}
/**
* Create the SqlSelectClause.
*/
public SqlTree() {
}
/**
* Set the select sql clause.
*/
public void setSelectSql(String selectSql) {
this.selectSql = selectSql;
}
public List<String> buildSelectExpressionChain() {
ArrayList<String> list = new ArrayList<String>();
rootNode.buildSelectExpressionChain(list);
return list;
}
public String getFromSql() {
return fromSql;
}
/**
* Return the includes. Associated beans lists etc.
*/
public Set<String> getIncludes() {
return includes;
}
public void setFromSql(String fromSql) {
this.fromSql = fromSql;
}
/**
* Return the where clause for inheritance.
*/
public String getInheritanceWhereSql() {
return inheritanceWhereSql;
}
/**
* Set the association includes (Ones and Many's).
*/
public void setIncludes(Set<String> includes) {
this.includes = includes;
}
/**
* Set where clause(s) for inheritance.
*/
public void setInheritanceWhereSql(String whereSql) {
this.inheritanceWhereSql = whereSql;
}
/**
* 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;
}
/**
* Set the summary description of the query.
*/
public void setSummary(String summary) {
this.summary = summary;
}
/**
* Return the String for the actual SQL.
*/
public String getSelectSql() {
return selectSql;
}
/**
* 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;
}
/**
* Set the select sql clause.
*/
public void setSelectSql(String selectSql) {
this.selectSql = selectSql;
}
/**
* 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 getFromSql() {
return fromSql;
}
public String getManyPropertyName() {
return manyPropertyName;
}
public void setFromSql(String fromSql) {
this.fromSql = fromSql;
}
public ElPropertyValue getManyPropertyEl() {
return manyPropEl;
}
/**
* Return the where clause for inheritance.
*/
public String getInheritanceWhereSql() {
return inheritanceWhereSql;
}
/**
* Return true if this query includes a Many association.
*/
public boolean isManyIncluded() {
return (manyProperty != null);
}
/**
* Set where clause(s) for inheritance.
*/
public void setInheritanceWhereSql(String whereSql) {
this.inheritanceWhereSql = whereSql;
}
public BeanProperty[] getEncryptedProps() {
return encryptedProps;
}
/**
* Set the summary description of the query.
*/
public void setSummary(String summary) {
this.summary = summary;
}
public void setEncryptedProps(BeanProperty[] encryptedProps) {
this.encryptedProps = encryptedProps;
}
/**
* 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;
}
}
File diff suppressed because it is too large. Load diff
@@ -8,48 +8,40 @@ 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 PERIOD = ".";
public static final String COMMA = ", ";
public static final String COMMA = ", ";
public static final int NORMAL = 0;
public static final int SHARED = 1;
public static final int READONLY = 2;
public static final int NORMAL = 0;
public static final int SHARED = 1;
public static final int READONLY = 2;
public void buildSelectExpressionChain(List<String> selectChain);
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 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 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);
/**
* 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;
/**
* 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;
}
@@ -27,496 +27,490 @@ import com.avaje.ebeaninternal.server.lib.util.StringHelper;
*/
public class SqlTreeNodeBean implements SqlTreeNode {
private static final SqlTreeNode[] NO_CHILDREN = new SqlTreeNode[0];
private static final SqlTreeNode[] NO_CHILDREN = new SqlTreeNode[0];
final BeanDescriptor<?> desc;
final IdBinder idBinder;
final BeanDescriptor<?> desc;
/**
* The children which will be other SelectBean or SelectProxyBean.
*/
final SqlTreeNode[] children;
final IdBinder idBinder;
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;
/**
* The children which will be other SelectBean or SelectProxyBean.
*/
final SqlTreeNode[] children;
final TableJoin[] tableJoins;
final boolean readOnlyLeaf;
/**
* 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;
/**
* Set to true if this is a partial object fetch.
*/
final boolean partialObject;
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) {
/**
* 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;
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;
}
}
/**
* The hash of the partialProps (calculate once).
*/
final int partialHash;
protected void postLoad(DbReadContext cquery, Object loadedBean, Object id) {
}
final BeanProperty[] properties;
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 {
/**
* Extra where clause added by Where annotation on associated many.
*/
final String extraWhere;
// 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;
}
}
}
}
final BeanPropertyAssoc<?> nodeBeanProp;
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);
}
final TableJoin[] tableJoins;
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);
}
/**
* False if report bean and has no id property.
*/
final boolean readId;
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);
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) {
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);
}
// temporarily turn off interception during load
((EntityBean) localBean)._ebean_getIntercept().setIntercepting(false);
}
}
if (parentBean != null && contextBean != null) {
// set this back to the parentBean
nodeBeanProp.setValue(parentBean, contextBean);
}
} else {
// ignore the DB data...
localBean = null;
}
}
}
}
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);
}
}
ctx.setCurrentPrefix(prefix, pathMap);
/**
* 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();
ctx.propagateState(localBean);
// load the List/Set/Map proxy objects (deferred fetching of lists)
BeanPropertyAssocMany<?>[] manys = localDesc.propertiesMany();
for (int i = 0; i < manys.length; i++) {
SqlBeanLoad sqlBeanLoad = new SqlBeanLoad(ctx, localType, localBean, queryMode);
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);
}
}
}
}
if (inheritInfo == null) {
// normal behavior with no inheritance
for (int i = 0, x = properties.length; i < x; i++) {
properties[i].load(sqlBeanLoad);
}
/**
* Append the property columns to the buffer.
*/
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
ctx.pushJoin(prefix);
ctx.pushTableAlias(prefix);
} 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);
}
}
}
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, x = tableJoins.length; i < x; i++) {
tableJoins[i].load(sqlBeanLoad);
}
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();
}
boolean lazyLoadMany = false;
if (localBean == null && queryMode.equals(Mode.LAZYLOAD_MANY)) {
// batch lazy load many into existing contextBean
localBean = contextBean;
lazyLoadMany = true;
}
private void appendSelectTableJoins(DbSqlContext ctx) {
// 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);
}
String baseAlias = ctx.getTableAlias(prefix);
for (int i = 0; i < tableJoins.length; i++) {
TableJoin join = tableJoins[i];
if (lazyLoadMany) {
// special case where we load children
String alias = baseAlias+i;
} else if (localBean != null) {
ctx.pushSecondaryTableAlias(alias);
join.appendSelect(ctx, false);
ctx.popTableAlias();
}
}
ctx.setCurrentPrefix(prefix, pathMap);
if (!ctx.isVanillaMode()) {
// only create lazy loading collection proxies
// when not in vanilla mode
createListProxies(localDesc, ctx, localBean);
}
/**
* Append the properties to the buffer.
*/
private void appendSelect(DbSqlContext ctx, boolean subQuery, BeanProperty[] props) {
localDesc.postLoad(localBean, includedProps);
for (int i = 0; i < props.length; i++) {
props[i].appendSelect(ctx, subQuery);
}
}
public void appendWhere(DbSqlContext ctx) {
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 (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) {
if (partialObject) {
ctx.register(null, ebi);
}
ctx.pushJoin(prefix);
ctx.pushTableAlias(prefix);
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);
}
}
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);
}
}
if (parentBean != null && contextBean != null) {
// set this back to the parentBean
nodeBeanProp.setValue(parentBean, contextBean);
}
/**
* Summary description.
*/
public String toString() {
return "SqlTreeNodeBean: " + desc;
}
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 (!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;
}
}
@@ -9,33 +9,32 @@ 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);
}
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
protected void postLoad(DbReadContext cquery, Object loadedBean, Object id) {
@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);
}
// 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);
}
/**
* Force outer join for everything after the many property.
*/
@Override
public void appendFrom(DbSqlContext ctx, boolean forceOuterJoin) {
super.appendFrom(ctx, true);
}
}