# DSL functions

The functions, operators and expressions you can use inside transforms such as `.filter()`, `.add()`, `.select()` and `.agg()`. For the transforms themselves, see [DSL transforms](/docs/dsl/transforms).

Function names are not case sensitive. A name that does not exist is reported when the query runs, not when you save it, so try new expressions with `solidafy dsl` first.

## Operators

| Operator | Meaning | Example |
| --- | --- | --- |
| `==`, `!=` | equal, not equal | `state == "merged"` |
| `>`, `>=`, `<`, `<=` | comparison | `cost_usd > 100` |
| `+`, `-`, `*`, `/`, `%` | arithmetic | `additions + deletions` |
| `and`, `or`, `not` | logic (lowercase) | `is_draft == false and not is_bot` |
| `in [...]`, `not in [...]` | membership | `status in ["failed", "cancelled"]` |
| `between a and b` | range, both ends included | `duration_s between 60 and 600` |
| `is null`, `is not null` | null checks | `merged_at is not null` |
| `matches "regex"` | regular expression match | `branch matches "^release/"` |
| `??` | first value if not null, otherwise the second | `team ?? "Unassigned"` |
| `-x` | negation | `-delta` |

> **Note:** Dividing two whole numbers gives a whole number: `3 / 4` is `0`. Multiply by `1.0` first when you want a fraction, for example `reviewed * 100.0 / total`.

Text is joined with `concat()`, not with `+`.

## Case expressions

```dsl
case(
  when: condition then value,
  when: condition then value,
  else: value
)
```

Conditions are checked in order and the first match wins. Without `else:`, unmatched rows get null. You may also write `then:` with a colon.

```dsl
source("github.pull_requests")
  .add([
    case(
      when: additions + deletions <= 10 then "XS",
      when: additions + deletions <= 50 then "S",
      when: additions + deletions <= 200 then "M",
      when: additions + deletions <= 500 then "L",
      else: "XL"
    ) as size
  ])
```

For a single condition, `if(condition, then_value, else_value)` is shorter:

```dsl
.add([if(conclusion == "success", 1, 0) as succeeded])
```

## Null handling

- `col is null` and `col is not null` are the only reliable null tests. `col == null` and `col != null` never match.
- `a ?? b` and `coalesce(a, b, ...)` return the first value that is not null.
- `nullif(a, b)` returns null when `a` equals `b`, which is handy to avoid dividing by zero: `failed / nullif(total, 0)`.
- The [fill_null](/docs/dsl/transforms#fill_null) and [coalesce](/docs/dsl/transforms#coalesce) transforms replace nulls in a column in place.
- `col.cast(type, default: value)` turns null, the text `"null"`, empty text and values that fail to convert into `value`.

## Aggregate functions

Use these inside `.agg([...])`. Without an alias, the result column is named `function_column`, for example `sum_cost_usd`.

| Function | Result |
| --- | --- |
| `count()` | number of rows |
| `count(col)` | number of non-null values |
| `count_distinct(col)` | number of distinct values |
| `sum(col)`, `avg(col)`, `min(col)`, `max(col)` | the usual |
| `median(col)` | exact median |
| `percentile_cont(col, p)` | exact percentile |
| `percentile(col, p)` | approximate percentile, faster on large tables |
| `stddev(col)`, `variance(col)` | sample standard deviation and variance |
| `first(col)`, `last(col)` | a value from the group; which one is not guaranteed unless the rows are ordered |
| `collect_list(col)` | all values as a list |
| `collect_set(col)` | distinct values as a list |
| `string_agg(col, ", ")` | values joined into one text value (separator defaults to `,`) |

For `percentile` and `percentile_cont`, a whole number is a percentage (`95` means the 95th percentile) and a decimal is a fraction (`0.95`). Without `p` you get the median.

The argument can be any expression, and aggregates can be combined with arithmetic and wrapped in `round`, `abs`, `ceil`, `floor` or `coalesce`:

```dsl
source("ai.usage_events")
  .since(ts, "30d")
  .group_by([model])
  .agg([
    count() as requests,
    sum(input_tokens + output_tokens) as tokens,
    round(sum(cost_usd), 2) as cost_usd,
    round(sum(cost_usd) * 1000.0 / sum(input_tokens + output_tokens), 4) as usd_per_1k_tokens,
    percentile_cont(latency_ms, 95) as p95_latency_ms,
    sum(if(status == "error", 1, 0)) as errors
  ])
```

## Window functions

Window functions compute a value per row from the rows around it. There are two ways to write them.

**After `.window(...)`**, in the next `.add([...])`:

```dsl
source("cloud.daily_costs")
  .window(partition: [service], order: [day: asc])
  .add([lag(cost, 1) as prev_cost, sum(cost) as running_cost])
```

**Inline with `over:`**, inside any `.add([...])`. `over:` lists the partition columns, and the order comes from the most recent `.sort()`:

```dsl
source("cloud.daily_costs")
  .sort([day: asc])
  .add([rolling_avg(cost, 7, over: [service]) as cost_7d_avg])
```

If there is no earlier `.sort()`, the partition columns are used as the order, which is rarely what you want.

| Function | Result |
| --- | --- |
| `row_number()` | 1, 2, 3... within the partition |
| `rank()` | rank with gaps after ties |
| `dense_rank()` | rank without gaps |
| `ntile(n)` | which of `n` roughly equal groups the row falls in |
| `percent_rank()`, `cume_dist()` | relative position, 0 to 1 |
| `lag(col, n)`, `lead(col, n)` | value `n` rows before or after (default 1) |
| `first_value(col)`, `last_value(col)` | first or last value in the window |
| `sum(col)`, `avg(col)`, `count(col)`, `min(col)`, `max(col)` | running value from the start of the partition to the current row |
| `rolling_avg(col, n)` | average of the current row and the `n - 1` rows before it (default 3) |

For a one-column window there are shortcut transforms too: [lag](/docs/dsl/transforms#lag), [diff](/docs/dsl/transforms#diff), [cumsum](/docs/dsl/transforms#cumsum), [rolling](/docs/dsl/transforms#rolling) and friends.

## Math functions

| Function | Result |
| --- | --- |
| `abs(x)` | absolute value |
| `round(x)`, `round(x, digits)` | rounded value |
| `floor(x)`, `ceil(x)` | round down, round up |
| `sqrt(x)`, `power(x, y)`, `exp(x)` | square root, `x` to the power `y`, e to the power `x` |
| `ln(x)`, `log(x)` | natural logarithm |
| `log(base, x)` | logarithm in another base, for example `log(10, x)` |
| `sign(x)` | -1, 0 or 1 |
| `greatest(a, b, ...)`, `least(a, b, ...)` | largest or smallest of the arguments |
| `sin(x)`, `cos(x)`, `tan(x)`, `asin(x)`, `acos(x)`, `atan(x)`, `atan2(y, x)` | trigonometry, in radians |
| `pi()` | 3.14159... |

## Text functions

| Function | Result |
| --- | --- |
| `lower(s)`, `upper(s)`, `initcap(s)` | change case |
| `trim(s)`, `ltrim(s)`, `rtrim(s)` | strip whitespace |
| `length(s)` | number of characters |
| `concat(a, b, ...)` | joined text |
| `concat_ws(sep, a, b, ...)` | joined with a separator |
| `left(s, n)`, `right(s, n)` | first or last `n` characters |
| `substr(s, start)`, `substr(s, start, length)` | part of the text; `start` counts from 1 |
| `lpad(s, n, fill)`, `rpad(s, n, fill)` | padded to `n` characters |
| `repeat(s, n)`, `reverse(s)` | repeated, reversed |
| `replace(s, from, to)` | every occurrence of `from` replaced |
| `contains(s, part)`, `starts_with(s, part)`, `ends_with(s, part)` | true or false |
| `strpos(s, part)` | position of `part` counting from 1, or 0 when absent |
| `split_part(s, sep, index)` | piece of `s` split on `sep`; `index` counts from 0 |
| `chr(code)` | the character for an ASCII code, for example `chr(10)` for a newline |
| `levenshtein(a, b)` | edit distance between two strings |
| `fuzzy_match(s, text)`, `fuzzy_match(s, text, max)` | true when the case-insensitive edit distance is at most `max` (default 3) |
| `md5(s)`, `sha256(s)` | hashes |
| `json_object(k1, v1, k2, v2, ...)` | a JSON object as text |

### Regular expressions

| Function | Result |
| --- | --- |
| `s matches "pattern"`, `matches(s, "pattern")` | true when the pattern matches anywhere in `s` |
| `regexp_replace(s, "pattern", "replacement")` | every match replaced |
| `regexp_extract(s, "pattern", group)` | the capture group with that number (1 is the first group) from the first match |
| `regexp_extract_all(s, "pattern")` | every match, as a list |

```dsl
source("github.pull_requests")
  .add([regexp_extract(title, "([A-Z]+-[0-9]+)", 1) as ticket_key])
  .filter(ticket_key is not null)
```

Backslashes in DSL strings are passed to the regex engine unchanged, so `"\."` matches a literal dot.

## Date and time functions

| Function | Result |
| --- | --- |
| `now()` | current timestamp |
| `today()`, `current_date()` | current date |
| `year(ts)`, `month(ts)`, `day(ts)`, `hour(ts)`, `minute(ts)`, `second(ts)` | one part as a number |
| `date_part("part", ts)`, `extract("part", ts)` | any part, for example `"dow"`, `"week"`, `"quarter"`, `"doy"` |
| `date_trunc("unit", ts)` | `ts` cut down to the start of the `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"` or `"year"`; text columns are converted first |
| `date(ts)`, `to_date(ts)` | `ts` cut to the start of the day; still a timestamp |
| `ts.truncate(unit)` | the same as `date_trunc`, written as a method: `merged_at.truncate(week)` |
| `hours_between(start, end)`, `days_between(start, end)` | elapsed time as a decimal number |
| `date_diff("unit", start, end)` | elapsed whole units, rounded down; units `second`, `minute`, `hour`, `day`, `week` |
| `date_add(ts, "7 days")`, `date_sub(ts, "3 hours")` | shifted timestamp; units `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years` |
| `epoch(ts)` | seconds since 1970-01-01 |
| `strftime("%Y-%m", ts)` | formatted text, format first |
| `to_char(ts, "%Y-%m-%d")` | formatted text, timestamp first |

`strftime` and `to_char` use `%` codes: `%Y` year, `%m` month, `%d` day, `%H` hour, `%M` minute, `%S` second.

```dsl
source("github.pull_requests")
  .filter(merged_at is not null)
  .add([
    hours_between(created_at, merged_at) as cycle_hours,
    date_trunc("week", merged_at) as week,
    date_part("dow", merged_at) as weekday
  ])
```

## Type conversion

| Form | Result |
| --- | --- |
| `col.cast(type)` | converted value; fails the query if a value cannot be converted |
| `col.cast(type, default: value)` | converted value, with `value` for null, `"null"`, empty text and failures |
| `col.try_cast(type)` | converted value, or null when it cannot be converted |
| `str(x)`, `int(x)`, `float(x)` | text, 64-bit whole number, 64-bit decimal |
| `timestamp(x)`, `to_timestamp(x)` | timestamp from text |
| `to_datetime(x)` | `x` converted to a timestamp without a time zone |

Types for the method forms: `string`, `int64` (also `integer`, `bigint`, `long`), `int` (32-bit, also `int32`), `float64` (also `double`), `float` (32-bit), `boolean` (also `bool`), `date`, `timestamp`.

```dsl
source("raw.ai_usage")
  .add([
    tokens.try_cast(int64) as tokens,
    cost.cast(float64, default: 0.0) as cost_usd,
    ts.try_cast(timestamp) as ts
  ])
```

> **Tip:** `int` in `.cast()` is 32-bit. Use `int64` for counts, IDs and token totals.

### Inspecting types

| Function | Result |
| --- | --- |
| `typeof(x)` | the column's type name, such as `Utf8`, `Int64`, `Struct`, `List`, `Map`, `Timestamp` |
| `if_type(col, "Struct", then_value, else_value)` | picks a value based on the column's type, for sources whose shape varies |

Both values of `if_type` must be valid for the column, so it cannot protect a read of a struct field that may not exist. Use [try_field](#struct-functions) for that.

## Nested data

Struct fields use dots: `author.login`, `payload.pull_request.head.ref`. In `.select()` without an alias the column is named with underscores (`author_login`).

### Struct functions

A table's struct columns are built from the records written to it. If the source never sent a field, that field is not part of the struct at all, and a dotted read such as `review.approved` fails the whole query with `Field approved not found in struct`.

| Function | Result |
| --- | --- |
| `try_field(struct, "field")` | the field's value when the struct has the field, otherwise null |
| `try_field(struct, "field", default)` | the same, but `default` instead of null |

The field name must be a non-empty text literal. Only a missing field is tolerated: if the first argument is not a struct, the query still fails, so pointing it at the wrong column shows up as an error rather than a column of nulls.

```dsl
source("raw.github_pull_requests")
  .add([
    try_field(review, "approved", false) as approved,
    try_field(review, "state") as review_state
  ])
```

### Map functions

Maps are key-value columns, such as OpenTelemetry attributes.

| Function | Result |
| --- | --- |
| `attr(map, "key")` | the value for `key` |
| `try_attr(map, "key")`, `try_attr(map, "key", default)` | the same, but null (or `default`) instead of an error when the column is not a map |
| `map_keys(map)`, `map_values(map)` | all keys or values as a list |
| `map_extract(map, "key")` | the value for `key`, as a one-element list |
| `map_contains(map, "key", value)` | true when `map[key]` equals `value`; false when the key is missing |
| `map_contains_key(map, "key")` | true when the key exists |

```dsl
source("otel.spans")
  .filter(map_contains(span_attributes, "http.method", "POST"))
  .add([attr(resource_attributes, "service.name") as service])
```

To pull several keys into columns at once, use the [unpack](/docs/dsl/transforms#unpack) transform.

### List functions

| Function | Result |
| --- | --- |
| `array_element(list, n)` | element `n`, counting from 1 |
| `first(list)`, `last(list)` | first or last element (outside `.agg()`) |
| `array_contains(list, value)` | true when the list holds `value` |
| `array_contains(list, "field", "value")` | for a list of structs: true when any element's `field` equals `"value"` |

```dsl
source("github.pull_requests")
  .filter(array_contains(labels, "name", "hotfix"))
```

To turn list elements into rows, use [explode](/docs/dsl/transforms#explode) or [unnest](/docs/dsl/transforms#unnest).
