Class BetterStackQuery

java.lang.Object
codes.grow.packages.betterstack.BetterStackQuery
All Implemented Interfaces:
LogQueryClient

public final class BetterStackQuery extends Object implements LogQueryClient
SQL query client for Better Stack Logs: the ClickHouse HTTP interface of the query host with the connection's own Basic credentials. Get it from BetterStackClient.query(); it is thread-safe. Better Stack allows 4 concurrent log queries per account.

Implements LogQueryClient over the configured source table: search runs searchLogs(codes.grow.packages.betterstack.SearchLogsOptions), tail polls searchLogs, listStreams returns the configured collection and listLabels is unsupported (Better Stack events have no labels).

  • Field Details

  • Method Details

    • queryRaw

      public String queryRaw(String sql)
      Runs SQL and returns the response text unchanged (any FORMAT).
      Parameters:
      sql - SQL text
      Returns:
      the body
    • queryRaw

      public String queryRaw(String sql, Map<String,?> params, QueryOptions options)
      Runs SQL with bound parameters and returns the response text unchanged.
      Parameters:
      sql - SQL with {name:Type} placeholders
      params - values: String, Number, Boolean, Instant (YYYY-MM-DD HH:MM:SS.ffffff UTC) or null (sent as \N)
      options - ClickHouse settings
      Returns:
      the body
      Throws:
      BetterStackException - mapped by ClickHouse exception code
    • queryRawAsync

      public CompletableFuture<String> queryRawAsync(String sql, Map<String,?> params, QueryOptions options)
      Asynchronous queryRaw(String, Map, QueryOptions). Parameters are bound server side: each {name:Type} placeholder takes the URL parameter param_<name>.
      Parameters:
      sql - SQL with placeholders
      params - values
      options - ClickHouse settings
      Returns:
      a future with the body
    • escapeParamValue

      public static String escapeParamValue(String value)
      Escapes a param_<name> value for ClickHouse, which parses query parameter values in the escaped (TabSeparated) text format: backslash becomes \\, tab \t, newline \n and carriage return \r (DECISIONS 12). Applied to every non-numeric parameter value by query(String, Map).
      Parameters:
      value - parameter text
      Returns:
      the escaped text
    • query

      public List<Map<String,Object>> query(String sql)
      Runs SQL and returns the rows.
      Parameters:
      sql - SQL text
      Returns:
      rows
    • query

      public List<Map<String,Object>> query(String sql, Map<String,?> params)
      Runs SQL with bound parameters and returns the rows.
      Parameters:
      sql - SQL with {name:Type} placeholders
      params - values (see queryRaw(String, Map, QueryOptions))
      Returns:
      rows
    • query

      public List<Map<String,Object>> query(String sql, Map<String,?> params, QueryOptions options)
      Runs SQL and returns the rows. Without a FORMAT clause FORMAT JSONEachRow is appended; FORMAT JSONEachRow/JSON (also with output_format_json_array_of_rows) are parsed, other formats raise ValidationException (use queryRaw(java.lang.String)). ClickHouse renders 64-bit integers as strings. A ClickHouse exception appended to a 200 answer raises the mapped error.
      
       List<Map<String, Object>> rows = q.query(
           "SELECT count() AS c FROM remote(t1_app_logs) WHERE position(raw, {needle:String}) > 0",
           Map.of("needle", "checkout"));
       
      Parameters:
      sql - SQL with placeholders
      params - values
      options - ClickHouse settings
      Returns:
      rows
    • queryAsync

      public CompletableFuture<List<Map<String,Object>>> queryAsync(String sql, Map<String,?> params, QueryOptions options)
      Parameters:
      sql - SQL with placeholders
      params - values
      options - ClickHouse settings
      Returns:
      a future with the rows
    • parseRows

      public static List<Map<String,Object>> parseRows(String text)
      Parses a JSON-family response body (JSONEachRow, a JSON array of rows or FORMAT JSON) into rows.
      Parameters:
      text - response body
      Returns:
      rows
      Throws:
      BetterStackException - for a ClickHouse exception in the body or invalid JSON
    • sqlString

      public static String sqlString(String value)
      Escapes a value as a ClickHouse single-quoted string literal (backslash, quote, newline, carriage return, tab and NUL are backslash-escaped).
      Parameters:
      value - text
      Returns:
      the literal including quotes
    • jsonEscape

      public static String jsonEscape(String text)
      Escapes text like a JSON string value without the surrounding quotes (quote, backslash and control characters), as it appears inside the raw event JSON.
      Parameters:
      text - text
      Returns:
      escaped text
    • formatDateTime64

      public static String formatDateTime64(Instant t)
      Formats an instant as ClickHouse DateTime64(6) text in UTC (YYYY-MM-DD HH:MM:SS.ffffff).
      Parameters:
      t - instant
      Returns:
      the text
    • parseDateTime

      public static Optional<Instant> parseDateTime(Object value)
      Parses a dt value: ClickHouse DateTime64 text (2026-11-18 21:00:00.123456, UTC, 0 to 9 fraction digits), an RFC 3339 string, UNIX seconds or milliseconds, or an Instant.
      Parameters:
      value - value
      Returns:
      the instant, or empty when unparseable
    • logRecordFromRow

      public static LogRecord logRecordFromRow(Map<String,?> row)
      Normalizes a {dt, raw} row into a LogRecord: body = message (else msg, else the raw text); severity from severity_number, else level/severity text (default INFO), with the canonical text when the level is known; timestamp from dt (else the event's dt); trace ids from span.trace_id/span.span_id (else top-level trace_id/span_id, hex only); resource from resource; every other key plus the attributes object into attributes.
      Parameters:
      row - result row
      Returns:
      the record
    • renderSearchSql

      public String renderSearchSql(SearchLogsOptions options)
      Renders the SQL of searchLogs(codes.grow.packages.betterstack.SearchLogsOptions): hot remote(<source>_logs) UNION ALL cold s3Cluster(primary, <source>_s3) WHERE _row_type = 1, the inclusive dt window ( toDateTime64('…', 6, 'UTC')), position(raw, <JSON-escaped contains>) > 0, ORDER BY dt, LIMIT <limit + 1> (to detect a next page) and the cursor's OFFSET, FORMAT JSONEachRow. Values are escaped string literals; the source is a checked identifier.
      Parameters:
      options - search options
      Returns:
      the SQL
      Throws:
      ConfigException - without a source and a configured source table
      ValidationException - for an invalid source, limit, window or cursor
    • searchLogs

      public LogSearchResult searchLogs(SearchLogsOptions options)
      Searches the hot and cold logs of a collection (see renderSearchSql(codes.grow.packages.betterstack.SearchLogsOptions)) with an inclusive time window and a literal substring match, newest first by default. Rows are normalized (logRecordFromRow(java.util.Map<java.lang.String, ?>)) and de-duplicated on (dt, raw) where hot and cold overlap; nextCursor is set when more rows exist.
      Parameters:
      options - search options
      Returns:
      one page
    • searchLogsAsync

      public CompletableFuture<LogSearchResult> searchLogsAsync(SearchLogsOptions options)
      Parameters:
      options - search options
      Returns:
      a future page
    • search

      public LogSearchResult search(String query, SearchOptions options)
      LogQueryClient.search(java.lang.String, codes.grow.packages.betterstack.logging.SearchOptions): query is the contains text, searched in the configured source table.
      Specified by:
      search in interface LogQueryClient
      Parameters:
      query - text
      options - window, limit, order, cursor
      Returns:
      one page
    • searchAsync

      public CompletableFuture<LogSearchResult> searchAsync(String query, SearchOptions options)
      Specified by:
      searchAsync in interface LogQueryClient
      Parameters:
      query - text
      options - options
      Returns:
      a future page
    • listStreams

      public List<String> listStreams()
      The configured collections: [sourceTable], or empty. Better Stack's data plane has no listing endpoint.
      Specified by:
      listStreams in interface LogQueryClient
      Returns:
      collection names
    • listLabels

      public List<String> listLabels()
      Better Stack events are schemaless JSON without labels.
      Specified by:
      listLabels in interface LogQueryClient
      Returns:
      never
      Throws:
      UnsupportedException - always
    • tail

      public TailHandle tail(String query, Consumer<LogRecord> onRecord, TailOptions options)
      Polls searchLogs(codes.grow.packages.betterstack.SearchLogsOptions) every options.interval() (default 1 s) for new records of the configured source table that contain query, starting at options.start() (default now), and calls onRecord for each new record in dt order. Records are de-duplicated at the polling boundary; polling errors go to options.onError() and the next poll retries. The tail ends when the handle is stopped or the client is closed.
      Specified by:
      tail in interface LogQueryClient
      Parameters:
      query - text to match
      onRecord - callback per record (exceptions are ignored)
      options - start, interval, error callback
      Returns:
      the handle
      Throws:
      ConfigException - without a configured source table