-
Notifications
You must be signed in to change notification settings - Fork 0
[8559] Add analytics commands #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
fred-paragraph
wants to merge
1
commit into
main
Choose a base branch
from
par-8559-analytics
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,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); | ||
| } | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| import { analyticsQueryBody } from "@paragraph-com/sdk/zod"; | ||
| import type { AnalyticsQuery200, AnalyticsSchema200 } from "@paragraph-com/sdk"; | ||
| import { createClient } from "./client.js"; | ||
|
|
||
| export async function runQuery( | ||
| sql: string, | ||
| apiKey: string | ||
| ): Promise<AnalyticsQuery200> { | ||
| analyticsQueryBody.parse({ sql }); | ||
| const client = createClient(apiKey); | ||
| return client.analytics.query({ sql }); | ||
| } | ||
|
|
||
| export async function getSchema(apiKey: string): Promise<AnalyticsSchema200> { | ||
| const client = createClient(apiKey); | ||
| return client.analytics.schema(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since
resolveSqlis anasyncfunction and already awaitsreadStdin(), it is better to use the promise-basedfs.promises.readFileinstead of the synchronousfs.readFileSync. This maintains consistency and avoids blocking the event loop in an asynchronous context.