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

# How to use the Atoti Configuration API with DirectQuery

> How to set up an Atoti DirectQuery application with the Atoti Configuration API, from the `api-application` dependency and the `DirectQueryConnector` bean to the external tables and database options declared with `IDirectQueryConfigurator` and the Spring wiring.

The Atoti Configuration API can build both the database and the cubes of an Atoti DirectQuery
application. The database is a composite database. It combines an external SQL database with an
in-memory datastore.

A DirectQuery application is configured the same way as an in-memory application. The database and the cubes are both declared through `IModelConfigurer`.
To find out more read:

* [How to configure the database](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/database.md)
* [How to configure cubes](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/cube/overview.md)
* [How to convert in-memory tables to external tables](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/convert-to-external-tables.md)

This page covers only configuration that is specific to DirectQuery.

## How to build a DirectQuery application with the Atoti Configuration API

### Step 1: Add the dependencies

`api-application` holds `Application`, `IDirectQueryConfigurator` and the Spring configuration the
starter imports. It is **optional** in the Atoti Server Spring Boot starter, so it must be declared
explicitly. Add it and the connector artifact of the target database to
`api-clickhouse`. That artifact provides the `ClickhouseConnectorFactory` used in
[Step 2](#step-2-configure-the-connector):

```xml theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
<dependency>
    <groupId>com.activeviam.directquery</groupId>
    <artifactId>api-application</artifactId>
</dependency>
<dependency>
    <groupId>com.activeviam.directquery</groupId>
    <artifactId>api-clickhouse</artifactId>
</dependency>
```

`api-application` pulls in `api-database`, which holds `DirectQueryConnector` and the rest of the
DirectQuery database API.

### Step 2: Configure the connector

Expose the DirectQuery connector as a Spring bean of type `DirectQueryConnector`. The following
example connects to ClickHouse. Use the connector factory and the settings of the target database:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Bean
public DirectQueryConnector<ClickhouseDatabaseSettings> directQueryConnector() {
  final ClickhousePropertiesV2 properties =
      ClickhousePropertiesV2.builder()
          .host(this.host)
          .protocol(Protocol.HTTP)
          .port(this.port)
          .database(this.database)
          .build();
  return ClickhouseConnectorFactory.INSTANCE.createConnector(
      ClickhouseClientSettings.builder().propertiesV2(properties).build());
}
```

### Step 3: Configure the database and the cubes

Provide an `IModelConfigurer` bean. The cubes are declared exactly as in an in-memory application,
described in [how to configure cubes](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/cube/overview.md). The rest of this step covers the database.

#### How to configure the composite database

The `IDatabaseConfigurator` passed to `configureDatabase` configures the composite database as a
whole. Both sides are visible to every method below, including a table that `configureDatabase`
already converted from an in-memory table to an external table with
[`convertToExternalTables`](./convert-to-external-tables). A converted external table can be
configured further.

* `getCurrentSchema()` returns the schema of the composite database. It covers in-memory tables and
  joins, plus the external tables and joins declared so far.
* `addTable(IStoreDescription)` and `addJoin(IReferenceDescription)` configure the in-memory side.
  Their parameter types make the side unambiguous. See
  [configure the database](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/database.md) for the complete list of in-memory methods.
* `table(String)` retrieves a table, whichever side it is on. It returns an `ITableConfigurator`,
  which cannot state an external column. Retrieve the same table with
  `IDirectQueryConfigurator.table(String)` to reach an `IDirectQueryTableConfigurator`, described
  in the list that follows the external-side methods.

Configure the external side through `IDirectQueryConfigurator.from(IDatabaseConfigurator)`:

* `addTable(ATableDescription)` declares an external table. Get its description from the
  connector's discoverer, build it manually, or back it by a SQL expression.
* `table(String)` retrieves a previously declared or converted external table, to configure it
  further.
* `addJoin(JoinDescription)` adds a join between two external tables.
* `addAggregateTable(AggregateTableDescription)` declares an aggregate table of an external table
  declared or converted earlier. See
  [how to set the options of the external database](#how-to-set-the-options-of-the-external-database).

A table declared by `addTable` or converted by
[`convertToExternalTables`](./convert-to-external-tables#how-does-the-conversion-work) is reached
with `table(String)`, which returns an `IDirectQueryTableConfigurator`. That object configures a
single external table:

* `withExternalColumn` corrects the external column backing one field.
* `addField` adds a new field, backed by an external column.
* `withMultiColumnVector` states that an existing field is a vector the external table spreads over
  several columns. It takes the external columns forming the vector, in vector-index order.
* `withMultiRowVector` states that existing fields are vectors spread over the rows sharing a key.
  It takes the external column holding the vector index.
* `withClusteringFields` sets the clustering fields of the table.
* `withTimeTravel` sets the emulated time-travel information of the table.

`withClusteringFields`, `withTimeTravel`, `withExternalColumn` and `addField` apply to any external
table, declared or converted. On a declared table the four are generally unnecessary. The
`ATableDescription` already names the external column. It can also carry the clustering fields and
the time-travel information. The two vector operations apply only to a converted table. See
[how to vectorize a converted table](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/convert-to-external-tables.md#how-to-vectorize-a-converted-table).

The following example declares an external Sales table, discovered from the connector, and an
in-memory Hobbies table:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
private final DirectQueryConnector<ClickhouseDatabaseSettings> connector;
@Override
public void configureDatabase(final IDatabaseConfigurator database) {
  // External side: declare tables of the external database
  final IDirectQueryTableDiscoverer discoverer = connector.getDiscoverer();
  final var salesTable =
      discoverer.discoverTable(new ClickhouseTableId(TEST_DATABASE_NAME, SALES_TABLE));
  IDirectQueryConfigurator.from(database).addTable(salesTable);
  // In-memory side: declare datastore tables as in a regular application
  database.addTable(hobbiesStore());
}
```

#### How to set the options of the external database

`IDirectQueryConfigurator` also carries the options of the external database. They are options of
the whole database, so the last configurer to set one of them wins:

* `addAggregateTable(AggregateTableDescription)` declares an aggregate table. Its base table must be
  an external table declared or converted earlier, and one aggregate table per underlying external
  table is accepted.
* `withCache(CacheDescription)` describes the local cache of the external database. A call replaces
  the description set by an earlier one.
* `addUserDefinedSqlAggregationFunction(UserDefinedSqlAggregationFunction)` adds the SQL
  counterpart of an aggregation function registered in memory under the same plugin key. Adding a
  function under the plugin key of an earlier one replaces it and logs a warning.
* `withDatabaseSettings(IDatabaseSettings)` sets the settings of the external database, which are
  those of its connector, such as `ClickhouseDatabaseSettings` for ClickHouse. The settings are not
  checked against the connector: settings of another kind fail when the database is created.
* `getDatabaseSettings()` returns the settings the external database is created with: the settings
  set by an earlier call to `withDatabaseSettings`, or the defaults of the connector when none were
  set. Read them to adjust a single setting with the `toBuilder()` method of the settings class.

The following example declares all of them:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
external
    // An aggregate table of the sales table, pre-aggregating it per product and date
    .addAggregateTable(salesByProductAndDate)
    // A local cache of the products table, partitioned by one of its key fields
    .withCache(
        CacheDescription.builder()
            .singleTableCacheDescriptions(
                List.of(
                    SingleTableCacheDescription.builder()
                        .tableName(PRODUCTS_TABLE_NAME)
                        .cacheName(CACHE_NAME)
                        .cachePartitioningFields(List.of(DATE_FIELD))
                        .capacity(MaxPartitionsCount.of(10))
                        .build()))
            .build())
    // The SQL counterpart of an aggregation function registered in memory under the same key
    .addUserDefinedSqlAggregationFunction(
        UserDefinedSqlAggregationFunction.builder()
            .pluginKey(DOUBLE_SUM_PLUGIN_KEY)
            .inputsNumber(1)
            .sqlExpressionProviders(List.of(columns -> "2 * SUM(" + columns.getFirst() + ")"))
            .outputTypes(List.of(StandardTypes.DOUBLE))
            .reaggregable(IAggregationFunction.SUM_FUNCTION_PLUGIN_KEY)
            .build())
    // The settings of the external database, specific to its connector
    .withDatabaseSettings(
        ClickhouseDatabaseSettings.builder()
            .feedingQueryTimeout(Duration.ofMinutes(42))
            .build());
```

### Step 4: Wire the configuration

With the Atoti Server Spring Boot starter, there is nothing to import. An auto-configuration builds
the application, provided:

* A `DirectQueryConnector` bean is present.
* An `IModelConfigurer` bean is present. An Atoti Solution supplies its own database
  configuration instead.
* The `api-application` dependency of [Step 1](#step-1-add-the-dependencies) is on the classpath.

Everything the application needs is declared through the Atoti Configuration API, so no
`Application` bean is needed.

The auto-configuration exposes three Spring beans: the `Application`, the `IActivePivotManager`,
and the database as an `IDirectQueryDatabase`.

## How DirectQuery behaves with the Atoti Configuration API

* The composite database does not support joins between an external table and an in-memory table.
  Model such relationships at the cube level instead, for example with a Many-to-Many relationship
  between dimensions.
* A table defined by a SQL expression does not support emulated time travel. Emulated time travel
  needs a named external table, resolved from a `SqlTableId`.
* Every external table is checked when the application is built, whether it is backed by a named
  table or defined by a SQL expression. The table is discovered, and the build fails if it is
  missing, if the expression is invalid, or if it lacks a column the description reads.

## Related pages

* [Convert in-memory tables to external tables](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/convert-to-external-tables.md): conversion, its checks, and vectorization
* [Configure cubes](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/cube/overview.md): dimensions, hierarchies, and measures
* [Create measures](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/cube/measures.md): measure definitions and aggregations
