# Server Evaluation of Expressions

Canonical page: https://www.adaptabletools.com/docs/adaptable-server-evaluation

- By default, Expressions are evaluated automatically by AdapTable on the Client
- However sometimes you might wish to perform the evaluation yourself on the server
- AdapTable facilitates this for you by:
  - allowing you to choose which Modules (or Expressions) will evaluate on the Server or Client
  - firing Events to give you oversight of what needs evaluation
  - providing you with the AST that is used by AdapTableQL when managing Expressions

Expression evaluation by AdapTable is generally abstracted away.

End users create Expressions at run-time - either in the UI using [Wizards](https://www.adaptabletools.com/docs/ui-settings-panel-wizards/index.md) or the [Expression Editor](https://www.adaptabletools.com/docs/ui-expression-editor/index.md) - or provide them at design-time in [Initial Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-initial-state/index.md), and everything "just works".

But some developers have a more complicated 2-step use case:

1. run-time users will build Expressions
2. but the developer team will perform the actual evaluation themselves on their Server

- This should not be confused with using the [Server-Side Row Model](https://www.adaptabletools.com/docs/dev-guide-row-models-server-overview/index.md) which <b>forces</b> server evaluation
- It should also not be confused with [Evaluating Expressions via the API](https://www.adaptabletools.com/docs/adaptable-ql-expression-evaluation/index.md) which still evaluates using AdapTableQL

This page provides some tips and tricks to help achieve this.

## Specifying Externally Evaluated Modules

The first, key, step is to tell AdapTable which [Modules](https://www.adaptabletools.com/docs/technical-reference-adaptable-modules/index.md) (or Expressions) should be evaluated externally.

Four Modules can be evaluated externally: [Alerts](https://www.adaptabletools.com/docs/handbook-alerting/index.md), [Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md), [Column Filters](https://www.adaptabletools.com/docs/handbook-column-filter/index.md) and [Grid Filter](https://www.adaptabletools.com/docs/handbook-grid-filter/index.md)

This is done via the `evaluateAdaptableQLExternally` property in [Expression Options](https://www.adaptabletools.com/docs/technical-reference-expression/index.md).

- This allows you to control when Server evaluation will take place
- e.g. you can evaluate the Grid Filter remotely but let AdapTable manage Calculated Columns and Column Filters

It is in the form of a function which receives context about the [Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md) / [Module](https://www.adaptabletools.com/docs/technical-reference-adaptable-modules/index.md) and returns a boolean.

- This is only required when using AG Grid's **Client-Side Row Model**
- If using the [Server-Side Row Model](https://www.adaptabletools.com/docs/dev-guide-row-models-server-overview/index.md) then **all** filtering (and sorting) is automatically ignored on the client

### `evaluateAdaptableQLExternally`

Whether a Module (or a specific Expression) should be evaluated externally

By default AdapTable will perform all evaluations of Expressions

However you might prefer to evaluate a particular Module (e.g. Column Filters) externally (i.e. yourselves).

Use this property to tell AdapTable which Modules (or Expressions) should not be evaluated by AdapTable.

It is in the form of a function which receives context about the expression / module and returns a boolean: return `true` to evaluate it externally, and `false` to leave it to AdapTable.

The context is of type [`EvaluateExpressionExternallyContext`](https://www.adaptabletools.com/docs/reference/evaluateexpressionexternallycontext.md) and is defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [expression](https://www.adaptabletools.com/docs/reference/evaluateexpressionexternallycontext.md#expression) | `string` | Expression to evaluate |
| [module](https://www.adaptabletools.com/docs/reference/evaluateexpressionexternallycontext.md#module) | [`AdaptableQLModule`](https://www.adaptabletools.com/docs/reference/adaptableqlmodule.md) | Module being evaluated: Alert, CalculatedColumn, ColumnFilter, GridFilter |
| [object](https://www.adaptabletools.com/docs/reference/evaluateexpressionexternallycontext.md#object) | [`AdaptableObject`](https://www.adaptabletools.com/docs/reference/adaptableobject.md) | AdapTable Object which contains the Expression |
| [referencedColumns](https://www.adaptabletools.com/docs/reference/evaluateexpressionexternallycontext.md#referencedcolumns) | [`AdaptableColumn`](https://www.adaptabletools.com/docs/reference/adaptablecolumn.md)`<TData>[]` | Columns contained in Expression |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/evaluateexpressionexternallycontext.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |

The `module` property is of type [`AdaptableQLModule`](https://www.adaptabletools.com/docs/reference/adaptableqlmodule.md) which can be of one of 4 values:

- `Alert` - runs [Alerts](https://www.adaptabletools.com/docs/handbook-alerting/index.md) externally

- `CalculatedColumn` - returns default value for the [Calculated Column](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) so value can be provided externally

- `ColumnFilter` - evaluates [Column Filters](https://www.adaptabletools.com/docs/handbook-column-filter/index.md) externally

- `GridFilter` - evaluates the [Grid Filter](https://www.adaptabletools.com/docs/handbook-grid-filter/index.md) externally

Leave this property undefined to maintain the default behaviour of AdapTableQL handling all evaluations

```ts {4,5}
// Evaluate Columns Filters, Alerts & Calculated Columns in AdapTableQL
// But evaluate the Grid Filter externally
expressionOptions: {
  evaluateAdaptableQLExternally: (context: EvaluateExpressionExternallyContext) => {
    return context.module === 'GridFilter';
  },
},
```

In more advanced use cases you can use the Context object to make a per-instance decision as it contains:

- the actual [Adaptable Object](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-initial-state/index.md#adaptable-objects) being evaluated
- an `expression` property containing the [Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md) being evaluated

```ts {3}
// Evaluate Expressions on the Server which use the MY_EXTERNAL_FUNCTION expression function
expressionOptions: {
  evaluateAdaptableQLExternally: (context: EvaluateExpressionExternallyContext) => {
    return context.expression?.includes('MY_EXTERNAL_FUNCTION') ?? false;
  },
},
```

## Turning off Automatic Validation

By default, AdapTableQL will validate Expressions automatically as they are being written.

If you are evaluating the [Grid Filter](https://www.adaptabletools.com/docs/handbook-grid-filter/index.md) on your server you might wish to set `performExpressionValidation` in [Expression Options](https://www.adaptabletools.com/docs/technical-reference-expression/index.md) to _false_ to avoid false positives.

### `performExpressionValidation`

Validate Expressions before they can be run or saved

By default AdaptablQL will validate all Expressions in the AdaptableUI before they can be run or saved.

This is generally the preferred behaviour to avoid confusion.

However sometimes, particularly if evaluation Expressions remotely, this can be intrusive and not helpful.

Simply set the property to false and AdapTable will permit Expressions it cannot understand to run regardless:

```ts {3}
// Don't allow AdapTableQL to validate Expressions
expressionOptions: {
  performExpressionValidation: false,
},
```

## Reducing Expression Complexity

Expressions are very rich and powerful, and potentially extremely complex.

When running on the Client that complexity is not problematic as AdapTable takes care of all evaluations.

However if evaluating the Grid Filter (or Calculated Columns) on the server it means a lot of work is required.

AdapTable helps you by allowing you to reduce the compexity of the Expressions in 2 ways:

- Limiting which **functions** are available in Expressions
- Limiting which **columns** can be included in Expressions or can be filtered

See [Reducing Expression Complexity](https://www.adaptabletools.com/docs/adaptable-ql-expression-managing/index.md) for more information

## AdapTable Events

As noted above, AdapTable will not evaluate any Modules for which the `evaluateAdaptableQLExternally` function returns _true_.

Instead developers should subscribe to [Adaptable Events](https://www.adaptabletools.com/docs/technical-reference-adaptable-events/index.md) designed for this purpose.

This allows developers to perform their own external evaluation as required

The results of the external evaluation will then need to be returned to AdapTable and displayed accordingly.

- There are many methods in [Grid API](https://www.adaptabletools.com/docs/handbook-managing-grid-data/index.md) which can be used to supply data to AdapTable
- The most commonly used is `loadGridData` (see [Managing Grid Data](https://www.adaptabletools.com/docs/handbook-managing-grid-data/index.md) for more information)

AdapTable will automatically populate AG Grid with any data with which it is provided.

It will also take care or re-applying all column sorts and column formats as required.

The 3 most relevant [Adaptable Events](https://www.adaptabletools.com/docs/technical-reference-adaptable-events/index.md) are:

### Grid Filter Applied

The [Grid Filter Applied Event](https://www.adaptabletools.com/docs/technical-reference-filter/index.md) is published any time a [Grid Filter](https://www.adaptabletools.com/docs/handbook-grid-filter/index.md) runs in AdapTable.

It contains details of the Grid Filter's Expression and the AST used by [AdapTableQL](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md) to evaluate it.

### Column Filter Applied

The [Column Filter Applied Event](https://www.adaptabletools.com/docs/technical-reference-filter/index.md) is published each time Column Filters are applied.

- If evaluating Column Filters externally, you can run them all in one batch if preferred
- To do this set `manuallyApplyColumnFilter` in [Column Filter Options](https://www.adaptabletools.com/docs/technical-reference-filter/index.md) to *true* (see [Manually Applying Column Filter](https://www.adaptabletools.com/docs/handbook-column-filter-manually-applying/index.md))

### Calculated Column Changed

The [Calculated Column Changed Event](https://www.adaptabletools.com/docs/technical-reference-calculated-column/index.md) fires whenever anything changes in Calculated Column State, i.e. if a Calculated Column has been added, edited or deleted.

### Using the AST

AdapTable will make the AST it uses when evaulating an Expression available where necessary.

This is available in the `Info` property provided by the related Adaptable Event:

| Event                                                                                                  | Info Class                                                                       | AST Property                    |
| ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | ------------------------------- |
| [Grid Filter Applied](https://www.adaptabletools.com/docs/technical-reference-filter/index.md)             | [`GridFilterAppliedInfo`](https://www.adaptabletools.com/docs/reference/gridfilterappliedinfo.md)             | `gridFilterExpressionAST`       |
| [Column Filter Applied](https://www.adaptabletools.com/docs/technical-reference-filter/index.md)         | [`ColumnFilterAppliedInfo`](https://www.adaptabletools.com/docs/reference/columnfilterappliedinfo.md)         | `columnFilterExpressionASTs`    |
| [Calculated Column Changed](https://www.adaptabletools.com/docs/technical-reference-calculated-column/index.md) | [`CalculatedColumnChangedInfo`](https://www.adaptabletools.com/docs/reference/calculatedcolumnchangedinfo.md) | `calculatedColumnExpressionAST` |

The [Column Filter Applied](https://www.adaptabletools.com/docs/technical-reference-filter/index.md) event provides one AST per applied Column Filter

Any Expression's AST can be retrieved via the `getASTForExpression` function in the [Expression API](https://www.adaptabletools.com/docs/technical-reference-expression/index.md)

**Example: AdapTableQL Server Evaluation**

Evaluating AdapTableQL on the Server

- This example demonstrates Server Evaluation using Filters
- In the demo we listen to the [Column Filter Applied Event](https://www.adaptabletools.com/docs/technical-reference-filter/index.md) to get the latest applied Filters in the Grid
- We then call our mock Server which translates the Expression into SQL - the rough and ready code we used is [here](https://github.com/AdaptableTools/showcase-server-side-row-model/blob/master/server/SqlService.ts) - which runs the associated SQL Query
- The server then returns the new data to AdapTable, which in turn populates AG Grid with it (using [Grid API](https://www.adaptabletools.com/docs/handbook-managing-grid-data/index.md) methods)
### Expand to see how Filters are evaluated externally

We tell AdapTableQL not to evaluate Column Filters:
```ts
expressionOptions: {
  evaluateAdaptableQLExternally: (
    context: EvaluateExpressionExternallyContext
  ) => { return context.module === 'ColumnFilter' },
},
```
In the AdaptableReady Event we populate the Grid with initial data:
```ts
export const onAdaptableReady = async (info: AdaptableReadyInfo) => {
  const adaptableApi: AdaptableApi = info.adaptableApi;
  const agGridApi = info.agGridApi;
  const startRow = 0;
  const endRow = 1000;
  const response = await fetch(API_BASE, {
    method: 'post',
    body: JSON.stringify({
      startRow,
      endRow,
    }),
    headers: {'Content-Type': 'application/json; charset=utf-8'},
  });
  const {rows} = await response.json();
  adaptableApi.gridApi.loadGridData(rows);
};
```
And we listen to the Filter Applied Event to run the Filters externally and then repopulate the Grid with the results.

AG Grid's `loading` Grid Option shows the loading overlay (skeleton rows on the Client-Side Row Model) while the server request runs.
```ts
adaptableApi.eventApi.on(
  'ColumnFilterApplied',
  async (eventInfo: ColumnFilterAppliedInfo) => {
    const filterState = adaptableApi.stateApi.getAdaptableFilterState();
    const astNodes: unknown[] = [];
    for (const columnFilter of filterState.columnFilters ?? []) {
      if (!columnFilter.Expression) {
        continue;
      }
      const ast = adaptableApi.expressionApi.getASTForExpression(
        columnFilter.Expression
      );
      astNodes.push(...(Array.isArray(ast) ? ast : [ast]));
    }
    const request = {
      adaptableFilters: [],
      gridFilterAST: astNodes.length ? astNodes : undefined,
      includeSQL: true,
      startRow,
      endRow,
    };
    agGridApi.setGridOption('loading', true);
    const response = await fetch(API_BASE, {
      method: 'post',
      body: JSON.stringify(request),
      headers: {'Content-Type': 'application/json; charset=utf-8'},
    });
    const {rows, sql} = await response.json();
    adaptableApi.gridApi.loadGridData(rows);
    agGridApi.setGridOption('loading', false);
  }
);
```

- Run a Column Filter in the Filter Bar and see how the Grid updates
- Note how we output the SQL to [System Status Toolbar](https://www.adaptabletools.com/docs/handbook-system-status-message/index.md)

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableOptions,
  EvaluateExpressionExternallyContext,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'AdapTableQL Server Evaluation',
  expressionOptions: {
    evaluateAdaptableQLExternally: (
      context: EvaluateExpressionExternallyContext
    ) => {
      return context.module === 'ColumnFilter';
    },
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Main',
          Toolbars: ['SystemStatus', 'Export'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'athlete',
            'gold',
            'silver',
            'bronze',
            'totalMedals',
            'country',
            'sport',
            'year',
          ],
          ColumnSizing: {
            athlete: {Width: 175},
            bronze: {Width: 100},
            country: {Width: 125},
            gold: {Width: 100},
            silver: {Width: 100},
            sport: {Width: 175},
            year: {Width: 115},
          },
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {
  AdaptableApi,
  ColumnFilterAppliedInfo,
  AdaptableReadyInfo,
} from '@adaptabletools/adaptable';

const API_BASE: string = process.env.NEXT_PUBLIC_ATHLETES_API_URL!;

export const onAdaptableReady = async (info: AdaptableReadyInfo) => {
  const adaptableApi: AdaptableApi = info.adaptableApi;
  const agGridApi = info.agGridApi;
  const startRow = 0;
  const endRow = 1000;

  const response = await fetch(API_BASE, {
    method: 'post',
    body: JSON.stringify({
      startRow,
      endRow,
    }),
    headers: {'Content-Type': 'application/json; charset=utf-8'},
  });
  const {rows} = await response.json();
  adaptableApi.gridApi.loadGridData(rows);

  adaptableApi.eventApi.on(
    'ColumnFilterApplied',
    async (eventInfo: ColumnFilterAppliedInfo) => {
      const filterState = adaptableApi.stateApi.getAdaptableFilterState();
      const astNodes: unknown[] = [];
      for (const columnFilter of filterState.columnFilters ?? []) {
        if (!columnFilter.Expression) {
          continue;
        }
        const ast = adaptableApi.expressionApi.getASTForExpression(
          columnFilter.Expression
        );
        astNodes.push(...(Array.isArray(ast) ? ast : [ast]));
      }
      const request = {
        adaptableFilters: [],
        gridFilterAST: astNodes.length ? astNodes : undefined,
        includeSQL: true,
        startRow,
        endRow,
      };

      agGridApi.setGridOption('loading', true);

      const response = await fetch(API_BASE, {
        method: 'post',
        body: JSON.stringify(request),
        headers: {'Content-Type': 'application/json; charset=utf-8'},
      });
      const {rows, sql} = await response.json();
      adaptableApi.systemStatusApi.setInfoSystemStatus(
        `SQL: ${sql.slice(0, 40)}`,
        sql
      );

      adaptableApi.gridApi.loadGridData(rows);
      agGridApi.setGridOption('loading', false);
    }
  );
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {WebFramework} from './rowData';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions<WebFramework> = {
  theme: themeBalham,
  defaultColDef: {
    //   headerName: '??',
    //   colId: 'xxs',
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {field: 'id', hide: true, cellDataType: 'text'},
  {
    field: 'athlete',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'country',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'sport',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'year',
    cellDataType: 'number',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'gold',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
  {
    field: 'silver',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
  {
    field: 'bronze',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
];
```

## JSON Translation

All Column Filter and Grid Filter objects (plus Alerts and Calculated Columns) in [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md) are JSON.

This means that in order to perform searching and filtering on the server this JSON will need to be 'translated' into something that the particular server can understand.

Obviously each server is different so AdapTable cannot provide an out of the box implemenation, but we do work with a number of partners who have performed this for clients.

We also have a [Grid Gurus consultancy service](https://www.adaptabletools.com/#grid-gurus) who can advise you in a bespoke manner.
