clickhouse-tool 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. clickhouse_tool/__about__.py +1 -0
  2. clickhouse_tool/__init__.py +5 -0
  3. clickhouse_tool/__main__.py +6 -0
  4. clickhouse_tool/cli/__init__.py +0 -0
  5. clickhouse_tool/cli/commands/__init__.py +0 -0
  6. clickhouse_tool/cli/commands/config.py +21 -0
  7. clickhouse_tool/cli/commands/facets.py +132 -0
  8. clickhouse_tool/cli/commands/listing.py +45 -0
  9. clickhouse_tool/cli/commands/logs.py +72 -0
  10. clickhouse_tool/cli/commands/metrics.py +204 -0
  11. clickhouse_tool/cli/commands/query.py +63 -0
  12. clickhouse_tool/cli/commands/tables.py +25 -0
  13. clickhouse_tool/cli/main.py +66 -0
  14. clickhouse_tool/cli/runner.py +141 -0
  15. clickhouse_tool/cli/wiring.py +95 -0
  16. clickhouse_tool/core/__init__.py +0 -0
  17. clickhouse_tool/core/client/__init__.py +0 -0
  18. clickhouse_tool/core/client/base.py +34 -0
  19. clickhouse_tool/core/client/factory.py +66 -0
  20. clickhouse_tool/core/client/http.py +95 -0
  21. clickhouse_tool/core/client/native.py +186 -0
  22. clickhouse_tool/core/config.py +265 -0
  23. clickhouse_tool/core/errors.py +126 -0
  24. clickhouse_tool/core/exit_codes.py +25 -0
  25. clickhouse_tool/core/humanize.py +58 -0
  26. clickhouse_tool/core/logging.py +67 -0
  27. clickhouse_tool/core/models.py +55 -0
  28. clickhouse_tool/core/monitoring.py +32 -0
  29. clickhouse_tool/core/ssm.py +77 -0
  30. clickhouse_tool/core/timezone.py +41 -0
  31. clickhouse_tool/formatters/__init__.py +47 -0
  32. clickhouse_tool/formatters/base.py +54 -0
  33. clickhouse_tool/formatters/json.py +43 -0
  34. clickhouse_tool/formatters/ndjson.py +31 -0
  35. clickhouse_tool/formatters/table.py +158 -0
  36. clickhouse_tool/formatters/toon.py +70 -0
  37. clickhouse_tool/query/__init__.py +0 -0
  38. clickhouse_tool/query/builder.py +426 -0
  39. clickhouse_tool/query/columns.py +34 -0
  40. clickhouse_tool/query/intents.py +91 -0
  41. clickhouse_tool/query/predicates.py +92 -0
  42. clickhouse_tool/query/sort.py +44 -0
  43. clickhouse_tool/query/tables.py +46 -0
  44. clickhouse_tool/query/timerange.py +91 -0
  45. clickhouse_tool-0.1.1.dist-info/METADATA +52 -0
  46. clickhouse_tool-0.1.1.dist-info/RECORD +49 -0
  47. clickhouse_tool-0.1.1.dist-info/WHEEL +4 -0
  48. clickhouse_tool-0.1.1.dist-info/entry_points.txt +2 -0
  49. clickhouse_tool-0.1.1.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,5 @@
1
+ from clickhouse_tool import __about__
2
+
3
+ __version__ = __about__.__version__
4
+
5
+ __all__ = ["__about__", "__version__"]
@@ -0,0 +1,6 @@
1
+ """Entry point for ``python -m clickhouse_tool``."""
2
+
3
+ from clickhouse_tool.cli.main import run
4
+
5
+ if __name__ == "__main__":
6
+ run()
File without changes
File without changes
@@ -0,0 +1,21 @@
1
+ """The skip-secrets verb: shows the resolved profile with provenance.
2
+
3
+ Never materialises secrets and never opens a connection, so it works
4
+ with no AWS credentials present at all.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+
11
+ import typer
12
+
13
+ from clickhouse_tool.cli import wiring
14
+
15
+
16
+ def config(
17
+ profile: str | None = typer.Option(None, "--profile", help="Named connection profile"),
18
+ ) -> None:
19
+ """Show the resolved configuration, with secrets redacted."""
20
+ resolved = wiring.load_profile(profile)
21
+ print(json.dumps(resolved.model_dump(), indent=2, default=str))
@@ -0,0 +1,132 @@
1
+ """The host and service verbs: a grouped count over the shared time and filter flags."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime
6
+
7
+ import typer
8
+
9
+ from clickhouse_tool.cli import wiring
10
+ from clickhouse_tool.cli.runner import run_statement
11
+ from clickhouse_tool.core.errors import ConfigError
12
+ from clickhouse_tool.core.humanize import format_relative_time
13
+ from clickhouse_tool.core.logging import setup_logging
14
+ from clickhouse_tool.core.models import RowSet
15
+ from clickhouse_tool.formatters import get_formatter
16
+ from clickhouse_tool.query.builder import build_facet, build_metrics_facet
17
+ from clickhouse_tool.query.intents import FacetIntent, Filters
18
+
19
+ _SUPPORTED_STREAMS = ("logs", "metrics")
20
+
21
+
22
+ def _humanize_last_seen(rows: RowSet) -> RowSet:
23
+ """Replace the raw `last_seen` datetime with a rendered '2h 20m ago' string."""
24
+ idx = next(i for i, col in enumerate(rows.columns) if col.name == "last_seen")
25
+ now = datetime.now(UTC)
26
+ new_rows = tuple(
27
+ row[:idx] + (format_relative_time(row[idx], now=now),) + row[idx + 1 :] for row in rows.rows
28
+ )
29
+ return RowSet(columns=rows.columns, rows=new_rows, row_count=rows.row_count, truncated=rows.truncated)
30
+
31
+
32
+ def _facet(
33
+ facet_field: str,
34
+ *,
35
+ profile: str | None,
36
+ namespace: str | None,
37
+ container: str | None,
38
+ level: str | None,
39
+ time_range: str | None,
40
+ search: str | None,
41
+ stream: str,
42
+ limit: int,
43
+ unbounded: bool,
44
+ output_format: str | None,
45
+ verbose: bool,
46
+ ) -> None:
47
+ setup_logging(verbose)
48
+ if stream not in _SUPPORTED_STREAMS:
49
+ accepted = ", ".join(_SUPPORTED_STREAMS)
50
+ raise ConfigError(f"unsupported stream '{stream}'; accepted: {accepted}")
51
+ resolved = wiring.load_profile(profile)
52
+ filters = Filters(
53
+ namespace=namespace,
54
+ container=container,
55
+ level=level,
56
+ time_range=time_range if time_range is not None else resolved.default_window,
57
+ search=search,
58
+ )
59
+ intent = FacetIntent(facet_field=facet_field, filters=filters, limit=limit, unbounded=unbounded)
60
+ if stream == "metrics":
61
+ table = wiring.resolve_metrics_table(resolved)
62
+ statement = build_metrics_facet(intent, table)
63
+ else:
64
+ table = wiring.resolve_logs_table(resolved)
65
+ statement = build_facet(intent, table)
66
+ formatter = get_formatter(output_format or resolved.default_format)
67
+ client = wiring.open_client(resolved)
68
+ run_statement(client, statement, formatter, table=table, row_transform=_humanize_last_seen)
69
+
70
+
71
+ def hosts(
72
+ profile: str | None = typer.Option(None, "--profile", help="Named connection profile"),
73
+ namespace: str | None = typer.Option(None, "--namespace", help="Filter by namespace"),
74
+ container: str | None = typer.Option(None, "--container", help="Filter by container name"),
75
+ level: str | None = typer.Option(None, "--level", "-l", help="Minimum severity level"),
76
+ time_range: str | None = typer.Option(
77
+ None, "-t", "--time-range", help="Time window, e.g. 15m, 2h, 1d [default: 2h]"
78
+ ),
79
+ search: str | None = typer.Option(None, "--search", "-s", help="Full-text search term"),
80
+ stream: str = typer.Option("metrics", "--stream", help="Data stream to facet over"),
81
+ limit: int = typer.Option(200, "-n", "--limit", help="Maximum number of hosts returned"),
82
+ unbounded: bool = typer.Option(False, "--unbounded", help="Return every host, no cap"),
83
+ output_format: str | None = typer.Option(None, "-f", "--format", help="Output format"),
84
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging"),
85
+ ) -> None:
86
+ """Count activity grouped by host, metrics stream by default."""
87
+ _facet(
88
+ "host",
89
+ profile=profile,
90
+ namespace=namespace,
91
+ container=container,
92
+ level=level,
93
+ time_range=time_range,
94
+ search=search,
95
+ stream=stream,
96
+ limit=limit,
97
+ unbounded=unbounded,
98
+ output_format=output_format,
99
+ verbose=verbose,
100
+ )
101
+
102
+
103
+ def services(
104
+ profile: str | None = typer.Option(None, "--profile", help="Named connection profile"),
105
+ namespace: str | None = typer.Option(None, "--namespace", help="Filter by namespace"),
106
+ container: str | None = typer.Option(None, "--container", help="Filter by container name"),
107
+ level: str | None = typer.Option(None, "--level", "-l", help="Minimum severity level"),
108
+ time_range: str | None = typer.Option(
109
+ None, "-t", "--time-range", help="Time window, e.g. 15m, 2h, 1d [default: 2h]"
110
+ ),
111
+ search: str | None = typer.Option(None, "--search", "-s", help="Full-text search term"),
112
+ stream: str = typer.Option("metrics", "--stream", help="Data stream to facet over"),
113
+ limit: int = typer.Option(200, "-n", "--limit", help="Maximum number of services returned"),
114
+ unbounded: bool = typer.Option(False, "--unbounded", help="Return every service, no cap"),
115
+ output_format: str | None = typer.Option(None, "-f", "--format", help="Output format"),
116
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging"),
117
+ ) -> None:
118
+ """Count activity grouped by service, metrics stream by default."""
119
+ _facet(
120
+ "service",
121
+ profile=profile,
122
+ namespace=namespace,
123
+ container=container,
124
+ level=level,
125
+ time_range=time_range,
126
+ search=search,
127
+ stream=stream,
128
+ limit=limit,
129
+ unbounded=unbounded,
130
+ output_format=output_format,
131
+ verbose=verbose,
132
+ )
@@ -0,0 +1,45 @@
1
+ """Low-level table inspection over the existing allow-list: list and lift."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+
7
+ from clickhouse_tool.cli import wiring
8
+ from clickhouse_tool.cli.runner import run_statement
9
+ from clickhouse_tool.core.logging import setup_logging
10
+ from clickhouse_tool.formatters import get_formatter
11
+ from clickhouse_tool.query.builder import build_lift, build_list
12
+ from clickhouse_tool.query.intents import LiftIntent, ListIntent
13
+
14
+ _LIFT_DEFAULT_FORMAT = "json"
15
+
16
+
17
+ def list_(
18
+ table: str = typer.Argument(..., help="Allow-listed table, e.g. otel.logs or system.parts"),
19
+ profile: str | None = typer.Option(None, "--profile", help="Named connection profile"),
20
+ limit: int | None = typer.Option(None, "-n", "--limit", help="Maximum rows returned"),
21
+ output_format: str | None = typer.Option(None, "-f", "--format", help="Output format"),
22
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging"),
23
+ ) -> None:
24
+ """List rows from an allow-listed table."""
25
+ setup_logging(verbose)
26
+ resolved = wiring.load_profile(profile)
27
+ statement = build_list(ListIntent(table=table, limit=limit))
28
+ formatter = get_formatter(output_format or resolved.default_format)
29
+ client = wiring.open_client(resolved)
30
+ run_statement(client, statement, formatter)
31
+
32
+
33
+ def lift(
34
+ table: str = typer.Argument(..., help="Allow-listed table, e.g. otel.logs or system.parts"),
35
+ profile: str | None = typer.Option(None, "--profile", help="Named connection profile"),
36
+ output_format: str | None = typer.Option(None, "-f", "--format", help="Output format"),
37
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging"),
38
+ ) -> None:
39
+ """Describe column metadata for an allow-listed table."""
40
+ setup_logging(verbose)
41
+ resolved = wiring.load_profile(profile)
42
+ statement = build_lift(LiftIntent(table=table))
43
+ formatter = get_formatter(output_format or _LIFT_DEFAULT_FORMAT)
44
+ client = wiring.open_client(resolved)
45
+ run_statement(client, statement, formatter)
@@ -0,0 +1,72 @@
1
+ """The baseline verb for querying raw log rows. The only verb that may stream."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+
7
+ from clickhouse_tool.cli import wiring
8
+ from clickhouse_tool.cli.runner import run_follow, run_statement
9
+ from clickhouse_tool.core.errors import ConfigError
10
+ from clickhouse_tool.core.logging import setup_logging
11
+ from clickhouse_tool.core.timezone import resolve_display_timezone
12
+ from clickhouse_tool.formatters import get_formatter
13
+ from clickhouse_tool.query.builder import build_count, build_initial_cursor, build_latest_cursor, build_logs
14
+ from clickhouse_tool.query.intents import CountIntent, Filters, LogsIntent
15
+
16
+
17
+ def logs(
18
+ profile: str | None = typer.Option(None, "--profile", help="Named connection profile"),
19
+ host: str | None = typer.Option(None, "--host", "-h", help="Filter by host name"),
20
+ service: str | None = typer.Option(None, "--service", help="Filter by service name"),
21
+ namespace: str | None = typer.Option(None, "--namespace", help="Filter by namespace"),
22
+ container: str | None = typer.Option(None, "--container", help="Filter by container name"),
23
+ level: str | None = typer.Option(None, "--level", "-l", help="Minimum severity level"),
24
+ time_range: str | None = typer.Option(
25
+ None, "-t", "--time-range", help="Time window, e.g. 15m, 2h, 1d [default: 2h]"
26
+ ),
27
+ search: str | None = typer.Option(None, "--search", "-s", help="Full-text search term"),
28
+ sort: str | None = typer.Option(None, "--sort", help="Sort order, e.g. @timestamp:desc"),
29
+ full: bool = typer.Option(False, "--full", help="Select every column, nested output"),
30
+ raw: bool = typer.Option(False, "--raw", help="Alias for --full"),
31
+ count: bool = typer.Option(False, "--count", help="Return a row count instead of rows"),
32
+ follow: bool = typer.Option(
33
+ False, "--follow", help="Poll continuously for new rows, oldest first (Ctrl-C to stop)"
34
+ ),
35
+ utc: bool = typer.Option(False, "--utc", help="Show timestamps in UTC instead of local time"),
36
+ limit: int | None = typer.Option(None, "-n", "--limit", help="Maximum rows returned"),
37
+ output_format: str | None = typer.Option(None, "-f", "--format", help="Output format"),
38
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging"),
39
+ ) -> None:
40
+ """Query raw log rows."""
41
+ setup_logging(verbose)
42
+ if follow and count:
43
+ raise ConfigError("--follow does not support --count")
44
+ if follow and sort is not None:
45
+ raise ConfigError("--follow always orders oldest-first and does not support --sort")
46
+ resolved = wiring.load_profile(profile)
47
+ table = wiring.resolve_logs_table(resolved)
48
+ window = time_range if time_range is not None else resolved.default_window
49
+ filters = Filters(
50
+ host=host,
51
+ service=service,
52
+ namespace=namespace,
53
+ container=container,
54
+ level=level,
55
+ time_range=window,
56
+ search=search,
57
+ )
58
+ tz = resolve_display_timezone(utc=utc, configured=resolved.default_timezone)
59
+ intent = LogsIntent(filters=filters, full=full, raw=raw, sort=sort, limit=limit, tz=tz)
60
+ formatter = get_formatter(output_format or resolved.default_format, follow=follow)
61
+ client = wiring.open_client(resolved)
62
+ if follow:
63
+ latest = client.execute(build_latest_cursor(intent, table))
64
+ since = latest.rows[0][0] if latest.rows else client.execute(build_initial_cursor(window)).rows[0][0]
65
+ run_follow(client, intent=intent, table=table, formatter=formatter, since=since)
66
+ return
67
+ statement = (
68
+ build_count(CountIntent.from_logs_intent(intent), table)
69
+ if count
70
+ else build_logs(intent, table)
71
+ )
72
+ run_statement(client, statement, formatter, table=table)
@@ -0,0 +1,204 @@
1
+ """The `metrics` verb group: names, summary stats, raw values, and histograms."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+
7
+ from clickhouse_tool.cli import wiring
8
+ from clickhouse_tool.cli.commands.facets import _facet
9
+ from clickhouse_tool.cli.runner import run_metric_follow, run_statement
10
+ from clickhouse_tool.core.logging import setup_logging
11
+ from clickhouse_tool.formatters import get_formatter
12
+ from clickhouse_tool.query.builder import (
13
+ build_initial_cursor,
14
+ build_latest_metric_cursor,
15
+ build_metric_histogram,
16
+ build_metric_status,
17
+ build_metric_values,
18
+ )
19
+ from clickhouse_tool.query.intents import MetricQuery
20
+ from clickhouse_tool.query.timerange import default_bucket_size, default_time_precision
21
+
22
+ app = typer.Typer(help="Metric names, summary stats, raw values, and histograms.")
23
+
24
+
25
+ @app.callback(invoke_without_command=True)
26
+ def _default_to_names(ctx: typer.Context) -> None:
27
+ """Bare `metrics` behaves as `metrics names` with every default."""
28
+ if ctx.invoked_subcommand is None:
29
+ _names_impl(profile=None, time_range=None, limit=200, unbounded=False, output_format=None, verbose=False)
30
+
31
+
32
+ _NAME_ARG = typer.Argument(..., help="Exact metric name, or a dotted stem matching every child")
33
+ _HOST_OPT = typer.Option(None, "--host", "-h", help="Filter by host name")
34
+ _SERVICE_OPT = typer.Option(None, "--service", help="Filter by service name")
35
+ _TIME_RANGE_OPT = typer.Option(None, "-t", "--time-range", help="Time window, e.g. 15m, 2h, 1d [default: 2h]")
36
+ _DECIMALS_OPT = typer.Option(2, "--decimals", help="Decimal places for humanized numbers in table output")
37
+ _TS_DECIMALS_OPT = typer.Option(
38
+ None,
39
+ "--ts-decimals",
40
+ help="Fractional-second digits for timestamps in table output "
41
+ "[default: auto -- seconds under 3h, minutes for longer windows]",
42
+ )
43
+ _SPLIT_BY_OPT = typer.Option(None, "--split-by", help="Break results out by host, service, or host,service")
44
+
45
+
46
+ def _parse_split_by(split_by: str | None) -> tuple[str, ...]:
47
+ return tuple(field.strip() for field in split_by.split(",")) if split_by else ()
48
+
49
+
50
+ def _resolve_ts_display(ts_decimals: int | None, window: str) -> tuple[int, str]:
51
+ """An explicit ``--ts-decimals`` always implies second-level display."""
52
+ if ts_decimals is not None:
53
+ return ts_decimals, "s"
54
+ return 0, default_time_precision(window)
55
+
56
+
57
+ def _query(name: str, host: str | None, service: str | None, window: str) -> MetricQuery:
58
+ return MetricQuery(name=name, host=host, service=service, time_range=window)
59
+
60
+
61
+ def _names_impl(
62
+ *,
63
+ profile: str | None,
64
+ time_range: str | None,
65
+ limit: int,
66
+ unbounded: bool,
67
+ output_format: str | None,
68
+ verbose: bool,
69
+ ) -> None:
70
+ _facet(
71
+ "metric",
72
+ profile=profile,
73
+ namespace=None,
74
+ container=None,
75
+ level=None,
76
+ time_range=time_range,
77
+ search=None,
78
+ stream="metrics",
79
+ limit=limit,
80
+ unbounded=unbounded,
81
+ output_format=output_format,
82
+ verbose=verbose,
83
+ )
84
+
85
+
86
+ @app.command("names")
87
+ def names(
88
+ profile: str | None = typer.Option(None, "--profile", help="Named connection profile"),
89
+ time_range: str | None = _TIME_RANGE_OPT,
90
+ limit: int = typer.Option(200, "-n", "--limit", help="Maximum number of metric names returned"),
91
+ unbounded: bool = typer.Option(False, "--unbounded", help="Return every metric name, no cap"),
92
+ output_format: str | None = typer.Option(None, "-f", "--format", help="Output format"),
93
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging"),
94
+ ) -> None:
95
+ """List available metric names, with datapoint counts and last-seen time."""
96
+ _names_impl(
97
+ profile=profile,
98
+ time_range=time_range,
99
+ limit=limit,
100
+ unbounded=unbounded,
101
+ output_format=output_format,
102
+ verbose=verbose,
103
+ )
104
+
105
+
106
+ @app.command("status")
107
+ def status(
108
+ name: str = _NAME_ARG,
109
+ profile: str | None = typer.Option(None, "--profile", help="Named connection profile"),
110
+ host: str | None = _HOST_OPT,
111
+ service: str | None = _SERVICE_OPT,
112
+ time_range: str | None = _TIME_RANGE_OPT,
113
+ split_by: str | None = _SPLIT_BY_OPT,
114
+ decimals: int = _DECIMALS_OPT,
115
+ output_format: str | None = typer.Option(None, "-f", "--format", help="Output format"),
116
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging"),
117
+ ) -> None:
118
+ """Min/max/avg/stddev for a metric (or every metric under a dotted stem)."""
119
+ setup_logging(verbose)
120
+ resolved = wiring.load_profile(profile)
121
+ table = wiring.resolve_metrics_table(resolved)
122
+ window = time_range if time_range is not None else resolved.default_window
123
+ statement = build_metric_status(_query(name, host, service, window), table, _parse_split_by(split_by))
124
+ formatter = get_formatter(output_format or resolved.default_format, decimals=decimals)
125
+ client = wiring.open_client(resolved)
126
+ run_statement(client, statement, formatter, table=table)
127
+
128
+
129
+ @app.command("values")
130
+ def values(
131
+ name: str = _NAME_ARG,
132
+ profile: str | None = typer.Option(None, "--profile", help="Named connection profile"),
133
+ host: str | None = _HOST_OPT,
134
+ service: str | None = _SERVICE_OPT,
135
+ time_range: str | None = _TIME_RANGE_OPT,
136
+ follow: bool = typer.Option(
137
+ False, "--follow", help="Poll continuously for new datapoints, oldest first (Ctrl-C to stop)"
138
+ ),
139
+ limit: int | None = typer.Option(None, "-n", "--limit", help="Maximum datapoints returned"),
140
+ decimals: int = _DECIMALS_OPT,
141
+ ts_decimals: int | None = _TS_DECIMALS_OPT,
142
+ output_format: str | None = typer.Option(None, "-f", "--format", help="Output format"),
143
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging"),
144
+ ) -> None:
145
+ """Raw datapoints for a metric (or every metric under a dotted stem)."""
146
+ setup_logging(verbose)
147
+ if follow and limit is not None:
148
+ raise typer.BadParameter("--follow does not support --limit") from None
149
+ resolved = wiring.load_profile(profile)
150
+ table = wiring.resolve_metrics_table(resolved)
151
+ window = time_range if time_range is not None else resolved.default_window
152
+ query = _query(name, host, service, window)
153
+ resolved_ts_decimals, ts_precision = _resolve_ts_display(ts_decimals, window)
154
+ formatter = get_formatter(
155
+ output_format or resolved.default_format,
156
+ follow=follow,
157
+ decimals=decimals,
158
+ ts_decimals=resolved_ts_decimals,
159
+ ts_precision=ts_precision,
160
+ )
161
+ client = wiring.open_client(resolved)
162
+ if follow:
163
+ latest = client.execute(build_latest_metric_cursor(query, table))
164
+ since = latest.rows[0][0] if latest.rows else client.execute(build_initial_cursor(window)).rows[0][0]
165
+ run_metric_follow(client, query=query, table=table, formatter=formatter, since=since)
166
+ return
167
+ statement = build_metric_values(query, table, limit=limit)
168
+ run_statement(client, statement, formatter, table=table)
169
+
170
+
171
+ @app.command("histogram")
172
+ def histogram(
173
+ name: str = _NAME_ARG,
174
+ profile: str | None = typer.Option(None, "--profile", help="Named connection profile"),
175
+ host: str | None = _HOST_OPT,
176
+ service: str | None = _SERVICE_OPT,
177
+ time_range: str | None = _TIME_RANGE_OPT,
178
+ bucket: str | None = typer.Option(
179
+ None, "--bucket", help="Bucket width, e.g. 5m, 1h [default: sized to the time window]"
180
+ ),
181
+ split_by: str | None = _SPLIT_BY_OPT,
182
+ decimals: int = _DECIMALS_OPT,
183
+ ts_decimals: int | None = _TS_DECIMALS_OPT,
184
+ output_format: str | None = typer.Option(None, "-f", "--format", help="Output format"),
185
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging"),
186
+ ) -> None:
187
+ """Time-bucketed min/max/avg/count for a metric (or every metric under a dotted stem)."""
188
+ setup_logging(verbose)
189
+ resolved = wiring.load_profile(profile)
190
+ table = wiring.resolve_metrics_table(resolved)
191
+ window = time_range if time_range is not None else resolved.default_window
192
+ bucket_size = bucket if bucket is not None else default_bucket_size(window)
193
+ statement = build_metric_histogram(
194
+ _query(name, host, service, window), table, bucket_size, _parse_split_by(split_by)
195
+ )
196
+ resolved_ts_decimals, ts_precision = _resolve_ts_display(ts_decimals, window)
197
+ formatter = get_formatter(
198
+ output_format or resolved.default_format,
199
+ decimals=decimals,
200
+ ts_decimals=resolved_ts_decimals,
201
+ ts_precision=ts_precision,
202
+ )
203
+ client = wiring.open_client(resolved)
204
+ run_statement(client, statement, formatter, table=table)
@@ -0,0 +1,63 @@
1
+ """The raw-SQL variant path; the query builder is not involved.
2
+
3
+ Read-only safety comes solely from the server-side ``readonly=2`` setting.
4
+ This module never parses the SQL. Server errors echo verbatim: the user
5
+ wrote the query.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+
12
+ import typer
13
+
14
+ from clickhouse_tool.cli import wiring
15
+ from clickhouse_tool.cli.runner import run_statement
16
+ from clickhouse_tool.core.errors import ConfigError
17
+ from clickhouse_tool.core.logging import setup_logging
18
+ from clickhouse_tool.core.models import SqlStatement
19
+ from clickhouse_tool.formatters import get_formatter
20
+
21
+
22
+ def _resolve_sql(sql_argument: str | None) -> str:
23
+ stdin_piped = not sys.stdin.isatty()
24
+ if sql_argument is not None and stdin_piped:
25
+ raise ConfigError("SQL given both as an argument and on stdin; supply exactly one")
26
+ if sql_argument is not None:
27
+ return sql_argument
28
+ if not stdin_piped:
29
+ raise ConfigError("no SQL given: pass it as an argument or pipe it on stdin")
30
+ piped = sys.stdin.read()
31
+ if not piped.strip():
32
+ raise ConfigError("no SQL given: stdin was empty")
33
+ return piped
34
+
35
+
36
+ def _parse_params(raw_params: list[str]) -> dict[str, str]:
37
+ params: dict[str, str] = {}
38
+ for raw in raw_params:
39
+ name, sep, value = raw.partition("=")
40
+ if not sep:
41
+ raise ConfigError(f"malformed --param '{raw}'; expected name=value")
42
+ params[name] = value
43
+ return params
44
+
45
+
46
+ def query(
47
+ sql: str | None = typer.Argument(None, help="SQL text (or pipe it on stdin)"),
48
+ profile: str | None = typer.Option(None, "--profile", help="Named connection profile"),
49
+ param: list[str] = typer.Option(
50
+ [], "--param", help="Bind a named parameter, name=value, repeatable"
51
+ ),
52
+ output_format: str | None = typer.Option(None, "-f", "--format", help="Output format"),
53
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging"),
54
+ ) -> None:
55
+ """Run a raw SQL statement, bypassing the query builder."""
56
+ setup_logging(verbose)
57
+ sql_text = _resolve_sql(sql)
58
+ params = _parse_params(param)
59
+ statement = SqlStatement(sql=sql_text, params=params)
60
+ resolved = wiring.load_profile(profile)
61
+ formatter = get_formatter(output_format or resolved.default_format)
62
+ client = wiring.open_client(resolved)
63
+ run_statement(client, statement, formatter)
@@ -0,0 +1,25 @@
1
+ """The tables verb: enumerate what `list`/`lift`/`query` may safely target."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+
7
+ from clickhouse_tool.cli import wiring
8
+ from clickhouse_tool.cli.runner import run_statement
9
+ from clickhouse_tool.core.logging import setup_logging
10
+ from clickhouse_tool.formatters import get_formatter
11
+ from clickhouse_tool.query.builder import build_tables_list
12
+
13
+
14
+ def tables(
15
+ profile: str | None = typer.Option(None, "--profile", help="Named connection profile"),
16
+ output_format: str | None = typer.Option(None, "-f", "--format", help="Output format"),
17
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging"),
18
+ ) -> None:
19
+ """List every table the allow-list permits `list`/`lift`/`query` to target."""
20
+ setup_logging(verbose)
21
+ resolved = wiring.load_profile(profile)
22
+ statement = build_tables_list(resolved.database)
23
+ formatter = get_formatter(output_format or resolved.default_format)
24
+ client = wiring.open_client(resolved)
25
+ run_statement(client, statement, formatter)
@@ -0,0 +1,66 @@
1
+ """The typer application, its global options, and the sole error funnel.
2
+
3
+ The only place in the package that decides an exit code.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import sys
10
+
11
+ import typer
12
+
13
+ from clickhouse_tool.cli.commands import config as config_command
14
+ from clickhouse_tool.cli.commands import facets, listing, logs, metrics, query, tables
15
+ from clickhouse_tool.core.errors import ClickhouseToolError
16
+ from clickhouse_tool.core.exit_codes import ExitCode
17
+ from clickhouse_tool.core.monitoring import setup_sentry
18
+
19
+ # Frees the single-letter flag from typer's default help binding so a verb
20
+ # can use it for --host instead.
21
+ app = typer.Typer(
22
+ help="clickhouse-tool -- query and administer the OTel ClickHouse pilot.",
23
+ context_settings={"help_option_names": ["--help"]},
24
+ no_args_is_help=True,
25
+ )
26
+
27
+ app.command("logs")(logs.logs)
28
+ app.command("hosts")(facets.hosts)
29
+ app.command("services")(facets.services)
30
+ app.command("list")(listing.list_)
31
+ app.command("lift")(listing.lift)
32
+ app.command("query")(query.query)
33
+ app.command("config")(config_command.config)
34
+ app.command("tables")(tables.tables)
35
+ app.add_typer(metrics.app, name="metrics")
36
+
37
+
38
+ def run() -> None:
39
+ """Entry point installed as the ``clickhouse-tool`` console script."""
40
+ setup_sentry()
41
+ try:
42
+ app()
43
+ except ClickhouseToolError as exc:
44
+ typer.echo(f"Error: {exc.message}", err=True)
45
+ raise SystemExit(int(exc.exit_code)) from None
46
+ except BrokenPipeError:
47
+ _silence_broken_pipe()
48
+ raise SystemExit(0) from None
49
+ except KeyboardInterrupt:
50
+ raise SystemExit(130) from None
51
+ except SystemExit:
52
+ raise
53
+ except Exception as exc: # pragma: no cover -- last-resort funnel
54
+ typer.echo(f"Error: {exc}", err=True)
55
+ raise SystemExit(int(ExitCode.GENERAL_ERROR)) from None
56
+
57
+
58
+ def _silence_broken_pipe() -> None:
59
+ """Redirect stdout to devnull so Python's shutdown doesn't report the pipe error."""
60
+ devnull = os.open(os.devnull, os.O_WRONLY)
61
+ os.dup2(devnull, sys.stdout.fileno())
62
+ os.close(devnull)
63
+
64
+
65
+ if __name__ == "__main__":
66
+ run()