Docs

Custom Backends for AI-Powered Grids and Charts

Give the LLM a SQL view of a REST API, a service, or files through an Apache Calcite adapter or a copy in a database.
Note
Commercial Feature

A commercial Vaadin subscription is required to use the AI-powered Grid and Chart in your project.

The AI-powered Grid and Chart let users explore data in natural language. The LLM reads a schema description and writes SQL. A QueryExecutor runs the query. When your data lives behind a REST API, in a service, or in files, it may have no SQL interface.

This guide covers two ways to add that interface:

  • Run the queries with Apache Calcite, an open-source Java library that runs SQL queries on data sources without a SQL interface of their own. Calcite runs inside your application and reads the data through an adapter, which presents a data source as SQL tables. It includes adapters for several data stores, and you can write one for your own backend.

  • Copy the data into a SQL database with a scheduled job, and let the database run the queries.

Calcite’s documentation covers adapter configuration and development. This guide focuses on connecting the resulting SQL interface to Vaadin.

Prerequisites

  • An application with an AI-powered Grid or Chart, set up as described on AI-Powered Grid or AI-Powered Chart.

  • Access to the backend, through an adapter or a client that can read the data to copy into a database.

Choose an Approach

For a data source with a JDBC driver, use a JDBC query executor like the one on the Controllers page. For a backend that runs SQL through its own API, implement QueryExecutor with that client. Override executeQuery(String query, QueryPage page) and count(String query) when it pages or counts in its own way.

For data without a SQL interface, compare the two approaches:

Calcite Adapter Database Copy

Query execution

The adapter sends the operations it supports to the backend, and Calcite runs the rest

The database runs queries against the copied data

Performance

Depends on the adapter. Calcite itself runs every operation that the adapter doesn’t send to the backend, such as a sort or a row count. It reads the rows for that and processes them in the application’s memory. A query can read a whole table that way, even for one page of a grid

The database filters, sorts, pages, and counts the rows with its own indexes, so the data doesn’t have to fit in the application’s memory

Freshness

Queries read from the backend, subject to any caching in the adapter or client

The data as of the last refresh of the copy

Several sources

Calcite can expose several sources as tables for queries that join or aggregate their data

Tables that are copied from several sources can be joined in the database

What you maintain

Adapter configuration and a query executor. A custom adapter also requires implementation and maintenance

A scheduled job that fills the copy, and a JDBC query executor

Use Calcite when a suitable built-in adapter can query the backend with the required performance. Check how the adapter performs with your data, as Check Paging and Query Performance describes. If no suitable adapter is available, compare the work of building a custom adapter with copying the data into a database. A custom adapter is small when it loads all the rows into memory and lets Calcite do the rest. One that sends filters, sorting, and paging to the backend, as large data requires, takes much more work. A copy handles large data, because the database runs the whole query. It requires that the data can be refreshed periodically and queried independently of the original backend.

Run the Queries with Calcite

Calcite runs inside your application as a library, without a server of its own. An adapter provides a schema: a set of tables that represents the data of the backend. Your QueryExecutor opens a JDBC connection to Calcite, adds the adapter’s schema to it, and runs the LLM’s queries through that connection.

Choose and Configure an Adapter

Start with Calcite’s built-in adapters. These include adapters for MongoDB, Elasticsearch, Cassandra, and files. Each adapter is an artifact of its own in the org.apache.calcite group, such as calcite-file, and brings in Calcite itself as calcite-core. Follow the selected adapter’s documentation for its dependencies, connection settings, schema configuration, and supported operations. The documentation shows the configuration as a model: a JSON file that names the adapter’s schema factory class in its factory field and the adapter’s settings in its operand field. The next section uses that class and those settings in code instead of the file. The adapter translates the SQL operations it supports into the backend’s own queries, so the backend’s rules apply to them. Not every SQL operation has an exact counterpart in the backend, for example a LIKE pattern or a date comparison. For such an operation, the adapter’s translation decides the result, or the adapter rejects the query. A query that runs can therefore still return wrong rows. Check which operations the adapter’s documentation lists as supported, and test the kinds of queries that users ask, as described in Check Paging and Query Performance. If the adapter gets them wrong, use a custom adapter or a copy of the data instead.

If no built-in adapter fits your backend, write a custom adapter by following the Calcite adapter tutorial. A custom adapter needs the calcite-core artifact. For a REST API or a service, the smallest custom adapter is a schema class with a table that implements ScannableTable and returns the objects from your backend client as rows. Calcite then filters, sorts, and groups all the rows in memory, so this suits data that is small enough to load in full. The same Vaadin integration applies to built-in and custom adapters.

Connect the Adapter to a Query Executor

The following query executor is a starting point for your own. It opens a Calcite connection for each query, adds one adapter schema to it, and runs the query through JDBC. It needs the org.apache.calcite:calcite-babel artifact, in the same version as calcite-core and the adapter’s artifact:

Source code
Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.runtime.CalciteContextException;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.sql.parser.SqlParseException;

import com.vaadin.flow.component.ai.provider.QueryExecutor;
import com.vaadin.flow.component.ai.provider.ToolException;

public class CalciteQueryExecutor implements QueryExecutor {

    private static final String SCHEMA_NAME = "backend";

    private final Schema adapterSchema;

    public CalciteQueryExecutor(Schema adapterSchema) {
        this.adapterSchema = adapterSchema;
    }

    @Override
    public String getSchema() { 1
        return """
                Tables:
                products(id INT, name VARCHAR, category VARCHAR, price DECIMAL)
                orders(id INT, product_id INT, quantity INT, ordered_on DATE)
                orders.product_id refers to products.id.
                Dialect: Apache Calcite.
                Compare dates with DATE literals, for example ordered_on >= DATE '2025-01-01'.
                Compare timestamps with TIMESTAMP literals, for example TIMESTAMP '2025-01-01 00:00:00'.
                Put aliases that are SQL keywords in double quotes, for example ordered_on AS "date".
                """;
    }

    @Override
    public List<Map<String, Object>> executeQuery(String query) {
        var sql = query.strip();
        if (sql.endsWith(";")) { 2
            sql = sql.substring(0, sql.length() - 1);
        }
        try (var connection = openConnection();
                var statement = connection.createStatement();
                var resultSet = statement.executeQuery(sql)) {
            var metaData = resultSet.getMetaData();
            var rows = new ArrayList<Map<String, Object>>();
            while (resultSet.next()) {
                var row = new LinkedHashMap<String, Object>();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    row.put(metaData.getColumnLabel(i),
                            resultSet.getObject(i));
                }
                rows.add(row);
            }
            return rows;
        } catch (SQLException e) {
            for (Throwable t = e; t != null; t = t.getCause()) {
                if (t instanceof SqlParseException
                        || t instanceof CalciteContextException) {
                    throw new ToolException(t.getMessage(), e); 3
                }
            }
            throw new IllegalStateException("Query failed", e);
        } catch (AssertionError e) { 4
            throw new IllegalStateException("Query failed", e);
        }
    }

    private Connection openConnection() throws SQLException {
        var properties = new Properties();
        properties.setProperty("lex", "MYSQL_ANSI"); 5
        properties.setProperty("conformance", "MYSQL_5"); 6
        properties.setProperty("parserFactory", 7
                "org.apache.calcite.sql.parser.babel.SqlBabelParserImpl#FACTORY");
        var connection = DriverManager.getConnection("jdbc:calcite:",
                properties);
        var calcite = connection.unwrap(CalciteConnection.class);
        calcite.getRootSchema().add(SCHEMA_NAME, adapterSchema); 8
        calcite.setSchema(SCHEMA_NAME);
        return connection;
    }
}
  1. A description of example tables. Replace it with one for the tables of your adapter, as described in Describe the Schema for the LLM.

  2. Calcite rejects a query that ends with a semicolon, and an LLM may write one.

  3. Calcite reports SQL parse and validation errors as a SqlParseException or a CalciteContextException in the cause chain of the SQLException. Their messages describe the problem in the SQL, so the query executor relays them in a ToolException for the LLM to correct its query. The message of the SQLException itself can include the error text of your backend, so other failures get a generic message.

  4. Some failures arrive as an AssertionError instead of an exception. The error handling of the controllers covers only exceptions.

  5. Lets queries name tables and columns without quotes. Calcite’s default converts unquoted names to upper case and matches names case-sensitively. A query for products then doesn’t find a table of that name. MYSQL_ANSI matches names in any case. A query that sorts the grid’s rows has the sort columns in double quotes, and MYSQL_ANSI reads those as names.

  6. Accepts SQL that an LLM may write and that Calcite rejects by default, such as grouping by a column alias or position, and !=. By default, Calcite also pads the string literals of a CASE or UNION with spaces to the same length. A label 'low' next to 'higher' gets three trailing spaces and no longer equals a column value. This setting turns the padding off.

  7. LLMs often use SQL keywords such as value or year as column aliases. Calcite’s Babel parser accepts many of them as names.

  8. Adds the adapter’s schema to the connection and makes it the default schema, so that queries can name its tables without a prefix.

Calcite’s JDBC connection reference describes the connection properties. The MYSQL_ANSI and MYSQL_5 values are named after the SQL dialect whose rules Calcite follows when it reads a query. They don’t depend on the backend and apply with any adapter.

The query executor takes the adapter’s schema as an object. Calcite’s documentation passes a model to the connection instead, and the connection creates the schema from it. That doesn’t suit a query executor that opens a connection for each query. Every connection would create the schema again, and an adapter that creates a backend client for each schema would open a new client for each query.

Create the schema once. Keep it in an object that outlives the views, such as a Spring bean, and reuse it for every query. For a built-in adapter, use the factory class and the settings of its model:

Source code
Java
// Your adapter's factory class. The file adapter's is only an example.
SchemaFactory schemaFactory = FileSchemaFactory.INSTANCE;
SchemaPlus rootSchema = Frameworks.createRootSchema(false);
Schema adapterSchema = schemaFactory.create(rootSchema, "backend",
        settings);
rootSchema.add("backend", adapterSchema);

Here, schemaFactory is an instance of the class in the model’s factory field. Use the INSTANCE constant of that class if it has one, as in the snippet, and create an instance otherwise. The settings variable is a Map<String, Object> with the adapter’s settings, such as the entries of the model’s operand field. The root schema in the snippet is a separate one, not the root schema of a connection. The factory requires it as the parent of the schema it creates. Some adapters look their schema up in it by name, so add the schema to it, and use the same name as the query executor, backend in the listing. Calcite makes similar calls when a connection reads a model.

For a custom adapter, create an instance of your own schema class instead.

A model can also declare views. They aren’t part of the adapter’s schema, so the snippet doesn’t create them. Add them to each connection in openConnection() instead, with a ViewTable.

Configure the adapter and its backend credentials for read-only access. The query executor doesn’t prevent writes: Calcite runs a write statement from the LLM when the adapter supports it. Follow the Controllers page’s guidance on the scope of the schema description and on error messages.

Describe the Schema for the LLM

The text that getSchema() returns is all the LLM knows about your data. Follow the general advice on the Controllers page. Describe the tables and columns exposed by the adapter, their relationships, and any restrictions that affect queries.

Name Apache Calcite as the SQL dialect and use its SQL reference for syntax and types. Tell the LLM how to write date and timestamp literals in a form that your adapter handles.

Even with the Babel parser, some names such as date and order require double quotes. This applies to column names and to aliases chosen by the LLM. Also avoid column names that are SQL functions written without parentheses, such as user or current_date. An unquoted SELECT user FROM tickets returns the function’s value instead of the column. Rename these columns in the exposed schema or tell the LLM to quote them.

Use the Query Executor

Create the query executor in the view and pass it to a GridAiController or a ChartAiController:

Source code
Java
var queryExecutor = new CalciteQueryExecutor(adapterSchema);
var controller = new GridAiController(grid, queryExecutor);

Attach the controller to the orchestrator as described on AI-Powered Grid and AI-Powered Chart.

The controllers call the query executor concurrently and from background threads, where the user’s session and security context aren’t available. The Query Executor section of the Controllers page describes this.

Check Paging and Query Performance

The grid uses executeQuery(String query, QueryPage page) and count(String query) to load rows lazily. Their defaults add sorting, paging, and counting to the SQL before calling executeQuery(String query).

Check that the adapter sends the grid’s sorting, paging, and counting to the backend. The backend’s query log shows which of them reach it. A table that only implements ScannableTable sends nothing: Calcite scans it for each query. If a scan loads all the rows from the backend, cache them for a short time. Override the query executor’s paging and counting methods when the backend can perform them more efficiently.

A grid render can query the backend several times: for a sample row, for the row count, and for each page. The chart calls executeQuery(String query) for each series query and receives its full result. Queries also run when the LLM proposes them for validation. Account for these repeated calls when choosing an adapter and any caching.

Test the query executor directly with SQL before involving an LLM. Include joins, aggregates with and without GROUP BY, grouping by a function, sorted and unsorted pages, and counts. In the conditions, cover date and decimal comparisons, date arithmetic, <>, and LIKE. Compare the returned rows with data read from the backend directly, because a mistranslated query can run without an error. Check the work the backend performs as well.

Copy the Data into a Database

The application can keep a copy of the data in a database and let the database run the LLM’s SQL. Queries then run independently of the original backend, and the application controls when to refresh the copy. The trade-off is that the grid and the chart show the data as of the last refresh of the copy.

Any database with a JDBC driver can hold the copy, such as a schema of its own in the database the application already uses, or an embedded database.

Fill the copy with a scheduled job that replaces its rows in one transaction, so that the grid and the chart never read a half-filled table.

Query the copy with a JDBC query executor like the one on the Controllers page, and describe the tables of the copy in its getSchema(). Give the query executor a database account that can only read the copy, as that page advises. The query executor on that page relays the database’s error messages to the LLM. Such a message can quote a row value, so check what your database reports before relaying it.

Updated –