Edgewall Software

This page documents the 0.12 release. Documentation for other releases can be found here.

Trac Ticket Queries

Languages:

In addition to reports, Trac provides support for custom ticket queries, used to display lists of tickets meeting a specified set of criteria.

To configure and execute a custom query, switch to the View Tickets module from the navigation bar, and select the Custom Query link.

Filters

When you first go to the query page the default filter will display tickets relevant to you:

  • If logged in then all open tickets it will display open tickets assigned to you.
  • If not logged in but you have specified a name or email address in the preferences then it will display all open tickets where your email (or name if email not defined) is in the CC list.
  • If not logged and no name/email defined in the preferences then all open issues are displayed.

Current filters can be removed by clicking the button to the left with the minus sign on the label. New filters are added from the pulldown lists at the bottom corners of the filters box ('And' conditions on the left, 'Or' conditions on the right). Filters with either a text box or a pulldown menu of options can be added multiple times to perform an or of the criteria.

You can use the fields just below the filters box to group the results based on a field, or display the full description for each ticket.

Once you've edited your filters click the Update button to refresh your results.

Clicking on one of the query results will take you to that ticket. You can navigate through the results by clicking the Next Ticket or Previous Ticket links just below the main menu bar, or click the Back to Query link to return to the query page.

You can safely edit any of the tickets and continue to navigate through the results using the Next/Previous/Back to Query links after saving your results. When you return to the query any tickets which were edited will be displayed with italicized text. If one of the tickets was edited such that it no longer matches the query criteria the text will also be greyed. Lastly, if a new ticket matching the query criteria has been created, it will be shown in bold.

The query results can be refreshed and cleared of these status indicators by clicking the Update button again.

Saving Queries

Trac allows you to save the query as a named query accessible from the reports module. To save a query ensure that you have Updated the view and then click the Save query button displayed beneath the results. You can also save references to queries in Wiki content, as described below.

Note: one way to easily build queries like the ones below, you can build and test the queries in the Custom report module and when ready - click Save query. This will build the query string for you. All you need to do is remove the extra line breaks.

Note: you must have the REPORT_CREATE permission in order to save queries to the list of default reports. The Save query button will only appear if you are logged in as a user that has been granted this permission. If your account does not have permission to create reports, you can still use the methods below to save a query.

You may want to save some queries so that you can come back to them later. You can do this by making a link to the query from any Wiki page.

[query:status=new|assigned|reopened&version=1.0 Active tickets against 1.0]

Which is displayed as:

Active tickets against 1.0

This uses a very simple query language to specify the criteria (see Query Language).

Alternatively, you can copy the query string of a query and paste that into the Wiki link, including the leading ? character:

[query:?status=new&status=assigned&status=reopened&group=owner Assigned tickets by owner]

Which is displayed as:

Assigned tickets by owner

Using the [[TicketQuery]] Macro

The TicketQuery macro lets you display lists of tickets matching certain criteria anywhere you can use WikiFormatting.

Example:

[[TicketQuery(version=0.6|0.7&resolution=duplicate)]]

This is displayed as:

#181
Wiki preview injects new lines
#204
request for colour legend (or something similar) for ticket groups in reports
#226
Ticket Dependencies
#239
Link to diff of specifik wiki change instead of the page itself
#351
All ticket modifications should be tracked in timeline
#413
Installing on Windows, drive other than C:
#450
Diffviewer should try to convert the text into utf-8.
#475
merging of similar tickets
#519
Python process sometimes hangs on Windows Server 2003
#529
IE 5-6 over HTTPS broken downloads

Just like the query: wiki links, the parameter of this macro expects a query string formatted according to the rules of the simple ticket query language. This also allows displaying the link and description of a single ticket:

[[TicketQuery(id=123)]]

This is displayed as:

#123
No SQL error display

A more compact representation without the ticket summaries is also available:

[[TicketQuery(version=0.6|0.7&resolution=duplicate, compact)]]

This is displayed as:

#181, #204, #226, #239, #351, #413, #450, #475, #519, #529

Finally, if you wish to receive only the number of defects that match the query, use the count parameter.

[[TicketQuery(version=0.6|0.7&resolution=duplicate, count)]]

This is displayed as:

10

Customizing the table format

You can also customize the columns displayed in the table format (format=table) by using col≤field> - you can specify multiple fields and what order they are displayed by placing pipes (|) between the columns like below:

[[TicketQuery(max=3,status=closed,order=id,desc=1,format=table,col=resolution|summary|owner|reporter)]]

This is displayed as:

Full rows

In table format you can also have full rows by using rows≤field> like below:

[[TicketQuery(max=3,status=closed,order=id,desc=1,format=table,col=resolution|summary|owner|reporter,rows=description)]]

This is displayed as:

Results (1 - 3 of 11311)

1 2 3 4 5 6 7 8 9 10 11
Ticket Resolution Summary Owner Reporter
#13871 fixed Daysback in timeline page has off-by-one issue Jun Omae Jun Omae
Description

When submitting form in timeline page with 1 in daysback field, the user expects searching events between yesterday of the from date and the from date (just one day). However, it actually searches events between 2 days ago of the from date and the from date.

Also, entering 0 in the daysback field, the timeline page treat as 1. As the result, it is unable to search events for just one day. Before Trac 1.2, entering 0 in the daysback field is able to search events for just one day.

  • trac/timeline/web_ui.py

    diff --git a/trac/timeline/web_ui.py b/trac/timeline/web_ui.py
    index 719618fd2..c186add27 100644
    a b class TimelineModule(Component):  
    174174
    175175        stop = fromdate
    176176        start = to_datetime(stop.replace(tzinfo=None) -
    177                             timedelta(days=daysback + 1), req.tz)
     177                            timedelta(days=daysback), req.tz)
    178178
    179179        # create author include and exclude sets
    180180        include = set()
  • trac/timeline/tests/web_ui.py

    diff --git a/trac/timeline/tests/web_ui.py b/trac/timeline/tests/web_ui.py
    index 0877c6225..b917b0e30 100644
    a b class TimelineEventProviderTestCase(unittest.TestCase):  
    225225                yield ('test', 'Test')
    226226
    227227            def get_timeline_events(self, req, start, stop, filters):
    228                 return iter(self._events or ())
     228                for event in self._events:
     229                    if start <= event[1] <= stop:
     230                        yield event
    229231
    230232            def render_timeline_event(self, context, field, event):
    231233                return event[3].render(context, field, event)
    class TimelineEventProviderTestCase(unittest.TestCase):  
    270272            ('test&2', datetime(2018, 3, 19, 23, 56, 12, 987654, utc),
    271273             'Joe <joe@example.org>', Mock(render=render)),
    272274        ]
    273         req = MockRequest(self.env, path_info='/timeline',
    274                           args={'format': 'rss'})
     275        req = MockRequest(self.env, path_info='/timeline', tz=utc,
     276                          args={'format': 'rss', 'daysback': '90',
     277                                'from': '2018-04-30T00:00:00Z'})
    275278        rv = self._process_request(req)
    276279        self.assertEqual('timeline.rss', rv[0])
    277280        self.assertEqual({'content_type': 'application/rss+xml'}, rv[2])
    class TimelineEventProviderTestCase(unittest.TestCase):  
    307310        self.assertEqual('<?xml version="1.0"?>', output[:21])
    308311        minidom.parseString(output)  # verify valid xml
    309312
     313    def test_daysback(self):
     314        provider = self.timeline_event_providers['normal'](self.env)
     315        provider._events = [
     316            ('test', datetime(2025, 2, 19, 12, tzinfo=utc),
     317             'trac', None),
     318            ('test', datetime(2025, 2, 18, 12, tzinfo=utc),
     319             'trac', None),
     320        ]
     321        req = MockRequest(self.env, path_info='/timeline', tz=utc,
     322                          args={'from': '2025-02-19T00:00:00Z',
     323                                'daysback': '1'})
     324        rv = self._process_request(req)
     325        data = rv[1]
     326        events = data['events']
     327        self.assertEqual(1, len(events))
     328        self.assertEqual(datetime(2025, 2, 19, 12, tzinfo=utc),
     329                         events[0]['datetime'])
     330
    310331    def _process_request(self, req):
    311332        mod = TimelineModule(self.env)
    312         req = MockRequest(self.env, path_info='/timeline',
    313                           args={'format': 'rss'})
    314333        self.assertTrue(mod.match_request(req))
    315334        return mod.process_request(req)
    316335
#13867 fixed Unit tests failing with Subversion 1.14.5 Jun Omae Jun Omae
Description

It seems that SubversionNode.get_copy_ancestry raises the following AttributeError in the all failures.

======================================================================
ERROR: test_get_copy_ancestry_for_move (tracopt.versioncontrol.svn.tests.svn_fs.SvnCachedRepositoryScopedTests.test_get_copy_ancestry_for_move)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/runner/work/trac/trac/tracopt/versioncontrol/svn/tests/svn_fs.py", line 1267, in test_get_copy_ancestry_for_move
    ancestry = node.get_copy_ancestry()
               ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/runner/work/trac/trac/tracopt/versioncontrol/svn/svn_fs.py", line 855, in get_copy_ancestry
    path = path.lstrip(b'/')
           ^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'lstrip'

...
Ran 2810 tests in 554.016s

FAILED (errors=12, skipped=5)
#13866 fixed Syntax hightlihging has unexpected styles after Pygments 2.7.0 Jun Omae Jun Omae
Description

After Pygments 2.7.0, the syntax highlighting has unexpected styles (e.g. pre, td.linenoes pre).

$ script='import pygments; from pygments.formatters.html import HtmlFormatter as F; print(pygments.__version__); print(F().get_style_defs("div.code pre"))'
$ diff -u <(/venv/pygments-2.6.1/bin/python -c "$script") \
>         <(/venv/pygments-2.7.0/bin/python -c "$script")
--- /dev/fd/63  2025-02-05 19:05:33.783629775 +0900
+++ /dev/fd/62  2025-02-05 19:05:33.783629775 +0900
@@ -1,6 +1,11 @@
-2.6.1
+2.7.0
+pre { line-height: 125%; margin: 0; }
+td.linenos pre { color: #000000; background-color: #f0f0f0; padding: 0 5px 0 5px; }
+span.linenos { color: #000000; background-color: #f0f0f0; padding: 0 5px 0 5px; }
+td.linenos pre.special { color: #000000; background-color: #ffffc0; padding: 0 5px 0 5px; }
+span.linenos.special { color: #000000; background-color: #ffffc0; padding: 0 5px 0 5px; }
 div.code pre .hll { background-color: #ffffcc }
-div.code pre  { background: #f8f8f8; }
+div.code pre { background: #f8f8f8; }
 div.code pre .c { color: #408080; font-style: italic } /* Comment */
 div.code pre .err { border: 1px solid #FF0000 } /* Error */
 div.code pre .k { color: #008000; font-weight: bold } /* Keyword */

I think we could directly invoke get_background_style_defs and get_token_style_defs in the HtmlFormatter.

  • trac/mimeview/pygments.py

     
    3737__all__ = ['PygmentsRenderer']
    3838
    3939
     40if hasattr(HtmlFormatter, 'get_background_style_defs') and \
     41        hasattr(HtmlFormatter, 'get_token_style_defs'):
     42    def _get_style_defs(style, arg):  # Pygments 2.7.0+
     43        lines = []
     44        formatter = HtmlFormatter(style=style)
     45        lines.extend(formatter.get_background_style_defs(arg))
     46        lines.extend(formatter.get_token_style_defs(arg))
     47        return '\n'.join(lines)
     48else:
     49    def _get_style_defs(style, arg):
     50        formatter = HtmlFormatter(style=style)
     51        return formatter.get_style_defs(arg)
     52
     53
    4054class PygmentsRenderer(Component):
    4155    """HTML renderer for syntax highlighting based on Pygments."""
    4256
     
    186200            req.end_headers()
    187201            return
    188202
    189         formatter = HtmlFormatter(style=style_cls)
    190         content = formatter.get_style_defs(['div.code pre', 'table.code td'])
     203        content = _get_style_defs(style_cls, ['div.code pre', 'table.code td'])
    191204        content = content.encode('utf-8')
    192205
    193206        req.send_response(200)

See also: https://github.com/pygments/pygments/blob/2.19.1/pygments/formatters/html.py#L516

1 2 3 4 5 6 7 8 9 10 11

Query Language

query: TracLinks and the [[TicketQuery]] macro both use a mini “query language” for specifying query filters. Basically, the filters are separated by ampersands (&). Each filter then consists of the ticket field name, an operator, and one or more values. More than one value are separated by a pipe (|), meaning that the filter matches any of the values. To include a literal & or | in a value, escape the character with a backslash (\).

The available operators are:

= the field content exactly matches one of the values
~= the field content contains one or more of the values
^= the field content starts with one of the values
$= the field content ends with one of the values

All of these operators can also be negated:

!= the field content matches none of the values
!~= the field content does not contain any of the values
!^= the field content does not start with any of the values
!$= the field content does not end with any of the values

The date fields created and modified can be constrained by using the = operator and specifying a value containing two dates separated by two dots (..). Either end of the date range can be left empty, meaning that the corresponding end of the range is open. The date parser understands a few natural date specifications like "3 weeks ago", "last month" and "now", as well as Bugzilla-style date specifications like "1d", "2w", "3m" or "4y" for 1 day, 2 weeks, 3 months and 4 years, respectively. Spaces in date specifications can be left out to avoid having to quote the query string.

created=2007-01-01..2008-01-01 query tickets created in 2007
created=lastmonth..thismonth query tickets created during the previous month
modified=1weekago.. query tickets that have been modified in the last week
modified=..30daysago query tickets that have been inactive for the last 30 days

See also: TracTickets, TracReports, TracGuide

Last modified 10 years ago Last modified on Nov 3, 2014, 3:40:46 AM
Note: See TracWiki for help on using the wiki.