Skip to content

Commit

Permalink
Merge pull request #474 from hprange/count-distinct-general
Browse files Browse the repository at this point in the history
Extract the construction of count distinct expression into its own method
  • Loading branch information
hprange committed Sep 12, 2013
2 parents 34bc8d6 + 9a76b04 commit aa68984
Showing 1 changed file with 26 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1142,12 +1142,7 @@ public int rowCountForFetchSpecification(EOEditingContext ec, EOFetchSpecificati

String countExpression;
if (spec.usesDistinct()) {
NSArray<String> primaryKeyAttributeNames = entity.primaryKeyAttributeNames();
if (primaryKeyAttributeNames.count() > 1)
log.warn("Composite primary keys are currently unsupported in rowCountForFetchSpecification, when the spec uses distinct");
String pkAttributeName = primaryKeyAttributeNames.lastObject();
String pkColumnName = entity.attributeNamed(pkAttributeName).columnName();
countExpression = "count(distinct " + quoteColumnName("t0." + pkColumnName) + ") ";
countExpression = sqlForCountDistinct(entity);
} else {
countExpression = "count(*) ";
}
Expand Down Expand Up @@ -1193,7 +1188,31 @@ public int rowCountForFetchSpecification(EOEditingContext ec, EOFetchSpecificati
}
return rowCount;
}


/**
* Returns the SQL to count the distinct number of rows. The general implementation doesn't
* support composite primary keys and chooses only one primary key column when formatting the
* SQL expression.
* <p>
* Concrete classes may override this implementation to add support for composite
* primary keys according to their database specific SQL syntax.
*
* @param entity the base entity used in this query
* @return the formatted SQL count using distinct for the given entity
*/
protected String sqlForCountDistinct(EOEntity entity) {
NSArray<String> primaryKeyAttributeNames = entity.primaryKeyAttributeNames();

if (primaryKeyAttributeNames.count() > 1) {
log.warn("Composite primary keys are currently unsupported in rowCountForFetchSpecification, when the spec uses distinct");
}

String pkAttributeName = primaryKeyAttributeNames.lastObject();
String pkColumnName = entity.attributeNamed(pkAttributeName).columnName();

return "count(distinct " + quoteColumnName("t0." + pkColumnName) + ") ";
}

/**
* Returns the syntax for using the given query as an aliased subquery in a from-clause.
*
Expand Down

0 comments on commit aa68984

Please sign in to comment.