diff --git a/README.md b/README.md
index c350ac6..db933d2 100644
--- a/README.md
+++ b/README.md
@@ -49,6 +49,7 @@ It copies tables (with indexes, constraints, sequences and partitions) **directl
| Custom and modern types | PostgreSQL enums and domains, DuckDB unions and fixed arrays, ClickHouse variants, maps and tuples |
| Embeddings move with their search | Vectors of pgvector, MySQL, MariaDB, Oracle, SQL Server, Db2, DuckDB and ClickHouse keep their dimensions, and vector indexes (HNSW, IVF) keep their distances and options |
| Embeddings live in a vector database | **Vector databases** sit in the connection tree like the other data sources: Milvus, Qdrant, Weaviate, Pinecone, Elasticsearch, OpenSearch and Chroma, read by their REST APIs. Expand one to its databases, collections, partitions, tenants or namespaces, open a collection to browse its fields and records page by page, then **Import…** writes it straight into a database with vectors: ids and vectors become columns, every top-level field becomes a column of its type and the whole payload is kept as JSON. Conditions, native filters and nearest neighbor searches choose the rows |
+| The rows of Elasticsearch or OpenSearch indexes belong in a table | **SQL Query** on an Elasticsearch or OpenSearch data source, or on one of its indexes, runs SQL on the indexes (the SQL of these servers reads only). The rows of a query are exported like the rows of a table into SQL, Parquet, CSV or Excel packages or any database, an index becomes a plain table. Vectors with their vector indexes take the other way, **Import Vectors into Database** |
| The database sits behind a bastion host | **SSH tunnel** per data source, with a password or a private key (ed25519, RSA, ECDSA, with a passphrase). Host keys are trusted on first use and remembered, a changed host key is refused. A broken tunnel opens again by itself |
| Which server is this, and is it well? | **Info** opens the overview (product, version, driver, session, features SqlJam detected) and the health of a data source or a vector database (uptime, connections, size, cluster state, load), refreshed when you ask. Its **Dashboard** draws live charts of the last 5 minutes, sampled every 1 to 30 seconds: sessions, transactions, statements, rows, cache hits, locks, network, CPU, memory and size, read from the statistics of each database. Embedded databases show the CPU and the memory of SqlJam, in which they run. Vector databases show their collections and records, Elasticsearch and OpenSearch also CPU, heap, indexing and searches, Qdrant requests and memory. Metrics which a server does not tell are listed with the reason |
| Long values and rows for a chat or a ticket | Cells show one line, a **double click** or **Shift+Enter** opens the whole value with JSON indented and vectors described. Select rows and **Copy Rows As** CSV, TSV, JSON or Markdown, or press **Ctrl+C** to paste them into a spreadsheet |
@@ -127,8 +128,8 @@ Only **Java 17+** is needed to run SqlJam. JavaFX and all JDBC drivers are insid
| Qdrant | 1.19 | 1.10 | scroll, named, sparse and multivectors |
| Weaviate | 1.39 | 1.24 | objects cursor and GraphQL, named vectors and tenants |
| Pinecone and Pinecone Local | API 2025-01 | API 2025-01 | list and fetch, namespaces, dense and sparse values |
-| Elasticsearch | 8.19 | 8.0 | point in time, `dense_vector` |
-| OpenSearch | 2.19 | 2.4 | point in time, `knn_vector` |
+| Elasticsearch | 8.19 | 8.0 | point in time, `dense_vector`, SQL of indexes |
+| OpenSearch | 2.19 | 2.4 | point in time, `knn_vector`, SQL of indexes |
| Chroma | 1.5 | 1.0 | REST API v2, tenants and databases |
Collections of vector databases go into the databases above which have vectors, never the other way round. Vector types and indexes are detected on the target before they are used, by a probe of each feature, so an older server, a missing extension or a setting which is turned off keeps the vectors as text.
@@ -171,8 +172,8 @@ SqlJam starts with a splash screen while it loads the configuration, the data so
2. Right-click a database or schema → **Export…**
3. Pick tables, choose **SQL scripts**, **Parquet**, **CSV** or **Excel** (folder) or **Database** (another data source, or a new one from the **+** button next to it), press **Start**. An import into a database runs in one transaction or commits every N rows (N is typed next to it), check **Skip rows with errors** to go on after bad rows and **Confirm before commit** to review it first, and choose **Update or insert by key** or **Skip existing by key** for rows which exist already.
4. Open a table, narrow its rows on the **Data** tab with columns, WHERE, GROUP BY and ORDER BY, then **Export…** just those rows. A header sorts the rows of the page, a double click shows a whole value and **Copy Rows As** copies the selected rows. **Info** on the toolbar or a right-click shows the overview and the health of the data source.
-5. **SQL Query** on the toolbar or a right-click opens an editor for the data source. **Ctrl+Enter** (**⌘+Enter** on macOS) runs the statement at the caret, **Ctrl+Shift+Enter** runs them all, then **Export…** sends all rows of the query through the same exits.
-6. Create a data source of the **Vector databases** category for Milvus, Qdrant, Weaviate, Pinecone, Elasticsearch, OpenSearch or Chroma, with an API key, a user and password or neither, as the database asks. Expand it in the tree to its databases, collections and partitions (tenants of Weaviate, namespaces of Pinecone), open a collection to see its fields and its records page by page, narrowed by conditions, a native filter or a nearest neighbor search. **Import…** on the collection tab, a right-click or **File → Import from Vector Database…** opens the wizard which imports the checked collections into a data source with vectors. Only such data sources are offered as targets.
+5. **SQL Query** on the toolbar or a right-click opens an editor for the data source. **Ctrl+Enter** (**⌘+Enter** on macOS) runs the statement at the caret, **Ctrl+Shift+Enter** runs them all, **Ctrl+Space** or a dot after a table or alias completes the names of tables and columns, then **Export…** sends all rows of the query through the same exits. **Help → Keyboard Shortcuts** lists every key.
+6. Create a data source of the **Vector databases** category for Milvus, Qdrant, Weaviate, Pinecone, Elasticsearch, OpenSearch or Chroma, with an API key, a user and password or neither, as the database asks. Expand it in the tree to its databases, collections and partitions (tenants of Weaviate, namespaces of Pinecone), open a collection to see its fields and its records page by page, narrowed by conditions, a native filter or a nearest neighbor search. **Import…** on the collection tab, a right-click or **File → Import from Vector Database…** opens the wizard which imports the checked collections into a data source with vectors. Only such data sources are offered as targets. **SQL Query** on an Elasticsearch or OpenSearch data source or index opens an editor for SQL on the indexes, **Export…** reads all rows of the query and exports them like a table, the wizard tells that vectors go through **Import Vectors into Database**.
7. Right-click a connected data source → **Disconnect** when you are done, its table tabs close with it. **Exit** sits at the right end of the toolbar. **Help → About SqlJam** shows the version, the home page, the repository and the author, and the GitHub icon at the bottom right opens the repository.
Three tutorial videos of about 2 minutes each walk through SqlJam:
@@ -559,6 +560,7 @@ Environment: Apple M2 Max, 32 GB, JDK 17. The databases run in Docker on a serve
| Can I copy a table inside the same database? | Yes. Choose the same data source and schema as the target and a table name such as `{table}_copy` |
| How are LOBs stored in Parquet? | Inside the Parquet columns (strings and binaries), no extra LOB files |
| How exact is CSV? | Exact. NULL is an empty field, an empty string is `""`, binaries are escaped, and every column is read back with its type from `manifest.json` |
+| Can I write SQL against Elasticsearch or OpenSearch? | Yes, to read. **SQL Query** on the data source or an index runs their SQL (`SELECT`, `SHOW`, `DESCRIBE`), the first rows are shown and **Export…** sends all rows to a package or a database as a table. Objects and arrays become JSON text. Vectors keep their type only through **Import Vectors into Database** |
| How exact is Excel? | Exact as well. A cell holds 15 digits and milliseconds, so longer numbers and timestamps with microseconds are written as text, and every column is read back with its type from `manifest.json` |
| Can I import an Excel file without `manifest.json`? | Yes. **Import Parquet, CSV or Excel Files**, add the `.xlsx` file and choose a sheet. Its first row names the columns, number, date and boolean cells keep their types, formulas give their computed values. Older workbooks (`.xls`) are saved as `.xlsx` first |
| How are rows matched when they are updated or skipped? | By the primary key, or by the columns chosen in **Key Columns**. Choose the columns of a unique index of the target table: MySQL and MariaDB match rows by their unique indexes, PostgreSQL, SQLite and DuckDB require such an index. A table without primary key and chosen columns is inserted |
diff --git a/docs/blogger/sqljam-en.md b/docs/blogger/sqljam-en.md
index f691ef8..f7df33b 100644
--- a/docs/blogger/sqljam-en.md
+++ b/docs/blogger/sqljam-en.md
@@ -42,6 +42,7 @@ SqlJam reads **one metadata tree** and generates SQL with a **dialect chosen by
| Custom and modern types | PostgreSQL enums and domains, unions, maps, tuples and variants |
| Embeddings move with their search | Vectors of pgvector, MySQL, MariaDB, Oracle, SQL Server, Db2, DuckDB and ClickHouse keep their dimensions, vector indexes keep their distances and options |
| Embeddings live in a vector database | Milvus, Qdrant, Weaviate, Pinecone, Elasticsearch, OpenSearch and Chroma sit in the tree as **vector databases**: browse their databases, collections, partitions, tenants and namespaces, page through the records, then import collections straight into a database with vectors: ids, vectors, a column of each field and the whole payload as JSON |
+| Rows of an Elasticsearch index for a table | **SQL Query** on Elasticsearch or OpenSearch runs SQL on the indexes, the rows of a query are exported like a table into packages or any database. Vectors with their indexes take **Import Vectors into Database** |
| Database behind a bastion host | **SSH tunnel** per data source with a password or a private key, host keys trusted on first use, a broken tunnel opens again by itself |
| Which server, how healthy? | **Info** shows the overview and the health of a data source or a vector database, and a **Dashboard** of live charts: sessions, transactions, rows, cache, locks, network, CPU and memory, collections and records of vector databases |
| Long values, rows for a ticket | One line per cell, a double click shows the whole value, **Copy Rows As** CSV, TSV, JSON or Markdown |
@@ -78,13 +79,13 @@ SqlJam opens its main window like DBeaver and DataGrip, where it was closed, wit
Right-click a data source to **Connect**, and once it is connected the same menu offers **Disconnect**, which also closes its table tabs. When an import or export needs a target data source, the **+** button next to it creates one on the spot. **Exit** sits at the right end of the toolbar. **Help → About SqlJam** shows the version, the home page, the repository and how to reach the author, and the GitHub icon at the bottom right opens the repository.
-**SQL Query** on the toolbar opens an editor for the selected data source. **Ctrl+Enter** (**⌘+Enter** on macOS) runs the statement at the caret, **Ctrl+Shift+Enter** runs them all, and **Export…** sends all rows of the query to SQL, Parquet, CSV, Excel or another database:
+**SQL Query** on the toolbar opens an editor for the selected data source. **Ctrl+Enter** (**⌘+Enter** on macOS) runs the statement at the caret, **Ctrl+Shift+Enter** runs them all, **Ctrl+Space** or a dot completes the names of tables and columns (**Help → Keyboard Shortcuts** lists every key), and **Export…** sends all rows of the query to SQL, Parquet, CSV, Excel or another database:

A new data source starts with its category: relational, OLAP or vector databases, and the types and fields follow it. **Connect through SSH tunnel** reaches a database behind a bastion host with a password or a private key.
-A vector database is a data source of the **Vector databases** category, with an API key, a user and password or neither. Expand it in the tree to its databases, collections and partitions (tenants of Weaviate, namespaces of Pinecone) and open a collection: its fields, and its records page by page, narrowed by conditions, a native filter or a nearest neighbor search. **Import…** opens the wizard which writes the checked collections into a data source with vectors. Only such data sources are offered as targets.
+A vector database is a data source of the **Vector databases** category, with an API key, a user and password or neither. Expand it in the tree to its databases, collections and partitions (tenants of Weaviate, namespaces of Pinecone) and open a collection: its fields, and its records page by page, narrowed by conditions, a native filter or a nearest neighbor search. **Import…** opens the wizard which writes the checked collections into a data source with vectors. Only such data sources are offered as targets. **SQL Query** on an Elasticsearch or OpenSearch data source or index opens an editor for their read only SQL, and **Export…** sends all rows of a query to a package or a database as a plain table.
Every data table shows one line per cell. A double click or **Shift+Enter** opens the whole value with JSON indented and vectors described, a header sorts the rows of the page, and **Copy Rows As** copies the selected rows as CSV, TSV, JSON or Markdown. **Info** on the toolbar shows the server, the driver, the session and the health of the selected data source.
diff --git a/docs/blogger/sqljam-medium.md b/docs/blogger/sqljam-medium.md
index 32cb23f..16816d0 100644
--- a/docs/blogger/sqljam-medium.md
+++ b/docs/blogger/sqljam-medium.md
@@ -39,6 +39,7 @@ SqlJam reads one metadata tree and generates SQL with a dialect chosen by target
- **Custom and modern types** → PostgreSQL enums and domains, unions, maps, tuples and variants
- **Embeddings move with their search** → vectors of pgvector, MySQL, MariaDB, Oracle, SQL Server, Db2, DuckDB and ClickHouse keep their dimensions, vector indexes keep their distances and options
- **Embeddings live in a vector database** → Milvus, Qdrant, Weaviate, Pinecone, Elasticsearch, OpenSearch and Chroma sit in the tree as vector databases. Browse their databases, collections, partitions, tenants and namespaces, page through the records, then import collections straight into a database with vectors: ids, vectors, a column of each field and the whole payload as JSON
+- **Rows of an Elasticsearch index for a table** → SQL Query on Elasticsearch or OpenSearch runs SQL on the indexes, the rows of a query are exported like a table into packages or any database. Vectors with their indexes take Import Vectors into Database
- **Database behind a bastion host** → an SSH tunnel per data source with a password or a private key, host keys trusted on first use, a broken tunnel opens again by itself
- **Which server, how healthy?** → Info shows the overview and the health of a data source or a vector database, and a Dashboard of live charts: sessions, transactions, rows, cache, locks, network, CPU and memory, collections and records of vector databases
- **Long values, rows for a ticket** → one line per cell, a double click shows the whole value, Copy Rows As CSV, TSV, JSON or Markdown
@@ -76,7 +77,7 @@ Step 4. narrow the rows of a table on the Data tab and export just those rows. R

-Step 5. open SQL Query on the toolbar, run a query with Ctrl+Enter (⌘+Enter on macOS) and press Export… to send all its rows to SQL, Parquet, CSV, Excel or another database:
+Step 5. open SQL Query on the toolbar, run a query with Ctrl+Enter (⌘+Enter on macOS), complete names of tables and columns with Ctrl+Space, and press Export… to send all its rows to SQL, Parquet, CSV, Excel or another database:

@@ -88,7 +89,7 @@ Step 7. load Parquet files of other tools into a table:

-Step 8. Create a data source of the Vector databases category, with an API key, a user and password or neither. Expand it in the tree to its databases, collections and partitions, open a collection to page through its records, narrowed by conditions, a native filter or a nearest neighbor search, and Import… writes the checked collections into a data source with vectors. Only such data sources are offered as targets.
+Step 8. Create a data source of the Vector databases category, with an API key, a user and password or neither. Expand it in the tree to its databases, collections and partitions, open a collection to page through its records, narrowed by conditions, a native filter or a nearest neighbor search, and Import… writes the checked collections into a data source with vectors. Only such data sources are offered as targets. SQL Query on an Elasticsearch or OpenSearch data source or index opens an editor for their read only SQL, and Export… sends all rows of a query to a package or a database as a plain table.

diff --git a/docs/blogger/sqljam-zh.md b/docs/blogger/sqljam-zh.md
index 9699876..316aefe 100644
--- a/docs/blogger/sqljam-zh.md
+++ b/docs/blogger/sqljam-zh.md
@@ -78,13 +78,13 @@ bin/
右键数据源选 **Connect**,连上之后同一个菜单变成 **Disconnect**,断开时它的表页签一起关闭。导入导出选目标数据源时,旁边的 **+** 按钮可以当场新建一个。工具栏最右边是 **Exit**。**Help → About SqlJam** 里有版本、主页、仓库地址和作者联系方式,右下角的 GitHub 图标点一下直接打开仓库。
-工具栏的 **SQL Query** 为选中的数据源打开查询器。**Ctrl+Enter**(macOS 上是 **⌘+Enter**)执行光标所在的语句,**Ctrl+Shift+Enter** 执行全部,**Export…** 把查询的全部结果导出为 SQL、Parquet、CSV、Excel 或导入另一个数据库:
+工具栏的 **SQL Query** 为选中的数据源打开查询器。**Ctrl+Enter**(macOS 上是 **⌘+Enter**)执行光标所在的语句,**Ctrl+Shift+Enter** 执行全部,**Ctrl+Space** 或在表名、别名后输入点号可以补全表名和列名(**Help → Keyboard Shortcuts** 列出全部快捷键),**Export…** 把查询的全部结果导出为 SQL、Parquet、CSV、Excel 或导入另一个数据库:

新建数据源先选类别:关系型、OLAP 或向量数据库,类型和字段随类别变化。勾选 **Connect through SSH tunnel** 可以经跳板机连接数据库,用密码或私钥认证。
-向量数据库是**向量数据库**类别的数据源,按各库的要求填 API key、用户和密码,或者都不填。在树中展开到数据库、集合和分区(Weaviate 的租户、Pinecone 的命名空间),打开集合就能看到字段和分页的记录,可以按条件、原生过滤或最近邻搜索筛选。**Import…** 打开导入向导,把勾选的集合写进支持向量的数据源。目标列表只显示支持向量的数据源。
+向量数据库是**向量数据库**类别的数据源,按各库的要求填 API key、用户和密码,或者都不填。在树中展开到数据库、集合和分区(Weaviate 的租户、Pinecone 的命名空间),打开集合就能看到字段和分页的记录,可以按条件、原生过滤或最近邻搜索筛选。**Import…** 打开导入向导,把勾选的集合写进支持向量的数据源。目标列表只显示支持向量的数据源。Elasticsearch 和 OpenSearch 还可以在数据源或索引上打开 **SQL Query**,用它们只读的 SQL 查询索引,**Export…** 把查询的全部结果当作普通表导出到导出包或任何数据库。向量连同向量索引要走 **Import Vectors into Database**。
所有数据表格每格只显示一行,双击或 **Shift+Enter** 查看完整内容(JSON 自动缩进,向量显示维度),点表头对本页排序,**Copy Rows As** 把选中的行复制为 CSV、TSV、JSON 或 Markdown。工具栏的 **Info** 显示所选数据源的服务器、驱动、会话和健康状况。
@@ -354,4 +354,4 @@ schtasks /Create /TN "SqlJam sync" /SC MINUTE /MO 15 /TR "C:\SqlJam\sqljam.bat s
9. Parquet、CSV、Excel 导出包与外部文件加载,DuckDB、ClickHouse 作为 OLAP 数据源,导入默认一个事务、出错整体回滚,支持按主键更新或插入。
10. SQL Query 查询器的任意查询结果都能走同样的导出出口,来自表的列保留原类型。
11. 表数据可查询,只导出查询结果,也能在同一 schema 内复制表。
-12. Milvus、Qdrant、Weaviate、Pinecone、Elasticsearch、OpenSearch、Chroma 的集合直接导入支持向量的数据库,导入前可按条件、原生过滤或最近邻搜索预览。
+12. Milvus、Qdrant、Weaviate、Pinecone、Elasticsearch、OpenSearch、Chroma 的集合直接导入支持向量的数据库,导入前可按条件、原生过滤或最近邻搜索预览。Elasticsearch、OpenSearch 的索引还能用 SQL 查询,结果按普通表导出。
diff --git a/docs/index.html b/docs/index.html
index bb90a48..9859b17 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -244,7 +244,7 @@
Everything a table needs on the other side
Query & export A highlighted SQL Query editor or the data viewer shapes the rows, then every exit exports all of them.
Copies in place Copy tables inside the same schema with names like {table}_copy.
Vectors & embeddings pgvector, MySQL, MariaDB, Oracle, SQL Server, Db2, DuckDB and ClickHouse vectors keep their dimensions, HNSW and IVF indexes keep their distances.
- From vector databases Milvus, Qdrant, Weaviate, Pinecone, Elasticsearch, OpenSearch and Chroma in the tree: databases, collections, partitions and tenants, records page by page, imported into tables of ids, vectors, fields and the payload as JSON.
+ From vector databases Milvus, Qdrant, Weaviate, Pinecone, Elasticsearch, OpenSearch and Chroma in the tree: databases, collections, partitions and tenants, records page by page, imported into tables of ids, vectors, fields and the payload as JSON. SQL on Elasticsearch and OpenSearch exports the rows of indexes like tables.
Column mapping Rename a column, give it a type of the target or leave it out, keys and indexes follow, other columns stay as they are.
SSH tunnels Reach a database behind a bastion host with a password or a private key, host keys trusted on first use.
Info, health & dashboard Server, driver, session and the health of a data source or a vector database, and live charts of sessions, transactions, rows, cache, locks, CPU and memory.
@@ -362,7 +362,7 @@ Ways to move a table
-
Add a vector database as a data source, expand it in the tree to its databases, collections and partitions, page through the records of conditions, a native filter or a nearest neighbor search, and import the collections into a data source with vectors. Only such data sources are offered as targets.
+
Add a vector database as a data source, expand it in the tree to its databases, collections and partitions, page through the records of conditions, a native filter or a nearest neighbor search, and import the collections into a data source with vectors. Only such data sources are offered as targets. On Elasticsearch and OpenSearch, SQL Query reads the indexes and exports the rows of a query like a table.
configuration.addCollection("docs" , "docs" );
configuration.setQuery(VdbQuery.all().where("lang = 'en'" ));
new VdbExporter(client, dataSource, configuration).export(); // id, embedding vector(1024), payload jsonb
diff --git a/src/main/java/com/github/sqljam/face/vdb/VdbDataSourceExtension.java b/src/main/java/com/github/sqljam/face/vdb/VdbDataSourceExtension.java
index 9b4c73a..9061a0b 100644
--- a/src/main/java/com/github/sqljam/face/vdb/VdbDataSourceExtension.java
+++ b/src/main/java/com/github/sqljam/face/vdb/VdbDataSourceExtension.java
@@ -93,6 +93,20 @@ public void open(Window owner, AppContext context) {
new VdbImportDialog(owner, context, store, profile).showAndImport();
}
+ /**
+ * Elasticsearch and OpenSearch run SQL on their indexes, the rows are exported like the rows of tables
+ */
+ @Override
+ public boolean isSqlSupported() {
+ return profile.getType() == VdbType.ELASTICSEARCH || profile.getType() == VdbType.OPENSEARCH;
+ }
+
+ @Override
+ public Tab openSqlTab(AppContext context, int number, SourceItem item, QueryExport export) {
+ return isSqlSupported() ? new VdbSqlTab(context, profile, number, item != null ? item.getName() : null,
+ export) : null;
+ }
+
/**
* Levels of the source: databases (Milvus, Chroma), collections, then their partitions (partitions of
* Milvus, tenants of Weaviate, namespaces of Pinecone)
diff --git a/src/main/java/com/github/sqljam/face/vdb/VdbSqlStaging.java b/src/main/java/com/github/sqljam/face/vdb/VdbSqlStaging.java
new file mode 100644
index 0000000..f2b7e0c
--- /dev/null
+++ b/src/main/java/com/github/sqljam/face/vdb/VdbSqlStaging.java
@@ -0,0 +1,248 @@
+/*
+ * Copyright 2023-2026 Fred Feng
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.sqljam.face.vdb;
+
+import java.io.File;
+import java.math.BigDecimal;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongConsumer;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.StringUtils;
+import com.github.sqljam.impexp.ExportCancelledException;
+import com.github.sqljam.vdb.VdbClient;
+import com.github.sqljam.vdb.VdbSqlResult;
+
+/**
+ * @Description: VdbSqlStaging reads all rows of a SQL query of Elasticsearch or OpenSearch, page by page by its
+ * cursor, into a table of a DuckDB file, which the export wizard reads like any data source: rows of
+ * indexes are exported like the rows of tables into packages and databases. The columns get the
+ * types of their values (numbers, booleans, timestamps), others are text, arrays and objects (and
+ * vectors) JSON text. The file is deleted when SqlJam ends.
+ * @Author: Fred Feng
+ * @Date: 07/11/2026
+ * @Version 1.0.0
+ */
+final class VdbSqlStaging {
+
+ /**
+ * Rows of a page read from the server
+ */
+ static final int PAGE_SIZE = 1000;
+ private static final Pattern FROM = Pattern.compile("(?is)\\bFROM\\s+(\"([^\"]+)\"|`([^`]+)`|([^\\s,;()]+))");
+
+ private VdbSqlStaging() {
+ }
+
+ /**
+ * Rows of a query in a table of a DuckDB file
+ */
+ static final class Staged {
+
+ final File file;
+ final String table;
+ final long rows;
+
+ Staged(File file, String table, long rows) {
+ this.file = file;
+ this.table = table;
+ this.rows = rows;
+ }
+ }
+
+ /**
+ * Reads the rows of the query into the table of a new DuckDB file
+ *
+ * @param progress receives the rows read so far
+ */
+ static Staged stage(VdbClient client, String sql, String table, AtomicBoolean cancelled, LongConsumer progress)
+ throws Exception {
+ File directory = new File(FileUtils.getTempDirectory(), ".sqljam-queries");
+ FileUtils.forceMkdir(directory);
+ File file = new File(directory, UUID.randomUUID() + ".duckdb");
+ file.deleteOnExit();
+ new File(file.getPath() + ".wal").deleteOnExit();
+ VdbSqlResult page = client.querySql(sql, PAGE_SIZE);
+ List
columns = uniqueNames(page.getColumns());
+ long rows = 0;
+ try (Connection connection = DriverManager.getConnection("jdbc:duckdb:" + file.getAbsolutePath())) {
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("CREATE TABLE \"raw\" (" + columns.stream().map(column -> quote(column[0])
+ + " VARCHAR").collect(Collectors.joining(", ")) + ")");
+ }
+ String insert = "INSERT INTO \"raw\" VALUES (" + columns.stream().map(column -> "?")
+ .collect(Collectors.joining(", ")) + ")";
+ try (PreparedStatement statement = connection.prepareStatement(insert)) {
+ while (true) {
+ for (List row : page.getRows()) {
+ for (int i = 0; i < columns.size(); i++) {
+ statement.setString(i + 1, text(i < row.size() ? row.get(i) : null));
+ }
+ statement.addBatch();
+ }
+ statement.executeBatch();
+ rows += page.getRows().size();
+ progress.accept(rows);
+ if (!page.hasMore()) {
+ break;
+ }
+ if (cancelled.get()) {
+ client.closeSqlCursor(page.getCursor());
+ throw new ExportCancelledException();
+ }
+ page = client.nextSqlPage(page.getCursor());
+ }
+ }
+ try (Statement statement = connection.createStatement()) {
+ statement.execute("CREATE TABLE " + quote(table) + " AS SELECT " + columns.stream()
+ .map(column -> cast(column[0], column[1])).collect(Collectors.joining(", "))
+ + " FROM \"raw\"");
+ statement.execute("DROP TABLE \"raw\"");
+ }
+ } catch (Exception e) {
+ FileUtils.deleteQuietly(file);
+ FileUtils.deleteQuietly(new File(file.getPath() + ".wal"));
+ throw e;
+ }
+ return new Staged(file, table, rows);
+ }
+
+ /**
+ * Columns with names which are not empty and not repeated, a repeated name is numbered
+ */
+ static List uniqueNames(List columns) {
+ List named = new ArrayList<>();
+ Set names = new HashSet<>();
+ for (String[] column : columns) {
+ String base = StringUtils.defaultIfBlank(column[0], "column" + (named.size() + 1));
+ String name = base;
+ for (int i = 2; !names.add(name.toLowerCase(Locale.ENGLISH)); i++) {
+ name = base + "_" + i;
+ }
+ named.add(new String[]{name, column[1]});
+ }
+ return named;
+ }
+
+ /**
+ * The value of a column of the type of the server, text which is not of the type is NULL
+ */
+ static String cast(String column, String serverType) {
+ String type = duckdbType(serverType);
+ String quoted = quote(column);
+ if ("TIMESTAMP".equals(type)) {
+ // 2024-01-02T03:04:05.123Z of Elasticsearch and 2024-01-02 03:04:05 of OpenSearch
+ return String.format("TRY_CAST(replace(regexp_replace(%1$s, 'Z$', ''), 'T', ' ') AS TIMESTAMP) AS %1$s",
+ quoted);
+ }
+ return "VARCHAR".equals(type) ? quoted : String.format("TRY_CAST(%1$s AS %2$s) AS %1$s", quoted, type);
+ }
+
+ /**
+ * DuckDB type of a type of Elasticsearch or OpenSearch, text for strings, objects, arrays and others
+ */
+ static String duckdbType(String serverType) {
+ switch (StringUtils.defaultString(serverType).toLowerCase(Locale.ENGLISH)) {
+ case "boolean":
+ return "BOOLEAN";
+ case "byte":
+ return "TINYINT";
+ case "short":
+ return "SMALLINT";
+ case "integer":
+ return "INTEGER";
+ case "long":
+ return "BIGINT";
+ case "unsigned_long":
+ return "DECIMAL(20, 0)";
+ case "float":
+ case "half_float":
+ return "FLOAT";
+ case "double":
+ case "scaled_float":
+ return "DOUBLE";
+ case "datetime":
+ case "date":
+ case "date_nanos":
+ case "timestamp":
+ return "TIMESTAMP";
+ default:
+ return "VARCHAR";
+ }
+ }
+
+ static String text(Object value) {
+ if (value == null) {
+ return null;
+ }
+ return value instanceof BigDecimal ? ((BigDecimal) value).toPlainString() : value.toString();
+ }
+
+ /**
+ * Columns which hold vectors: types of vectors, or values which are arrays of numbers
+ */
+ static List vectorColumns(List columns, List> rows) {
+ List vectors = new ArrayList<>();
+ for (int i = 0; i < columns.size(); i++) {
+ String type = StringUtils.defaultString(columns.get(i)[1]).toLowerCase(Locale.ENGLISH);
+ boolean vector = type.contains("vector");
+ for (List row : rows) {
+ if (vector || i >= row.size() || row.get(i) == null) {
+ continue;
+ }
+ vector = row.get(i).toString().matches("(?s)\\[\\s*-?[0-9][^\\[\\]{}\"]*\\]");
+ break;
+ }
+ if (vector) {
+ vectors.add(columns.get(i)[0]);
+ }
+ }
+ return vectors;
+ }
+
+ /**
+ * Name of the table of a query: the index after FROM made an identifier (logs-2024.* is logs_2024__), query
+ * if there is none
+ */
+ static String tableName(String sql) {
+ Matcher matcher = FROM.matcher(StringUtils.defaultString(sql));
+ if (!matcher.find()) {
+ return "query";
+ }
+ String index = matcher.group(2) != null ? matcher.group(2) : matcher.group(3) != null ? matcher.group(3)
+ : matcher.group(4);
+ String name = index.replaceAll("[^\\p{L}\\p{N}_]", "_");
+ return name.isEmpty() || Character.isDigit(name.charAt(0)) ? "t_" + name : name;
+ }
+
+ private static String quote(String name) {
+ return "\"" + name.replace("\"", "\"\"") + "\"";
+ }
+}
diff --git a/src/main/java/com/github/sqljam/face/vdb/VdbSqlTab.java b/src/main/java/com/github/sqljam/face/vdb/VdbSqlTab.java
new file mode 100644
index 0000000..6d23ed9
--- /dev/null
+++ b/src/main/java/com/github/sqljam/face/vdb/VdbSqlTab.java
@@ -0,0 +1,410 @@
+/*
+ * Copyright 2023-2026 Fred Feng
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.sqljam.face.vdb;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+
+import org.apache.commons.lang3.StringUtils;
+import com.github.sqljam.face.model.ConnectionProfile;
+import com.github.sqljam.face.service.SqlStatements;
+import com.github.sqljam.face.view.AppContext;
+import com.github.sqljam.face.view.DataPane;
+import com.github.sqljam.face.view.DataSourceExtension;
+import com.github.sqljam.face.view.DbNode;
+import com.github.sqljam.face.view.Dialogs;
+import com.github.sqljam.face.view.Icons;
+import com.github.sqljam.face.view.Messages;
+import com.github.sqljam.face.view.SqlCompletion;
+import com.github.sqljam.face.view.SqlEditor;
+import com.github.sqljam.face.view.TableColumns;
+import com.github.sqljam.face.view.TaskRunner;
+import com.github.sqljam.face.view.ValueCell;
+import com.github.sqljam.impexp.DbType;
+import com.github.sqljam.impexp.ExportCancelledException;
+import com.github.sqljam.vdb.VdbClient;
+import com.github.sqljam.vdb.VdbField;
+import com.github.sqljam.vdb.VdbSqlResult;
+import javafx.beans.property.ReadOnlyObjectWrapper;
+import javafx.collections.ObservableList;
+import javafx.geometry.Orientation;
+import javafx.geometry.Pos;
+import javafx.scene.control.Button;
+import javafx.scene.control.Label;
+import javafx.scene.control.ListCell;
+import javafx.scene.control.ListView;
+import javafx.scene.control.SplitPane;
+import javafx.scene.control.Tab;
+import javafx.scene.control.TabPane;
+import javafx.scene.control.TableColumn;
+import javafx.scene.control.TableView;
+import javafx.scene.control.ToolBar;
+import javafx.scene.control.Tooltip;
+import javafx.scene.input.KeyCode;
+import javafx.scene.input.KeyCodeCombination;
+import javafx.scene.input.KeyCombination;
+import javafx.scene.input.KeyEvent;
+import javafx.scene.layout.BorderPane;
+import javafx.scene.layout.HBox;
+import javafx.scene.layout.Priority;
+import javafx.scene.layout.Region;
+
+/**
+ * @Description: VdbSqlTab runs SQL on the indexes of Elasticsearch or OpenSearch and exports the rows of a query
+ * like the rows of a table: Ctrl+Enter runs the selected text or the statement at the caret, the
+ * first rows are shown, Export reads all rows by the cursor of the query into a DuckDB file and opens
+ * the export wizard on it. The SQL of these servers reads only. Vectors with their indexes are
+ * imported by Import Vectors into Database, the rows of a query carry vectors as JSON text.
+ * Ctrl+Space completes the names of indexes and their fields.
+ * @Author: Fred Feng
+ * @Date: 07/11/2026
+ * @Version 1.0.0
+ */
+public class VdbSqlTab extends Tab {
+
+ /**
+ * Rows of a query shown in the editor, an export reads all of them
+ */
+ static final int MAX_ROWS = 500;
+ private static final KeyCombination RUN = new KeyCodeCombination(KeyCode.ENTER, KeyCombination.SHORTCUT_DOWN);
+ private static final KeyCombination RUN_ALL = new KeyCodeCombination(KeyCode.ENTER,
+ KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN);
+
+ private final VdbProfile profile;
+ private final DataSourceExtension.QueryExport export;
+ private final SqlEditor editor = new SqlEditor();
+ private final TableView> resultTable = new TableView<>();
+ private final ObservableList> resultRows = TableColumns.sortedRows(resultTable);
+ private final ListView messageList = new ListView<>();
+ private final TabPane resultTabs = new TabPane();
+ private final Tab resultTab = new Tab(Messages.get("sql.result"));
+ private final Tab messageTab = new Tab(Messages.get("sql.messages"));
+ private final Button runButton = new Button(Messages.get("sql.run"), Icons.of(Icons.START));
+ private final Button runAllButton = new Button(Messages.get("sql.runAll"), Icons.of(Icons.START));
+ private final Button stopButton = new Button(Messages.get("sql.stop"), Icons.of(Icons.CANCEL));
+ private final Button exportButton = new Button(Messages.get("sql.export"), Icons.of(Icons.EXPORT));
+ private final Label statusLabel = new Label();
+ private final AtomicBoolean cancelled = new AtomicBoolean();
+ private VdbClient client;
+ private String lastQuery;
+ private List lastColumns = new ArrayList<>();
+ private List> lastRows = new ArrayList<>();
+ private boolean busy;
+ private final SqlCompletion completion;
+
+ public VdbSqlTab(AppContext context, VdbProfile profile, int number, String index,
+ DataSourceExtension.QueryExport export) {
+ this.profile = profile;
+ this.export = export;
+ setText(Messages.format("sql.tabTitle", number, profile.getName()));
+ setGraphic(Icons.of(Icons.SQL));
+ setTooltip(new Tooltip(Messages.get("vdb.sql.hint")));
+
+ runButton.setId("sqlRunButton");
+ runAllButton.setId("sqlRunAllButton");
+ stopButton.setId("sqlStopButton");
+ exportButton.setId("sqlExportButton");
+ statusLabel.setId("sqlStatusLabel");
+ resultTable.setId("sqlResultTable");
+ messageList.setId("sqlMessageList");
+ TableColumns.fill(resultTable);
+ runButton.setTooltip(new Tooltip(Messages.get("sql.run.tooltip")));
+ runAllButton.setTooltip(new Tooltip(Messages.get("sql.runAll.tooltip")));
+ exportButton.setTooltip(new Tooltip(Messages.get("vdb.sql.export.tooltip")));
+ runButton.setOnAction(event -> run(false));
+ runAllButton.setOnAction(event -> run(true));
+ stopButton.setOnAction(event -> stop());
+ exportButton.setOnAction(event -> export());
+ stopButton.setDisable(true);
+ exportButton.setDisable(true);
+ editor.getCodeArea().addEventFilter(KeyEvent.KEY_PRESSED, event -> {
+ if (RUN_ALL.match(event)) {
+ run(true);
+ event.consume();
+ } else if (RUN.match(event)) {
+ run(false);
+ event.consume();
+ }
+ });
+ if (StringUtils.isNotBlank(index)) {
+ editor.setText("SELECT * FROM \"" + index.replace("\"", "\"\"") + "\"");
+ }
+ // Indexes and their fields
+ completion = SqlCompletion.attach(editor, new SqlCompletion.Source() {
+ @Override
+ public List tables() {
+ return getClient().getCollections();
+ }
+
+ @Override
+ public List columns(String table) {
+ return getClient().describe(table).getFields().stream().map(VdbField::getName).collect(Collectors
+ .toList());
+ }
+ });
+
+ // Rows of indexes are exported like tables, vectors take the other way
+ Label hint = new Label(Messages.get("vdb.sql.hint"));
+ hint.setId("vdbSqlHint");
+ hint.getStyleClass().add("muted");
+ Region spacer = new Region();
+ HBox.setHgrow(spacer, Priority.ALWAYS);
+ ToolBar toolBar = new ToolBar(runButton, runAllButton, stopButton, exportButton, spacer, hint);
+
+ resultTable.setPlaceholder(new Label(Messages.get("sql.noResult")));
+ resultTab.setContent(resultTable);
+ resultTab.setClosable(false);
+ messageList.setCellFactory(view -> new ListCell<>() {
+ @Override
+ protected void updateItem(String[] item, boolean empty) {
+ super.updateItem(item, empty);
+ getStyleClass().remove("log-error");
+ setText(empty || item == null ? null : item[0]);
+ if (!empty && item != null && item.length > 1) {
+ getStyleClass().add("log-error");
+ }
+ }
+ });
+ messageList.getStyleClass().add("log-list");
+ messageTab.setContent(messageList);
+ messageTab.setClosable(false);
+ resultTabs.getTabs().addAll(resultTab, messageTab);
+ BorderPane resultPane = new BorderPane(resultTabs);
+ HBox statusBar = new HBox(statusLabel);
+ statusBar.setAlignment(Pos.CENTER_LEFT);
+ statusBar.getStyleClass().add("sql-status");
+ resultPane.setBottom(statusBar);
+ SplitPane splitPane = new SplitPane(editor.getNode(), resultPane);
+ splitPane.setOrientation(Orientation.VERTICAL);
+ splitPane.setDividerPositions(0.45);
+ BorderPane root = new BorderPane(splitPane);
+ root.setTop(toolBar);
+ root.getStyleClass().add("sql-tab");
+ setContent(root);
+ setOnClosed(event -> close());
+ }
+
+ /**
+ * Runs the selected text, the statement at the caret or all statements, the rows of the last query are shown
+ */
+ void run(boolean all) {
+ if (busy) {
+ return;
+ }
+ String selected = editor.getSelectedText();
+ List statements;
+ if (all) {
+ statements = texts(SqlStatements.split(editor.getText()));
+ } else if (StringUtils.isNotBlank(selected)) {
+ statements = texts(SqlStatements.split(selected));
+ } else {
+ SqlStatements.Statement statement = SqlStatements.at(editor.getText(), editor.getCaretPosition());
+ statements = statement != null ? List.of(statement.getText()) : List.of();
+ }
+ if (statements.isEmpty()) {
+ statusLabel.setText(Messages.get("sql.nothing"));
+ return;
+ }
+ setBusy(true);
+ cancelled.set(false);
+ statusLabel.setText(Messages.get("sql.running"));
+ List results = new ArrayList<>();
+ TaskRunner.run(() -> {
+ for (String sql : statements) {
+ if (cancelled.get()) {
+ break;
+ }
+ long start = System.currentTimeMillis();
+ try {
+ VdbSqlResult result = getClient().querySql(sql, MAX_ROWS);
+ if (result.hasMore()) {
+ // The first rows are shown, an export reads all of them again
+ getClient().closeSqlCursor(result.getCursor());
+ }
+ results.add(new Object[]{sql, result, System.currentTimeMillis() - start});
+ } catch (RuntimeException e) {
+ results.add(new Object[]{sql, e, System.currentTimeMillis() - start});
+ break;
+ }
+ }
+ return results;
+ }, this::showResults, e -> {
+ addMessage(StringUtils.defaultIfBlank(e.getMessage(), e.getClass().getName()), true);
+ statusLabel.setText(Messages.get("sql.failed"));
+ resultTabs.getSelectionModel().select(messageTab);
+ setBusy(false);
+ });
+ }
+
+ private static List texts(List statements) {
+ return statements.stream().map(SqlStatements.Statement::getText).collect(Collectors.toList());
+ }
+
+ private void showResults(List results) {
+ Object[] shown = null;
+ boolean failed = false;
+ for (Object[] result : results) {
+ String sql = (String) result[0];
+ if (result[1] instanceof Throwable) {
+ addMessage(Messages.format("sql.error", abbreviate(sql), ((Throwable) result[1]).getMessage()), true);
+ failed = true;
+ } else {
+ VdbSqlResult rows = (VdbSqlResult) result[1];
+ addMessage(Messages.format(rows.hasMore() ? "sql.rowsFirst" : "sql.rows", rows.getRows().size(),
+ result[2], abbreviate(sql)), false);
+ shown = result;
+ }
+ }
+ if (shown != null) {
+ VdbSqlResult result = (VdbSqlResult) shown[1];
+ showRows(result);
+ lastQuery = (String) shown[0];
+ lastColumns = result.getColumns();
+ lastRows = result.getRows();
+ statusLabel.setText(Messages.format(result.hasMore() ? "sql.status.first" : "sql.status.rows",
+ result.getRows().size()));
+ }
+ if (failed) {
+ resultTabs.getSelectionModel().select(messageTab);
+ statusLabel.setText(cancelled.get() ? Messages.get("sql.cancelled") : Messages.get("sql.failed"));
+ } else if (shown != null) {
+ resultTabs.getSelectionModel().select(resultTab);
+ }
+ setBusy(false);
+ }
+
+ private void showRows(VdbSqlResult result) {
+ resultTable.getColumns().clear();
+ List> rows = new ArrayList<>();
+ for (List row : result.getRows()) {
+ rows.add(row.stream().map(VdbSqlStaging::text).collect(Collectors.toList()));
+ }
+ List columns = result.getColumns();
+ for (int i = 0; i < columns.size(); i++) {
+ final int index = i;
+ TableColumn, String> column = new TableColumn<>(columns.get(i)[0]);
+ column.setCellValueFactory(features -> new ReadOnlyObjectWrapper<>(index < features.getValue().size()
+ ? features.getValue().get(index) : null));
+ column.setCellFactory(tableColumn -> new ValueCell());
+ column.setPrefWidth(DataPane.getColumnWidth(columns.get(i)[0], rows, index));
+ column.setComparator(ValueCell.COMPARATOR);
+ resultTable.getColumns().add(column);
+ }
+ resultRows.setAll(rows);
+ resultTable.setPlaceholder(new Label(Messages.get("data.empty")));
+ }
+
+ /**
+ * Reads all rows of the last query into a DuckDB file and opens the export wizard on them, a query with
+ * vectors tells that they are exported as text
+ */
+ void export() {
+ if (lastQuery == null || export == null || busy) {
+ return;
+ }
+ List vectors = VdbSqlStaging.vectorColumns(lastColumns, lastRows);
+ String note = vectors.isEmpty() ? Messages.get("vdb.sql.note") : Messages.format("vdb.sql.vectorNote",
+ String.join(", ", vectors));
+ if (!vectors.isEmpty() && !Dialogs.confirm(getTabPane() != null ? getTabPane().getScene().getWindow()
+ : null, Messages.get("sql.export"), note)) {
+ return;
+ }
+ String sql = lastQuery;
+ String table = VdbSqlStaging.tableName(sql);
+ setBusy(true);
+ cancelled.set(false);
+ TaskRunner.run(() -> VdbSqlStaging.stage(getClient(), sql, table, cancelled, rows -> javafx.application.Platform.runLater(() ->
+ statusLabel.setText(Messages.format("vdb.sql.reading", rows)))), staged -> {
+ setBusy(false);
+ statusLabel.setText(Messages.format("sql.status.rows", staged.rows));
+ ConnectionProfile results = new ConnectionProfile();
+ results.setName(Messages.format("vdb.sql.results", profile.getName()));
+ results.setDbType(DbType.DUCKDB);
+ results.setDatabase(staged.file.getAbsolutePath());
+ export.export(DbNode.connection(results), "SELECT * FROM \"" + staged.table.replace("\"", "\"\"")
+ + "\"", staged.table, note);
+ }, e -> {
+ setBusy(false);
+ boolean stopped = e instanceof ExportCancelledException;
+ statusLabel.setText(stopped ? Messages.get("sql.cancelled") : Messages.get("sql.failed"));
+ if (!stopped) {
+ addMessage(Messages.format("sql.error", abbreviate(sql), e.getMessage()), true);
+ resultTabs.getSelectionModel().select(messageTab);
+ }
+ });
+ }
+
+ private synchronized VdbClient getClient() {
+ if (client == null) {
+ client = profile.getType().createClient(profile.toSource());
+ }
+ return client;
+ }
+
+ private void addMessage(String message, boolean error) {
+ messageList.getItems().add(error ? new String[]{message, "error"} : new String[]{message});
+ messageList.scrollTo(messageList.getItems().size() - 1);
+ }
+
+ private static String abbreviate(String sql) {
+ return StringUtils.abbreviate(sql.replaceAll("\\s+", " "), 120);
+ }
+
+ private void setBusy(boolean busy) {
+ this.busy = busy;
+ runButton.setDisable(busy);
+ runAllButton.setDisable(busy);
+ stopButton.setDisable(!busy);
+ exportButton.setDisable(busy || lastQuery == null);
+ }
+
+ /**
+ * Stops after the page or the statement which is read, the cursor of the query is closed
+ */
+ void stop() {
+ cancelled.set(true);
+ }
+
+ SqlEditor getEditor() {
+ return editor;
+ }
+
+ public SqlCompletion getCompletion() {
+ return completion;
+ }
+
+ String getLastQuery() {
+ return lastQuery;
+ }
+
+ public void close() {
+ stop();
+ VdbClient current;
+ synchronized (this) {
+ current = client;
+ client = null;
+ }
+ if (current != null) {
+ TaskRunner.execute(current::close);
+ }
+ }
+
+ public VdbProfile getProfile() {
+ return profile;
+ }
+}
diff --git a/src/main/java/com/github/sqljam/face/view/ConnectionTree.java b/src/main/java/com/github/sqljam/face/view/ConnectionTree.java
index 644cb2d..10d7791 100644
--- a/src/main/java/com/github/sqljam/face/view/ConnectionTree.java
+++ b/src/main/java/com/github/sqljam/face/view/ConnectionTree.java
@@ -947,7 +947,14 @@ private ContextMenu createContextMenu(DbNode node) {
MenuItem open = new MenuItem(node.getExtension().getOpenText(), Icons.of(Icons.IMPORT));
open.setId("openSourceMenuItem");
open.setOnAction(event -> node.getSource().open(getScene().getWindow(), context));
- menu.getItems().addAll(open, menuItem("action.refresh", Icons.REFRESH,
+ menu.getItems().add(open);
+ if (node.getSource().isSqlSupported()) {
+ // Rows of indexes are exported like tables, vectors are imported by the main action
+ MenuItem sql = menuItem("action.sqlQuery", Icons.SQL, () -> fire(onSqlQuery, node));
+ sql.setId("sourceSqlMenuItem");
+ menu.getItems().add(sql);
+ }
+ menu.getItems().addAll(menuItem("action.refresh", Icons.REFRESH,
ConnectionTree.this::refreshSelected), menuItem("action.info", Icons.INFO,
() -> fire(onInfo, node)), new SeparatorMenuItem(),
menuItem("action.editConnection", Icons.EDIT, () -> editSource(node)),
@@ -967,6 +974,11 @@ private ContextMenu createContextMenu(DbNode node) {
openItem.setId("openSourceItemMenuItem");
openItem.setOnAction(event -> fire(onOpenSourceItem, node));
menu.getItems().addAll(openItem, importItem);
+ if (node.getSource().isSqlSupported()) {
+ MenuItem sql = menuItem("action.sqlQuery", Icons.SQL, () -> fire(onSqlQuery, node));
+ sql.setId("sourceItemSqlMenuItem");
+ menu.getItems().add(sql);
+ }
}
break;
default:
diff --git a/src/main/java/com/github/sqljam/face/view/DataSourceExtension.java b/src/main/java/com/github/sqljam/face/view/DataSourceExtension.java
index d2ce61f..f9a5e74 100644
--- a/src/main/java/com/github/sqljam/face/view/DataSourceExtension.java
+++ b/src/main/java/com/github/sqljam/face/view/DataSourceExtension.java
@@ -63,6 +63,26 @@ interface Source {
*/
void open(Window owner, AppContext context);
+ /**
+ * Whether the source runs SQL queries whose rows are exported like the rows of a table, e.g. the indexes
+ * of Elasticsearch and OpenSearch
+ */
+ default boolean isSqlSupported() {
+ return false;
+ }
+
+ /**
+ * A SQL editor of the source, null for sources which run no SQL
+ *
+ * @param number number of the editor in its title
+ * @param item collection whose rows the editor queries first, null for none
+ * @param export receives the rows of a query to export: a data source holding them, the SQL reading them
+ * and the name of their table
+ */
+ default Tab openSqlTab(AppContext context, int number, SourceItem item, QueryExport export) {
+ return null;
+ }
+
/**
* Metrics of the dashboard of the info of the source, null for sources without
*/
@@ -118,6 +138,19 @@ default boolean authenticate(Window owner, Throwable error) {
/**
* Fields of a source of the kind below its name and type, shown by the data source form
*/
+ /**
+ * Export of the rows of a query of a source: the data source holding the rows, the SQL reading them, the name
+ * of their table in the target and a note of the export
+ */
+ @FunctionalInterface
+ interface QueryExport {
+
+ /**
+ * @param note shown with the query in the export wizard, e.g. that vectors are exported as text
+ */
+ void export(DbNode node, String sql, String tableName, String note);
+ }
+
interface SourceForm {
Node getNode();
diff --git a/src/main/java/com/github/sqljam/face/view/ExportDialog.java b/src/main/java/com/github/sqljam/face/view/ExportDialog.java
index ac1744b..812520f 100644
--- a/src/main/java/com/github/sqljam/face/view/ExportDialog.java
+++ b/src/main/java/com/github/sqljam/face/view/ExportDialog.java
@@ -186,6 +186,10 @@ public class ExportDialog extends Dialog {
private final String freeQuery;
private final DbNode queryNode;
private final TextField queryTableField = new TextField(DEFAULT_QUERY_TABLE);
+ /**
+ * A note of the query, e.g. that its vectors are exported as text
+ */
+ private final Label queryNoteLabel = new Label();
private VBox tablesBox;
private Label tableNamePatternLabel;
private Label mappingColumnsLabel;
@@ -226,6 +230,25 @@ public static ExportDialog forQuery(Window owner, AppContext context, DbNode nod
return new ExportDialog(owner, context, node, null, sql);
}
+ /**
+ * A note shown with the query, e.g. that the rows of an index are exported as a table and its vectors as text
+ */
+ public void setQueryNote(String note) {
+ queryNoteLabel.setText(StringUtils.defaultString(note));
+ boolean shown = freeQuery != null && StringUtils.isNotBlank(note);
+ queryNoteLabel.setVisible(shown);
+ queryNoteLabel.setManaged(shown);
+ }
+
+ /**
+ * Name of the table of the rows of the query in the target, a name which is not an identifier is kept as typed
+ */
+ public void setQueryTableName(String tableName) {
+ if (freeQuery != null && StringUtils.isNotBlank(tableName)) {
+ queryTableField.setText(tableName);
+ }
+ }
+
private ExportDialog(Window owner, AppContext context, DbNode node, TableQuery query, String sql) {
this.context = context;
this.freeQuery = StringUtils.trimToNull(sql);
@@ -743,6 +766,12 @@ private void applyQueryMode() {
GridPane queryGrid = grid();
queryGrid.addRow(0, new Label(Messages.get("export.query.table")), queryTableField);
queryGrid.addRow(1, new Label(Messages.get("export.query.sql")), sqlLabel);
+ queryNoteLabel.setId("queryNoteLabel");
+ queryNoteLabel.getStyleClass().add("status-pending");
+ queryNoteLabel.setWrapText(true);
+ queryNoteLabel.setVisible(false);
+ queryNoteLabel.setManaged(false);
+ queryGrid.add(queryNoteLabel, 1, 2);
tablesBox.getChildren().setAll(queryGrid);
for (Node control : new Node[]{sourceCombo, catalogCombo, schemaCombo}) {
// Shown but not changed, a disabled catalog or schema means none
@@ -768,6 +797,10 @@ private void preselect(DbNode node) {
ConnectionProfile profile = sourceCombo.getItems().stream()
.filter(item -> item.getId().equals(node.getProfile().getId())).findFirst()
.orElse(node.getProfile());
+ if (!sourceCombo.getItems().contains(profile)) {
+ // A data source which is not saved, e.g. the rows of a query of an index fetched into a file
+ sourceCombo.getItems().add(profile);
+ }
String table = node.getTable() != null ? node.getTable().getName() : null;
// Selecting the profile triggers loading, the node path is passed to keep the selection
sourceCombo.setValue(null);
diff --git a/src/main/java/com/github/sqljam/face/view/MainView.java b/src/main/java/com/github/sqljam/face/view/MainView.java
index d5a40ec..52ff780 100644
--- a/src/main/java/com/github/sqljam/face/view/MainView.java
+++ b/src/main/java/com/github/sqljam/face/view/MainView.java
@@ -405,7 +405,8 @@ private Menu createHelpMenu() {
selectConnection(profile);
}));
restoreExample.setId("restoreExampleMenuItem");
- MenuItem shortcuts = item("help.shortcuts", null, null, this::showShortcuts);
+ MenuItem shortcuts = item("help.shortcuts", null, shortcut(KeyCode.L, KeyCombination.SHIFT_DOWN),
+ this::showShortcuts);
MenuItem about = item("action.about", Icons.INFO, null, () -> Dialogs.showAbout(getWindow(),
context::openDocument));
return new Menu(Messages.get("menu.help"), null, videos, docs, guide, issue, new SeparatorMenuItem(),
@@ -454,6 +455,18 @@ List getShortcuts() {
for (Menu menu : menuBar.getMenus()) {
collectShortcuts(menu, rows);
}
+ // Keys of the editors and tables, which have no menu item
+ String sql = Messages.get("shortcuts.sqlEditor") + " > ";
+ rows.add(new String[]{sql + Messages.get("sql.run"), SqlTab.RUN.getDisplayText()});
+ rows.add(new String[]{sql + Messages.get("sql.runAll"), SqlTab.RUN_ALL.getDisplayText()});
+ rows.add(new String[]{sql + Messages.get("shortcuts.complete"), SqlCompletion.COMPLETE.getDisplayText()});
+ rows.add(new String[]{sql + Messages.get("shortcuts.columns"), "."});
+ String table = Messages.get("shortcuts.dataTable") + " > ";
+ rows.add(new String[]{table + Messages.get("shortcuts.copy"), TableCopy.COPY.getDisplayText()});
+ rows.add(new String[]{table + Messages.get("shortcuts.copyHeaders"), TableCopy.COPY_WITH_HEADERS
+ .getDisplayText()});
+ rows.add(new String[]{table + Messages.get("shortcuts.value"), new KeyCodeCombination(KeyCode.ENTER,
+ KeyCombination.SHIFT_DOWN).getDisplayText()});
return rows;
}
@@ -719,6 +732,10 @@ void closeTabs(List tabs) {
* is selected
*/
void openSqlTab(DbNode node) {
+ if (node != null && node.getSource() != null && node.getSource().isSqlSupported()) {
+ openSourceSqlTab(node);
+ return;
+ }
DbNode target = node;
if (target == null || target.getProfile() == null) {
if (context.getProfileRegistry().getProfiles().isEmpty()) {
@@ -735,6 +752,32 @@ void openSqlTab(DbNode node) {
tabPane.getSelectionModel().select(tab);
}
+ /**
+ * Opens the SQL editor of a source, e.g. of the indexes of Elasticsearch, a collection fills in its query
+ */
+ private void openSourceSqlTab(DbNode node) {
+ SourceItem item = node.getKind() == DbNode.Kind.SOURCE_ITEM ? node.getItem() : null;
+ Tab tab = node.getSource().openSqlTab(context, ++sqlTabCount, item, this::showQueryExportDialog);
+ if (tab == null) {
+ return;
+ }
+ tab.setUserData(node.getSource().getId() + "|sql|" + sqlTabCount);
+ tabPane.getTabs().add(tab);
+ tabPane.getSelectionModel().select(tab);
+ }
+
+ /**
+ * Exports all rows of a query of the SQL editor of a source as a table named after the query, with a note
+ */
+ private void showQueryExportDialog(DbNode node, String sql, String tableName, String note) {
+ ExportDialog dialog = ExportDialog.forQuery(getWindow(), context, node, sql);
+ dialog.setQueryTableName(tableName);
+ dialog.setQueryNote(note);
+ Optional request = dialog.showAndWait();
+ connectionTree.addNewConnections();
+ request.ifPresent(transferRequest -> startTransfer(transferRequest, 1));
+ }
+
/**
* Exports all rows of a query of the SQL editor as a table
*/
diff --git a/src/main/java/com/github/sqljam/face/view/SqlCompletion.java b/src/main/java/com/github/sqljam/face/view/SqlCompletion.java
new file mode 100644
index 0000000..00db8d0
--- /dev/null
+++ b/src/main/java/com/github/sqljam/face/view/SqlCompletion.java
@@ -0,0 +1,325 @@
+/*
+ * Copyright 2023-2026 Fred Feng
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.sqljam.face.view;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.commons.lang3.StringUtils;
+import org.fxmisc.richtext.CodeArea;
+import com.github.sqljam.face.service.SqlStatements;
+import javafx.application.Platform;
+import javafx.geometry.Bounds;
+import javafx.scene.control.ContextMenu;
+import javafx.scene.control.CustomMenuItem;
+import javafx.scene.control.Label;
+import javafx.scene.input.KeyCode;
+import javafx.scene.input.KeyCodeCombination;
+import javafx.scene.input.KeyCombination;
+import javafx.scene.input.KeyEvent;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * @Description: SqlCompletion suggests names in a SQL editor like DBeaver and DataGrip: Ctrl+Space lists the
+ * columns of the tables of the statement, the tables and the keywords which start with the word at
+ * the caret, a dot after a table or an alias lists the columns of that table. Tables and columns
+ * come from the source of the editor (the metadata of a database, the indexes of a search engine),
+ * read in the background once and kept. A name which is no plain identifier is inserted quoted.
+ * @Author: Fred Feng
+ * @Date: 07/11/2026
+ * @Version 1.0.0
+ */
+@Slf4j
+public final class SqlCompletion {
+
+ /**
+ * Suggestions shown at most
+ */
+ static final int MAX_ITEMS = 60;
+ static final KeyCombination COMPLETE = new KeyCodeCombination(KeyCode.SPACE,
+ KeyCombination.CONTROL_DOWN);
+ private static final Pattern TABLE = Pattern.compile("(?i)\\b(?:FROM|JOIN|UPDATE|INTO)\\s+"
+ + "((?:\"[^\"]+\"|`[^`]+`|[\\w$-]+)(?:\\.(?:\"[^\"]+\"|`[^`]+`|[\\w$-]+))*)"
+ + "(?:\\s+(?:AS\\s+)?(?!(?i:WHERE|ON|JOIN|INNER|LEFT|RIGHT|FULL|CROSS|GROUP|ORDER|LIMIT|UNION|SET"
+ + "|VALUES|HAVING|SELECT)\\b)(\\w+))?");
+ private static final Pattern PLAIN = Pattern.compile("[A-Za-z_][A-Za-z0-9_$]*");
+
+ /**
+ * Tables and their columns of the source of an editor
+ */
+ public interface Source {
+
+ List tables() throws Exception;
+
+ List columns(String table) throws Exception;
+ }
+
+ /**
+ * The word at the caret and the name before its dot
+ */
+ static final class Context {
+
+ final int start;
+ final String prefix;
+ final String qualifier;
+
+ Context(int start, String prefix, String qualifier) {
+ this.start = start;
+ this.prefix = prefix;
+ this.qualifier = qualifier;
+ }
+ }
+
+ private final SqlEditor editor;
+ private final Source source;
+ private final ContextMenu menu = new ContextMenu();
+ private volatile List tables;
+ private final Map> columns = new ConcurrentHashMap<>();
+
+ private SqlCompletion(SqlEditor editor, Source source) {
+ this.editor = editor;
+ this.source = source;
+ menu.setId("sqlCompletionMenu");
+ CodeArea area = editor.getCodeArea();
+ area.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
+ if (COMPLETE.match(event)) {
+ show();
+ event.consume();
+ }
+ });
+ area.addEventHandler(KeyEvent.KEY_TYPED, event -> {
+ if (".".equals(event.getCharacter())) {
+ // After the dot is in the text
+ Platform.runLater(this::show);
+ }
+ });
+ }
+
+ /**
+ * Suggests names in the editor from the source
+ */
+ public static SqlCompletion attach(SqlEditor editor, Source source) {
+ return new SqlCompletion(editor, source);
+ }
+
+ /**
+ * Tables and columns are read again at the next completion, e.g. after another schema is chosen
+ */
+ public void reset() {
+ tables = null;
+ columns.clear();
+ }
+
+ /**
+ * Lists the suggestions at the caret, read in the background
+ */
+ public void show() {
+ String text = editor.getText();
+ int caret = editor.getCaretPosition();
+ Context context = contextAt(text, caret);
+ SqlStatements.Statement statement = SqlStatements.at(text, caret);
+ String sql = statement != null ? statement.getText() : text;
+ TaskRunner.run(() -> suggest(context, sql), names -> {
+ if (editor.getCaretPosition() == caret && editor.getText().equals(text)) {
+ showMenu(context, names);
+ }
+ }, e -> {
+ if (log.isDebugEnabled()) {
+ log.debug("Unable to read the names of the completion: {}", e.getMessage());
+ }
+ });
+ }
+
+ List suggest(Context context, String sql) throws Exception {
+ Map aliases = aliases(sql);
+ if (context.qualifier != null) {
+ String table = aliases.getOrDefault(context.qualifier.toLowerCase(Locale.ENGLISH), context.qualifier);
+ return filter(columnsOf(table), context.prefix);
+ }
+ Set names = new LinkedHashSet<>();
+ for (String table : new LinkedHashSet<>(aliases.values())) {
+ names.addAll(columnsOf(table));
+ }
+ names.addAll(tables());
+ List suggestions = filter(new ArrayList<>(names), context.prefix);
+ if (!context.prefix.isEmpty()) {
+ // Keywords complete a word, they are not listed for nothing
+ for (String keyword : SqlEditor.keywords()) {
+ if (keyword.startsWith(context.prefix.toUpperCase(Locale.ENGLISH))
+ && !keyword.equalsIgnoreCase(context.prefix)) {
+ suggestions.add(keyword);
+ }
+ }
+ }
+ return suggestions.size() > MAX_ITEMS ? suggestions.subList(0, MAX_ITEMS) : suggestions;
+ }
+
+ private List tables() throws Exception {
+ List read = tables;
+ if (read == null) {
+ read = Collections.unmodifiableList(new ArrayList<>(source.tables()));
+ tables = read;
+ }
+ return read;
+ }
+
+ /**
+ * Columns of a table, read once. A table which the source does not know has none
+ */
+ private List columnsOf(String table) {
+ String name = unquote(table.contains(".") && !table.startsWith("\"") ? StringUtils.substringAfterLast(table,
+ ".") : table);
+ return columns.computeIfAbsent(name.toLowerCase(Locale.ENGLISH), key -> {
+ try {
+ return Collections.unmodifiableList(new ArrayList<>(source.columns(name)));
+ } catch (Exception e) {
+ return Collections.emptyList();
+ }
+ });
+ }
+
+ private void showMenu(Context context, List names) {
+ menu.hide();
+ menu.getItems().clear();
+ if (names.isEmpty()) {
+ return;
+ }
+ for (String name : names) {
+ Label label = new Label(name);
+ CustomMenuItem item = new CustomMenuItem(label, true);
+ item.setOnAction(event -> insert(context, name));
+ menu.getItems().add(item);
+ }
+ CodeArea area = editor.getCodeArea();
+ Optional caret = area.getCaretBounds();
+ if (caret.isPresent()) {
+ menu.show(area, caret.get().getMinX(), caret.get().getMaxY());
+ } else {
+ Bounds bounds = area.localToScreen(area.getBoundsInLocal());
+ menu.show(area, bounds.getMinX(), bounds.getMinY());
+ }
+ // The first suggestion is chosen by Enter
+ if (menu.getSkin() != null) {
+ menu.getSkin().getNode().requestFocus();
+ }
+ }
+
+ /**
+ * Replaces the word at the caret by the name, quoted when it is no plain identifier
+ */
+ void insert(Context context, String name) {
+ CodeArea area = editor.getCodeArea();
+ boolean keyword = SqlEditor.keywords().contains(name);
+ area.replaceText(context.start, context.start + context.prefix.length(), keyword ? name : quoteIfNeeded(
+ name));
+ area.requestFocus();
+ }
+
+ ContextMenu getMenu() {
+ return menu;
+ }
+
+ /**
+ * The word before the caret and the name before its dot: "o.na" is the qualifier o and the prefix na
+ */
+ static Context contextAt(String text, int caret) {
+ int end = Math.max(0, Math.min(caret, text.length()));
+ int start = end;
+ while (start > 0 && isNamePart(text.charAt(start - 1))) {
+ start--;
+ }
+ String prefix = text.substring(start, end);
+ String qualifier = null;
+ if (start > 0 && text.charAt(start - 1) == '.') {
+ int qualifierEnd = start - 1;
+ int qualifierStart = qualifierEnd;
+ if (qualifierEnd > 0 && text.charAt(qualifierEnd - 1) == '"') {
+ int open = text.lastIndexOf('"', qualifierEnd - 2);
+ if (open >= 0) {
+ qualifierStart = open;
+ }
+ } else {
+ while (qualifierStart > 0 && isNamePart(text.charAt(qualifierStart - 1))) {
+ qualifierStart--;
+ }
+ }
+ if (qualifierStart < qualifierEnd) {
+ qualifier = unquote(text.substring(qualifierStart, qualifierEnd));
+ }
+ }
+ return new Context(start, prefix, qualifier);
+ }
+
+ /**
+ * Tables of a statement by their aliases and names in lower case: FROM orders o JOIN items i maps o and
+ * orders to orders, i and items to items
+ */
+ static Map aliases(String sql) {
+ Map aliases = new LinkedHashMap<>();
+ Matcher matcher = TABLE.matcher(StringUtils.defaultString(sql));
+ while (matcher.find()) {
+ String table = matcher.group(1);
+ String name = unquote(table.contains(".") && !table.startsWith("\"") && !table.startsWith("`")
+ ? StringUtils.substringAfterLast(table, ".") : table);
+ aliases.put(name.toLowerCase(Locale.ENGLISH), name);
+ if (matcher.group(2) != null) {
+ aliases.put(matcher.group(2).toLowerCase(Locale.ENGLISH), name);
+ }
+ }
+ return aliases;
+ }
+
+ /**
+ * Names which start with the prefix, without case
+ */
+ static List filter(List names, String prefix) {
+ List matched = new ArrayList<>();
+ String lower = prefix.toLowerCase(Locale.ENGLISH);
+ for (String name : names) {
+ if (name.toLowerCase(Locale.ENGLISH).startsWith(lower) && !name.equals(prefix)) {
+ matched.add(name);
+ }
+ }
+ return matched;
+ }
+
+ static String quoteIfNeeded(String name) {
+ return PLAIN.matcher(name).matches() ? name : "\"" + name.replace("\"", "\"\"") + "\"";
+ }
+
+ private static String unquote(String name) {
+ if (name.length() >= 2 && (name.startsWith("\"") && name.endsWith("\"") || name.startsWith("`")
+ && name.endsWith("`"))) {
+ return name.substring(1, name.length() - 1).replace("\"\"", "\"");
+ }
+ return name;
+ }
+
+ private static boolean isNamePart(char c) {
+ return Character.isLetterOrDigit(c) || c == '_' || c == '$';
+ }
+}
diff --git a/src/main/java/com/github/sqljam/face/view/SqlEditor.java b/src/main/java/com/github/sqljam/face/view/SqlEditor.java
index 3c28801..14401f9 100644
--- a/src/main/java/com/github/sqljam/face/view/SqlEditor.java
+++ b/src/main/java/com/github/sqljam/face/view/SqlEditor.java
@@ -17,6 +17,7 @@
import java.util.Collection;
import java.util.Collections;
+import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -34,7 +35,7 @@
* @Date: 17/10/2026
* @Version 1.0.0
*/
-final class SqlEditor {
+public final class SqlEditor {
private static final String[] KEYWORDS = {
"ADD", "ALL", "ALTER", "AND", "ANY", "AS", "ASC", "BEGIN", "BETWEEN", "BY", "CALL", "CASE", "CAST",
@@ -56,41 +57,50 @@ final class SqlEditor {
+ "|(?\\b(?i:" + String.join("|", KEYWORDS) + ")\\b)"
+ "|(?\\b\\d+(\\.\\d+)?\\b)");
+ private static final List KEYWORD_LIST = List.of(KEYWORDS);
+
private final CodeArea codeArea = new CodeArea();
private final VirtualizedScrollPane scrollPane = new VirtualizedScrollPane<>(codeArea);
- SqlEditor() {
+ public SqlEditor() {
codeArea.setId("sqlEditor");
codeArea.getStyleClass().add("sql-editor");
codeArea.setParagraphGraphicFactory(LineNumberFactory.get(codeArea));
codeArea.textProperty().addListener((obs, oldText, text) -> codeArea.setStyleSpans(0, highlight(text)));
}
- Node getNode() {
+ public Node getNode() {
return scrollPane;
}
- CodeArea getCodeArea() {
+ public CodeArea getCodeArea() {
return codeArea;
}
- String getText() {
+ public String getText() {
return codeArea.getText();
}
- void setText(String text) {
+ public void setText(String text) {
codeArea.replaceText(text != null ? text : "");
codeArea.moveTo(codeArea.getLength());
}
- String getSelectedText() {
+ public String getSelectedText() {
return codeArea.getSelectedText();
}
- int getCaretPosition() {
+ public int getCaretPosition() {
return codeArea.getCaretPosition();
}
+ /**
+ * Keywords of the highlighting, offered by the completion
+ */
+ static List keywords() {
+ return KEYWORD_LIST;
+ }
+
/**
* Style classes of the text: sql-keyword, sql-string, sql-name, sql-number and sql-comment
*/
diff --git a/src/main/java/com/github/sqljam/face/view/SqlTab.java b/src/main/java/com/github/sqljam/face/view/SqlTab.java
index 6b8a775..aa8766e 100644
--- a/src/main/java/com/github/sqljam/face/view/SqlTab.java
+++ b/src/main/java/com/github/sqljam/face/view/SqlTab.java
@@ -28,6 +28,8 @@
import org.apache.commons.lang3.StringUtils;
import lombok.extern.slf4j.Slf4j;
import com.github.sqljam.face.model.ConnectionProfile;
+import com.github.sqljam.face.model.ColumnInfo;
+import com.github.sqljam.face.model.TableInfo;
import com.github.sqljam.face.model.SqlResult;
import com.github.sqljam.face.service.DatabaseSession;
import com.github.sqljam.face.service.SqlStatements;
@@ -62,7 +64,8 @@
/**
* @Description: SqlTab runs SQL on a data source and exports the rows of a query, SqlJam is an import and export
* tool, the editor serves exports: Ctrl+Enter runs the selected text or the statement at the caret,
- * Ctrl+Shift+Enter runs all statements, every statement is committed at once. The first rows of the
+ * Ctrl+Shift+Enter runs all statements, every statement is committed at once. Ctrl+Space and a dot
+ * complete the names of tables and columns. The first rows of the
* last query are shown, Export sends the query to the export wizard which reads all its rows. The
* tab has a connection of its own, so session settings and temporary tables stay between runs.
* @Author: Fred Feng
@@ -76,8 +79,8 @@ public class SqlTab extends Tab {
* Rows of a query shown in the editor, an export reads all of them
*/
static final int MAX_ROWS = 500;
- private static final KeyCombination RUN = new KeyCodeCombination(KeyCode.ENTER, KeyCombination.SHORTCUT_DOWN);
- private static final KeyCombination RUN_ALL = new KeyCodeCombination(KeyCode.ENTER,
+ static final KeyCombination RUN = new KeyCodeCombination(KeyCode.ENTER, KeyCombination.SHORTCUT_DOWN);
+ static final KeyCombination RUN_ALL = new KeyCodeCombination(KeyCode.ENTER,
KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN);
private final ConnectionProfile profile;
@@ -109,6 +112,7 @@ public class SqlTab extends Tab {
private String lastQuery;
private boolean busy;
private BiConsumer onExport;
+ private SqlCompletion completion;
private static class LogEntry {
@@ -168,6 +172,20 @@ public SqlTab(AppContext context, DbNode node, int number) {
this.schema = StringUtils.defaultIfBlank(tableSchema, schema);
}
+ // Tables and columns of the database and schema of the editor
+ completion = SqlCompletion.attach(editor, new SqlCompletion.Source() {
+ @Override
+ public List tables() throws Exception {
+ return session.getTables(catalog, schema).stream().map(TableInfo::getName).collect(Collectors
+ .toList());
+ }
+
+ @Override
+ public List columns(String table) throws Exception {
+ return session.getColumns(catalog, schema, table).stream().map(ColumnInfo::getName).collect(
+ Collectors.toList());
+ }
+ });
targetLabel.setText(profile.getName());
targetLabel.setId("sqlTargetLabel");
targetLabel.getStyleClass().add("muted");
@@ -274,6 +292,9 @@ void switchTo(String newCatalog, String newSchema) {
boolean otherDatabase = !StringUtils.equals(newCatalog, catalog);
catalog = newCatalog;
schema = newSchema;
+ if (completion != null) {
+ completion.reset();
+ }
setTooltip(new Tooltip(describeTarget()));
Connection open = connection;
if (open == null) {
@@ -317,6 +338,10 @@ SqlEditor getEditor() {
return editor;
}
+ SqlCompletion getCompletion() {
+ return completion;
+ }
+
String getLastQuery() {
return lastQuery;
}
diff --git a/src/main/java/com/github/sqljam/vdb/VdbClient.java b/src/main/java/com/github/sqljam/vdb/VdbClient.java
index 93f1a27..6feca76 100644
--- a/src/main/java/com/github/sqljam/vdb/VdbClient.java
+++ b/src/main/java/com/github/sqljam/vdb/VdbClient.java
@@ -170,6 +170,35 @@ interface PageConsumer {
boolean accept(List> records, boolean last);
}
+ /**
+ * Whether the server runs SQL queries, Elasticsearch and OpenSearch do. Their SQL reads only, it writes nothing
+ */
+ default boolean isSqlSupported() {
+ return false;
+ }
+
+ /**
+ * Runs a SQL query of the server and returns its first page, the cursor of the result reads the next pages
+ *
+ * @param fetchSize rows of a page
+ */
+ default VdbSqlResult querySql(String sql, int fetchSize) {
+ throw new VdbException(getType() + " runs no SQL");
+ }
+
+ /**
+ * The next page of a SQL query, its columns are those of the first page
+ */
+ default VdbSqlResult nextSqlPage(String cursor) {
+ throw new VdbException(getType() + " runs no SQL");
+ }
+
+ /**
+ * Closes the cursor of a SQL query which is not read to its end, a closed or unknown cursor is fine
+ */
+ default void closeSqlCursor(String cursor) {
+ }
+
@Override
default void close() {
}
diff --git a/src/main/java/com/github/sqljam/vdb/VdbSqlResult.java b/src/main/java/com/github/sqljam/vdb/VdbSqlResult.java
new file mode 100644
index 0000000..4d97aaf
--- /dev/null
+++ b/src/main/java/com/github/sqljam/vdb/VdbSqlResult.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2023-2026 Fred Feng
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.sqljam.vdb;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @Description: VdbSqlResult is a page of the rows of a SQL query of a vector database (the SQL of Elasticsearch
+ * and OpenSearch): the columns with the types of the server, the rows with values of JSON (strings,
+ * numbers, booleans, null, arrays and objects as JSON text) and the cursor of the next page, null on
+ * the last page
+ * @Author: Fred Feng
+ * @Date: 07/11/2026
+ * @Version 1.0.0
+ */
+public class VdbSqlResult {
+
+ private final List columns;
+ private final List> rows;
+ private final String cursor;
+
+ public VdbSqlResult(List columns, List> rows, String cursor) {
+ this.columns = columns != null ? columns : Collections.emptyList();
+ this.rows = rows != null ? rows : Collections.emptyList();
+ this.cursor = cursor;
+ }
+
+ /**
+ * Name and type of each column as the server tells them, e.g. keyword, integer, datetime. The next pages of a
+ * cursor have none, the columns of the first page apply
+ */
+ public List getColumns() {
+ return columns;
+ }
+
+ public List> getRows() {
+ return rows;
+ }
+
+ /**
+ * Cursor of the next page, null when the rows are all read
+ */
+ public String getCursor() {
+ return cursor;
+ }
+
+ public boolean hasMore() {
+ return cursor != null && !cursor.isEmpty();
+ }
+}
diff --git a/src/main/java/com/github/sqljam/vdb/client/ElasticsearchClient.java b/src/main/java/com/github/sqljam/vdb/client/ElasticsearchClient.java
index 7d5edbb..96fe29d 100644
--- a/src/main/java/com/github/sqljam/vdb/client/ElasticsearchClient.java
+++ b/src/main/java/com/github/sqljam/vdb/client/ElasticsearchClient.java
@@ -29,16 +29,20 @@
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.sqljam.utils.RestClient;
+import com.github.sqljam.utils.RestException;
import com.github.sqljam.vdb.VdbCollection;
import com.github.sqljam.vdb.VdbException;
import com.github.sqljam.vdb.VdbField;
import com.github.sqljam.vdb.VdbInfo;
import com.github.sqljam.vdb.VdbQuery;
import com.github.sqljam.vdb.VdbSource;
+import com.github.sqljam.vdb.VdbSqlResult;
import com.github.sqljam.vdb.VdbValues;
import com.github.sqljam.vdb.VectorIndex;
import com.github.sqljam.vdb.VectorType;
+import lombok.extern.slf4j.Slf4j;
+
/**
* @Description: ElasticsearchClient reads Elasticsearch 8.0 and later by its REST API with a user and a password or
* an API key. An index is a collection: _id is the id, dense_vector fields are vectors of their
@@ -49,8 +53,15 @@
* @Date: 24/10/2026
* @Version 1.0.0
*/
+@Slf4j
public class ElasticsearchClient extends AbstractVdbClient {
+ /**
+ * The reason of an error in the JSON of the server, the first one is the cause
+ */
+ private static final java.util.regex.Pattern SQL_REASON = java.util.regex.Pattern.compile(
+ "\"reason\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
+
static final String ID = "_id";
/**
* Length of _id at most
@@ -511,4 +522,118 @@ static String rangeOperator(VdbQuery.Operator operator) {
return "lte";
}
}
+
+ @Override
+ public boolean isSqlSupported() {
+ return true;
+ }
+
+ /**
+ * Path of SQL queries in JSON: columns, rows and a cursor
+ */
+ protected String sqlPath() {
+ return "/_sql?format=json";
+ }
+
+ protected String sqlClosePath() {
+ return "/_sql/close";
+ }
+
+ @Override
+ public VdbSqlResult querySql(String sql, int fetchSize) {
+ ObjectNode body = RestClient.getMapper().createObjectNode().put("query", sql);
+ if (fetchSize > 0) {
+ body.put("fetch_size", fetchSize);
+ }
+ return toSqlResult(postSql(body));
+ }
+
+ @Override
+ public VdbSqlResult nextSqlPage(String cursor) {
+ return toSqlResult(postSql(RestClient.getMapper().createObjectNode().put("cursor", cursor)));
+ }
+
+ @Override
+ public void closeSqlCursor(String cursor) {
+ if (StringUtils.isEmpty(cursor)) {
+ return;
+ }
+ try {
+ rest.post(sqlClosePath(), RestClient.getMapper().createObjectNode().put("cursor", cursor));
+ } catch (RestException e) {
+ // A cursor of the last page is closed by the server already
+ if (log.isDebugEnabled()) {
+ log.debug("Unable to close a SQL cursor: {}", e.getMessage());
+ }
+ }
+ }
+
+ private JsonNode postSql(ObjectNode body) {
+ try {
+ return rest.post(sqlPath(), body);
+ } catch (RestException e) {
+ throw new VdbException(sqlError(e.getMessage()), e);
+ }
+ }
+
+ /**
+ * The reason of an error of SQL which the server tells in its JSON, the whole message otherwise
+ */
+ static String sqlError(String message) {
+ java.util.regex.Matcher matcher = SQL_REASON.matcher(StringUtils.defaultString(message));
+ if (!matcher.find()) {
+ return message;
+ }
+ try {
+ return RestClient.getMapper().readValue("\"" + matcher.group(1) + "\"", String.class);
+ } catch (IOException e) {
+ return matcher.group(1);
+ }
+ }
+
+ /**
+ * Columns and rows of Elasticsearch (columns, rows) and of OpenSearch (schema, datarows), the cursor if more
+ * rows follow
+ */
+ static VdbSqlResult toSqlResult(JsonNode response) {
+ List columns = new ArrayList<>();
+ JsonNode schema = response.has("columns") ? response.path("columns") : response.path("schema");
+ for (JsonNode column : schema) {
+ columns.add(new String[]{column.path("name").asText(), column.path("type").asText()});
+ }
+ List> rows = new ArrayList<>();
+ JsonNode data = response.has("rows") ? response.path("rows") : response.path("datarows");
+ for (JsonNode row : data) {
+ List values = new ArrayList<>(row.size());
+ for (JsonNode value : row) {
+ values.add(sqlValue(value));
+ }
+ rows.add(values);
+ }
+ String cursor = response.hasNonNull("cursor") ? StringUtils.trimToNull(response.path("cursor").asText())
+ : null;
+ return new VdbSqlResult(columns, rows, cursor);
+ }
+
+ /**
+ * A value of JSON as Java: text, a whole or decimal number, a boolean, null, arrays and objects as JSON text
+ */
+ static Object sqlValue(JsonNode value) {
+ if (value == null || value.isNull() || value.isMissingNode()) {
+ return null;
+ }
+ if (value.isTextual()) {
+ return value.asText();
+ }
+ if (value.isBoolean()) {
+ return value.asBoolean();
+ }
+ if (value.isIntegralNumber()) {
+ return value.canConvertToLong() ? (Object) value.asLong() : value.bigIntegerValue();
+ }
+ if (value.isNumber()) {
+ return value.decimalValue();
+ }
+ return value.toString();
+ }
}
diff --git a/src/main/java/com/github/sqljam/vdb/client/OpenSearchClient.java b/src/main/java/com/github/sqljam/vdb/client/OpenSearchClient.java
index 0fb3abf..4162cfe 100644
--- a/src/main/java/com/github/sqljam/vdb/client/OpenSearchClient.java
+++ b/src/main/java/com/github/sqljam/vdb/client/OpenSearchClient.java
@@ -48,6 +48,19 @@ public OpenSearchClient(VdbSource source) {
/**
* Indexes of the security audit log and of the query insights are of the server too
*/
+ /**
+ * The SQL plugin of OpenSearch answers in the JDBC format: schema, datarows and a cursor
+ */
+ @Override
+ protected String sqlPath() {
+ return "/_plugins/_sql";
+ }
+
+ @Override
+ protected String sqlClosePath() {
+ return "/_plugins/_sql/close";
+ }
+
@Override
protected boolean isSystemIndex(String name) {
return super.isSystemIndex(name) || name.startsWith("security-auditlog-") || name.startsWith("top_queries-");
diff --git a/src/main/resources/com/github/sqljam/face/messages.properties b/src/main/resources/com/github/sqljam/face/messages.properties
index 1c8e19d..2725606 100644
--- a/src/main/resources/com/github/sqljam/face/messages.properties
+++ b/src/main/resources/com/github/sqljam/face/messages.properties
@@ -497,8 +497,8 @@ sql.runAll=Run All
sql.runAll.tooltip=Run all statements one after another (Ctrl+Shift+Enter, Cmd+Shift+Enter on macOS)
sql.stop=Stop
sql.export=Export...
-sql.export.tooltip=Export all rows of the last query: SQL, Parquet, CSV or another database
-sql.noResult=Run a query with Ctrl+Enter (Cmd+Enter on macOS), its first rows are shown here
+sql.export.tooltip=Export all rows of the last query: SQL, Parquet, CSV, Excel or another database
+sql.noResult=Run a query with Ctrl+Enter (Cmd+Enter on macOS), its first rows are shown here. Ctrl+Space completes names of tables and columns
sql.nothing=No statement to run
sql.running=Running...
sql.cancelled=Cancelled
@@ -513,8 +513,14 @@ sql.status.done={0} statements done
vdb.title=Import from Vector Database
vdb.group=Vector databases
-vdb.open=Import into Database...
+vdb.open=Import Vectors into Database...
vdb.openItem=Open Collection
+vdb.sql.hint=Rows of indexes are exported like tables, vectors with their indexes by Import Vectors into Database
+vdb.sql.export.tooltip=Read all rows of the last query and export them like a table: SQL, Parquet, CSV, Excel or another database
+vdb.sql.note=The rows of the index are exported as a table. To keep vectors and their vector indexes, use Import Vectors into Database
+vdb.sql.vectorNote=Columns {0} hold vectors, this export writes them as JSON text. To keep them as vectors with their vector indexes, use Import Vectors into Database. Export the rows as a table?
+vdb.sql.reading=Reading the rows of the query: {0}
+vdb.sql.results={0} query results
vdb.connection=Vector database
vdb.rows=Records
vdb.rows.all=All records of the collections
@@ -690,6 +696,13 @@ help.dataFolder=Open SqlJam Folder
help.shortcuts=Keyboard Shortcuts
shortcuts.action=Action
shortcuts.keys=Keys
+shortcuts.sqlEditor=SQL editor
+shortcuts.complete=Complete names of tables and columns
+shortcuts.columns=Columns of a table after its name or alias
+shortcuts.dataTable=Data table
+shortcuts.copy=Copy the selected rows
+shortcuts.copyHeaders=Copy the selected rows with headers
+shortcuts.value=Show the whole value of a cell
sync.column.runBy=Last run by
sync.copyCommand=Copy Command
sync.copyCommand.tooltip=Copies the command which runs the task without the window, e.g. for a cron or the Task Scheduler of your own
diff --git a/src/test/java/com/github/sqljam/face/vdb/DataSourceKindsTest.java b/src/test/java/com/github/sqljam/face/vdb/DataSourceKindsTest.java
index 5c2b560..645c2e1 100644
--- a/src/test/java/com/github/sqljam/face/vdb/DataSourceKindsTest.java
+++ b/src/test/java/com/github/sqljam/face/vdb/DataSourceKindsTest.java
@@ -351,7 +351,7 @@ void managesVectorDatabasesOfTree() throws Exception {
item -> "Docs Chroma".equals(item.getValue().getLabel())).findFirst().orElseThrow());
fire(contextMenu(chroma), "Edit Data Source");
press(waitForDialog("vdbUrlField"), ButtonType.CANCEL);
- fire(contextMenu(chroma), "Import into Database...");
+ fire(contextMenu(chroma), "Import Vectors into Database...");
DialogPane importPane = waitForDialog("vdbSourceCombo");
@SuppressWarnings("unchecked")
ComboBox sources = (ComboBox) importPane.lookup("#vdbSourceCombo");
@@ -406,8 +406,32 @@ void neverOffersVectorDatabasesAsTargets() {
// A vector database is imported into a database, nothing is written into it
TreeItem qdrant = FxTestSupport.call(() -> group("Vector databases").getChildren().get(0));
- assertEquals(List.of("Import into Database...", "Refresh", "Info", "Edit Data Source", "Delete Data Source"),
- FxTestSupport.call(() -> contextMenu(qdrant).getItems().stream().map(MenuItem::getText).filter(
- text -> text != null).collect(Collectors.toList())));
+ assertEquals(List.of("Import Vectors into Database...", "Refresh", "Info", "Edit Data Source",
+ "Delete Data Source"), FxTestSupport.call(() -> contextMenu(qdrant).getItems().stream()
+ .map(MenuItem::getText).filter(text -> text != null).collect(Collectors.toList())));
+
+ // Elasticsearch also runs SQL on its indexes, their rows are exported like tables
+ VdbProfile search = new VdbProfile();
+ search.setName("Logs Search");
+ search.setType(VdbType.ELASTICSEARCH);
+ search.setUrl("http://127.0.0.1:1");
+ try {
+ store.saveProfile(search, true);
+ } catch (java.io.IOException e) {
+ throw new AssertionError(e);
+ }
+ java.util.concurrent.atomic.AtomicReference queried = new java.util.concurrent.atomic
+ .AtomicReference<>();
+ FxTestSupport.run(() -> tree.setOnSqlQuery(queried::set));
+ fire(contextMenu(group("Vector databases")), "Refresh");
+ FxTestSupport.waitUntil(() -> labels(group("Vector databases")).contains("Logs Search"));
+ TreeItem logs = FxTestSupport.call(() -> group("Vector databases").getChildren().stream().filter(
+ item -> "Logs Search".equals(item.getValue().getLabel())).findFirst().orElseThrow());
+ assertEquals(List.of("Import Vectors into Database...", "SQL Query", "Refresh", "Info", "Edit Data Source",
+ "Delete Data Source"), FxTestSupport.call(() -> contextMenu(logs).getItems().stream()
+ .map(MenuItem::getText).filter(text -> text != null).collect(Collectors.toList())));
+ fire(contextMenu(logs), "SQL Query");
+ FxTestSupport.waitUntil(() -> queried.get() != null);
+ assertEquals("Logs Search", queried.get().getLabel());
}
}
diff --git a/src/test/java/com/github/sqljam/face/vdb/VdbSqlIT.java b/src/test/java/com/github/sqljam/face/vdb/VdbSqlIT.java
new file mode 100644
index 0000000..dcbbd55
--- /dev/null
+++ b/src/test/java/com/github/sqljam/face/vdb/VdbSqlIT.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright 2023-2026 Fred Feng
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.sqljam.face.vdb;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
+import java.io.File;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import com.github.sqljam.face.model.ConnectionProfile;
+import com.github.sqljam.face.model.TransferRequest;
+import com.github.sqljam.face.service.TransferService;
+import com.github.sqljam.impexp.DbType;
+import com.github.sqljam.impexp.ExportMode;
+import com.github.sqljam.utils.RestClient;
+import com.github.sqljam.utils.RestException;
+import com.github.sqljam.vdb.VdbClient;
+import com.github.sqljam.vdb.VdbSqlResult;
+import com.github.sqljam.vdb.it.VdbServer;
+
+/**
+ * @Description: VdbSqlIT runs SQL on an index of a real Elasticsearch and OpenSearch: pages of a cursor, the rows
+ * read into a DuckDB file with the types of their columns, vectors of OpenSearch told as vectors, and
+ * the rows exported like a table into an H2 database by the export of the application
+ * @Author: Fred Feng
+ * @Date: 07/11/2026
+ * @Version 1.0.0
+ */
+class VdbSqlIT {
+
+ private static final String INDEX = "sjvt_sql";
+ private static final int DOCUMENTS = 25;
+
+ @TempDir
+ File dir;
+
+ private static void createIndex(VdbServer server) {
+ RestClient rest = server.rest();
+ try {
+ rest.delete("/" + INDEX);
+ } catch (RestException e) {
+ // Not there yet
+ }
+ boolean open = server == VdbServer.OPENSEARCH;
+ Map vector = open ? Map.of("type", "knn_vector", "dimension", 3)
+ : Map.of("type", "dense_vector", "dims", 3);
+ Map properties = Map.of("name", Map.of("type", "keyword"), "n", Map.of("type", "integer"),
+ "price", Map.of("type", "double"), "ok", Map.of("type", "boolean"), "at", Map.of("type", "date"),
+ "note", Map.of("type", "text"), "embedding", vector);
+ rest.put("/" + INDEX, open ? Map.of("settings", Map.of("index", Map.of("knn", true)), "mappings",
+ Map.of("properties", properties)) : Map.of("mappings", Map.of("properties", properties)));
+ StringBuilder bulk = new StringBuilder();
+ for (int i = 1; i <= DOCUMENTS; i++) {
+ bulk.append("{\"index\": {\"_index\": \"").append(INDEX).append("\", \"_id\": \"").append(i)
+ .append("\"}}\n").append(String.format("{\"name\": \"doc %d\", \"n\": %d, \"price\": %d.5,"
+ + " \"ok\": %b, \"at\": \"2024-01-%02dT10:00:00Z\", \"note\": \"文本 %d\", \"embedding\":"
+ + " [%d, 0.5, -1]}%n", i, i, i, i % 2 == 0, i, i, i));
+ }
+ rest.post("/_bulk?refresh=true", bulk.toString());
+ }
+
+ @ParameterizedTest(name = "sql of {0}")
+ @EnumSource(value = VdbServer.class, names = {"ELASTICSEARCH", "OPENSEARCH"})
+ void exportsRowsOfIndexLikeTable(VdbServer server) throws Exception {
+ assumeTrue(server.isAvailable(), server + " is not available");
+ createIndex(server);
+ try (VdbClient client = server.createClient()) {
+ // Pages of the cursor
+ VdbSqlResult page = client.querySql("SELECT name, n, price, ok, at, note FROM " + INDEX
+ + " ORDER BY n", 10);
+ List names = new ArrayList<>();
+ int pages = 1;
+ while (true) {
+ page.getRows().forEach(row -> names.add(row.get(0)));
+ if (!page.hasMore()) {
+ break;
+ }
+ page = client.nextSqlPage(page.getCursor());
+ pages++;
+ }
+ assertEquals(DOCUMENTS, names.size());
+ assertEquals("doc 1", names.get(0));
+ assertTrue(pages >= 3, "pages: " + pages);
+
+ // All rows in a DuckDB file with their types
+ VdbSqlStaging.Staged staged = VdbSqlStaging.stage(client, "SELECT name, n, price, ok, at, note FROM "
+ + INDEX, INDEX, new AtomicBoolean(), rows -> { });
+ assertEquals(DOCUMENTS, staged.rows);
+ try (Connection connection = DriverManager.getConnection("jdbc:duckdb:" + staged.file
+ .getAbsolutePath()); Statement statement = connection.createStatement()) {
+ List types = new ArrayList<>();
+ try (ResultSet rs = statement.executeQuery("DESCRIBE \"" + INDEX + "\"")) {
+ while (rs.next()) {
+ types.add(rs.getString("column_name") + " " + rs.getString("column_type"));
+ }
+ }
+ assertTrue(types.containsAll(List.of("name VARCHAR", "n INTEGER", "price DOUBLE", "ok BOOLEAN",
+ "at TIMESTAMP")), types.toString());
+ try (ResultSet rs = statement.executeQuery("SELECT count(*), sum(\"n\"), min(\"at\") FROM \"" + INDEX
+ + "\"")) {
+ rs.next();
+ assertEquals(DOCUMENTS, rs.getInt(1));
+ assertEquals(DOCUMENTS * (DOCUMENTS + 1) / 2, rs.getInt(2));
+ assertEquals("2024-01-01 10:00:00.0", rs.getTimestamp(3).toString());
+ }
+ }
+
+ // OpenSearch returns vectors as arrays, they are told before the export
+ if (server == VdbServer.OPENSEARCH) {
+ VdbSqlResult withVectors = client.querySql("SELECT name, embedding FROM " + INDEX, 5);
+ assertEquals(List.of("embedding"), VdbSqlStaging.vectorColumns(withVectors.getColumns(),
+ withVectors.getRows()));
+ client.closeSqlCursor(withVectors.getCursor());
+ }
+
+ // Exported like a table into H2 by the export of the application
+ ConnectionProfile results = new ConnectionProfile();
+ results.setName(server + " query results");
+ results.setDbType(DbType.DUCKDB);
+ results.setDatabase(staged.file.getAbsolutePath());
+ ConnectionProfile h2 = new ConnectionProfile();
+ h2.setName("Target H2");
+ h2.setDbType(DbType.H2);
+ h2.setDatabase(new File(dir, "target").getAbsolutePath());
+ h2.setUsername("sa");
+ h2.setPassword("");
+ TransferRequest request = new TransferRequest();
+ request.setSource(results);
+ request.getQueries().put("docs_of_index", "SELECT * FROM \"" + INDEX + "\"");
+ request.setTarget(TransferRequest.Target.DATABASE);
+ request.setTargetProfile(h2);
+ request.setTargetSchema("PUBLIC");
+ request.setExportMode(ExportMode.DDL_DATA);
+ com.github.sqljam.it.CollectingListener listener = new com.github.sqljam.it.CollectingListener();
+ new TransferService().transfer(request, listener);
+ assertEquals(List.of(), listener.getErrors());
+ try (Connection connection = DriverManager.getConnection(h2.getJdbcUrl(), "sa", "");
+ Statement statement = connection.createStatement();
+ ResultSet rs = statement.executeQuery("SELECT COUNT(*), SUM(N) FROM DOCS_OF_INDEX")) {
+ rs.next();
+ assertEquals(DOCUMENTS, rs.getInt(1));
+ assertEquals(DOCUMENTS * (DOCUMENTS + 1) / 2, rs.getInt(2));
+ }
+ } finally {
+ try {
+ server.rest().delete("/" + INDEX);
+ } catch (RestException e) {
+ // Dropped already
+ }
+ }
+ }
+}
diff --git a/src/test/java/com/github/sqljam/face/vdb/VdbSqlStagingTest.java b/src/test/java/com/github/sqljam/face/vdb/VdbSqlStagingTest.java
new file mode 100644
index 0000000..2450e9c
--- /dev/null
+++ b/src/test/java/com/github/sqljam/face/vdb/VdbSqlStagingTest.java
@@ -0,0 +1,177 @@
+/*
+ * Copyright 2023-2026 Fred Feng
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.sqljam.face.vdb;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.math.BigDecimal;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.junit.jupiter.api.Test;
+
+import com.github.sqljam.impexp.ExportCancelledException;
+import com.github.sqljam.vdb.VdbClient;
+import com.github.sqljam.vdb.VdbException;
+import com.github.sqljam.vdb.VdbSource;
+import com.github.sqljam.vdb.VdbType;
+import com.github.sqljam.vdb.client.FakeServer;
+
+/**
+ * @Description: VdbSqlStagingTest verifies that the rows of a SQL query of Elasticsearch are read page by page
+ * into a DuckDB file with the types of their columns (timestamps of Elasticsearch, numbers, booleans,
+ * text, JSON of objects), a stop between pages which closes the cursor, an error which leaves no
+ * file, the names of tables of queries, repeated names of columns and columns of vectors
+ * @Author: Fred Feng
+ * @Date: 07/11/2026
+ * @Version 1.0.0
+ */
+class VdbSqlStagingTest {
+
+ private static final String FIRST = "{\"columns\": [{\"name\": \"id\", \"type\": \"keyword\"},"
+ + " {\"name\": \"n\", \"type\": \"integer\"}, {\"name\": \"price\", \"type\": \"double\"},"
+ + " {\"name\": \"ok\", \"type\": \"boolean\"}, {\"name\": \"at\", \"type\": \"datetime\"},"
+ + " {\"name\": \"big\", \"type\": \"unsigned_long\"}, {\"name\": \"tags\", \"type\": \"object\"}],"
+ + " \"rows\": [[\"a\", 1, 1.5, true, \"2024-01-02T03:04:05.123Z\", 18446744073709551615, {\"k\": 1}]],"
+ + " \"cursor\": \"c1\"}";
+ private static final String NEXT = "{\"rows\": [[\"b\", null, 2, false, \"bad date\", 1, null]]}";
+
+ private static VdbClient client(FakeServer server) {
+ VdbSource source = new VdbSource(VdbType.ELASTICSEARCH, server.getUrl());
+ source.setTimeoutSeconds(5);
+ return VdbType.ELASTICSEARCH.createClient(source);
+ }
+
+ @Test
+ void readsAllPagesWithTypes() throws Exception {
+ try (FakeServer server = new FakeServer()) {
+ server.route("POST /_sql?format=json", body -> body.contains("\"cursor\"") ? NEXT : FIRST);
+ List progress = new ArrayList<>();
+ VdbSqlStaging.Staged staged;
+ try (VdbClient client = client(server)) {
+ staged = VdbSqlStaging.stage(client, "SELECT * FROM docs", "docs", new AtomicBoolean(),
+ progress::add);
+ }
+ assertEquals(2, staged.rows);
+ assertEquals(List.of(1L, 2L), progress);
+ assertTrue(staged.file.isFile());
+ try (Connection connection = DriverManager.getConnection("jdbc:duckdb:" + staged.file
+ .getAbsolutePath()); Statement statement = connection.createStatement()) {
+ List types = new ArrayList<>();
+ try (ResultSet rs = statement.executeQuery("DESCRIBE \"docs\"")) {
+ while (rs.next()) {
+ types.add(rs.getString("column_name") + " " + rs.getString("column_type"));
+ }
+ }
+ assertEquals(List.of("id VARCHAR", "n INTEGER", "price DOUBLE", "ok BOOLEAN", "at TIMESTAMP",
+ "big DECIMAL(20,0)", "tags VARCHAR"), types);
+ try (ResultSet rs = statement.executeQuery("SELECT * FROM \"docs\" ORDER BY id")) {
+ assertTrue(rs.next());
+ assertEquals("2024-01-02 03:04:05.123", rs.getTimestamp("at").toString());
+ assertEquals(new BigDecimal("18446744073709551615"), rs.getBigDecimal("big"));
+ assertEquals("{\"k\":1}", rs.getString("tags"));
+ assertTrue(rs.next());
+ // A value which is not of the type of its column is NULL
+ rs.getInt("n");
+ assertTrue(rs.wasNull());
+ assertEquals(null, rs.getTimestamp("at"));
+ }
+ try (ResultSet rs = statement.executeQuery("SELECT count(*) FROM duckdb_tables() WHERE"
+ + " table_name = 'raw'")) {
+ rs.next();
+ assertEquals(0, rs.getInt(1));
+ }
+ }
+ }
+ }
+
+ @Test
+ void stopsBetweenPagesAndClosesTheCursor() throws Exception {
+ try (FakeServer server = new FakeServer()) {
+ server.route("POST /_sql?format=json", FIRST).route("POST /_sql/close", "{\"succeeded\": true}");
+ AtomicBoolean cancelled = new AtomicBoolean();
+ try (VdbClient client = client(server)) {
+ assertThrows(ExportCancelledException.class, () -> VdbSqlStaging.stage(client, "SELECT * FROM docs",
+ "docs", cancelled, rows -> cancelled.set(true)));
+ }
+ assertEquals(1, server.requests("POST /_sql/close").size());
+ assertTrue(server.requests("POST /_sql/close").get(0).body.contains("c1"));
+ }
+ }
+
+ @Test
+ void errorsLeaveNoFile() throws Exception {
+ java.io.File directory = new java.io.File(org.apache.commons.io.FileUtils.getTempDirectory(),
+ ".sqljam-queries");
+ int before = files(directory);
+ try (FakeServer server = new FakeServer()) {
+ server.route("POST /_sql?format=json", body -> {
+ if (body.contains("\"cursor\"")) {
+ throw new IllegalStateException("broken");
+ }
+ return FIRST;
+ });
+ try (VdbClient client = client(server)) {
+ assertThrows(VdbException.class, () -> VdbSqlStaging.stage(client, "SELECT * FROM docs", "docs",
+ new AtomicBoolean(), rows -> { }));
+ }
+ }
+ assertEquals(before, files(directory));
+ }
+
+ private static int files(java.io.File directory) {
+ String[] names = directory.list();
+ return names == null ? 0 : names.length;
+ }
+
+ @Test
+ void namesTypesAndVectors() {
+ assertEquals("docs", VdbSqlStaging.tableName("select * from docs where n > 1"));
+ assertEquals("logs_2024__", VdbSqlStaging.tableName("SELECT a FROM \"logs-2024.*\""));
+ assertEquals("my_index", VdbSqlStaging.tableName("SELECT a FROM `my index`"));
+ assertEquals("t_2024", VdbSqlStaging.tableName("SELECT a FROM 2024"));
+ assertEquals("query", VdbSqlStaging.tableName("SHOW TABLES"));
+ assertEquals("query", VdbSqlStaging.tableName(null));
+ assertEquals("VARCHAR", VdbSqlStaging.duckdbType("geo_point"));
+ assertEquals("VARCHAR", VdbSqlStaging.duckdbType(null));
+ assertEquals("TINYINT", VdbSqlStaging.duckdbType("byte"));
+ assertEquals("SMALLINT", VdbSqlStaging.duckdbType("short"));
+ assertEquals("BIGINT", VdbSqlStaging.duckdbType("LONG"));
+ assertEquals("FLOAT", VdbSqlStaging.duckdbType("half_float"));
+ assertEquals("DOUBLE", VdbSqlStaging.duckdbType("scaled_float"));
+ assertEquals("TIMESTAMP", VdbSqlStaging.duckdbType("timestamp"));
+ assertEquals("\"t\"", VdbSqlStaging.cast("t", "text"));
+ assertEquals("1.50", VdbSqlStaging.text(new BigDecimal("1.50")));
+ assertEquals(List.of("a", "A_2", "column3"), VdbSqlStaging.uniqueNames(List.of(
+ new String[]{"a", "keyword"}, new String[]{"A", "long"}, new String[]{"", "long"})).stream()
+ .map(column -> column[0]).toList());
+ List> rows = List.of(Arrays.asList("x", "[0.5,-1.0]", "[\"a\"]", null, "y"),
+ Arrays.asList("z", "[1]", "[\"b\"]", "[2,3]", "w"));
+ assertEquals(List.of("embedding", "dense"), VdbSqlStaging.vectorColumns(List.of(new String[]{"id", "text"},
+ new String[]{"embedding", "nested"}, new String[]{"tags", "nested"}, new String[]{"dense",
+ "dense_vector"}, new String[]{"note", "text"}), rows));
+ assertTrue(VdbSqlStaging.vectorColumns(List.of(new String[]{"id", "text"}), List.of()).isEmpty());
+ }
+}
diff --git a/src/test/java/com/github/sqljam/face/vdb/VdbSqlTabTest.java b/src/test/java/com/github/sqljam/face/vdb/VdbSqlTabTest.java
new file mode 100644
index 0000000..27cfb35
--- /dev/null
+++ b/src/test/java/com/github/sqljam/face/vdb/VdbSqlTabTest.java
@@ -0,0 +1,250 @@
+/*
+ * Copyright 2023-2026 Fred Feng
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.sqljam.face.vdb;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.File;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+import org.testfx.framework.junit5.ApplicationExtension;
+import org.testfx.framework.junit5.Start;
+
+import com.github.sqljam.face.view.AppContext;
+import com.github.sqljam.face.view.DbNode;
+import com.github.sqljam.face.view.FxTestSupport;
+import com.github.sqljam.face.view.SourceItem;
+import com.github.sqljam.impexp.DbType;
+import com.github.sqljam.vdb.VdbType;
+import com.github.sqljam.vdb.client.FakeServer;
+import javafx.scene.Scene;
+import javafx.scene.control.Button;
+import javafx.scene.control.ButtonType;
+import javafx.scene.control.Label;
+import javafx.scene.control.ListView;
+import javafx.scene.control.TabPane;
+import javafx.scene.control.TableView;
+import javafx.stage.Stage;
+
+/**
+ * @Description: VdbSqlTabTest runs SQL on the indexes of a fake Elasticsearch: the first rows of a query, the
+ * errors of the server, an export which reads all rows into a DuckDB file and opens the export with
+ * the name of the index and the note that rows go as a table, and a query with vectors which asks
+ * first and tells that vectors take Import Vectors into Database
+ * @Author: Fred Feng
+ * @Date: 07/11/2026
+ * @Version 1.0.0
+ */
+@ExtendWith(ApplicationExtension.class)
+class VdbSqlTabTest {
+
+ @TempDir
+ File dir;
+
+ private Stage stage;
+ private AppContext context;
+ private FakeServer server;
+ private VdbSqlTab tab;
+ private final AtomicReference exported = new AtomicReference<>();
+
+ @Start
+ void start(Stage stage) {
+ this.stage = stage;
+ FxTestSupport.applyAppStyle();
+ stage.setScene(new Scene(new TabPane(), 1000, 700));
+ stage.show();
+ }
+
+ @AfterEach
+ void stop() {
+ if (tab != null) {
+ FxTestSupport.run(tab::close);
+ }
+ FxTestSupport.closeAllDialogs();
+ if (server != null) {
+ server.close();
+ }
+ }
+
+ private void open(String index, String response) throws Exception {
+ context = FxTestSupport.createContext(dir);
+ server = new FakeServer();
+ server.route("POST /_sql?format=json", body -> body.contains("\"cursor\"")
+ ? "{\"rows\": [[\"b\", 2, \"[3,4]\"]]}" : response)
+ .route("POST /_sql/close", "{\"succeeded\": true}");
+ VdbProfile profile = new VdbProfile();
+ profile.setName("Search");
+ profile.setType(VdbType.ELASTICSEARCH);
+ profile.setUrl(server.getUrl());
+ profile.setTimeoutSeconds(5);
+ tab = FxTestSupport.call(() -> {
+ VdbSqlTab created = new VdbSqlTab(context, profile, 1, index, (node, sql, table, note) -> exported.set(
+ new Object[]{node, sql, table, note}));
+ ((TabPane) stage.getScene().getRoot()).getTabs().setAll(created);
+ return created;
+ });
+ }
+
+ /**
+ * Text of a label of the tab, nodes in the split pane are in the scene after its skin is created
+ */
+ private String text(String id) {
+ return FxTestSupport.call(() -> {
+ tab.getContent().applyCss();
+ return ((Label) tab.getContent().lookup("#" + id)).getText();
+ });
+ }
+
+ private Button button(String id) {
+ return (Button) toolBarItem(id);
+ }
+
+ /**
+ * An item of the tool bar, also when a narrow window puts it into the overflow menu
+ */
+ private javafx.scene.Node toolBarItem(String id) {
+ return FxTestSupport.call(() -> {
+ tab.getContent().applyCss();
+ return tab.getContent().lookupAll(".tool-bar").stream().flatMap(bar -> ((javafx.scene.control
+ .ToolBar) bar).getItems().stream()).filter(item -> id.equals(item.getId())).findFirst()
+ .orElseThrow();
+ });
+ }
+
+ @SuppressWarnings("unchecked")
+ private TableView> results() {
+ return FxTestSupport.call(() -> {
+ tab.getContent().applyCss();
+ return (TableView>) tab.getContent().lookup("#sqlResultTable");
+ });
+ }
+
+ @SuppressWarnings("unchecked")
+ private List messages() {
+ return FxTestSupport.call(() -> {
+ tab.getContent().applyCss();
+ return ((ListView) tab.getContent().lookup("#sqlMessageList")).getItems().stream()
+ .map(item -> item[0]).toList();
+ });
+ }
+
+ private static final String DOCS = "{\"columns\": [{\"name\": \"id\", \"type\": \"keyword\"}, {\"name\": \"n\","
+ + " \"type\": \"long\"}, {\"name\": \"note\", \"type\": \"text\"}], \"rows\": [[\"a\", 1, \"x\"]],"
+ + " \"cursor\": \"c1\"}";
+
+ @Test
+ void runsQueriesAndExportsRowsAsTable() throws Exception {
+ open("docs", DOCS);
+ assertEquals("SELECT * FROM \"docs\"", FxTestSupport.call(() -> tab.getEditor().getText()));
+ assertTrue(FxTestSupport.call(() -> ((Label) toolBarItem("vdbSqlHint")).getText()).contains(
+ "Import Vectors into Database"));
+ assertTrue(FxTestSupport.call(() -> button("sqlExportButton").isDisabled()));
+ FxTestSupport.run(() -> tab.run(false));
+ FxTestSupport.waitUntil(() -> FxTestSupport.call(() -> !results().getItems().isEmpty()));
+ assertEquals(List.of("a", "1", "x"), FxTestSupport.call(() -> results().getItems().get(0)));
+ assertEquals("First 1 rows, Export reads all of them", text("sqlStatusLabel"));
+ // The first page is shown, its cursor is closed
+ assertEquals(1, server.requests("POST /_sql/close").size());
+ assertEquals("SELECT * FROM \"docs\"", tab.getLastQuery());
+
+ FxTestSupport.run(tab::export);
+ FxTestSupport.waitUntil(() -> exported.get() != null);
+ DbNode node = (DbNode) exported.get()[0];
+ assertEquals(DbType.DUCKDB, node.getProfile().getDbType());
+ assertEquals("Search query results", node.getProfile().getName());
+ assertTrue(new File(node.getProfile().getDatabase()).isFile());
+ assertEquals("SELECT * FROM \"docs\"", exported.get()[1]);
+ assertEquals("docs", exported.get()[2]);
+ assertTrue(((String) exported.get()[3]).startsWith("The rows of the index are exported as a table"));
+ assertEquals("2 rows", text("sqlStatusLabel"));
+ }
+
+ @Test
+ void asksBeforeExportingVectorsAsText() throws Exception {
+ open(null, "{\"columns\": [{\"name\": \"id\", \"type\": \"keyword\"}, {\"name\": \"n\", \"type\": \"long\"},"
+ + " {\"name\": \"embedding\", \"type\": \"nested\"}], \"rows\": [[\"a\", 1, [0.5, -1]]]}");
+ FxTestSupport.run(() -> tab.getEditor().setText("SELECT * FROM vectors"));
+ FxTestSupport.run(() -> tab.run(true));
+ FxTestSupport.waitUntil(() -> FxTestSupport.call(() -> !results().getItems().isEmpty()));
+ FxTestSupport.fireLater(button("sqlExportButton"));
+ FxTestSupport.waitUntil(() -> FxTestSupport.getDialogPanes().stream().anyMatch(pane -> pane
+ .getContentText() != null && pane.getContentText().contains("Columns embedding hold vectors")));
+ // Cancelled, nothing is exported
+ FxTestSupport.closeDialog(ButtonType.CANCEL);
+ assertNull(exported.get());
+ FxTestSupport.fireLater(button("sqlExportButton"));
+ FxTestSupport.waitForDialogPane();
+ FxTestSupport.closeDialog(ButtonType.OK);
+ FxTestSupport.waitUntil(() -> exported.get() != null);
+ assertTrue(((String) exported.get()[3]).contains("Import Vectors into Database"));
+ assertEquals("vectors", exported.get()[2]);
+ }
+
+ @Test
+ void showsErrorsOfTheServer() throws Exception {
+ open(null, DOCS);
+ server.route("POST /_sql?format=json", 400, "{\"error\": {\"root_cause\": [{\"reason\":"
+ + " \"Unknown index [missing]\"}]}}");
+ FxTestSupport.run(() -> tab.getEditor().setText("SELECT * FROM missing"));
+ FxTestSupport.run(() -> tab.run(false));
+ FxTestSupport.waitUntil(() -> "Failed".equals(text("sqlStatusLabel")));
+ assertTrue(messages().get(0).contains("Unknown index [missing]"), messages().toString());
+ assertTrue(FxTestSupport.call(() -> button("sqlExportButton").isDisabled()));
+ // Nothing to run
+ FxTestSupport.run(() -> tab.getEditor().setText(" "));
+ FxTestSupport.run(() -> tab.run(false));
+ assertEquals("No statement to run", text("sqlStatusLabel"));
+ FxTestSupport.run(tab::export);
+ assertNull(exported.get());
+ assertNotNull(tab.getProfile());
+ assertFalse(FxTestSupport.call(() -> tab.getText().isEmpty()));
+ }
+
+ /**
+ * Elasticsearch and OpenSearch sources open SQL editors, other vector databases have none
+ */
+ @Test
+ void sourcesOfIndexesRunSql() throws Exception {
+ context = FxTestSupport.createContext(dir);
+ VdbProfileStore store = new VdbProfileStore(new File(dir, VdbProfileStore.FILE_NAME));
+ for (VdbType type : VdbType.values()) {
+ VdbProfile profile = new VdbProfile();
+ profile.setName(type.name());
+ profile.setType(type);
+ profile.setUrl("http://127.0.0.1:1");
+ VdbDataSourceExtension.VdbSourceItem source = new VdbDataSourceExtension.VdbSourceItem(profile, store);
+ boolean sql = type == VdbType.ELASTICSEARCH || type == VdbType.OPENSEARCH;
+ assertEquals(sql, source.isSqlSupported(), type.name());
+ Object opened = FxTestSupport.call(() -> source.openSqlTab(context, 3, new SourceItem(SourceItem.Kind
+ .COLLECTION, List.of("orders"), "Index", true), (node, query, table, note) -> { }));
+ assertEquals(sql, opened != null, type.name());
+ if (opened != null) {
+ assertEquals("SELECT * FROM \"orders\"", FxTestSupport.call(() -> ((VdbSqlTab) opened).getEditor()
+ .getText()));
+ FxTestSupport.run(((VdbSqlTab) opened)::close);
+ }
+ }
+ }
+}
diff --git a/src/test/java/com/github/sqljam/face/view/ExportDialogTest.java b/src/test/java/com/github/sqljam/face/view/ExportDialogTest.java
index d91af34..616f3b3 100644
--- a/src/test/java/com/github/sqljam/face/view/ExportDialogTest.java
+++ b/src/test/java/com/github/sqljam/face/view/ExportDialogTest.java
@@ -884,6 +884,48 @@ void choosesKeyColumnsOfTables() throws Exception {
* Rows of a query of the SQL editor are exported as one table: the source is fixed, the table list is the
* name of the table, options of tables are hidden, the same schema is a valid target
*/
+ /**
+ * The rows of a query of an index fetched into a DuckDB file which is no saved data source: the export names
+ * the table after the index and tells that the rows go as a table
+ */
+ @Test
+ void exportsRowsOfIndexFromUnsavedSource() throws Exception {
+ File file = new File(dir, "results.duckdb");
+ try (java.sql.Connection connection = java.sql.DriverManager.getConnection("jdbc:duckdb:" + file
+ .getAbsolutePath()); java.sql.Statement statement = connection.createStatement()) {
+ statement.execute("CREATE TABLE \"logs\" (id VARCHAR, n INTEGER)");
+ statement.execute("INSERT INTO \"logs\" VALUES ('a', 1)");
+ }
+ ConnectionProfile results = new ConnectionProfile();
+ results.setName("Search query results");
+ results.setDbType(DbType.DUCKDB);
+ results.setDatabase(file.getAbsolutePath());
+ dialog = FxTestSupport.call(() -> {
+ ExportDialog exportDialog = ExportDialog.forQuery(stage, context, DbNode.connection(results),
+ "SELECT * FROM \"logs\"");
+ exportDialog.setQueryTableName("logs");
+ exportDialog.setQueryNote("The rows of the index are exported as a table");
+ exportDialog.show();
+ return exportDialog;
+ });
+ assertEquals("logs", FxTestSupport.call(((TextField) node("queryTableField"))::getText));
+ Label note = node("queryNoteLabel");
+ assertTrue(FxTestSupport.call(note::isVisible));
+ assertEquals("The rows of the index are exported as a table", FxTestSupport.call(note::getText));
+ setText("directoryField", dir.getAbsolutePath());
+ FxTestSupport.waitUntil(() -> !startDisabled());
+ TransferRequest request = build();
+ assertEquals("Search query results", request.getSource().getName());
+ assertEquals("SELECT * FROM \"logs\"", request.getQueries().get("logs"));
+ // No note, no label, a blank name keeps the default
+ FxTestSupport.run(() -> {
+ dialog.setQueryNote(null);
+ dialog.setQueryTableName(" ");
+ });
+ assertFalse(FxTestSupport.call(note::isVisible));
+ assertEquals("logs", FxTestSupport.call(((TextField) node("queryTableField"))::getText));
+ }
+
@Test
void exportsQueryAsTable() throws Exception {
dialog = FxTestSupport.call(() -> {
diff --git a/src/test/java/com/github/sqljam/face/view/MainViewTest.java b/src/test/java/com/github/sqljam/face/view/MainViewTest.java
index b2d43e8..c2381c8 100644
--- a/src/test/java/com/github/sqljam/face/view/MainViewTest.java
+++ b/src/test/java/com/github/sqljam/face/view/MainViewTest.java
@@ -691,6 +691,13 @@ void offersActionsInMenus() {
assertTrue(shortcuts.stream().anyMatch(row -> row[0].equals("Transfer > Export...")), shortcuts.stream().map(
row -> row[0]).collect(Collectors.joining(", ")));
assertTrue(shortcuts.stream().anyMatch(row -> row[0].equals("Database > Refresh")));
+ // Keys of the editors and tables, which have no menu item, and the key of this list
+ for (String action : new String[]{"SQL editor > Run", "SQL editor > Run All",
+ "SQL editor > Complete names of tables and columns", "Data table > Copy the selected rows",
+ "Data table > Show the whole value of a cell", "Help > Keyboard Shortcuts"}) {
+ assertTrue(shortcuts.stream().anyMatch(row -> row[0].equals(action)), action);
+ }
+ assertTrue(shortcuts.stream().noneMatch(row -> row[1] == null || row[1].isEmpty()));
FxTestSupport.run(FxTestSupport.menuItem(mainView, "help-shortcuts-menu")::fire);
javafx.scene.control.DialogPane pane = FxTestSupport.waitForDialogPane();
assertEquals(shortcuts.size(), FxTestSupport.call(() -> ((javafx.scene.control.TableView>) pane.lookup(
diff --git a/src/test/java/com/github/sqljam/face/view/SqlCompletionTest.java b/src/test/java/com/github/sqljam/face/view/SqlCompletionTest.java
new file mode 100644
index 0000000..edcd89e
--- /dev/null
+++ b/src/test/java/com/github/sqljam/face/view/SqlCompletionTest.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright 2023-2026 Fred Feng
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.sqljam.face.view;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.testfx.framework.junit5.ApplicationExtension;
+import org.testfx.framework.junit5.Start;
+
+import javafx.scene.Scene;
+import javafx.scene.layout.StackPane;
+import javafx.stage.Stage;
+
+/**
+ * @Description: SqlCompletionTest verifies the completion of SQL editors: the word and the name before the dot at
+ * the caret, aliases and names of tables of a statement (quoted, qualified, with AS), the
+ * suggestions of columns, tables and keywords, names quoted when they are no identifiers, and the
+ * names of a source read once until the completion is reset
+ * @Author: Fred Feng
+ * @Date: 07/11/2026
+ * @Version 1.0.0
+ */
+@ExtendWith(ApplicationExtension.class)
+class SqlCompletionTest {
+
+ private SqlEditor editor;
+
+ @Start
+ void start(Stage stage) {
+ editor = new SqlEditor();
+ stage.setScene(new Scene(new StackPane(editor.getNode()), 400, 300));
+ stage.show();
+ }
+
+ @Test
+ void readsTheWordAtTheCaret() {
+ SqlCompletion.Context context = SqlCompletion.contextAt("SELECT o.na FROM orders o", 11);
+ assertEquals("na", context.prefix);
+ assertEquals("o", context.qualifier);
+ assertEquals(9, context.start);
+ context = SqlCompletion.contextAt("SELECT \"my orders\".", 19);
+ assertEquals("", context.prefix);
+ assertEquals("my orders", context.qualifier);
+ context = SqlCompletion.contextAt("SELECT ", 7);
+ assertEquals("", context.prefix);
+ assertNull(context.qualifier);
+ context = SqlCompletion.contextAt(".x", 2);
+ assertNull(context.qualifier);
+ assertEquals("ab", SqlCompletion.contextAt("ab", 99).prefix);
+ }
+
+ @Test
+ void findsTablesAndAliases() {
+ Map aliases = SqlCompletion.aliases("SELECT * FROM shop.orders o JOIN \"Line Items\" AS"
+ + " li ON o.id = li.order_id LEFT JOIN `logs-2024` WHERE x = 1");
+ assertEquals("orders", aliases.get("o"));
+ assertEquals("orders", aliases.get("orders"));
+ assertEquals("Line Items", aliases.get("li"));
+ assertEquals("Line Items", aliases.get("line items"));
+ assertEquals("logs-2024", aliases.get("logs-2024"));
+ assertNull(aliases.get("where"));
+ assertTrue(SqlCompletion.aliases(null).isEmpty());
+ assertEquals(List.of("NAME"), SqlCompletion.filter(List.of("ID", "NAME", "note", "na"), "na"));
+ assertEquals("orders", SqlCompletion.quoteIfNeeded("orders"));
+ assertEquals("\"logs-2024\"", SqlCompletion.quoteIfNeeded("logs-2024"));
+ assertEquals("\"a\"\"b\"", SqlCompletion.quoteIfNeeded("a\"b"));
+ }
+
+ @Test
+ void suggestsColumnsTablesAndKeywordsOnce() throws Exception {
+ AtomicInteger tableReads = new AtomicInteger();
+ AtomicInteger columnReads = new AtomicInteger();
+ SqlCompletion completion = FxTestSupport.call(() -> SqlCompletion.attach(editor, new SqlCompletion.Source() {
+ @Override
+ public List tables() {
+ tableReads.incrementAndGet();
+ return List.of("orders", "order_items", "logs-2024");
+ }
+
+ @Override
+ public List columns(String table) {
+ columnReads.incrementAndGet();
+ if ("missing".equals(table)) {
+ throw new IllegalStateException("no such table");
+ }
+ return "orders".equals(table) ? List.of("id", "ordered_at", "total") : List.of("item");
+ }
+ }));
+ String sql = "SELECT * FROM orders o";
+ // Columns of the tables of the statement, then tables, then keywords
+ assertEquals(List.of("ordered_at", "orders", "order_items", "ORDER"), completion.suggest(
+ SqlCompletion.contextAt("SELECT ord", 10), sql));
+ assertEquals(List.of("id", "ordered_at", "total"), completion.suggest(SqlCompletion.contextAt("o.", 2),
+ sql));
+ assertEquals(List.of("total"), completion.suggest(SqlCompletion.contextAt("orders.t", 8), sql));
+ // A table which the source does not know has no columns
+ assertEquals(List.of(), completion.suggest(SqlCompletion.contextAt("m.", 2), "SELECT * FROM missing m"));
+ // Nothing typed: names only, no keywords
+ assertTrue(completion.suggest(SqlCompletion.contextAt("", 0), "SELECT 1").stream().noneMatch("SELECT"::equals));
+ assertEquals(1, tableReads.get());
+ assertEquals(2, columnReads.get());
+ completion.reset();
+ completion.suggest(SqlCompletion.contextAt("o.", 2), sql);
+ assertEquals(3, columnReads.get());
+
+ // Chosen names replace the word, names which are no identifiers are quoted
+ FxTestSupport.run(() -> {
+ editor.setText("SELECT * FROM log");
+ completion.insert(SqlCompletion.contextAt(editor.getText(), 17), "logs-2024");
+ });
+ assertEquals("SELECT * FROM \"logs-2024\"", FxTestSupport.call(editor::getText));
+ FxTestSupport.run(() -> {
+ editor.setText("sel");
+ completion.insert(SqlCompletion.contextAt(editor.getText(), 3), "SELECT");
+ });
+ assertEquals("SELECT", FxTestSupport.call(editor::getText));
+ }
+}
diff --git a/src/test/java/com/github/sqljam/face/view/SqlTabTest.java b/src/test/java/com/github/sqljam/face/view/SqlTabTest.java
index 0ed8cec..48e0a4e 100644
--- a/src/test/java/com/github/sqljam/face/view/SqlTabTest.java
+++ b/src/test/java/com/github/sqljam/face/view/SqlTabTest.java
@@ -344,4 +344,33 @@ void switchesBeforeFirstStatement() throws Exception {
FxTestSupport.waitUntil(() -> FxTestSupport.call(() -> results().getItems().size() == 1));
assertEquals("0", FxTestSupport.call(() -> results().getItems().get(0).get(0)));
}
+
+ /**
+ * Ctrl+Space lists the tables of the schema of the editor, a dot after an alias the columns of its table
+ */
+ @Test
+ void completesTablesAndColumns() {
+ open(schemaNode());
+ type("SELECT * FROM T_O", 17);
+ FxTestSupport.run(() -> tab.getEditor().getCodeArea().requestFocus());
+ FxTestSupport.run(() -> javafx.event.Event.fireEvent(tab.getEditor().getCodeArea(), new javafx.scene.input
+ .KeyEvent(javafx.scene.input.KeyEvent.KEY_PRESSED, " ", " ", javafx.scene.input.KeyCode.SPACE, false,
+ true, false, false)));
+ javafx.scene.control.ContextMenu menu = tab.getCompletion().getMenu();
+ FxTestSupport.waitUntil(() -> FxTestSupport.call(menu::isShowing));
+ List names = FxTestSupport.call(() -> menu.getItems().stream().map(item -> ((Label)
+ ((javafx.scene.control.CustomMenuItem) item).getContent()).getText()).toList());
+ assertTrue(names.contains("T_ONE"), names.toString());
+ FxTestSupport.run(() -> menu.getItems().stream().filter(item -> "T_ONE".equals(((Label)
+ ((javafx.scene.control.CustomMenuItem) item).getContent()).getText())).findFirst().orElseThrow()
+ .fire());
+ assertEquals("SELECT * FROM T_ONE", FxTestSupport.call(() -> tab.getEditor().getText()));
+
+ type("SELECT t. FROM T_ONE t", 9);
+ FxTestSupport.run(() -> tab.getCompletion().show());
+ FxTestSupport.waitUntil(() -> FxTestSupport.call(() -> menu.isShowing() && menu.getItems().stream()
+ .anyMatch(item -> "ID".equals(((Label) ((javafx.scene.control.CustomMenuItem) item).getContent())
+ .getText()))));
+ FxTestSupport.run(menu::hide);
+ }
}
diff --git a/src/test/java/com/github/sqljam/vdb/client/FakeServer.java b/src/test/java/com/github/sqljam/vdb/client/FakeServer.java
index 271e73a..4855ed9 100644
--- a/src/test/java/com/github/sqljam/vdb/client/FakeServer.java
+++ b/src/test/java/com/github/sqljam/vdb/client/FakeServer.java
@@ -35,15 +35,15 @@
* @Date: 24/10/2026
* @Version 1.0.0
*/
-final class FakeServer implements AutoCloseable {
+public final class FakeServer implements AutoCloseable {
/**
* A request: method, path with the query, body and the authorization header
*/
- static final class Request {
- final String target;
- final String body;
- final String authorization;
+ public static final class Request {
+ public final String target;
+ public final String body;
+ public final String authorization;
Request(String target, String body, String authorization) {
this.target = target;
@@ -55,9 +55,9 @@ static final class Request {
private final HttpServer server;
private final Map> routes = new LinkedHashMap<>();
private final Map statuses = new LinkedHashMap<>();
- final List requests = new ArrayList<>();
+ public final List requests = new ArrayList<>();
- FakeServer() throws IOException {
+ public FakeServer() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
String target = exchange.getRequestMethod() + " " + exchange.getRequestURI().toString();
@@ -83,28 +83,28 @@ static final class Request {
server.start();
}
- FakeServer route(String prefix, String response) {
+ public FakeServer route(String prefix, String response) {
return route(prefix, body -> response);
}
- FakeServer route(String prefix, int status, String response) {
+ public FakeServer route(String prefix, int status, String response) {
statuses.put(prefix, status);
return route(prefix, body -> response);
}
- FakeServer route(String prefix, Function response) {
+ public FakeServer route(String prefix, Function response) {
routes.put(prefix, response);
return this;
}
- String getUrl() {
+ public String getUrl() {
return "http://127.0.0.1:" + server.getAddress().getPort();
}
/**
* Requests whose method and path start with the prefix
*/
- List requests(String prefix) {
+ public List requests(String prefix) {
List matched = new ArrayList<>();
synchronized (requests) {
requests.stream().filter(request -> request.target.startsWith(prefix)).forEach(matched::add);
diff --git a/src/test/java/com/github/sqljam/vdb/client/VdbSqlClientTest.java b/src/test/java/com/github/sqljam/vdb/client/VdbSqlClientTest.java
new file mode 100644
index 0000000..0e171a9
--- /dev/null
+++ b/src/test/java/com/github/sqljam/vdb/client/VdbSqlClientTest.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright 2023-2026 Fred Feng
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.github.sqljam.vdb.client;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.github.sqljam.utils.RestClient;
+import com.github.sqljam.vdb.VdbClient;
+import com.github.sqljam.vdb.VdbException;
+import com.github.sqljam.vdb.VdbSqlResult;
+import com.github.sqljam.vdb.VdbType;
+
+/**
+ * @Description: VdbSqlClientTest verifies the SQL of Elasticsearch (columns, rows) and OpenSearch (schema,
+ * datarows) on fake servers: the first page and the next pages of a cursor, the close of a cursor
+ * which the server refuses, the reasons of errors, values of JSON, and servers without SQL
+ * @Author: Fred Feng
+ * @Date: 07/11/2026
+ * @Version 1.0.0
+ */
+class VdbSqlClientTest {
+
+ @Test
+ void readsPagesOfElasticsearch() throws Exception {
+ try (FakeServer server = new FakeServer()) {
+ server.route("POST /_sql?format=json", body -> body.contains("\"cursor\"")
+ ? "{\"rows\": [[\"b\", 2, false]]}"
+ : "{\"columns\": [{\"name\": \"name\", \"type\": \"keyword\"}, {\"name\": \"n\", \"type\":"
+ + " \"long\"}, {\"name\": \"ok\", \"type\": \"boolean\"}], \"rows\": [[\"a\", 1, true]],"
+ + " \"cursor\": \"c1\"}")
+ .route("POST /_sql/close", 404, "{\"error\": \"gone\"}");
+ try (VdbClient client = VdbType.ELASTICSEARCH.createClient(VdbClientsTest.source(VdbType.ELASTICSEARCH,
+ server))) {
+ assertTrue(client.isSqlSupported());
+ VdbSqlResult first = client.querySql("SELECT * FROM docs", 1);
+ assertEquals("name", first.getColumns().get(0)[0]);
+ assertEquals("long", first.getColumns().get(1)[1]);
+ assertEquals(List.of(Arrays.asList("a", 1L, true)), first.getRows());
+ assertTrue(first.hasMore());
+ assertTrue(server.requests("POST /_sql").get(0).body.contains("\"fetch_size\":1"));
+ VdbSqlResult next = client.nextSqlPage(first.getCursor());
+ assertFalse(next.hasMore());
+ assertTrue(next.getColumns().isEmpty());
+ assertEquals(List.of(Arrays.asList("b", 2L, false)), next.getRows());
+ // A refused close is fine, an empty cursor is not sent
+ client.closeSqlCursor("c1");
+ client.closeSqlCursor("");
+ assertEquals(1, server.requests("POST /_sql/close").size());
+ }
+ }
+ }
+
+ @Test
+ void readsPagesOfOpenSearch() throws Exception {
+ try (FakeServer server = new FakeServer()) {
+ server.route("POST /_plugins/_sql", "{\"schema\": [{\"name\": \"id\", \"type\": \"integer\"},"
+ + " {\"name\": \"embedding\", \"type\": \"nested\"}], \"datarows\": [[1, [0.5, -1]]],"
+ + " \"total\": 1, \"size\": 1, \"status\": 200}")
+ .route("POST /_plugins/_sql/close", "{\"succeeded\": true}");
+ try (VdbClient client = VdbType.OPENSEARCH.createClient(VdbClientsTest.source(VdbType.OPENSEARCH,
+ server))) {
+ VdbSqlResult result = client.querySql("SELECT * FROM docs", 0);
+ assertEquals("embedding", result.getColumns().get(1)[0]);
+ assertEquals(List.of(Arrays.asList(1L, "[0.5,-1]")), result.getRows());
+ assertFalse(result.hasMore());
+ assertFalse(server.requests("POST /_plugins/_sql").get(0).body.contains("fetch_size"));
+ client.closeSqlCursor("c2");
+ assertEquals(1, server.requests("POST /_plugins/_sql/close").size());
+ }
+ }
+ }
+
+ @Test
+ void tellsReasonsOfErrors() throws Exception {
+ try (FakeServer server = new FakeServer()) {
+ server.route("POST /_sql", 400, "{\"error\": {\"root_cause\": [{\"type\": \"parsing_exception\","
+ + " \"reason\": \"line 1:1: mismatched input \\\"SELEC\\\"\"}], \"type\": \"parsing_exception\"}}");
+ try (VdbClient client = VdbType.ELASTICSEARCH.createClient(VdbClientsTest.source(VdbType.ELASTICSEARCH,
+ server))) {
+ VdbException e = assertThrows(VdbException.class, () -> client.querySql("SELEC x", 10));
+ assertEquals("line 1:1: mismatched input \"SELEC\"", e.getMessage());
+ }
+ }
+ assertEquals("plain message", ElasticsearchClient.sqlError("plain message"));
+ assertNull(ElasticsearchClient.sqlError(null));
+ }
+
+ @Test
+ void readsValuesOfJson() throws Exception {
+ JsonNode values = RestClient.getMapper().readTree("[\"t\", 9223372036854775807, 18446744073709551615,"
+ + " 1.25, false, null, {\"a\": 1}]");
+ assertEquals("t", ElasticsearchClient.sqlValue(values.get(0)));
+ assertEquals(Long.MAX_VALUE, ElasticsearchClient.sqlValue(values.get(1)));
+ assertEquals(new BigInteger("18446744073709551615"), ElasticsearchClient.sqlValue(values.get(2)));
+ assertEquals(new BigDecimal("1.25"), ElasticsearchClient.sqlValue(values.get(3)));
+ assertEquals(Boolean.FALSE, ElasticsearchClient.sqlValue(values.get(4)));
+ assertNull(ElasticsearchClient.sqlValue(values.get(5)));
+ assertEquals("{\"a\":1}", ElasticsearchClient.sqlValue(values.get(6)));
+ assertNull(ElasticsearchClient.sqlValue(null));
+ }
+
+ @Test
+ void otherServersRunNoSql() throws Exception {
+ try (FakeServer server = new FakeServer();
+ VdbClient client = VdbType.QDRANT.createClient(VdbClientsTest.source(VdbType.QDRANT, server))) {
+ assertFalse(client.isSqlSupported());
+ assertThrows(VdbException.class, () -> client.querySql("SELECT 1", 10));
+ assertThrows(VdbException.class, () -> client.nextSqlPage("c"));
+ client.closeSqlCursor("c");
+ }
+ }
+}
diff --git a/src/test/resources/it-vdb-local.properties b/src/test/resources/it-vdb-local.properties
new file mode 100644
index 0000000..d2051b7
--- /dev/null
+++ b/src/test/resources/it-vdb-local.properties
@@ -0,0 +1,6 @@
+# Vector databases of the local environment (mvn verify -Dit.env=local): Docker containers of the developer
+# machine. A system property of the same name overrides a key. The others are skipped.
+
+elasticsearch.url=http://localhost:9200
+
+opensearch.url=http://localhost:19200