Question

I'm developing a system using Trac, and I want to limit the number of "changelog" entries returned. The issue is that Trac collates these entries from multiple tables using a union, and then later combines them into single 'changesets' based on their timestamp. I wish to limit the results to the latest e.g. 3 changesets, but this requires retrieving as many rows as necessary until I've got 3 unique timestamps. Solution needs to work for SQLite/Postgres.

Trac's current SQL

Current SQL Result

Time                User  Field         oldvalue   newvalue   permanent
=======================================================================
1371806593507544    a     owner         b         c           1
1371806593507544    a     comment       2         lipsum      1
1371806593507544    a     description   foo       bar         1
1371806593324529    b     comment       hello     world       1
1371806593125677    c     priority      minor     major       1
1371806592492812    d     comment       x         y           1

Intended SQL Result (Limited to 1 timestamp e.g.)

Time                User  Field         oldvalue   newvalue   permanent
=======================================================================
1371806593507544    a     owner         b         c           1
1371806593507544    a     comment       2         lipsum      1
1371806593507544    a     description   foo       bar         1
Was it helpful?

Solution

As you already pointed out on your own, this cannot be resolved in SQL due to the undetermined number of results. And I think this is not even required.

You can use a slightly modified trac/ticket/templates/ticket.html Genshi template to get what you want. Change

      <div id="changelog">
        <py:for each="change in changes">

into

      <div id="changelog">
        <py:for each="change in changes[-3:]">

and place the file into <env>/templates/ restart your web-server. But watch out for changes to ticket.html, whenever you attempt to upgrade your Trac install. Every time you do that, you might need to re-apply this change on the current template of the respective version. But IMHO its still a lot faster and cleaner than to patch Trac core code.

OTHER TIPS

If you want just three records (as in the "Data Limit 1" result set), you can use limit:

select *
from t
order by time desc
limit 3

If you want all records for the three most recent time stamps, you can use a join:

select t.*
from t join
     (select distinct time
      from t
      order by times desc
      limit 3
     ) tt
     on tt.time = t.time
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top