Changes between Version 1 and Version 2 of TracReports

Show
Ignore:
Timestamp:
11/04/11 12:49:55 (19 months ago)
Author:
trac
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • TracReports

    v1 v2  
    1 = Relatórios Trac = 
    2 [[TracGuideToc]]  
    3  
    4 O módulo de relatórios Trac fornece um simples mas poderoso facilitador de geração de relatórios para apresentar informações sobre tickets na base de dados Trac. 
    5  
    6 Ao invés de ter sua própria definição do formato do relatório, TracReports baseia-se na sintaxe padrão SQL SELECT para customizar definições de relatório. 
    7  
    8 Um relatório consiste basicamente em: 
    9  * ID -- Identificador único (sequencial) 
    10  * Title  -- Título descritivo 
    11  * Description  -- Uma breve descrição do relatório, no texto em formato WikiFormatting. 
    12  * Report Body -- Lista dos resultados da consulta do relatório, formatado de acordo com os métodos descritos abaixo. 
    13  * Footer -- Links para outros formatos de download para este relatório. 
    14  
    15  
    16 == Mudando a ordenação == 
    17 Relatórios simples - relatórios não agrupados para ser específico - podem ser ordenados por qualquer coluna simplesmente clicando no cabeçalho da coluna. 
    18  
    19 Se um cabeçalho da coluna é um hyperlink (vermelho), clique na coluna na qual você deseja ordernar por. Clicando no cabeçalho novamente, inverterá a ordenação. 
    20  
    21 == Outros Formatos de Download  == 
    22 Exceto na visualização padrão HTML, relatórios podem também serem exportados em vários formatos alternativos. 
    23 No fim da página do relatório, você achará uma lista de formatos disponíveis. Clique no link desejado para fazer o download do relatório no formato desejado. 
    24  
    25  
    26 === Delimitador de Virgulas - CSV(Comma Separated Values) === 
    27 Exporte o relatório em texto-puro, cada linha na sua própria linha,cada coluna separada por uma vírgula (',').  
    28 '''Nota:''' O dado de uma coluna é retirado dos caracteres de retorno de linha, próxima linha e vírgulas para preservar a estrutura. 
    29  
    30 === Delimitador-Tab === 
    31 Como acima, mas utiliza o caracter tab (\t) ao invés de vírgula. (',') 
    32  
    33 === RSS - Conteúdo XML para Syndication === 
    34 Todos relatórios suportam syndications usando XML/RSS2.0. Para assinar, clique no ícone laranja 'XML' no fim da página. Veja TracRss para informações gerais sobre o suporte RSS no Trac. 
    35  
    36 ---- 
    37 == Criando Relatórios Customizados == 
    38  
    39 ''Criar um relatório customizado necessita um bom conhecimento de SQL.'' 
    40  
    41 Um relatório é basicamente uma consulta SQL, executada e apresentada pelo Trac.  
    42 Relatórios podem ser visualizados e criados de uma expressão SQL customizada diretamente pela interface web. 
    43  
    44 Basicamente, um relatório consiste de uma expressão SELECT de uma tabela 'ticket', 
    45 usando colunas disponíveis e ordenando na forma que você desejar. 
    46  
    47 == Colunas Ticket == 
    48 Uma tabela ''ticket'' contém as seguintes colunas: 
     1= Trac Reports = 
     2[[TracGuideToc]] 
     3 
     4The Trac reports module provides a simple, yet powerful reporting facility 
     5to present information about tickets in the Trac database. 
     6 
     7Rather than have its own report definition format, TracReports relies on standard SQL 
     8`SELECT` statements for custom report definition.  
     9 
     10  '''Note:''' ''The report module is being phased out in its current form because it seriously limits the ability of the Trac team to make adjustments to the underlying database schema. We believe that the [wiki:TracQuery query module] is a good replacement that provides more flexibility and better usability. While there are certain reports that cannot yet be handled by the query module, we intend to further enhance it so that at some point the reports module can be completely removed. This also means that there will be no major enhancements to the report module anymore.'' 
     11 
     12  ''You can already completely replace the reports module by the query module simply by disabling the former in [wiki:TracIni trac.ini]:'' 
     13  {{{ 
     14  [components] 
     15  trac.ticket.report.* = disabled 
     16  }}} 
     17  ''This will make the query module the default handler for the “View Tickets” navigation item. We encourage you to try this configuration and report back what kind of features of reports you are missing, if any.'' 
     18 
     19 
     20A report consists of these basic parts: 
     21 * '''ID''' -- Unique (sequential) identifier  
     22 * '''Title'''  -- Descriptive title 
     23 * '''Description'''  -- A brief description of the report, in WikiFormatting text. 
     24 * '''Report Body''' -- List of results from report query, formatted according to the methods described below. 
     25 * '''Footer''' -- Links to alternative download formats for this report. 
     26 
     27== Changing Sort Order == 
     28Simple reports - ungrouped reports to be specific - can be changed to be sorted by any column simply by clicking the column header.  
     29 
     30If a column header is a hyperlink (red), click the column you would like to sort by. Clicking the same header again reverses the order. 
     31 
     32== Changing Report Numbering == 
     33There may be instances where you need to change the ID of the report, perhaps to organize the reports better. At present this requires changes to the trac database. The ''report'' table has the following schema (as of 0.10): 
     34 * id integer PRIMARY KEY 
     35 * author text 
     36 * title text 
     37 * query text 
     38 * description text 
     39Changing the ID changes the shown order and number in the ''Available Reports'' list and the report's perma-link. This is done by running something like: 
     40{{{ 
     41update report set id=5 where id=3; 
     42}}} 
     43Keep in mind that the integrity has to be maintained (i.e., ID has to be unique, and you don't want to exceed the max, since that's managed by SQLite someplace). 
     44 
     45You may also need to update or remove the report number stored in the report or query. 
     46 
     47== Navigating Tickets == 
     48Clicking on one of the report 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 Report'' link to return to the report page. 
     49 
     50You can safely edit any of the tickets and continue to navigate through the results using the Next/Previous/Back to Report links after saving your results, but when you return to the report, there will be no hint about what has changed, as would happen if you were navigating a list of tickets obtained from a query (see TracQuery#NavigatingTickets). ''(since 0.11)'' 
     51 
     52== Alternative Download Formats == 
     53Aside from the default HTML view, reports can also be exported in a number of alternative formats. 
     54At the bottom of the report page, you will find a list of available data formats. Click the desired link to  
     55download the alternative report format. 
     56 
     57=== Comma-delimited - CSV (Comma Separated Values) === 
     58Export the report as plain text, each row on its own line, columns separated by a single comma (','). 
     59'''Note:''' Carriage returns, line feeds, and commas are stripped from column data to preserve the CSV structure. 
     60 
     61=== Tab-delimited === 
     62Like above, but uses tabs (\t) instead of comma. 
     63 
     64=== RSS - XML Content Syndication === 
     65All reports support syndication using XML/RSS 2.0. To subscribe to an RSS feed, click the orange 'XML' icon at the bottom of the page. See TracRss for general information on RSS support in Trac. 
     66 
     67---- 
     68 
     69== Creating Custom Reports == 
     70 
     71''Creating a custom report requires a comfortable knowledge of SQL.'' 
     72 
     73A report is basically a single named SQL query, executed and presented by 
     74Trac.  Reports can be viewed and created from a custom SQL expression directly 
     75in from the web interface. 
     76 
     77Typically, a report consists of a SELECT-expression from the 'ticket' table, 
     78using the available columns and sorting the way you want it. 
     79 
     80== Ticket columns == 
     81The ''ticket'' table has the following columns: 
    4982 * id 
     83 * type 
    5084 * time 
    5185 * changetime 
     
    5690 * reporter 
    5791 * cc 
    58  * url 
    5992 * version 
    6093 * milestone 
     
    6396 * summary 
    6497 * description 
    65  
    66 Veja TracTickets para uma detalhada descrição dos campos da coluna. 
    67  
    68 '''Exemplo:''' ''Todos tickets ativos, ordenados por prioridade e tempo'' 
     98 * keywords 
     99 
     100See TracTickets for a detailed description of the column fields. 
     101 
     102'''all active tickets, sorted by priority and time''' 
     103 
     104'''Example:''' ''All active tickets, sorted by priority and time'' 
    69105{{{ 
    70106SELECT id AS ticket, status, severity, priority, owner,  
     
    78114 
    79115 
    80 == Relatórios Avançados: Variáveis Dinâmicas == 
    81 Para relatórios mais flexíveis, Trac suporta o uso de ''variáveis dinâmicas'' em relatórios de sintaxe SQL. 
    82 Em poucas palavras, variáveis dinâmicas são ''strings especiais'' que são substitídos por dados customizados antes da execução da consulta. 
    83  
    84 === Usando Variáveis na Consulta === 
    85 A sintaxe para variáveis dinâmicas é simples, qualquer palavra maiúscula começando com '$' é considerado variável. 
    86  
    87 Exemplo: 
    88 {{{ 
    89 SELECT id AS ticket,summary FROM ticket WHERE priority='$PRIORITY' 
    90 }}} 
    91  
    92 Para atribuir um valor a $PRIORITY ao visualizar o relatório, você deve defini-lo como um argumento no URL do relatório, deixando de fora o '$'. 
    93  
    94 Exemplo: 
    95 {{{ 
    96  http://projects.edgewall.com/trac/reports/14?PRIORITY=high 
    97 }}} 
    98  
    99  
    100 === Variáveis Constantes/Especiais === 
    101 Aqui está uma ''mágica'' das variáveis dinâmicas para permitir relatórios práticos, seus valores são automaticamente setados sem ter que mudar o URL. 
    102  
    103  * $USER -- Nome do usuário logado. 
    104  
    105 Exemplo (''Lista todos tickets associados a mim''): 
    106 {{{ 
    107 SELECT id AS ticket,summary FROM ticket WHERE owner='$USER' 
    108 }}} 
    109  
    110  
    111 ---- 
    112  
    113  
    114 == Relatórios Avançados: Customizando Formatações == 
    115 Trac também é capaz de relatórios mais avançados, incluindo customização de layouts, 
    116 grupos de resultados e estilos de CSS definidos pelo usuário. Para criar estes relatórios, nós iremos usar 
    117 sintaxes SQL especializados para controlar a saída do relatório Trac. 
    118  
    119  
    120 == Colunas Especiais == 
    121 Para formatar relatórios, TracReports procura por nome de colunas 'mágicas' no resultado da consulta.  
    122 Estes nomes 'mágicos' são processados e afetam o layout e estilo do relatório final. 
    123  
    124 === Formatação Automáticas de Colunas === 
    125  * '''ticket''' -- Número ID do Ticket. Se transforma em um hyperlink para aquele ticket. 
    126  * '''created, modified, date, time''' -- Formata células como uma data e/ou hora. 
    127  * '''description''' -- Campo de descrição do Ticket, analisado pelo wiki. 
    128  
    129 '''Exemplo:''' 
     116== Advanced Reports: Dynamic Variables == 
     117For more flexible reports, Trac supports the use of ''dynamic variables'' in report SQL statements.  
     118In short, dynamic variables are ''special'' strings that are replaced by custom data before query execution. 
     119 
     120=== Using Variables in a Query === 
     121The syntax for dynamic variables is simple, any upper case word beginning with '$' is considered a variable. 
     122 
     123Example: 
     124{{{ 
     125SELECT id AS ticket,summary FROM ticket WHERE priority=$PRIORITY 
     126}}} 
     127 
     128To assign a value to $PRIORITY when viewing the report, you must define it as an argument in the report URL, leaving out the leading '$'. 
     129 
     130Example: 
     131{{{ 
     132 http://trac.edgewall.org/reports/14?PRIORITY=high 
     133}}} 
     134 
     135To use multiple variables, separate them with an '&'. 
     136 
     137Example: 
     138{{{ 
     139 http://trac.edgewall.org/reports/14?PRIORITY=high&SEVERITY=critical 
     140}}} 
     141 
     142 
     143=== Special/Constant Variables === 
     144There is one ''magic'' dynamic variable to allow practical reports, its value automatically set without having to change the URL.  
     145 
     146 * $USER -- Username of logged in user. 
     147 
     148Example (''List all tickets assigned to me''): 
     149{{{ 
     150SELECT id AS ticket,summary FROM ticket WHERE owner=$USER 
     151}}} 
     152 
     153 
     154---- 
     155 
     156 
     157== Advanced Reports: Custom Formatting == 
     158Trac is also capable of more advanced reports, including custom layouts, 
     159result grouping and user-defined CSS styles. To create such reports, we'll use 
     160specialized SQL statements to control the output of the Trac report engine. 
     161 
     162== Special Columns == 
     163To format reports, TracReports looks for 'magic' column names in the query 
     164result. These 'magic' names are processed and affect the layout and style of the  
     165final report. 
     166 
     167=== Automatically formatted columns === 
     168 * '''ticket''' -- Ticket ID number. Becomes a hyperlink to that ticket.  
     169 * '''id''' -- same as '''ticket''' above when '''realm''' is not set 
     170 * '''realm''' -- together with '''id''', can be used to create links to other resources than tickets (e.g. a realm of ''wiki'' and an ''id'' to a page name will create a link to that wiki page) 
     171 * '''created, modified, date, time''' -- Format cell as a date and/or time. 
     172 * '''description''' -- Ticket description field, parsed through the wiki engine. 
     173 
     174'''Example:''' 
    130175{{{ 
    131176SELECT id as ticket, created, status, summary FROM ticket  
    132177}}} 
    133178 
    134 === Customizando Formatação de Colunas === 
    135 Colunas nas quais os nomes começam e terminam com 2 underscores (Exemplo: '''_''''''_color_''''''_''')são 
    136 assumidos como ''dicas de formatação'', afetando a aparência da coluna. 
    137  
    138  * '''_''''''_group_''''''_''' -- Resultados do grupo baseado nos valores desta coluna. Cada grupo deverá ter seu próprio cabeçalho e tabela. 
    139  * '''_''''''_color_''''''_''' -- Deve ser valor numérico de 1 até 5 para selecionar uma cor de linha pre-definida. Tipicamente usado para colorir linhas de acordo com a prioridade. 
    140  * '''_''''''_style_''''''_''' -- Uma expressão CSS style customizada para usar na linha atual.  
    141  
    142 '''Exemplo:''' ''Lista tickets ativos, agrupados por milestone, coloridos por priority'' 
     179Those columns can also be defined but marked as hidden, see [#column-syntax below]. 
     180 
     181=== Custom formatting columns === 
     182Columns whose names begin and end with 2 underscores (Example: '''`__color__`''') are 
     183assumed to be ''formatting hints'', affecting the appearance of the row. 
     184  
     185 * '''`__group__`''' -- Group results based on values in this column. Each group will have its own header and table. 
     186 * '''`__color__`''' -- Should be a numeric value ranging from 1 to 5 to select a pre-defined row color. Typically used to color rows by issue priority. 
     187{{{ 
     188#!html 
     189<div style="margin-left:7.5em">Defaults:  
     190<span style="border: none; color: #333; background: transparent;  font-size: 85%; background: #fdc; border-color: #e88; color: #a22">Color 1</span> 
     191<span style="border: none; color: #333; background: transparent;  font-size: 85%; background: #ffb; border-color: #eea; color: #880">Color 2</span> 
     192<span style="border: none; color: #333; background: transparent;  font-size: 85%; background: #fbfbfb; border-color: #ddd; color: #444">Color 3</span> 
     193<span style="border: none; color: #333; background: transparent; font-size: 85%; background: #e7ffff; border-color: #cee; color: #099">Color 4</span> 
     194<span style="border: none; color: #333; background: transparent;  font-size: 85%; background: #e7eeff; border-color: #cde; color: #469">Color 5</span> 
     195</div> 
     196}}} 
     197 * '''`__style__`''' -- A custom CSS style expression to use for the current row.  
     198 
     199'''Example:''' ''List active tickets, grouped by milestone, colored by priority'' 
    143200{{{ 
    144201SELECT p.value AS __color__, 
     
    152209}}} 
    153210 
    154 '''Nota:''' O resultado da concatenação das tabelas é usado para associar prioridades de ''ticket'' com seus respectivas representações numéricas da tabela ''enum''. 
    155  
    156 === Mudando layout das linhas do relatório === 
    157 Por padrão, Todas colunas de cada linha são mostradas em uma única linha no relatório HTML, 
    158 possivelmente formatado de acordo com a descrição acima. Porém, é também possível criar múltiplas linhas de entrada do relatório. 
    159  
    160  * '''column_''' -- ''Quebre a linha após isto''. Colocando um underscore ('_') no nome da coluna, as colunas restantes continuarão na segunda linha. 
    161  
    162  * '''_column_''' -- ''Linha cheia''. Adicionando um underscore ('_') ambas no começo e fim no nome da coluna, os dados serão mostrados em linhas separadas. 
    163  
    164  * '''_column'''  --  ''Esconda dados''. Prefixando um underscore ('_') no nome da coluna instrui Trac a esconder o conteúdo da saída do HTML. Isto é útil para informações que serão visíveis apenas se for salva em outros formatos (CSV ou RSS/XML). 
    165  
    166 '''Exemplo:''' '' Lista tickets ativos, agrupados por milestone, colorido por prioridade, com descrição e layout de linhas múltiplas'' 
     211'''Note:''' A table join is used to match ''ticket'' priorities with their 
     212numeric representation from the ''enum'' table. 
     213 
     214=== Changing layout of report rows === #column-syntax 
     215By default, all columns on each row are display on a single row in the HTML 
     216report, possibly formatted according to the descriptions above. However, it's 
     217also possible to create multi-line report entries. 
     218 
     219 * '''`column_`''' -- ''Break row after this''. By appending an underscore ('_') to the column name, the remaining columns will be be continued on a second line. 
     220 
     221 * '''`_column_`''' -- ''Full row''. By adding an underscore ('_') both at the beginning and the end of a column name, the data will be shown on a separate row. 
     222 
     223 * '''`_column`'''  --  ''Hide data''. Prepending an underscore ('_') to a column name instructs Trac to hide the contents from the HTML output. This is useful for information to be visible only if downloaded in other formats (like CSV or RSS/XML). 
     224   This can be used to hide any kind of column, even important ones required for identifying the resource, e.g. `id as _id` will hide the '''Id''' column but the link to the ticket will be present. 
     225 
     226'''Example:''' ''List active tickets, grouped by milestone, colored by priority, with  description and multi-line layout'' 
    167227 
    168228{{{ 
     
    172232          WHEN 'daniel' THEN 'font-weight: bold; background: red;'  
    173233          ELSE '' END) AS __style__, 
    174        t.id AS ticket, summary AS summary_,             -- ## Quebra de linha aqui 
     234       t.id AS ticket, summary AS summary_,             -- ## Break line here 
    175235       component,version, severity, milestone, status, owner, 
    176        time AS created, changetime AS modified,         -- ## Date é formatada 
    177        description AS _description_,                    -- ## Usa uma linha inteira 
    178        changetime AS _changetime, reporter AS _reporter -- ## Esconde da saída HTML 
     236       time AS created, changetime AS modified,         -- ## Dates are formatted 
     237       description AS _description_,                    -- ## Uses a full row 
     238       changetime AS _changetime, reporter AS _reporter -- ## Hidden from HTML output 
    179239  FROM ticket t,enum p 
    180240  WHERE t.status IN ('new', 'assigned', 'reopened')  
     
    183243}}} 
    184244 
    185  
    186 ---- 
    187 Veja também: TracTickets, TracQuery, TracGuide 
     245=== Reporting on custom fields === 
     246 
     247If you have added custom fields to your tickets (a feature since v0.8, see TracTicketsCustomFields), you can write a SQL query to cover them. You'll need to make a join on the ticket_custom table, but this isn't especially easy. 
     248 
     249If you have tickets in the database ''before'' you declare the extra fields in trac.ini, there will be no associated data in the ticket_custom table. To get around this, use SQL's "LEFT OUTER JOIN" clauses. See [trac:TracIniReportCustomFieldSample TracIniReportCustomFieldSample] for some examples. 
     250 
     251'''Note that you need to set up permissions in order to see the buttons for adding or editing reports.''' 
     252 
     253---- 
     254See also: TracTickets, TracQuery, TracGuide, [http://www.sqlite.org/lang_expr.html Query Language Understood by SQLite]