> ## 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 convert in-memory tables to external tables

> How `convertToExternalTables` moves in-memory tables of an Atoti DirectQuery application to the external database, including conversion onto a named table or a SQL expression, the join closure, call-time and build-time checks, and vectorizing a converted table with `withMultiColumnVector` and `withMultiRowVector`.

An Atoti DirectQuery application built with the Atoti Configuration API can declare a table in memory and
convert it afterwards. The declaration uses `addTable(IStoreDescription)` and joins, as for any
in-memory table. The converted table ends up backed by the external database instead of the
datastore. The declaration survives the conversion. See
[when conversion is the right tool](#how-does-the-conversion-work) below.

## Prerequisites

* A DirectQuery application built with the Atoti Configuration API, wired as described in
  [how to use the Atoti Configuration API with DirectQuery](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/direct-query.md).
* Each converted table has an external table backing it: either a named table in the external
  database, in the catalog and schema the conversion names, or a SQL expression the external
  database can run.
* Familiarity with the in-memory declarations described in
  [how to configure the database](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/database.md).

## How does the conversion work?

Convert with
`IDirectQueryConfigurator.from(database).convertToExternalTables(Map.of(tableName, externalTable, ...))`.
`database` is the `IDatabaseConfigurator` received in `IModelConfigurer.configureDatabase`. Each
entry maps the local name of an in-memory table to the `ExternalTable` backing it. Build that
`ExternalTable` from a table id with `ExternalTable.fromTableId(tableId)`, or from a SQL expression
with `ExternalTable.fromSqlExpression(sql)`.

The conversion is **eager**. It discovers, converts and re-declares the named tables immediately.
From that point in the database-configuration phase onward, the converted tables are external, and
`getCurrentSchema()` reports them as such.

* **Why a map, not one table at a time?** Converting a table also converts every in-memory table
  connected to it through joins. That set is the join closure. The composite database does not
  support joins between an external table and an in-memory table.
* **The other tables of the closure are resolved implicitly.** Only the tables named in the map get
  an external table of their own. The rest are looked up in the catalog and schema of the named
  external table, built with `fromTableId`, that reached them, under their own local names.
* **Name a table in the map to place it explicitly.** This overrides the closure lookup for that
  table. When two named tables reach the same unnamed table, the lookup uses the named table whose
  local name sorts first.
* **In-memory storage options are dropped.** Partitioning, indexes and duplicate-key handling do not
  apply to an external table.
* **Converted tables are no longer written locally.** Anything loading data into them must be
  removed.
* **Local names, types, key fields, join names and field mappings are preserved.**

> [!NOTE]
>
> Conversion is not the general way to get external tables. An application that only needs
> external tables declares them directly, with `addTable(ATableDescription)`.
> Conversion mainly serves two cases:
>
> * An Atoti Solutions application declares the tables in memory. The project's `IModelConfigurer`
>   then converts them.
> * Some configuration code deploys an application either fully in memory or with most or all
>   tables external. That shared code calls `convertToExternalTables` once, at the end, over most
>   or all of the tables it declared.

The following example declares three in-memory tables: `sales`, `products` and `competitors`. The
`sales` table is joined to `products`. The helper `declareCompetitorsTable`, not shown, declares the
`competitors` table and joins it to `products` on `id` and `date`. The example then converts `sales`
alone. The join closure converts `products` through the first join, and `competitors` through the
second. A table is converted however many joins away it is:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
databaseConfigurator.addTable(inMemorySalesStoreWithProduct());
databaseConfigurator.addTable(inMemoryProductsStore());
databaseConfigurator.addJoin(
    StartBuilding.reference()
        .fromStore(SALES_TABLE)
        .toStore(PRODUCTS_TABLE)
        .withName(SALES_TO_PRODUCTS)
        .withMapping("product", "id")
        .withMapping("date", "date")
        .build());
// Joined to the products table rather than to the sales table: the closure only reaches it
// through two joins
declareCompetitorsTable(databaseConfigurator);
// Converting the sales table converts every table joined to it, however many joins away
IDirectQueryConfigurator.from(databaseConfigurator)
    .convertToExternalTables(
        Map.of(
            SALES_TABLE,
            ExternalTable.fromTableId(new ClickhouseTableId(TEST_DATABASE_NAME, SALES_TABLE))));
```

## What is checked at the call and what is checked at build time?

Converting a table resolves two different things, with different strictness:

| What is resolved | How | When it is checked | If it is wrong |
| - | - | - | - |
| The table's location: catalog, schema and external name | From the table id given in the map, or looked up beside the table id that reached it through a join. A SQL expression is discovered at the call, and an invalid one fails the call. | At the `convertToExternalTables` call | The conversion fails immediately. |
| The external column backing each field | Inferred by name: the column named exactly like the field, or the local field name itself | When the application is built | The build fails and names the real column list. Call `withExternalColumn` to state the column. |

The following example names the table backing a converted table explicitly. Its local name
(`Catalog`) does not match its external name (`products`):

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
databaseConfigurator.addTable(inMemorySalesStoreWithProduct());
// The joined table bears a local name of its own
databaseConfigurator.addTable(inMemoryProductsStore(CATALOG_TABLE));
databaseConfigurator.addJoin(
    StartBuilding.reference()
        .fromStore(SALES_TABLE)
        .toStore(CATALOG_TABLE)
        .withName(SALES_TO_PRODUCTS)
        .withMapping("product", "id")
        .withMapping("date", "date")
        .build());
// Naming the joined table too: without it, the closure would look for a table named after
// its local name
IDirectQueryConfigurator.from(databaseConfigurator)
    .convertToExternalTables(
        Map.of(
            SALES_TABLE,
            ExternalTable.fromTableId(new ClickhouseTableId(TEST_DATABASE_NAME, SALES_TABLE)),
            CATALOG_TABLE,
            ExternalTable.fromTableId(
                new ClickhouseTableId(TEST_DATABASE_NAME, PRODUCTS_TABLE))));
```

The following example declares the `sales` table with its seller field under a local name that
matches no external column. It converts the table, then states the column with
`withExternalColumn`:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
databaseConfigurator.addTable(
    StartBuilding.store()
        .withStoreName(SALES_TABLE)
        .withField("id", ILiteralType.LONG)
        .asKeyField()
        // This field is named after no column of the external sales table
        .withField(LOCAL_SELLER_FIELD, ILiteralType.STRING)
        .withField(QUANTITY_COLUMN, ILiteralType.DOUBLE)
        .build());
final IDirectQueryConfigurator directQuery =
    IDirectQueryConfigurator.from(databaseConfigurator);
directQuery.convertToExternalTables(
    Map.of(
        SALES_TABLE,
        ExternalTable.fromTableId(new ClickhouseTableId(TEST_DATABASE_NAME, SALES_TABLE))));
// withExternalColumn points the field at the seller column
directQuery.table(SALES_TABLE).withExternalColumn(LOCAL_SELLER_FIELD, SELLER_COLUMN);
```

## How to convert a table onto a SQL expression

A table can read the rows of a SQL expression instead of those of a named table. The expression is
discovered at the `convertToExternalTables` call, like a named table. Fields are matched to the
columns of the expression by name, exactly as for a named table.

The following example declares `sales` and `products` in memory, joined together. It converts
`sales` onto a SQL expression that filters out the rows of product `p2`. It names `products` by
table id, because the expression has no catalog or schema to look it up in:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
databaseConfigurator.addTable(inMemorySalesStoreWithProduct());
databaseConfigurator.addTable(inMemoryProductsStore());
databaseConfigurator.addJoin(
    StartBuilding.reference()
        .fromStore(SALES_TABLE)
        .toStore(PRODUCTS_TABLE)
        .withName(SALES_TO_PRODUCTS)
        .withMapping("product", "id")
        .withMapping("date", "date")
        .build());
IDirectQueryConfigurator.from(databaseConfigurator)
    .convertToExternalTables(
        Map.of(
            // The sales table reads the rows of a SQL expression rather than of a table
            SALES_TABLE,
            ExternalTable.fromSqlExpression(
                "(SELECT * FROM "
                    + TEST_DATABASE_NAME
                    + "."
                    + SALES_TABLE
                    + " WHERE product <> 'p2')"),
            // The joined table must be named: an expression has no catalog or schema to look
            // it up in
            PRODUCTS_TABLE,
            ExternalTable.fromTableId(
                new ClickhouseTableId(TEST_DATABASE_NAME, PRODUCTS_TABLE))));
```

## How to vectorize a converted table

A table holding vector data declares **one vector field**, whatever shape the external table stores
it in. The following declaration gives the `simulations_multi_columns` table a single `array` vector
field:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
private static IStoreDescription inMemoryMultiColumnVectorStore() {
  return StartBuilding.store()
      .withStoreName(MULTI_COLUMN_VECTOR_TABLE)
      .withField("id", ILiteralType.STRING)
      .asKeyField()
      .withField("date", ILiteralType.LOCAL_DATE)
      .asKeyField()
      .withVectorField(VECTOR_FIELD, ILiteralType.DOUBLE)
      .build();
}
```

The external table spreads that vector over the columns `p1` to `p5`. The conversion maps fields,
not columns. It therefore leaves the table with one `array` field reading a column that does not
exist. The vector operations state the physical shape instead.

> [!NOTE]
>
> `withMultiColumnVector` and `withMultiRowVector` reject a table declared with `addTable(ATableDescription)`.
> Such a table states every column it reads, so its description already carries everything a vector needs.
> Vectorize it with `Vectorization.vectorizeMultiColumn` or `Vectorization.vectorizeMultiRow` before
> passing it to `addTable`.

The following example declares the table with `addTable(IStoreDescription)` and converts it. It then states that the
`array` field is spread over the columns `p1` to `p5`. `database` is the `IDatabaseConfigurator`
received in `IModelConfigurer.configureDatabase`. `IDirectQueryConfigurator.from(database)` returns
the configurator of the external side:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
database.addTable(inMemoryMultiColumnVectorStore());
// The table is converted and vectorized within the same database-configuration
// phase
IDirectQueryConfigurator.from(database)
    .convertToExternalTables(
        Map.of(
            MULTI_COLUMN_VECTOR_TABLE,
            ExternalTable.fromTableId(
                new ClickhouseTableId(
                    TEST_DATABASE_NAME, MULTI_COLUMN_VECTOR_TABLE))))
    .table(MULTI_COLUMN_VECTOR_TABLE)
    // The store declares one vector field; the external table spreads it over
    // p1 to p5, which are columns of the discovery and of no local field
    .withMultiColumnVector(VECTOR_FIELD, List.of("p1", "p2", "p3", "p4", "p5"));
```

* **The vector is a field that already exists.** The call states how the external table stores that
  field, keeping its local name and type. Naming a field the table does not have throws
  an exception. Use `addField` to create a field.
* **The columns come from the discovery, not from the fields.** The explicit column list and the
  multi-row index column are both resolved against the discovered external table.
* **A multi-row table vectorizes once.** `withMultiRowVector` takes every field sharing the index in
  a single call, and vectorizing an already-vectorized table is rejected.

`withMultiRowVector` names fields, not columns. The column holding a vector's values is carried by
the field, and the conversion infers it from the local field name. When the two differ, state the
column with `withExternalColumn`, before or after the vectorization.

The following example declares a table with two vectors under local names of their own. It converts
the table and points each vector at the column holding its values. It then regroups both vectors
over the index column they share:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
databaseConfigurator.addTable(
    StartBuilding.store()
        .withStoreName(MULTI_ROW_VECTOR_TABLE)
        .withField("id", ILiteralType.STRING)
        .asKeyField()
        .withField("date", ILiteralType.LOCAL_DATE)
        .asKeyField()
        // One vector per key, under local names of their own: the external table holds their
        // values in the columns 'p' and 'q', spread over the rows sharing a key
        .withVectorField(PRICE_VECTOR_FIELD, ILiteralType.DOUBLE)
        .withVectorField(QUANTITY_VECTOR_FIELD, ILiteralType.DOUBLE)
        .build());
IDirectQueryConfigurator.from(databaseConfigurator)
    .convertToExternalTables(
        Map.of(
            MULTI_ROW_VECTOR_TABLE,
            ExternalTable.fromTableId(
                new ClickhouseTableId(TEST_DATABASE_NAME, MULTI_ROW_VECTOR_TABLE))))
    .table(MULTI_ROW_VECTOR_TABLE)
    // Points the two fields at the columns holding their values.
    .withExternalColumn(PRICE_VECTOR_FIELD, "p")
    .withExternalColumn(QUANTITY_VECTOR_FIELD, "q")
    // Both vectors are spread over the same rows, addressed by the same index column, so a
    // single call regroups them.
    .withMultiRowVector(Set.of(PRICE_VECTOR_FIELD, QUANTITY_VECTOR_FIELD), VECTOR_INDEX_COLUMN);
```

## How conversion and vectorization behave

* Conversion is applied to all the tables that are joined to the converted table. None of them can
  be kept in memory.
* A table defined by a SQL expression can back a converted table. The expression is discovered at
  the call, and an invalid expression fails the call.
* The discovery of an expression reports no key fields. The key fields of a table converted onto an
  expression are the local ones, and they are not checked against the external database.
* Time travel is rejected on a table defined by an expression.
* An external column stated explicitly, with `withExternalColumn` or
  `IDirectQueryTableConfigurator.addField(AFieldDescription)`, is checked at the call. An unknown
  column throws an exception there.
* An external column left to inference is only checked when the application is built. Conversion
  infers it, and so does `ITableConfigurator.addField(IFieldDescription)` on a converted table,
  because neither can state a column.

## Related pages

* [Use the Atoti Configuration API with DirectQuery](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/direct-query.md): dependencies, connector, configurers and wiring
* [Configure the database](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/database.md): in-memory tables, joins, and field configuration
* [Configure cubes](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/foundry/cube/overview.md): dimensions, hierarchies, and measures
