Repository navigation
Expand file tree
/
Copy pathReports.java
More file actions
323 lines (291 loc) · 11.8 KB
/
Copy pathReports.java
File metadata and controls
323 lines (291 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import io.trino.cli.lexer.StatementSplitter;
import io.trino.client.ClientSession;
import io.trino.client.Column;
import io.trino.client.QueryStatusInfo;
import io.trino.client.Row;
import io.trino.client.StatementClient;
import okhttp3.OkHttpClient;
import org.jline.utils.WCWidth;
import static io.trino.client.StatementClientFactory.newStatementClient;
// Generates the pages in reports/ from the queries in sql/, listed in sql/pages.properties, with the Trino CLI in the
// class path, for its client and statement splitter: bin/reports.sh [page ...]
// Every file is a section of its page: the first comment line is the title, and the next ones are the description.
// The result is an HTML table, or, if the file has the word "chart" anywhere, a table in a monospace font, aligned like
// the CLI does. Values made by memory.default.link and the other functions in sql/setup/01-functions.sql are links.
final Path PAGES_FILE = Path.of("sql/pages.properties");
final Set<String> NUMERIC_TYPES = Set.of("tinyint", "smallint", "integer", "bigint", "real", "double", "decimal");
final OkHttpClient httpClient = new OkHttpClient();
// in UTC, like the server, so functions like current_date don't depend on where this runs
final ClientSession session = ClientSession.builder()
.server(URI.create(System.getenv().getOrDefault("TRINO_URL", "http://localhost:8080")))
.user(Optional.of("reports"))
.source("reports")
.catalog("trinocicd")
.schema("github")
.timeZone(ZoneId.of("UTC"))
.build();
int failedReports;
void main(String[] args)
throws Exception
{
Properties pages = new Properties();
pages.load(Files.newBufferedReader(PAGES_FILE));
List<String> names = List.of(args.length > 0 ? args : pages.getProperty("pages").split(","));
checkListedEverywhere(names, pages);
runSetup();
for (String name : names) {
writePage(name, pages.getProperty(name + ".title"));
}
if (failedReports > 0) {
System.err.printf("%d reports failed%n", failedReports);
}
// the HTTP client keeps threads that would keep the JVM running for a while
System.exit(failedReports > 0 ? 1 : 0);
}
// the menu and the index are edited by hand, so a new page would be missing from them
void checkListedEverywhere(List<String> names, Properties pages)
throws IOException
{
String menu = Files.readString(Path.of("_config.yml"));
String index = Files.readString(Path.of("reports/index.md"));
for (String name : names) {
if (!pages.containsKey(name + ".title") || !menu.contains("reports/%s/index.md".formatted(name)) || !index.contains("/reports/%s/".formatted(name))) {
throw new IllegalArgumentException("Add the page %s to %s, nav_pages in _config.yml, and reports/index.md".formatted(name, PAGES_FILE));
}
}
}
// tables and functions in the memory catalog, which all reports use, so a failure stops all of them
void runSetup()
throws IOException, QueryFailedException
{
for (Path file : sqlFiles("setup")) {
System.err.println("Executing setup queries from " + file);
run(Files.readString(file));
}
}
void writePage(String name, String title)
throws IOException
{
StringBuilder page = new StringBuilder("---\ntitle: %s\n---\n\n".formatted(title));
for (Path file : sqlFiles(name)) {
page.append(section(file));
}
page.append("Generated on ").append(new Date()).append('\n');
Files.createDirectories(Path.of("reports", name));
Files.writeString(Path.of("reports", name, "index.md"), page);
}
String section(Path file)
throws IOException
{
System.err.println("Executing query from " + file);
String sql = Files.readString(file);
List<String> comments = sql.lines()
.takeWhile(line -> line.startsWith("--"))
.map(line -> line.replaceFirst("^-- ?", ""))
.toList();
String title = comments.getFirst();
String description = String.join("\n", comments.subList(1, comments.size()));
boolean chart = sql.toLowerCase(Locale.ENGLISH).contains("chart");
return "## %s\n\n%s\n\n%s%s\n".formatted(title, description, results(file, sql, chart), queryLink(file));
}
String results(Path file, String sql, boolean chart)
{
try {
StringBuilder tables = new StringBuilder();
for (Result result : run(sql)) {
tables.append(chart ? alignedTable(result) : htmlTable(result));
}
return chart ? "<pre><code>\n" + tables + "</code></pre>\n" : tables + "\n";
}
catch (QueryFailedException e) {
failedReports++;
System.err.printf("Query in %s failed: %s%n", file, e.getMessage());
return "This report failed: " + escapeHtml(e.getMessage()) + "\n\n";
}
}
// a link to the query on GitHub, when generated by a workflow
static String queryLink(Path file)
{
String repository = System.getenv("GITHUB_REPOSITORY");
if (repository == null) {
return "";
}
String server = System.getenv().getOrDefault("GITHUB_SERVER_URL", "https://github.com");
String commit = System.getenv().getOrDefault("GITHUB_SHA", "main");
return "[query](%s/%s/blob/%s/%s)\n".formatted(server, repository, commit, file);
}
List<Result> run(String sql)
throws QueryFailedException
{
List<Result> results = new ArrayList<>();
for (String statement : statements(sql)) {
execute(statement).ifPresent(results::add);
}
return results;
}
static List<String> statements(String sql)
{
StatementSplitter splitter = new StatementSplitter(sql);
List<String> statements = new ArrayList<>();
splitter.getCompleteStatements().forEach(statement -> statements.add(statement.statement()));
if (!StatementSplitter.isEmptyStatement(splitter.getPartialStatement())) {
statements.add(splitter.getPartialStatement());
}
return statements;
}
// the result of a query, or nothing for statements that don't return rows, like CREATE TABLE
Optional<Result> execute(String statement)
throws QueryFailedException
{
try (StatementClient client = newStatementClient(httpClient, session, statement, Optional.empty())) {
List<List<Object>> rows = new ArrayList<>();
while (client.isRunning()) {
client.currentRows().forEach(rows::add);
client.advance();
}
QueryStatusInfo status = client.finalStatusInfo();
if (status.getError() != null) {
throw new QueryFailedException(status.getError().getMessage());
}
return Optional.ofNullable(status.getColumns()).map(columns -> result(columns, rows));
}
}
Result result(List<Column> columns, List<List<Object>> rows)
{
return new Result(
columns.stream().map(Column::getName).toList(),
columns.stream().map(column -> NUMERIC_TYPES.contains(column.getType().replaceFirst("\\(.*", ""))).toList(),
rows.stream().map(row -> row.stream().map(Cell::of).toList()).toList());
}
static String htmlTable(Result result)
{
StringBuilder table = new StringBuilder("<table>\n<thead>\n<tr>");
for (int i = 0; i < result.names().size(); i++) {
table.append(htmlCell("th", escapeHtml(result.names().get(i)), result.numeric().get(i)));
}
table.append("</tr>\n</thead>\n<tbody>\n");
for (List<Cell> row : result.rows()) {
table.append("<tr>");
for (int i = 0; i < row.size(); i++) {
table.append(htmlCell("td", row.get(i).html().replace("\n", "<br>"), result.numeric().get(i)));
}
table.append("</tr>\n");
}
return table.append("</tbody>\n</table>\n").toString();
}
static String htmlCell(String tag, String content, boolean numeric)
{
return "<%s%s>%s</%s>".formatted(tag, numeric ? " style=\"text-align: right\"" : "", content, tag);
}
// aligned like the Trino CLI does, so characters of charts line up between rows
static String alignedTable(Result result)
{
int[] widths = columnWidths(result);
List<String> header = new ArrayList<>();
List<String> separator = new ArrayList<>();
for (int i = 0; i < widths.length; i++) {
header.add(center(escapeHtml(result.names().get(i)), displayWidth(result.names().get(i)), widths[i]));
separator.add("-".repeat(widths[i] + 2));
}
StringBuilder table = new StringBuilder();
table.append(String.join("|", header)).append('\n');
table.append(String.join("+", separator)).append('\n');
for (List<Cell> row : result.rows()) {
List<String> cells = new ArrayList<>();
for (int i = 0; i < widths.length; i++) {
cells.add(align(row.get(i).html(), row.get(i).width(), widths[i], result.numeric().get(i)));
}
table.append(String.join("|", cells)).append('\n');
}
int rows = result.rows().size();
return table.append("(%d row%s)\n".formatted(rows, rows == 1 ? "" : "s")).toString();
}
static int[] columnWidths(Result result)
{
int[] widths = new int[result.names().size()];
for (int i = 0; i < widths.length; i++) {
widths[i] = displayWidth(result.names().get(i));
for (List<Cell> row : result.rows()) {
widths[i] = Math.max(widths[i], row.get(i).width());
}
}
return widths;
}
// the content is HTML, so its width is given
static String center(String content, int width, int columnWidth)
{
int left = (columnWidth - width) / 2;
return " ".repeat(left + 1) + content + " ".repeat(columnWidth - width - left + 1);
}
static String align(String content, int width, int columnWidth, boolean right)
{
String padding = " ".repeat(columnWidth - width + 1);
return right ? padding + content + " " : " " + content + padding;
}
// the number of columns that the text takes in a terminal, where some characters, like CJK ideographs, take two
static int displayWidth(String text)
{
return text.codePoints().map(codePoint -> Math.max(WCWidth.wcwidth(codePoint), 0)).sum();
}
static String escapeHtml(String text)
{
return text.replace("&", "&").replace("<", "<").replace(">", ">");
}
static List<Path> sqlFiles(String dir)
throws IOException
{
try (Stream<Path> files = Files.list(Path.of("sql", dir))) {
return files.filter(file -> file.toString().endsWith(".sql")).sorted().toList();
}
}
record Result(List<String> names, List<Boolean> numeric, List<List<Cell>> rows) {}
// text with links, which memory.default.link and the other functions in sql/setup/01-functions.sql return
// as an array of rows with the text and url fields
record Cell(List<Part> parts)
{
static Cell of(Object value)
{
if (value == null) {
return new Cell(List.of());
}
if (value instanceof List<?> list && isTextWithLinks(list)) {
return new Cell(list.stream()
.map(item -> ((Row) item).getFields())
.map(fields -> new Part(String.valueOf(fields.getFirst().getValue()), (String) fields.getLast().getValue()))
.toList());
}
return new Cell(List.of(new Part(value.toString(), null)));
}
static boolean isTextWithLinks(List<?> list)
{
return !list.isEmpty() && list.stream().allMatch(item -> item instanceof Row row
&& row.getFields().size() == 2
&& row.getFields().getLast().getName().equals(Optional.of("url")));
}
int width()
{
return parts.stream().mapToInt(part -> displayWidth(part.text())).sum();
}
String html()
{
return parts.stream().map(Part::html).collect(Collectors.joining());
}
}
record Part(String text, String url)
{
String html()
{
if (url == null) {
return escapeHtml(text);
}
return "<a href=\"%s\">%s</a>".formatted(escapeHtml(url), escapeHtml(text));
}
}
static class QueryFailedException
extends Exception
{
QueryFailedException(String message)
{
super(message);
}
}