> ## 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.

# Databricks

## Time-travel support

Time-travel is supported by DirectQuery with Databricks, but is limited to tables (and not views, as it is not supported by Databricks).
This means that updating applications based on this Database are subject to data desynchronization in case of changes in a view of the database.\


To choose the time-travel behavior, `DatabricksDirectQuerySettings#timeTravelPolicy` can be configured with the following values:

* `DatabricksDirectQuerySettings.TimeTravelPolicy#DISABLED`: time-travel will not be used.
* `DatabricksDirectQuerySettings.TimeTravelPolicy#STRICT`: time-travel will be used if there are only tables and no views, and otherwise will throw an error. This is the default mode.
* `DatabricksDirectQuerySettings.TimeTravelPolicy#LIGHT`: time-travel will be used only for tables and views will be queried without it.

Read this [page](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/versioning.md) to learn more about the visible effects of this desynchronization.

## Vectors support

Databricks handles vectors natively, via the `Array` type in the model and thanks to special functions at query time.

Native aggregation of `Array` columns, available from Atoti Server 6.2.2, is supported for the following aggregation functions:

* sum
* average
* long (sum of positive parts)
* short (sum of negative parts)
* gross (sum of absolute values)
* sum-product of a vector with scalar factors
* count

As on every other database, min, max, multiply, square sum and distinct count remain unsupported on native `Array` columns, and fail at query time.

Native vector aggregation relies on Databricks' [`vector_sum`](https://docs.databricks.com/aws/en/sql/language-manual/functions/vector_sum) function, which requires Databricks Runtime 18.1 or above. See the [compatibility matrix](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/compatibility.md#databricks-cluster) for the runtime versions supported by DirectQuery.

### Array aggregation precision

`vector_sum` only accepts `ARRAY<FLOAT>`. A column of that type is aggregated as it is, with no conversion.

Aggregating an array of any other numeric type requires casting each of its elements to `FLOAT` first, which performs the whole aggregation in single precision: a `DOUBLE` element keeps roughly 7 significant digits instead of 15, and a `BIGINT` or `INT` element above 2<sup>24</sup> is rounded. Because that loss of accuracy must never be silent, `DatabricksDialectSettings` chooses between the two with `ArrayAggregationPrecision`:

* `EXACT`, the default: such an aggregation is rejected, rather than silently returning inaccurate values.
* `FLOAT`: such an aggregation is performed, at the cost of accuracy.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
DatabricksClientSettings.builder()
    .dialectSettings(
        DatabricksDialectSettings.builder()
            .arrayAggregationPrecision(ArrayAggregationPrecision.FLOAT)
            .build())
    .build();
```

Only the type of the aggregated column matters, not the type of the resulting measure: the result of an `ARRAY<FLOAT>` aggregation is widened back without losing anything. The sum-product of an array with scalar factors, for instance, returns a `double[]` measure but stays exact when it aggregates an `ARRAY<FLOAT>` column.

> [!NOTE]
>
> Two alternatives avoid the setting entirely: expose the column as `ARRAY<FLOAT>`, for instance with `CAST(price AS ARRAY<FLOAT>)` in a view, or use [emulated vectors](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/directquery-vectors.md#vector-emulation) (multi-row or multi-column), which Databricks aggregates at the full precision of the column type.

## Gotchas

### Nullable fields

Databricks can define fields with nullable types.
DirectQuery is capable of detecting this and defines its internal model accordingly.\

While this is not a problem in itself, it can conflict with the rule in Atoti cubes that all levels must be based on non-nullable values.
This does not create an issue of any sort as the local model is updated behind the scene, assigning a default value based on the type.\

It has a side effect on the query performance, as DirectQuery must convert on-the-fly null values to their assigned default values, as well as adding extra conditions during joins to handle null values on both sides.

### Connection pool configuration

DirectQuery uses the HikariCP connection pool to manage connections to Databricks.

It is possible to tune this connection pool by specifying a configuration file and providing its path with the system property `hikaricp.configurationFile` (via `-Dhikaricp.configurationFile=path/to/hikari.properties`).

Not all the parameters can be set that way, as some are set directly by DirectQuery.

The associated file format is:

```properties theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
maximumPoolSize=31
idleTimeout=15000
minimumIdle=17
```

#### Pool size

`maximumPoolSize`: if not set, the pool size is configured automatically by the DirectQuery connector, based on the number of CPU cores available.

#### Connection timeout

`idleTimeout`: the maximum time a connection can be idle before being closed. This parameter is not set by DirectQuery and defaults to the Hikari default.

#### Minimum idle connections

`minimumIdle`: the minimum number of idle connections that the pool will maintain.
DirectQuery sets this parameter to `0` by default, so connections are opened on demand.

### Feeding connection string

On modern cloud distributed databases such as Databricks, a key design point is the separation of compute and storage.
This allows to use different computing resources to process queries and brings flexibility and the capability to scale up and down the resources (and the associated bill!).
On Databricks, the compute resources can be clusters or SQL warehouses. A bigger compute will process queries faster but will also cost more.

The load on the external database of a DirectQuery application is quite particular:

* At the application startup and refresh, many queries are performed on the database to initialize the cube and cache data in it (the hierarchies and aggregate providers).
* After the initial feeding, if the aggregate providers have been chosen wisely, most user queries will hit the cache data and actually never been run on the external database. Additionally, queries hitting the external database should most of the time be drill-down with a very reduced scope and should be easier for Databricks to handle.

In order to have faster startup time, it is recommended to use bigger computational resources during that time.
Afterward, to save on cost, the computational resources can be scaled down.
DirectQuery provides a way to define two compute resources to use for your application:

* one powerful cluster or SQL warehouse, used during initial feeding and refresh, to guarantee faster startup and refresh times
* a regular cluster or SQL warehouse, to serve the queries after the initial feeding in a cost-efficient manner

After the initial feeding, the large compute resource will become idle and be automatically shut down if you configured it as such.

This feeding connection string can be defined as such:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
final DatabricksConnectionProperties properties =
    DatabricksConnectionProperties.builder()
        .connectionString("CONNECTION_STRING_TO_SMALL_AND_CHEAP_CLUSTER")
        .feedingConnectionString("CONNECTION_STRING_TO_LARGE_AND_EXPENSIVE_CLUSTER")
        .additionalOption(
            DatabricksConnectionProperties.PASSWORD_PROPERTY_KEY, "your-plain-password")
        .build();
```

You can then pass it as argument to your session:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
final DatabricksClientSettings clientSettings =
    DatabricksClientSettings.builder().connectionProperties(properties).build();
final DirectQueryConnector<DatabricksDatabaseSettings> connector =
    DatabricksConnectorFactory.INSTANCE.createConnector(clientSettings);
```

If it is not defined, the regular compute resource will be used for the feeding.

Note that both compute resources need to be of the same type (either cluster or SQL warehouse), to run the same
runtime version, and to share the same password.
