Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change rxOrderBy Regex and logic to be less greedy during Page<T> query rewrite to support sub-select ordering #94


Copy link

@tawman tawman commented Dec 28, 2011

Currently, PetaPoco does not support Page<T> operations on SQL statements that include an ORDER BY clause as part of a sub-select. The query rewrite logic only stores the first ORDER BY found for the COUNT, but removes all ORDER BY clauses for the items query causing a SQL error. I updated the Regex to perform a negative look ahead for a ') AS' after the ORDER BY, but other Regex forward/backward conditions could work as well. I also changed the Regex to search Right to Left whereby finding the last ORDER BY clause in the SQL statement first.

For example, the following method wants to perform a ROW_NUMBER() PARTITION BY query on the report date in order to return the most recent report generated on each day:

public Page<ComplianceReport> GetReportsForMember(int pageNumber, int pageSize, string userName, Guid complianceGroupId, DateTime startDate, DateTime endDate, string orderBy)
    var query = Sql.Builder
        .Append("SELECT cr.*")
        .Append("FROM (SELECT ROW_NUMBER() OVER (PARTITION BY CAST(cr.ReportDate AS DATE) ORDER BY ReportDate Desc) as samp_rn, cr.*")
        .Append("FROM ComplianceReport cr")
        .Append("INNER JOIN ScheduledReport sr ON cr.ComplianceGroupId = sr.ComplianceGroupId")
        .Append("WHERE (sr.UserName = @0)", userName)
        .Append("AND (sr.ComplianceGroupId = @0)", complianceGroupId)
        .Append("AND (cr.Published = 1)");

    if (startDate != DateTime.MinValue)
        query.Append("AND (cr.ReportDate >= @0 AND cr.ReportDate <= @1)", startDate, endDate);

    query.Append(") cr WHERE samp_rn = 1");

    if (!string.IsNullOrEmpty(orderBy))
        query.Append("ORDER BY " + orderBy);

    return CmsDatabase.Page<ComplianceReport>(pageNumber, pageSize, query);
…ast ORDER BY clause present during Page<T> rewrite to support ROW_NUMBER queries
Copy link

@ensecoz ensecoz commented Apr 17, 2012

why don't toptensoftware accept this bug fixed? anyway thanks for the fixed tawman

Copy link

@toptensoftware toptensoftware commented May 21, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
None yet
Linked issues

Successfully merging this pull request may close these issues.

None yet

3 participants