> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cube.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# `@cubejs-client/core`

> Vanilla JavaScript client for Cube.

## `cube`

> **cube**(**apiToken**: string |  () => *Promise‹string›*, **options**: [CubeApiOptions](#cubeapioptions)): *[CubeApi](#cubeapi)*

Creates an instance of the `CubeApi`. The API entry point.

```js theme={"dark"}
import cube from '@cubejs-client/core';
const cubeApi = cube(
  'CUBE-API-TOKEN',
  { apiUrl: 'http://localhost:4000/cubejs-api/v1' }
);
```

You can also pass an async function or a promise that will resolve to the API token

```js theme={"dark"}
import cube from '@cubejs-client/core';
const cubeApi = cube(
  async () => await Auth.getJwtToken(),
  { apiUrl: 'http://localhost:4000/cubejs-api/v1' }
);
```

If you need to set up cancellation for all requests made by this API instance:

```js theme={"dark"}
import cube from '@cubejs-client/core';

// Create a controller for managing request cancellation
const controller = new AbortController();
const { signal } = controller;

const cubeApi = cube(
  'CUBE-API-TOKEN',
  {
    apiUrl: 'http://localhost:4000/cubejs-api/v1',
    signal: signal
  }
);

// Later when you need to cancel all pending requests:
// controller.abort();
```

**Parameters:**

| Name | Type | Description |
| - | - | - |
| apiToken | string \|  () => *Promise‹string›* | [API token][ref-security] is used to authorize requests and determine SQL database you're accessing. In [development mode](https://docs.cube.dev/reference/configuration/environment-variables.md#cubejs_dev_mode) (local use only — it bypasses authentication), Cube will print the API token to the console on startup. In case of async function `authorization` is updated for `options.transport` on each request. |
| options | [CubeApiOptions](#cubeapioptions) | - |

> **cube**(**options**: [CubeApiOptions](#cubeapioptions)): *[CubeApi](#cubeapi)*

## `defaultHeuristics`

> **defaultHeuristics**(**newQuery**: [Query](#query-2), **oldQuery**: [Query](#query-2), **options**: [TDefaultHeuristicsOptions](#tdefaultheuristicsoptions)): *any*

## `defaultOrder`

> **defaultOrder**(**query**: [Query](#query-2)): *object*

## `movePivotItem`

> **movePivotItem**(**pivotConfig**: [PivotConfig](#pivotconfig), **sourceIndex**: number, **destinationIndex**: number, **sourceAxis**: TSourceAxis, **destinationAxis**: TSourceAxis): *[PivotConfig](#pivotconfig)*

## Format API

A set of helpers for formatting member values on the client, consistently with how
Cube formats them. They are imported from the `@cubejs-client/core/format` subpath:

```js theme={"dark"}
import { formatValue, getFormat, formatDateByGranularity } from '@cubejs-client/core/format';
```

### `formatValue`

> **formatValue**(**value**: any, **options**: FormatValueOptions): *string*

Formats a single value according to a member's `type` and `format`. `options` extends the
member's metadata (`type`, `format`, `currency`, `granularity`) with an optional `locale`
(e.g. `'en-US'`, `'de-DE'`) and an `emptyPlaceholder` for empty values. Numeric formats use
[d3-format](https://d3js.org/d3-format) specifiers, and the precision of named formats (e.g.
`currency_2`) is treated as an upper bound — insignificant trailing zeros are trimmed.

```js theme={"dark"}
import { formatValue } from '@cubejs-client/core/format';

formatValue(1234.5, { type: 'number', format: 'currency_2', currency: 'EUR', locale: 'de-DE' });
```

### `getFormat`

> **getFormat**(**member**: FormatValueMember, **options?**: GetFormatOptions): *GetFormatResult*

Returns a reusable formatter for a member. `options` accepts an optional `locale`. The result
has two properties: `formatString` (the resolved format specifier, or `null` for non-numeric
formats) and `formatFunc`, a function that formats a value. Use it when formatting many values
for the same member.

### `formatDateByGranularity`

> **formatDateByGranularity**(**value**: Date | string | number, **granularity?**: string): *string*

Formats a date value for a given time dimension `granularity` (e.g. `'day'`, `'month'`,
`'year'`).

## `CubeApi`

Main class for accessing Cube API

### `cubeSql`

> **cubeSql**(**sqlQuery**: string, **options?**: [CubeSqlOptions](#cubesqloptions)): *Promise‹[CubeSqlResult](#cubesqlresult)›*

> **cubeSql**(**sqlQuery**: string, **options?**: [CubeSqlOptions](#cubesqloptions), **callback?**: [LoadMethodCallback](#loadmethodcallback)‹[CubeSqlResult](#cubesqlresult)›): *void*

Run a SQL query via the [`/v1/cubesql`][ref-cubesql-endpoint] endpoint of the
[SQL API][ref-sql-api] and get the results.

```js theme={"dark"}
const result = await cubeApi.cubeSql(
  'SELECT status, MEASURE(count) FROM orders GROUP BY 1',
  { timezone: 'America/Los_Angeles' }
);
```

**Parameters:**

| Name | Type | Description |
| - | - | - |
| sqlQuery | string | The SQL query to run |
| options? | [CubeSqlOptions](#cubesqloptions) | - |
| callback? | [LoadMethodCallback](#loadmethodcallback)‹[CubeSqlResult](#cubesqlresult)› | - |

### `cubeSqlStream`

> **cubeSqlStream**(**sqlQuery**: string, **options?**: [CubeSqlOptions](#cubesqloptions)): *AsyncGenerator‹CubeSqlStreamChunk›*

Same as [`cubeSql`](#cubesql), but yields the results as they stream in. Each
chunk is either `{ type: 'schema', schema, lastRefreshTime?, external?, usedPreAggregations? }`,
`{ type: 'data', data }` (one row), or `{ type: 'error', error }`.

```js theme={"dark"}
for await (const chunk of cubeApi.cubeSqlStream(
  'SELECT status, MEASURE(count) FROM orders GROUP BY 1',
  { timezone: 'America/Los_Angeles' }
)) {
  if (chunk.type === 'data') {
    console.log(chunk.data);
  }
}
```

**Parameters:**

| Name | Type | Description |
| - | - | - |
| sqlQuery | string | The SQL query to run |
| options? | [CubeSqlOptions](#cubesqloptions) | - |

### `dryRun`

> **dryRun**(**query**: [Query](#query-2) | [Query](#query-2)\[], **options?**: [LoadMethodOptions](#loadmethodoptions)): *Promise‹[TDryRunResponse](#tdryrunresponse)›*

> **dryRun**(**query**: [Query](#query-2) | [Query](#query-2)\[], **options**: [LoadMethodOptions](#loadmethodoptions), **callback?**: [LoadMethodCallback](#loadmethodcallback)‹[TDryRunResponse](#tdryrunresponse)›): *void*

Get query related meta without query execution

### `load`

> **load**(**query**: [Query](#query-2) | [Query](#query-2)\[], **options?**: [LoadMethodOptions](#loadmethodoptions)): *Promise‹[ResultSet](#resultset)›*

> **load**(**query**: [Query](#query-2) | [Query](#query-2)\[], **options?**: [LoadMethodOptions](#loadmethodoptions), **callback?**: [LoadMethodCallback](#loadmethodcallback)‹[ResultSet](#resultset)›): *void*

Fetch data for the passed `query`.

```js theme={"dark"}
import cube from '@cubejs-client/core';
import Chart from 'chart.js';
import chartjsConfig from './toChartjsData';

const cubeApi = cube('CUBE_TOKEN');

const resultSet = await cubeApi.load({
 measures: ['Stories.count'],
 timeDimensions: [{
   dimension: 'Stories.time',
   dateRange: ['2015-01-01', '2015-12-31'],
   granularity: 'month'
  }]
});

const context = document.getElementById('myChart');
new Chart(context, chartjsConfig(resultSet));
```

You can also use AbortController to cancel a request:

```js theme={"dark"}
import cube from '@cubejs-client/core';

const cubeApi = cube('CUBE_TOKEN');

// Create an AbortController instance
const controller = new AbortController();
const { signal } = controller;

try {
  // Pass the signal to the load method
  const resultSetPromise = cubeApi.load(
    {
      measures: ['Orders.count'],
      dimensions: ['Orders.status']
    },
    { signal }
  );

  // To cancel the request at any time:
  // controller.abort();

  const resultSet = await resultSetPromise;
  // Process the result
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('Request was cancelled');
  } else {
    console.error('Error loading data:', error);
  }
}
```

**Parameters:**

| Name | Type | Description |
| - | - | - |
| query | [Query](#query-2) \| [Query](#query-2)\[] | [Query object][ref-query-format] |
| options? | [LoadMethodOptions](#loadmethodoptions) | - |
| callback? | [LoadMethodCallback](#loadmethodcallback)‹[ResultSet](#resultset)› | - |

### `meta`

> **meta**(**options?**: [MetaMethodOptions](#metamethodoptions)): *Promise‹[Meta](#meta-2)›*

> **meta**(**options?**: [MetaMethodOptions](#metamethodoptions), **callback?**: [LoadMethodCallback](#loadmethodcallback)‹[Meta](#meta-2)›): *void*

Get meta description of cubes available for querying.

Pass `onlyViews: true` to request views only. On large data models this keeps cubes
out of the response payload:

```js theme={"dark"}
const meta = await cubeApi.meta({ onlyViews: true });
```

> [!NOTE]
>
> Cube versions predating this option behave differently per transport: over HTTP they
> ignore it and return the full data model, while over
> [`WebSocketTransport`](https://docs.cube.dev/reference/javascript-sdk/reference/cubejs-client-ws-transport)
> they reject the message with a `400`, because `meta` params are validated strictly.

**Parameters:**

| Name | Type | Description |
| - | - | - |
| options? | [MetaMethodOptions](#metamethodoptions) | - |
| callback? | [LoadMethodCallback](#loadmethodcallback)‹[Meta](#meta-2)› | - |

### `sql`

> **sql**(**query**: [Query](#query-2) | [Query](#query-2)\[], **options?**: [LoadMethodOptions](#loadmethodoptions)): *Promise‹[SqlQuery](#sqlquery)›*

> **sql**(**query**: [Query](#query-2) | [Query](#query-2)\[], **options?**: [LoadMethodOptions](#loadmethodoptions), **callback?**: [LoadMethodCallback](#loadmethodcallback)‹[SqlQuery](#sqlquery)›): *void*

Get generated SQL string for the given `query`.

**Parameters:**

| Name | Type | Description |
| - | - | - |
| query | [Query](#query-2) \| [Query](#query-2)\[] | [Query object][ref-query-format] |
| options? | [LoadMethodOptions](#loadmethodoptions) | - |
| callback? | [LoadMethodCallback](#loadmethodcallback)‹[SqlQuery](#sqlquery)› | - |

### `subscribe`

> **subscribe**(**query**: [Query](#query-2) | [Query](#query-2)\[], **options**: [LoadMethodOptions](#loadmethodoptions) | null, **callback**: [LoadMethodCallback](#loadmethodcallback)‹[ResultSet](#resultset)›): *void*

Allows you to fetch data and receive updates over time. See [Real-Time Data Fetch](https://docs.cube.dev/recipes/core-data-api/real-time-data-fetch.md)

```js theme={"dark"}
cubeApi.subscribe(
  {
    measures: ['Logs.count'],
    timeDimensions: [
      {
        dimension: 'Logs.time',
        granularity: 'hour',
        dateRange: 'last 1440 minutes',
      },
    ],
  },
  options,
  (error, resultSet) => {
    if (!error) {
      // handle the update
    }
  }
);
```

## `HttpTransport`

Default transport implementation.

### constructor

> **new HttpTransport**(**options**: [TransportOptions](#transportoptions)): *[HttpTransport](#httptransport)*

### `request`

> **request**(**method**: string, **params**: any): () => *Promise‹any›*

*Implementation of ITransport*

## `Meta`

Contains information about available cubes and it's members.

### `defaultTimeDimensionNameFor`

> **defaultTimeDimensionNameFor**(**memberName**: string): *string*

### `filterOperatorsForMember`

> **filterOperatorsForMember**(**memberName**: string, **memberType**: [MemberType](#membertype) | [MemberType](#membertype)\[]): *any*

### `membersForQuery`

> **membersForQuery**(**query**: [Query](#query-2) | null, **memberType**: [MemberType](#membertype)): *[TCubeMeasure](#tcubemeasure)\[] | [TCubeDimension](#tcubedimension)\[] | [TCubeMember](#tcubemember)\[]*

Get all members of a specific type for a given query.
If empty query is provided no filtering is done based on query context and all available members are retrieved.

**Parameters:**

| Name | Type | Description |
| - | - | - |
| query | [Query](#query-2) \| null | context query to provide filtering of members available to add to this query |
| memberType | [MemberType](#membertype) | - |

### `resolveMember`

> **resolveMember**‹**T**›(**memberName**: string, **memberType**: T | T\[]): *object | [TCubeMemberByType](#tcubememberbytype)‹T›*

Get meta information for a cube member
Member meta information contains:

```javascript theme={"dark"}
{
  name,
  title,
  shortTitle,
  type,
  description,
  format
}
```

**Type parameters:**

* **T**: *[MemberType](#membertype)*

**Parameters:**

| Name | Type | Description |
| - | - | - |
| memberName | string | Fully qualified member name in a form `Cube.memberName` |
| memberType | T \| T\[] | - |

## `ProgressResult`

### `stage`

> **stage**(): *string*

### `timeElapsed`

> **timeElapsed**(): *string*

## `ResultSet`

Provides a convenient interface for data manipulation.

### `annotation`

> **annotation**(): *[QueryAnnotations](#queryannotations)*

### `chartPivot`

> **chartPivot**(**pivotConfig?**: [PivotConfig](#pivotconfig)): *[ChartPivotRow](#chartpivotrow)\[]*

Returns normalized query result data in the following format.

You can find the examples of using the `pivotConfig` [here](#pivotconfig)

```js theme={"dark"}
// For the query
{
  measures: ['Stories.count'],
  timeDimensions: [{
    dimension: 'Stories.time',
    dateRange: ['2015-01-01', '2015-12-31'],
    granularity: 'month'
  }]
}

// ResultSet.chartPivot() will return
[
  { "x":"2015-01-01T00:00:00", "Stories.count": 27120, "xValues": ["2015-01-01T00:00:00"] },
  { "x":"2015-02-01T00:00:00", "Stories.count": 25861, "xValues": ["2015-02-01T00:00:00"]  },
  { "x":"2015-03-01T00:00:00", "Stories.count": 29661, "xValues": ["2015-03-01T00:00:00"]  },
  //...
]

```

When using `chartPivot()` or `seriesNames()`, you can pass `aliasSeries` in the [pivotConfig](#pivotconfig)
to give each series a unique prefix. This is useful for `blending queries` which use the same measure multiple times.

```js theme={"dark"}
// For the queries
{
  measures: ['Stories.count'],
  timeDimensions: [
    {
      dimension: 'Stories.time',
      dateRange: ['2015-01-01', '2015-12-31'],
      granularity: 'month',
    },
  ],
},
{
  measures: ['Stories.count'],
  timeDimensions: [
    {
      dimension: 'Stories.time',
      dateRange: ['2015-01-01', '2015-12-31'],
      granularity: 'month',
    },
  ],
  filters: [
    {
      member: 'Stores.read',
      operator: 'equals',
      values: ['true'],
    },
  ],
},

// ResultSet.chartPivot({ aliasSeries: ['one', 'two'] }) will return
[
  {
    x: '2015-01-01T00:00:00',
    'one,Stories.count': 27120,
    'two,Stories.count': 8933,
    xValues: ['2015-01-01T00:00:00'],
  },
  {
    x: '2015-02-01T00:00:00',
    'one,Stories.count': 25861,
    'two,Stories.count': 8344,
    xValues: ['2015-02-01T00:00:00'],
  },
  {
    x: '2015-03-01T00:00:00',
    'one,Stories.count': 29661,
    'two,Stories.count': 9023,
    xValues: ['2015-03-01T00:00:00'],
  },
  //...
];
```

### `decompose`

> **decompose**(): *Object*

Can be used when you need access to the methods that can't be used with some query types (eg `compareDateRangeQuery` or `blendingQuery`)

```js theme={"dark"}
resultSet.decompose().forEach((currentResultSet) => {
  console.log(currentResultSet.rawData());
});
```

### `drillDown`

> **drillDown**(**drillDownLocator**: [DrillDownLocator](#drilldownlocator), **pivotConfig?**: [PivotConfig](#pivotconfig)): *[Query](#query-2) | null*

Returns a measure drill down query.

Provided you have a measure with the defined `drillMembers` on the `Orders` cube

```js theme={"dark"}
measures: {
  count: {
    type: `count`,
    drillMembers: [Orders.status, Users.city, count],
  },
  // ...
}
```

Then you can use the `drillDown` method to see the rows that contribute to that metric

```js theme={"dark"}
resultSet.drillDown(
  {
    xValues,
    yValues,
  },
  // you should pass the `pivotConfig` if you have used it for axes manipulation
  pivotConfig
)
```

the result will be a query with the required filters applied and the dimensions/measures filled out

```js theme={"dark"}
{
  measures: ['Orders.count'],
  dimensions: ['Orders.status', 'Users.city'],
  filters: [
    // dimension and measure filters
  ],
  timeDimensions: [
    //...
  ]
}
```

In case when you want to add `order` or `limit` to the query, you can simply spread it

```js theme={"dark"}
// An example for React
const drillDownResponse = useCubeQuery(
   {
     ...drillDownQuery,
     limit: 30,
     order: {
       'Orders.ts': 'desc'
     }
   },
   {
     skip: !drillDownQuery
   }
 );
```

### `pivot`

> **pivot**(**pivotConfig?**: [PivotConfig](#pivotconfig)): *[PivotRow](#pivotrow)\[]*

Base method for pivoting [ResultSet](#resultset) data.
Most of the times shouldn't be used directly and [`chartPivot`](#chartpivot)
or [`tablePivot`](#tablepivot) should be used instead.

You can find the examples of using the `pivotConfig` [here](#pivotconfig)

```js theme={"dark"}
// For query
{
  measures: ['Stories.count'],
  timeDimensions: [{
    dimension: 'Stories.time',
    dateRange: ['2015-01-01', '2015-03-31'],
    granularity: 'month'
  }]
}

// ResultSet.pivot({ x: ['Stories.time'], y: ['measures'] }) will return
[
  {
    xValues: ["2015-01-01T00:00:00"],
    yValuesArray: [
      [['Stories.count'], 27120]
    ]
  },
  {
    xValues: ["2015-02-01T00:00:00"],
    yValuesArray: [
      [['Stories.count'], 25861]
    ]
  },
  {
    xValues: ["2015-03-01T00:00:00"],
    yValuesArray: [
      [['Stories.count'], 29661]
    ]
  }
]
```

### `query`

> **query**(): *[Query](#query-2)*

### `rawData`

> **rawData**(): *T\[]*

### `serialize`

> **serialize**(): *Object*

Can be used to stash the `ResultSet` in a storage and restored later with [deserialize](#deserialize)

### `series`

> **series**‹**SeriesItem**›(**pivotConfig?**: [PivotConfig](#pivotconfig)): *[Series](#series-2)‹SeriesItem›\[]*

Returns an array of series with key, title and series data.

```js theme={"dark"}
// For the query
{
  measures: ['Stories.count'],
  timeDimensions: [{
    dimension: 'Stories.time',
    dateRange: ['2015-01-01', '2015-12-31'],
    granularity: 'month'
  }]
}

// ResultSet.series() will return
[
  {
    key: 'Stories.count',
    title: 'Stories Count',
    series: [
      { x: '2015-01-01T00:00:00', value: 27120 },
      { x: '2015-02-01T00:00:00', value: 25861 },
      { x: '2015-03-01T00:00:00', value: 29661 },
      //...
    ],
  },
]
```

**Type parameters:**

* **SeriesItem**

### `seriesNames`

> **seriesNames**(**pivotConfig?**: [PivotConfig](#pivotconfig)): *[SeriesNamesColumn](#seriesnamescolumn)\[]*

Returns an array of series objects, containing `key` and `title` parameters.

```js theme={"dark"}
// For query
{
  measures: ['Stories.count'],
  timeDimensions: [{
    dimension: 'Stories.time',
    dateRange: ['2015-01-01', '2015-12-31'],
    granularity: 'month'
  }]
}

// ResultSet.seriesNames() will return
[
  {
    key: 'Stories.count',
    title: 'Stories Count',
    yValues: ['Stories.count'],
  },
]
```

### `tableColumns`

> **tableColumns**(**pivotConfig?**: [PivotConfig](#pivotconfig)): *[TableColumn](#tablecolumn)\[]*

Returns an array of column definitions for `tablePivot`.

For example:

```js theme={"dark"}
// For the query
{
  measures: ['Stories.count'],
  timeDimensions: [{
    dimension: 'Stories.time',
    dateRange: ['2015-01-01', '2015-12-31'],
    granularity: 'month'
  }]
}

// ResultSet.tableColumns() will return
[
  {
    key: 'Stories.time',
    dataIndex: 'Stories.time',
    title: 'Stories Time',
    shortTitle: 'Time',
    type: 'time',
    format: undefined,
  },
  {
    key: 'Stories.count',
    dataIndex: 'Stories.count',
    title: 'Stories Count',
    shortTitle: 'Count',
    type: 'count',
    format: undefined,
  },
  //...
]
```

In case we want to pivot the table axes

```js theme={"dark"}
// Let's take this query as an example
{
  measures: ['Orders.count'],
  dimensions: ['Users.country', 'Users.gender']
}

// and put the dimensions on `y` axis
resultSet.tableColumns({
  x: [],
  y: ['Users.country', 'Users.gender', 'measures']
})
```

then `tableColumns` will group the table head and return

```js theme={"dark"}
{
  key: 'Germany',
  type: 'string',
  title: 'Users Country Germany',
  shortTitle: 'Germany',
  meta: undefined,
  format: undefined,
  children: [
    {
      key: 'male',
      type: 'string',
      title: 'Users Gender male',
      shortTitle: 'male',
      meta: undefined,
      format: undefined,
      children: [
        {
          // ...
          dataIndex: 'Germany.male.Orders.count',
          shortTitle: 'Count',
        },
      ],
    },
    {
      // ...
      shortTitle: 'female',
      children: [
        {
          // ...
          dataIndex: 'Germany.female.Orders.count',
          shortTitle: 'Count',
        },
      ],
    },
  ],
},
// ...
```

### `tablePivot`

> **tablePivot**(**pivotConfig?**: [PivotConfig](#pivotconfig)): *Array‹object›*

Returns normalized query result data prepared for visualization in the table format.

You can find the examples of using the `pivotConfig` [here](#pivotconfig)

For example:

```js theme={"dark"}
// For the query
{
  measures: ['Stories.count'],
  timeDimensions: [{
    dimension: 'Stories.time',
    dateRange: ['2015-01-01', '2015-12-31'],
    granularity: 'month'
  }]
}

// ResultSet.tablePivot() will return
[
  { "Stories.time": "2015-01-01T00:00:00", "Stories.count": 27120 },
  { "Stories.time": "2015-02-01T00:00:00", "Stories.count": 25861 },
  { "Stories.time": "2015-03-01T00:00:00", "Stories.count": 29661 },
  //...
]
```

### `deserialize`

> `static` **deserialize**‹**TData**›(**data**: Object, **options?**: Object): *[ResultSet](#resultset)‹TData›*

```js theme={"dark"}
import { ResultSet } from '@cubejs-client/core';

const resultSet = await cubeApi.load(query);
// You can store the result somewhere
const tmp = resultSet.serialize();

// and restore it later
const resultSet = ResultSet.deserialize(tmp);
```

**Type parameters:**

* **TData**

**Parameters:**

| Name | Type | Description |
| - | - | - |
| data | Object | the result of [serialize](#serialize) |
| options? | Object | - |

### `getNormalizedPivotConfig`

> `static` **getNormalizedPivotConfig**(**query**: [PivotQuery](#pivotquery), **pivotConfig?**: Partial‹[PivotConfig](#pivotconfig)›): *[PivotConfig](#pivotconfig)*

## `SqlQuery`

### `rawQuery`

> **rawQuery**(): *[SqlData](#sqldata)*

### `sql`

> **sql**(): *string*

## `ITransport`

### `request`

> **request**(**method**: string, **params**: any): () => *Promise‹void›*

## Types

### `Annotation`

| Name | Type |
| - | - |
| format? | "currency" \| "percent" \| "number" |
| shortTitle | string |
| title | string |
| type | string |

### `CacheMode`

> **CacheMode**: *"stale-if-slow" | "stale-while-revalidate" | "must-revalidate" | "no-cache"*

Cache mode options for query execution. See [cache control][ref-cache-control] for details on available strategies.

### `BinaryFilter`

| Name | Type |
| - | - |
| and? | [BinaryFilter](#binaryfilter)\[] |
| dimension? | string |
| member? | string |
| operator | [BinaryOperator](#binaryoperator) |
| or? | [BinaryFilter](#binaryfilter)\[] |
| values | string\[] |

### `BinaryOperator`

> **BinaryOperator**: *"equals" | "notEquals" | "contains" | "notContains" | "gt" | "gte" | "lt" | "lte" | "inDateRange" | "notInDateRange" | "beforeDate" | "afterDate"*

### `ChartPivotRow`

| Name | Type |
| - | - |
| x | string |
| xValues | string\[] |

### `Column`

| Name | Type |
| - | - |
| key | string |
| series | \[] |
| title | string |

### `CubeApiOptions`

| Name | Type | Description |
| - | - | - |
| apiUrl | string | URL of your Cube API. By default, in the development environment it is `http://localhost:4000/cubejs-api/v1` |
| credentials? | "omit" \| "same-origin" \| "include" | - |
| headers? | Record‹string, string› | - |
| parseDateMeasures? | boolean | - |
| pollInterval? | number | - |
| transport? | [ITransport](#itransport) | Transport implementation to use. [HttpTransport](#httptransport) will be used by default. |
| signal? | AbortSignal | AbortSignal to cancel requests |

### `CubeSqlOptions`

Extends [`LoadMethodOptions`](#loadmethodoptions) with the options accepted by
[`cubeSql`](#cubesql) and [`cubeSqlStream`](#cubesqlstream).

| Name | Type | Optional? | Description |
| - | - | - | - |
| `timeout` | `number` | ✅ Yes | Query timeout in milliseconds. |
| `timezone` | `string` | ✅ Yes | The [time zone][ref-time-zone] for this query in the [TZ Database Name][link-tzdb] format, e.g., `America/Los_Angeles` — same as `query.timezone` in the REST (JSON) API's [`/v1/load`][ref-query-format]. When omitted, the query runs in the deployment's default time zone. |

### `CubeSqlResult`

| Name | Type | Description |
| - | - | - |
| schema | `{ name: string, column_type: string, format?: string }[]` | - |
| data | `(string \| number \| boolean \| null)[][]` | - |
| lastRefreshTime? | string | - |
| external? | boolean | Whether the result was served from the external (pre-aggregation) store. Only reported when true. |
| usedPreAggregations? | `Record<string, { preAggregationId?: string, lastUpdatedAt?: number, type: string }>` | Pre-aggregations this result was served from, keyed by pre-aggregation table name. Absent when the query hit none, and on deployments older than the field. Entries also carry `targetTableName` in dev mode and for the Playground. |

### `DateRange`

> **DateRange**: *string | \[string, string]*

### `DrillDownLocator`

| Name | Type |
| - | - |
| xValues | string\[] |
| yValues? | string\[] |

### `Filter`

> **Filter**: *[BinaryFilter](#binaryfilter) | [UnaryFilter](#unaryfilter)*

### `LoadMethodCallback`

> **LoadMethodCallback**: *function*

### `LoadMethodOptions`

| Name | Type | Optional? | Description |
| - | - | - | - |
| `cache` | [`CacheMode`](#cachemode) | ✅ Yes | Server-side cache policy for query execution. Does not control client-side caching. See [cache control][ref-cache-control] for details on available strategies. |
| `castNumerics` | `boolean` | ✅ Yes | Pass `true` if you'd like all members with the `number` type to be automatically converted to JavaScript `Number` type. Note that this is a potentially unsafe operation since numbers more than [`Number.MAX_SAFE_INTEGER`][link-mdn-max-safe-integer] or less than `Number.MIN_SAFE_INTEGER` can't be represented as JavaScript `Number` |
| `mutexKey` | `string` | ✅ Yes | Key to store the current request's MUTEX inside the `mutexObj`. MUTEX object is used to reject orphaned queries results when new queries are sent. For example: if two queries are sent with the same `mutexKey` only the last one will return results. |
| `mutexObj` | `Object` | ✅ Yes | Object to store MUTEX |
| `progressCallback` | | ✅ Yes | |
| `subscribe` | `boolean` | ✅ Yes | Pass `true` to use continuous fetch behavior. |
| `signal` | `AbortSignal` | ✅ Yes | AbortSignal to cancel the request. This allows you to manually abort requests using AbortController. |
| `baseRequestId` | `string` | ✅ Yes | Base request ID ([`spanId`](https://docs.cube.dev/reference/core-data-apis/rest-api#request-span-annotation)) to be used for the request. If not provided a random request ID will be generated. |

### `MetaMethodOptions`

Extends [`LoadMethodOptions`](#loadmethodoptions) with the options accepted by [`meta`](#meta).

| Name | Type | Optional? | Description |
| - | - | - | - |
| `onlyViews` | `boolean` | ✅ Yes | Pass `true` to request views only — the response's `cubes` array then contains only entries whose `type` is `view`. Over HTTP, Cube versions predating this flag ignore it and return the full data model, so don't assume the response is filtered. |

### `LoadResponse`

| Name | Type |
| - | - |
| pivotQuery | [PivotQuery](#pivotquery) |
| queryType | [QueryType](#querytype) |
| results | [LoadResponseResult](#loadresponseresult)‹T›\[] |

### `LoadResponseResult`

| Name | Type |
| - | - |
| annotation | [QueryAnnotations](#queryannotations) |
| data | T\[] |
| lastRefreshTime | string |
| query | [Query](#query-2) |

### `MemberType`

> **MemberType**: *"measures" | "dimensions" | "segments"*

### `PivotConfig`

Configuration object that contains information about pivot axes and other options.

Let's apply `pivotConfig` and see how it affects the axes

```js theme={"dark"}
// Example query
{
  measures: ['Orders.count'],
  dimensions: ['Users.country', 'Users.gender']
}
```

If we put the `Users.gender` dimension on **y** axis

```js theme={"dark"}
resultSet.tablePivot({
  x: ['Users.country'],
  y: ['Users.gender', 'measures']
})
```

The resulting table will look the following way

| Users Country | male, Orders.count | female, Orders.count |
| - | - | - |
| Australia | 3 | 27 |
| Germany | 10 | 12 |
| US | 5 | 7 |

Now let's put the `Users.country` dimension on **y** axis instead

```js theme={"dark"}
resultSet.tablePivot({
  x: ['Users.gender'],
  y: ['Users.country', 'measures'],
});
```

in this case the `Users.country` values will be laid out on **y** or **columns** axis

| Users Gender | Australia, Orders.count | Germany, Orders.count | US, Orders.count |
| - | - | - | - |
| male | 3 | 10 | 5 |
| female | 27 | 12 | 7 |

It's also possible to put the `measures` on **x** axis. But in either case it should always be the last item of the array.

```js theme={"dark"}
resultSet.tablePivot({
  x: ['Users.gender', 'measures'],
  y: ['Users.country'],
});
```

| Users Gender | measures | Australia | Germany | US |
| - | - | - | - | - |
| male | Orders.count | 3 | 10 | 5 |
| female | Orders.count | 27 | 12 | 7 |

| Name | Type | Description |
| - | - | - |
| aliasSeries? | string\[] | Give each series a prefix alias. Should have one entry for each query:measure. See [chartPivot](#chartpivot) |
| fillMissingDates? | boolean \| null | **`true` by default.** If set to `true`, missing dates on the time dimensions will be filled with `fillWithValue` or `0` by default for all measures. Note: setting this option to `true` will override any `order` applied to the query. |
| fillWithValue? | string \| null | Value to autofill all the missing date's measure. |
| x? | string\[] | Dimensions to put on **x** or **rows** axis. |
| y? | string\[] | Dimensions to put on **y** or **columns** axis. |

### `PivotQuery`

> **PivotQuery**: *[Query](#query-2) & object*

### `PivotRow`

| Name | Type |
| - | - |
| xValues | Array‹string \| number› |
| yValuesArray | Array‹\[string\[], number]› |

### `ProgressResponse`

| Name | Type |
| - | - |
| stage | string |
| timeElapsed | number |

### `Query`

| Name | Type |
| - | - |
| dimensions? | string\[] |
| filters? | [Filter](#filter)\[] |
| limit? | number |
| measures? | string\[] |
| offset? | number |
| order? | [TQueryOrderObject](#tqueryorderobject) \| [TQueryOrderArray](#tqueryorderarray) |
| segments? | string\[] |
| timeDimensions? | [TimeDimension](#timedimension)\[] |
| timezone? | string |
| ungrouped? | boolean |

### `QueryAnnotations`

| Name | Type |
| - | - |
| dimensions | Record‹string, [Annotation](#annotation-2)› |
| measures | Record‹string, [Annotation](#annotation-2)› |
| timeDimensions | Record‹string, [Annotation](#annotation-2)› |

### `QueryOrder`

> **QueryOrder**: *"asc" | "desc"*

### `QueryType`

> **QueryType**: *"regularQuery" | "compareDateRangeQuery" | "blendingQuery"*

### `Series`

| Name | Type |
| - | - |
| key | string |
| series | T\[] |
| title | string |

### `SeriesNamesColumn`

| Name | Type |
| - | - |
| key | string |
| title | string |
| yValues | string\[] |

### `SqlApiResponse`

| Name | Type |
| - | - |
| sql | [SqlData](#sqldata) |

### `SqlData`

| Name | Type |
| - | - |
| aliasNameToMember | Record‹string, string› |
| cacheKeyQueries | object |
| dataSource | boolean |
| external | boolean |
| sql | [SqlQueryTuple](#sqlquerytuple) |

### `SqlQueryTuple`

> **SqlQueryTuple**: *\[string, boolean | string | number]*

### `TCubeDimension`

> **TCubeDimension**: *[TCubeMember](#tcubemember) & object*

### `TCubeMeasure`

> **TCubeMeasure**: *[TCubeMember](#tcubemember) & object*

### `TCubeMember`

| Name | Type |
| - | - |
| name | string |
| shortTitle | string |
| title | string |
| isVisible? | boolean |
| meta? | any |
| type | [TCubeMemberType](#tcubemembertype) |

### `TCubeMemberByType`

> **TCubeMemberByType**: *T extends "measures" ? TCubeMeasure : T extends "dimensions" ? TCubeDimension : T extends "segments" ? TCubeSegment : never*

### `TCubeMemberType`

> **TCubeMemberType**: *"time" | "number" | "string" | "boolean"*

### `TCubeSegment`

> **TCubeSegment**: *Pick‹[TCubeMember](#tcubemember), "name" | "shortTitle" | "title"›*

### `TDefaultHeuristicsOptions`

| Name | Type |
| - | - |
| meta | [Meta](#meta-2) |
| sessionGranularity? | [TimeDimensionGranularity](#timedimensiongranularity) |

### `TDryRunResponse`

| Name | Type |
| - | - |
| normalizedQueries | [Query](#query-2)\[] |
| pivotQuery | [PivotQuery](#pivotquery) |
| queryOrder | Array‹object› |
| queryType | [QueryType](#querytype) |

### `TFlatFilter`

| Name | Type |
| - | - |
| dimension? | string |
| member? | string |
| operator | [BinaryOperator](#binaryoperator) |
| values | string\[] |

### `TQueryOrderArray`

> **TQueryOrderArray**: *Array‹\[string, [QueryOrder](#queryorder)]›*

### `TQueryOrderObject`

### `TableColumn`

| Name | Type |
| - | - |
| children? | [TableColumn](#tablecolumn)\[] |
| dataIndex | string |
| format? | any |
| key | string |
| meta | any |
| shortTitle | string |
| title | string |
| type | string \| number |

### `TimeDimension`

> **TimeDimension**: *[TimeDimensionComparison](#timedimensioncomparison) | [TimeDimensionRanged](#timedimensionranged)*

### `TimeDimensionBase`

| Name | Type |
| - | - |
| dimension | string |
| granularity? | [TimeDimensionGranularity](#timedimensiongranularity) |

### `TimeDimensionComparison`

> **TimeDimensionComparison**: *[TimeDimensionBase](#timedimensionbase) & object*

### `TimeDimensionGranularity`

> **TimeDimensionGranularity**: *"second" | "minute" | "hour" | "day" | "week" | "month" | "year"*

### `TimeDimensionRanged`

> **TimeDimensionRanged**: *[TimeDimensionBase](#timedimensionbase) & object*

### `TransportOptions`

| Name | Type | Description |
| - | - | - |
| apiUrl | string | path to `/cubejs-api/v1` |
| authorization | string | [jwt auth token][ref-security] |
| credentials? | "omit" \| "same-origin" \| "include" | - |
| headers? | Record‹string, string› | custom headers |
| signal? | AbortSignal | AbortSignal to cancel requests |

### `UnaryFilter`

| Name | Type |
| - | - |
| and? | [UnaryFilter](#unaryfilter)\[] |
| dimension? | string |
| member? | string |
| operator | [UnaryOperator](#unaryoperator) |
| or? | [UnaryFilter](#unaryfilter)\[] |
| values? | never |

### `UnaryOperator`

> **UnaryOperator**: *"set" | "notSet"*

[link-mdn-max-safe-integer]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER

[ref-query-format]: https://docs.cube.dev/reference/core-data-apis/rest-api/query-format.md

[ref-security]: https://docs.cube.dev/docs/data-modeling/access-control.md

[ref-cache-control]: https://docs.cube.dev/reference/core-data-apis/rest-api#cache-control

[ref-sql-api]: https://docs.cube.dev/reference/core-data-apis/sql-api

[ref-cubesql-endpoint]: https://docs.cube.dev/reference/core-data-apis/rest-api/reference.md#base_path/v1/cubesql

[ref-time-zone]: https://docs.cube.dev/reference/core-data-apis/queries.md#time-zone

[link-tzdb]: https://en.wikipedia.org/wiki/Tz_database


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.