package io.ebeaninternal.server.query;
import io.ebean.config.dbplatform.SqlLimitResponse;
import io.ebean.core.type.DataReader;
import io.ebeaninternal.server.core.OrmQueryRequest;
import io.ebeaninternal.server.rawsql.SpiRawSql.ColumnMapping;
import io.ebeaninternal.server.type.RsetDataReaderIndexed;
import java.sql.ResultSet;
import java.util.List;
class CQueryPlanRawSql extends CQueryPlan {
private final int[] rsetIndexPositions;
CQueryPlanRawSql(OrmQueryRequest<?> request, SqlLimitResponse sqlRes, SqlTree sqlTree, String logWhereSql) {
super(request, sqlRes, sqlTree, true, logWhereSql);
this.rsetIndexPositions = createIndexPositions(request, sqlTree);
}
@Override
public DataReader createDataReader(ResultSet rset) {
return new RsetDataReaderIndexed(dataTimeZone, rset, rsetIndexPositions);
}
private int[] createIndexPositions(OrmQueryRequest<?> request, SqlTree sqlTree) {
List<String> chain = sqlTree.buildRawSqlSelectChain();
ColumnMapping columnMapping = request.getQuery().getRawSql().getColumnMapping();
int[] indexPositions = new int[chain.size()];
for (int i = 0; i < chain.size(); i++) {
String logicalPropertyPath = chain.get(i);
int mappedPosition = columnMapping.getIndexPosition(logicalPropertyPath);
if (mappedPosition == -1 && logicalPropertyPath.endsWith(".id")) {
mappedPosition = columnMapping.getIndexPosition(foreignKeyPath(logicalPropertyPath));
}
indexPositions[i] = 1 + mappedPosition;
}
for (int i = 0; i < indexPositions.length; i++) {
if (indexPositions[i] == 0) {
indexPositions[i] = indexPositions[i + 1] - 1;
}
}
return indexPositions;
}
private String foreignKeyPath(String logicalPropertyPath) {
return logicalPropertyPath.substring(0, logicalPropertyPath.length() - 3) + "Id";
}
}