-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanalytics.ts
More file actions
140 lines (128 loc) · 4.34 KB
/
Copy pathanalytics.ts
File metadata and controls
140 lines (128 loc) · 4.34 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
import * as fs from "fs";
import { Command } from "commander";
import { requireApiKey } from "../../services/auth.js";
import * as analytics from "../../services/analytics.js";
import {
outputTable,
writeInfo,
isJsonMode,
} from "../lib/output.js";
import { handleError } from "../lib/error.js";
import { readStdin } from "../lib/stdin.js";
async function resolveSql(
positional: string | undefined,
opts: { sql?: string; file?: string }
): Promise<string | undefined> {
if (opts.sql) return opts.sql;
if (positional) return positional;
if (opts.file) {
if (!fs.existsSync(opts.file)) {
throw new Error(
`File not found: "${opts.file}". Check the path, or pass the SQL inline via --sql or as a positional argument.`
);
}
return fs.readFileSync(opts.file, "utf-8");
}
const stdin = await readStdin();
return stdin?.trim() || undefined;
}
function formatCell(value: unknown): string {
if (value === null) return "NULL";
if (value === undefined) return "";
if (typeof value === "object") return JSON.stringify(value);
return String(value);
}
export function registerAnalyticsCommands(program: Command): void {
const root = program
.command("analytics")
.description("Run SQL queries against your publication's analytics");
root
.command("query [sql]")
.description(
"Run a read-only SQL query against your publication's analytics schema"
)
.option("--sql <query>", "SQL query string")
.option("--file <path>", "Read SQL from a file")
.addHelpText(
"after",
`
Examples:
$ paragraph analytics query "SELECT active_subscriber_count FROM blog_subscriber_counts"
$ paragraph analytics query --file ./top-posts.sql
$ cat query.sql | paragraph analytics query
$ paragraph analytics query "SELECT title, open_rate FROM post_analytics_summary LIMIT 5" --json | jq '.rows'
Rules:
- SELECT / WITH (CTE) statements only
- Tables are scoped to your publication automatically
- No semicolons; 30-second timeout; 10,000-row cap
- Run \`paragraph analytics schema\` to discover tables and columns`
)
.action(async function (
this: Command,
positionalSql: string | undefined,
opts
) {
try {
const apiKey = requireApiKey();
const sql = await resolveSql(positionalSql, opts);
if (!sql) {
throw new Error(
"Provide a SQL query via positional argument, --sql, --file, or pipe to stdin."
);
}
const result = await analytics.runQuery(sql, apiKey);
if (isJsonMode(this)) {
process.stdout.write(JSON.stringify(result, null, 2) + "\n");
return;
}
const headers = result.fields.map((f) => f.name);
const rows = result.rows.map((row) =>
headers.map((h) => formatCell((row as Record<string, unknown>)[h]))
);
outputTable(this, headers, rows, result.rows);
const rowLabel = result.rowCount === 1 ? "row" : "rows";
const truncatedSuffix = result.truncated ? " (truncated at 10,000)" : "";
writeInfo(`${result.rowCount} ${rowLabel} returned${truncatedSuffix}`);
} catch (err) {
handleError(err);
}
});
root
.command("schema")
.description(
"List tables and columns available in your publication's analytics schema"
)
.addHelpText(
"after",
`
Examples:
$ paragraph analytics schema
$ paragraph analytics schema --json | jq '.tables[] | select(.table_name == "post_analytics_summary")'`
)
.action(async function (this: Command) {
try {
const apiKey = requireApiKey();
const result = await analytics.getSchema(apiKey);
if (isJsonMode(this)) {
process.stdout.write(JSON.stringify(result, null, 2) + "\n");
return;
}
const sorted = [...result.tables].sort((a, b) => {
const byTable = a.table_name.localeCompare(b.table_name);
return byTable !== 0
? byTable
: a.column_name.localeCompare(b.column_name);
});
const headers = ["Table", "Column", "Type", "Nullable"];
const rows = sorted.map((t) => [
t.table_name,
t.column_name,
t.data_type,
t.is_nullable,
]);
outputTable(this, headers, rows, sorted);
} catch (err) {
handleError(err);
}
});
}