Search Docs

Search through documentation...

OpenStatus Logo

Tinybird

The data-table-tinybird block serves the table from a Tinybird datasource. Filters, faceted counts, cursor pagination and the timeline chart's buckets all run in ClickHouse. createTinybirdHandler answers exactly what createDrizzleHandler answers, so the client, the URL state and the chart do not change between stores.

It has no npm dependencies: it calls Tinybird's Query API (POST /v0/sql) with fetch.

To see it running first, the log viewer example installs a route on this handler, a datasource for tb deploy and a seed script in one command.

Pointing it at your own datasource

The handler takes a query function, the datasource, the filters, and a mapping from schema keys to ClickHouse columns. The mapping is also the projection, so rows come back keyed by schema key ("timing.dns", never timing_dns).

// app/logs/api/route.ts
import { defineFilters } from "@/lib/filters";
import {
  createTinybirdHandler,
  timelineChart,
  tinybirdQuery,
} from "@/lib/tinybird";
import { tableSchema } from "../table-schema";
 
const handler = createTinybirdHandler({
  query: tinybirdQuery({
    baseUrl: process.env.TINYBIRD_URL!,
    token: process.env.TINYBIRD_TOKEN!,
    onError: ({ status, message }) => console.error(status, message),
  }),
  datasource: "logs",
  filters: defineFilters(tableSchema.definition),
  columnMapping: {
    uuid: "uuid",
    date: "timestamp",
    level: "level",
    latency: "duration_ms",
    "timing.dns": "timing_dns",
  },
  cursorColumn: "date",
  tiebreakColumn: "uuid",
});
  • cursorColumn is the schema key rows are paged by: a DateTime or DateTime64 column. Cursors are epoch milliseconds, so use DateTime64(3) or coarser. Rows that differ only below a millisecond can fall between two pages.
  • tiebreakColumn is a unique column ordered last. Without it, rows sharing a timestamp keep their page but can swap places between refetches. ClickHouse has no primary key to default to, so name one.
  • Every filterable key must be mapped. The handler throws at construction if one is missing, rather than silently not filtering.
  • select adds fields that are never filtered or sorted: a column name, or an expression built with sqlConst.
  • maxSize (default 500) caps the page size a request can ask for. defaultSize (default 40) applies when it asks for none, or for a size that is not a positive integer.

In GET, pass meta: false for pagination requests and live polls. The client keeps the meta from the first page, so this skips the counts and facets queries entirely:

import { LEVELS } from "../table-schema";
import { searchParamsCache } from "../schema";
import SuperJSON from "superjson";
 
export async function GET(request: Request) {
  const url = new URL(request.url);
  const search = searchParamsCache.parse(Object.fromEntries(url.searchParams));
  const meta = url.searchParams.get("_meta") !== "false";
 
  const result = await handler.execute(search, { meta });
  const chartData = meta
    ? await timelineChart(result.scope, { groupBy: "level", values: LEVELS })
    : [];
 
  return Response.json(
    SuperJSON.stringify({
      data: result.data,
      meta: {
        totalRowCount: result.totalRowCount,
        filterRowCount: result.filterRowCount,
        chartData,
        facets: result.facets,
      },
      prevCursor: result.prevCursor,
      nextCursor: result.nextCursor,
    }),
  );
}

timelineChart counts rows per scope.bucketMs bucket, split by one column, over the same filtered set. values gives every bucket a count for each listed value (0 when absent), so the chart's series stay stable. Buckets are aligned to the epoch in UTC.

For aggregates of your own, result.scope carries the quoted datasource (from), the filtered where, whereWithoutSliders, the resolved range and bucketMs, plus the query function, the same as the Drizzle scope.

Live mode

The data-table-live block works with any endpoint that answers direction=prev with the rows newer than a cursor, as both handlers do. Add live to the URL state and wire three things into the table:

// schema.ts
live: field.boolean().default(false),
 
// client.tsx
const { fetchPreviousPage /* , ... */ } = useInfiniteQuery(dataOptions(search));
const liveMode = useLiveMode(flatData);
 
<DataTableInfinite
  fetchPreviousPage={fetchPreviousPage}
  toolbarActions={<LiveButton fetchPreviousPage={fetchPreviousPage} />}
  renderLiveRow={(props) =>
    liveMode.timestamp && props?.row.original.uuid === liveMode.row?.uuid ? (
      <LiveRow />
    ) : null
  }
  getRowClassName={(row) =>
    row.original.date.getTime() <= (liveMode.timestamp ?? -1)
      ? "opacity-50"
      : ""
  }
  // ...
/>;

While live mode is on, the button polls every five seconds. Each poll asks for the oldest page of rows newer than the newest one loaded, so a burst arrives over a few polls without a gap. A poll that finds nothing keeps its cursor instead of moving it to the clock, in both handlers: Tinybird makes an appended row queryable a moment after its timestamp, and moving on would skip it. Filtering the time column or sorting turns live mode off. Press ⌘J (Ctrl+J) to toggle it.

How values reach Tinybird

Tinybird's template parameters are not used. A String parameter arrives with every % escaped (50% becomes 50\%), so an exact match on such a value silently fails. Instead, each value is written into the SQL in a form that cannot leave its literal:

  • a string as unhex('…') of its UTF-8 bytes, so only 0-9a-f sits between the quotes;
  • a number as JavaScript prints it, and ±Infinity as inf / -inf (an open slider bound);
  • a boolean as true or false;
  • an instant as fromUnixTimestamp64Milli(toInt64(ms), 'UTC').

Column and datasource names come from your configuration, never from a request, and are still checked against [A-Za-z_][A-Za-z0-9_.]* before they are quoted. A sort on a key that is not in the mapping is ignored.

The token is only ever sent to baseUrl. When Tinybird answers with an error, including a rejected token (401 or 403), the thrown TinybirdError says only the HTTP status, because Tinybird's own message can quote the query. That message goes to onError for your server logs. A query that gets no answer within timeoutMs (default 30,000) is aborted and throws a TinybirdError too.

ClickHouse sends 64-bit integers as quoted strings. The client turns a column back into numbers only when every value in the result is exact: if one UInt64 is beyond Number.MAX_SAFE_INTEGER (an id, say), that column stays strings in every row of the result. Read such a column as a number or a string, or project it with toString(...) to always get a string.

Semantics

The filters mean the same thing they mean everywhere else (see Database). The shared conformance corpus runs against Tinybird Local in CI, as it does against Postgres.

  • Text search is a case-insensitive substring match (positionCaseInsensitiveUTF8). % and _ mean themselves.
  • An Array(...) column filters with hasAny, and its facet counts members (arrayJoin).
  • Slider bounds are computed without the slider's own filter, so the full range stays visible after the user narrows it.
  • Counts and the discovered time range come from one scan (countIf, minIf, maxIf).