From eedc3d4799440401070fb7463d74f966586623d3 Mon Sep 17 00:00:00 2001 From: Fred Feng Date: Sun, 1 Nov 2026 13:24:09 +1100 Subject: [PATCH] feat: Excel import and export, CSV and Excel classes in impexp.fs, Utils classes in utils --- README.md | 31 +- docs/blogger/sqljam-en.md | 17 +- docs/blogger/sqljam-medium.md | 13 +- docs/blogger/sqljam-zh.md | 17 +- docs/developer-guide.md | 35 +- docs/index.html | 19 +- pom.xml | 12 + .../sqljam/face/model/TransferRequest.java | 2 +- .../sqljam/face/service/DatabaseSession.java | 2 +- .../sqljam/face/service/TransferService.java | 74 +++- .../sqljam/face/vdb/VdbImportDialog.java | 1 - .../sqljam/face/view/CsvOptionsPane.java | 4 +- .../github/sqljam/face/view/ExportDialog.java | 23 +- .../sqljam/face/view/ImportPackageDialog.java | 11 +- .../sqljam/face/view/ImportParquetDialog.java | 91 +++- .../com/github/sqljam/face/view/MainView.java | 5 +- .../com/github/sqljam/face/view/SqlTab.java | 2 +- .../sqljam/impexp/AbstractFileImporter.java | 9 +- .../sqljam/impexp/DataFileExporter.java | 1 + .../sqljam/impexp/DataFileImporter.java | 2 + .../com/github/sqljam/impexp/DataFormat.java | 8 +- .../com/github/sqljam/impexp/DdlScripter.java | 1 + .../com/github/sqljam/impexp/Dialect.java | 3 +- .../github/sqljam/impexp/DuckDBWorkspace.java | 4 +- .../github/sqljam/impexp/ExportManifest.java | 7 +- .../com/github/sqljam/impexp/Exporter.java | 2 +- .../sqljam/impexp/ImportExportHandler.java | 3 +- .../sqljam/impexp/MetaDataOperations.java | 2 +- .../impexp/PooledConnectionFactory.java | 2 +- .../sqljam/impexp/ScriptExportHandler.java | 1 + .../github/sqljam/impexp/ScriptImporter.java | 6 +- .../github/sqljam/impexp/SqlScriptRunner.java | 2 +- .../db/ClickHouseMetaDataOperations.java | 2 +- .../impexp/db/Db2MetaDataOperations.java | 2 +- .../sqljam/impexp/db/DuckDBDialect.java | 1 - .../impexp/db/DuckDBMetaDataOperations.java | 2 +- .../impexp/db/H2MetaDataOperations.java | 2 +- .../impexp/db/MariaDBMetaDataOperations.java | 2 +- .../impexp/db/MySQLMetaDataOperations.java | 2 +- .../impexp/db/OracleMetaDataOperations.java | 2 +- .../sqljam/impexp/db/PostgreSQLDialect.java | 1 - .../db/PostgreSQLMetaDataOperations.java | 2 +- .../db/SQLServerMetaDataOperations.java | 2 +- .../impexp/db/SQLiteMetaDataOperations.java | 2 +- .../sqljam/impexp/{ => fs}/CsvExporter.java | 6 +- .../sqljam/impexp/{ => fs}/CsvImporter.java | 7 +- .../sqljam/impexp/{ => fs}/CsvOptions.java | 3 +- .../sqljam/impexp/{ => fs}/CsvSplitter.java | 3 +- .../sqljam/impexp/fs/ExcelExporter.java | 118 +++++ .../sqljam/impexp/fs/ExcelImporter.java | 123 ++++++ .../github/sqljam/jdbc/ConnectionFactory.java | 1 + .../github/sqljam/jdbc/ManualTransaction.java | 1 + .../sqljam/jdbc/SimpleConnectionFactory.java | 1 + .../sqljam/page/MapBasedPageReader.java | 2 +- .../com/github/sqljam/utils/ExcelUtils.java | 417 ++++++++++++++++++ .../sqljam/{jdbc => utils}/JdbcUtils.java | 7 +- .../{impexp => utils}/SqlTextUtils.java | 2 +- .../github/sqljam/face/messages.properties | 24 +- .../face/service/TransferServiceTest.java | 2 +- .../sqljam/face/view/DocScreenshots.java | 2 - .../sqljam/face/view/ExportDialogTest.java | 19 + .../face/view/ImportPackageDialogTest.java | 7 +- .../face/view/ImportParquetDialogTest.java | 64 ++- .../github/sqljam/face/view/MainViewTest.java | 6 +- .../sqljam/face/view/ReportBoundaryTest.java | 4 +- .../sqljam/impexp/DataFileBoundaryTest.java | 3 + .../github/sqljam/impexp/QueryExportTest.java | 1 + .../impexp/{ => fs}/CsvSplitterTest.java | 2 +- .../sqljam/impexp/fs/ExcelPackageTest.java | 247 +++++++++++ .../github/sqljam/it/AbstractParquetIT.java | 45 +- .../java/com/github/sqljam/it/ItDatabase.java | 2 +- .../com/github/sqljam/it/ManualCommitIT.java | 2 +- .../com/github/sqljam/it/PartitionIT.java | 2 +- .../com/github/sqljam/it/QueryExportIT.java | 2 +- .../github/sqljam/it/TransferBenchmark.java | 2 +- .../java/com/github/sqljam/it/UpsertIT.java | 2 +- .../java/com/github/sqljam/it/VectorIT.java | 2 +- .../github/sqljam/utils/ExcelUtilsTest.java | 118 +++++ .../sqljam/{jdbc => utils}/JdbcUtilsTest.java | 4 +- .../{impexp => utils}/SqlTextUtilsTest.java | 2 +- 80 files changed, 1532 insertions(+), 157 deletions(-) rename src/main/java/com/github/sqljam/impexp/{ => fs}/CsvExporter.java (94%) rename src/main/java/com/github/sqljam/impexp/{ => fs}/CsvImporter.java (91%) rename src/main/java/com/github/sqljam/impexp/{ => fs}/CsvOptions.java (98%) rename src/main/java/com/github/sqljam/impexp/{ => fs}/CsvSplitter.java (99%) create mode 100644 src/main/java/com/github/sqljam/impexp/fs/ExcelExporter.java create mode 100644 src/main/java/com/github/sqljam/impexp/fs/ExcelImporter.java create mode 100644 src/main/java/com/github/sqljam/utils/ExcelUtils.java rename src/main/java/com/github/sqljam/{jdbc => utils}/JdbcUtils.java (99%) rename src/main/java/com/github/sqljam/{impexp => utils}/SqlTextUtils.java (98%) rename src/test/java/com/github/sqljam/impexp/{ => fs}/CsvSplitterTest.java (99%) create mode 100644 src/test/java/com/github/sqljam/impexp/fs/ExcelPackageTest.java create mode 100644 src/test/java/com/github/sqljam/utils/ExcelUtilsTest.java rename src/test/java/com/github/sqljam/{jdbc => utils}/JdbcUtilsTest.java (99%) rename src/test/java/com/github/sqljam/{impexp => utils}/SqlTextUtilsTest.java (98%) diff --git a/README.md b/README.md index fcd7c27..c350ac6 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ **Move tables across databases. Schema, data and all.** SqlJam is a desktop import/export tool for relational and OLAP databases: MySQL, MariaDB, PostgreSQL, Oracle, SQL Server, Db2, H2, SQLite, Microsoft Access, DuckDB, ClickHouse and more. -It copies tables (with indexes, constraints, sequences and partitions) **directly into another database** or into the same schema as copies, or saves them as a **self-describing export package** of SQL, **Parquet** or **CSV** files that can be imported later. Imports into a database run in **one transaction** which an error rolls back as a whole, and rows are **inserted, updated or skipped by key**. +It copies tables (with indexes, constraints, sequences and partitions) **directly into another database** or into the same schema as copies, or saves them as a **self-describing export package** of SQL, **Parquet**, **CSV** or **Excel** files that can be imported later. Imports into a database run in **one transaction** which an error rolls back as a whole, and rows are **inserted, updated or skipped by key**. ![Java](https://img.shields.io/badge/Java-17-ED8B00?logo=openjdk&logoColor=white) ![JavaFX](https://img.shields.io/badge/JavaFX-17-1f6feb) @@ -35,16 +35,17 @@ It copies tables (with indexes, constraints, sequences and partitions) **directl | Long jobs are a black box | **Percentage progress**, per-table progress, error log and cancel in the UI | | Analytics teams want Parquet, not SQL | **Parquet packages** (ZSTD, Snappy, GZIP) through an embedded DuckDB, and **Parquet files of other tools** loaded into any table | | Spreadsheets and text tools want CSV | **CSV packages** with your delimiter, quote, NULL text, header, encoding (UTF-8 with BOM for Excel, GBK and more) and date format, read back with the exact column types kept in `manifest.json`, and **CSV files of other tools** with detected delimiter and types | +| Business teams work in Excel | **Excel packages**: one `.xlsx` workbook for each table, numbers, dates and booleans as real cells, read back exactly with the column types kept in `manifest.json`. **Excel workbooks of other tools** need no `manifest.json`: choose a sheet, its first row names the columns and the types are detected | | An import went wrong, now what? | **One transaction** by default: an error rolls back the whole import, or **commit every N rows** like other import tools. **Skip rows with errors** goes on and lists every skipped row in the log, which you can filter and save. **Confirm before commit** lets you review a successful import in one transaction, then **Commit** or **Roll Back** | | Did every row arrive, and what happened when it stopped? | A **migration report** for every import and export, successful, failed, cancelled or rolled back: source, target and options, each table with its source rows, written and skipped rows, the rows counted in the target afterwards and a ✓ or ✗ against the written rows, the objects which were created, every skipped row with its error, where the transfer stopped and the error which ended it. It opens on its own page with **View Report**, and **Transfer → Import History** lists every report. Export one as Markdown, HTML or JSON | | A copy has to stay up to date | **Sync Tasks** copy the rows which changed since the last run into another database, found by a column of the update time or an increasing key, every N minutes or every day at a time. The first run copies all rows, the watermark moves on only after the commit, errors of the connection are run again and errors of the data are not. SqlJam runs the tasks while it is open. To run them when it is closed, **Copy Command** gives the command line of a task for the scheduler of your system, SqlJam itself never changes it. Collections of vector databases sync the same way, and every run leaves a migration report | | Some rows exist already | **Update or insert by key** updates the rows of the same primary key, or of the columns you choose, and inserts the others. **Skip existing by key** keeps them and inserts the new rows only. Insert is the default | | Warehouses live apart from OLTP databases | **DuckDB and ClickHouse data sources**, grouped as OLAP databases next to the relational ones | -| The rows come from a join or a report, not from one table | **SQL Query** editor with syntax highlighting: run the SQL, check the first rows, then export all rows of the query as a table into SQL, Parquet, CSV or another database | +| The rows come from a join or a report, not from one table | **SQL Query** editor with syntax highlighting: run the SQL, check the first rows, then export all rows of the query as a table into SQL, Parquet, CSV, Excel or another database | | Only part of a table is needed | **Data viewer query**: columns, WHERE, GROUP BY and ORDER BY, then export the rows of the query. Missing target tables are created with the selected columns | | Target columns are named or typed differently | **Map Columns…** renames a column, gives it a type of the target or leaves it out, for tables and for the fields of vector database collections. Keys, indexes and foreign keys follow the new names. Columns which are not changed are imported as they are | | A copy next to the original | **Copy in the same schema** with a table name such as `{table}_copy`. Keys, indexes and constraints get their own names and the source tables are protected | -| What is inside this package? | **Package viewer**: files with size and modified time, previews of manifest, SQL, LOB, Parquet and CSV files | +| What is inside this package? | **Package viewer**: files with size and modified time, previews of manifest, SQL, LOB, Parquet, CSV and Excel files | | 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 | @@ -68,9 +69,9 @@ flowchart LR D --> DS[DdlScripter] DS --> I[ImportExporter] --> TD[(Target DB)] DS --> E[ScriptExporter] --> P[/Export package
schema.sql · data*.sql · lob/ · manifest.json/] - DS --> PE[ParquetExporter · CsvExporter
DuckDB workspace] --> PP[/Parquet or CSV package
schema.sql · data/*.parquet or *.csv · manifest.json/] + DS --> PE[ParquetExporter · CsvExporter · ExcelExporter
DuckDB workspace] --> PP[/Parquet, CSV or Excel package
schema.sql · data/*.parquet, *.csv or *.xlsx · manifest.json/] P --> SI[ScriptImporter] --> TD - PP --> PI[ParquetImporter · CsvImporter] --> TD + PP --> PI[ParquetImporter · CsvImporter · ExcelImporter] --> TD VS[(Vector DB
Milvus · Qdrant · Weaviate · Pinecone
Elasticsearch · OpenSearch · Chroma)] --> VC[VdbClient
REST API] VC --> VT[Collection tree
collection · field · key · vector index] VT --> VV[VdbMetaDataVisitor] --> VD[Vdb dialect
target with vectors] --> VI[VdbImportHandler] --> TD @@ -83,6 +84,7 @@ flowchart LR | `ScriptImporter` | Imports an export package (validates `manifest.json`, runs files in order, restores LOBs) | | `ParquetExporter` / `ParquetImporter` | Parquet packages and Parquet files of other tools, written and read by an embedded DuckDB workspace | | `CsvExporter` / `CsvImporter` | CSV packages (column types in `manifest.json`) and CSV files of other tools, through the same DuckDB workspace | +| `ExcelExporter` / `ExcelImporter` | Excel packages (column types in `manifest.json`) and Excel workbooks of other tools, a sheet is read through the same DuckDB workspace | | `ManualTransaction` | Runs an import in one transaction which the user commits or rolls back. DDL which would commit the rows (MySQL, MariaDB, Oracle, H2) waits for the commit | | `AbstractFileImporter` | Picks the importer of a package by the data format in its `manifest.json` | | `TableQuery` | Columns, WHERE, GROUP BY and ORDER BY of the data viewer, used by exports per table | @@ -167,7 +169,7 @@ SqlJam starts with a splash screen while it loads the configuration, the data so 1. SqlJam opens its main window with the data sources in the tree, where it was closed, and connects again the data sources which were connected then. Expand a data source to connect it. **+** on the toolbar creates one: choose its category first (relational, OLAP or vector databases), the types and the fields follow it. **Connect through SSH tunnel** reaches a database behind a bastion host. A password which is not saved is asked when the data source is connected, and asked again when the database refuses it. The first start brings an **Example Shop (H2)** data source with a few e-commerce tables to try everything right away. **Help → Restore Example Database** brings it back at any time. 2. Right-click a database or schema → **Export…** -3. Pick tables, choose **SQL scripts**, **Parquet** or **CSV** (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. +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. @@ -220,7 +222,7 @@ export/ └── manifest.json # source, target, options, files (sha256), row counts ``` -A Parquet package has the same layout with `data/.parquet` instead of SQL data and LOB files, a CSV package with `data/
.csv` and a header row. LOB values stay inside the Parquet or CSV columns, `manifest.json` records `"dataFormat": "PARQUET"` or `"CSV"` (with the type of every CSV column), so an import picks the right importer by itself and reads the values back exactly. +A Parquet package has the same layout with `data/
.parquet` instead of SQL data and LOB files, a CSV package with `data/
.csv` and a header row, an Excel package with `data/
.xlsx` (one sheet with a header row, `
_2.xlsx` above 1,048,575 rows). LOB values stay inside the Parquet, CSV or Excel columns, `manifest.json` records `"dataFormat": "PARQUET"`, `"CSV"` or `"EXCEL"` (with the type of every CSV and Excel column), so an import picks the right importer by itself and reads the values back exactly. --- @@ -256,6 +258,10 @@ CsvExporter csv = new CsvExporter(new File("export-csv")); csv.setDelimiter(";"); csv.setMaxFileSize(10 * 1024 * 1024); csv.exportDdlAndData(); + +// The same tables as an Excel package: data/orders.xlsx, one sheet with a header row +ExcelExporter excel = new ExcelExporter(new File("export-excel")); +excel.exportDdlAndData(); ``` **Output**: `export/schema.sql`, `export/data/orders.sql`, `export/data/orders_2.sql`, `export/lob/…`, `export/manifest.json`: @@ -337,7 +343,7 @@ try (Connection connection = DriverManager.getConnection( } ``` -**Output**: `ScriptImporter` refuses packages whose status is not `COMPLETED`, whose target type differs, or whose files fail the SHA-256 check. `AbstractFileImporter.forDirectory(dir, connection, dbType)` returns the importer of the package (SQL, Parquet or CSV), and files of other tools are loaded by `ParquetImporter` or `CsvImporter`. A `ManualTransaction` keeps the import open until you commit or roll back: +**Output**: `ScriptImporter` refuses packages whose status is not `COMPLETED`, whose target type differs, or whose files fail the SHA-256 check. `AbstractFileImporter.forDirectory(dir, connection, dbType)` returns the importer of the package (SQL, Parquet, CSV or Excel), and files of other tools are loaded by `ParquetImporter`, `CsvImporter` or `ExcelImporter` (`setSheet` picks a sheet, the first one by default). A `ManualTransaction` keeps the import open until you commit or roll back: ```java ParquetImporter importer = new ParquetImporter(connection, DbType.POSTGRESQL); @@ -384,6 +390,7 @@ try (ManualTransaction transaction = new ManualTransaction(connection, DbType.PO | Import packages with SqlJam | Manifest validation, ordered files, LOB restore and FKs last | | Use **Parquet** for analytics and lakes | Compact columnar files any engine reads, the schema still travels in `schema.sql` | | Use **CSV** for spreadsheets and text tools | Opens anywhere, and SqlJam still restores the exact types from `manifest.json` | +| Use **Excel** for business teams | Real number and date cells with a frozen header row, and the exact types still come back from `manifest.json` | | Keep **one transaction** for imports | An error rolls back everything, **Confirm before commit** shows the log and the row counts before the commit | | Load again with **Update or insert by key** | Kept tables are updated by their primary keys, nothing is dropped | | Shape a report in **SQL Query** first | The first rows show the columns and values, **Export…** then reads all rows by one cursor | @@ -490,7 +497,7 @@ Export options (UI / `ExportConfiguration`): | `indexIncluded` / `foreignKeyIncluded` / `commentIncluded` / `sequenceIncluded` | `true` | Objects to copy | | `failFast` | `true` | Stop on the first data error, `false` skips the rows with errors and reports each of them | | `identifierCase` | `AUTO` | `AUTO`, `KEEP`, `LOWER`, `UPPER` | -| `dataFormat` / `compression` | `SQL` / `ZSTD` | `SQL`, `PARQUET` or `CSV` packages, Parquet compression `ZSTD`, `SNAPPY`, `GZIP`, `UNCOMPRESSED` | +| `dataFormat` / `compression` | `SQL` / `ZSTD` | `SQL`, `PARQUET`, `CSV` or `EXCEL` packages, Parquet compression `ZSTD`, `SNAPPY`, `GZIP`, `UNCOMPRESSED` | | `csvDelimiter` | `,` | Delimiter of CSV packages | | `writeMode` / `keyColumnNames` | `INSERT` | `UPSERT` updates the rows of the same key (the primary key or chosen columns) and inserts the others, `SKIP_EXISTING` keeps them and inserts the others | | `CsvOptions` | comma, `"`, UTF-8 | Delimiter, quote, NULL text, header, encoding and date format of CSV files | @@ -527,7 +534,7 @@ Environment: Apple M2 Max, 32 GB, JDK 17. The databases run in Docker on a serve |---|---| | Rows paged by primary key | Stable, deterministic reads on every database | | Tables copied one by one | Predictable load on production servers | -| Packages contain plain SQL, Parquet or CSV | Readable, editable and portable, or columnar for analytics | +| Packages contain plain SQL, Parquet, CSV or Excel | Readable, editable and portable, or columnar for analytics | | Writes sized for each database | Batched inserts, rewritten into multi-row statements for PostgreSQL and MySQL, several rows a statement for DuckDB, with the same value conversions everywhere | | Inserts of a SQL package merged on import | The package stays one readable row a line, the database receives up to 100 rows a statement | @@ -541,7 +548,7 @@ Environment: Apple M2 Max, 32 GB, JDK 17. The databases run in Docker on a serve | Blog | [docs/blogger/sqljam-en.md](docs/blogger/sqljam-en.md) | | Developer guide | [docs/developer-guide.md](docs/developer-guide.md), the Java API for exports, imports, copies and queries | | Change logs | [change_logs](change_logs) | -| Core API | `com.github.sqljam.impexp` (`Exporter`, `ScriptExporter`, `ImportExporter`, `ScriptImporter`, `ParquetExporter`, `ParquetImporter`, `CsvExporter`, `CsvImporter`, `ManualTransaction`) | +| Core API | `com.github.sqljam.impexp` (`Exporter`, `ScriptExporter`, `ImportExporter`, `ScriptImporter`, `ParquetExporter`, `ParquetImporter`, `ManualTransaction`) and `com.github.sqljam.impexp.fs` (`CsvExporter`, `CsvImporter`, `ExcelExporter`, `ExcelImporter`) | **FAQ** @@ -552,6 +559,8 @@ 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` | +| 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 | | Why does Db2 refuse a wide table? | Rows wider than a 4K page need a table space of larger pages. Create one once, e.g. `CREATE BUFFERPOOL BP32K PAGESIZE 32K` and `CREATE TABLESPACE TS32K PAGESIZE 32K BUFFERPOOL BP32K`, Db2 then places wide tables there by itself | | Do names have to match in case? | No. An existing target table and its columns are matched without case, e.g. `OrderId` of the source writes the column `orderid` of PostgreSQL or `ORDERID` of Oracle | diff --git a/docs/blogger/sqljam-en.md b/docs/blogger/sqljam-en.md index f19cec5..f691ef8 100644 --- a/docs/blogger/sqljam-en.md +++ b/docs/blogger/sqljam-en.md @@ -9,7 +9,7 @@ **SqlJam**: *Move tables across databases. Schema, data and all.* A Java 17 + JavaFX desktop tool that copies tables between relational and OLAP databases (**MySQL, MariaDB, PostgreSQL, Oracle, SQL Server, Db2, H2, SQLite, Microsoft Access, DuckDB, ClickHouse** and more) in any direction: -**import directly** into a target database or into the same schema as copies, or save a self-describing **export package** of SQL, **Parquet** or **CSV** files and import it later. Imports into a database run in **one transaction** which an error rolls back, and rows are **inserted, updated or skipped by key**. +**import directly** into a target database or into the same schema as copies, or save a self-describing **export package** of SQL, **Parquet**, **CSV** or **Excel** files and import it later. Imports into a database run in **one transaction** which an error rolls back, and rows are **inserted, updated or skipped by key**. ![SqlJam main window](https://raw.githubusercontent.com/paganini2008/sqljam/master/docs/assets/main-dark.png) @@ -29,6 +29,7 @@ SqlJam reads **one metadata tree** and generates SQL with a **dialect chosen by | Scripts without context | `manifest.json`: source, target, options, SHA-256 per file, row counts | | Analytics needs Parquet | Parquet packages through an embedded DuckDB, Parquet files of other tools loaded into any table | | Spreadsheets need CSV | CSV packages with your delimiter, quote, NULL text, header, encoding (UTF-8 with BOM, GBK and more) and date format, exact types kept in `manifest.json`, CSV files of other tools loaded too | +| Business teams use Excel | Excel packages with one `.xlsx` workbook for each table, real number and date cells, exact types kept in `manifest.json`, workbooks of other tools loaded without `manifest.json` from the sheet you choose | | An import went wrong | **One transaction** by default, rolled back on any error, or **commit every N rows**. **Skip rows with errors** goes on and logs each skipped row. **Confirm before commit** reviews a successful import first | | Did every row arrive? | A **migration report** for every import and export, also when it fails or is cancelled: rows per table, skipped rows with their errors, target rows counted afterwards, created objects and where it stopped. **Import History** lists every report, Markdown, HTML or JSON on export | | A copy has to stay up to date | **Sync Tasks** copy the changed rows by an update time or an increasing key, every N minutes or every day, run by SqlJam while it is open or by your own scheduler through its command line, vector collections included, a report for every run | @@ -77,7 +78,7 @@ 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 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, and **Export…** sends all rows of the query to SQL, Parquet, CSV, Excel or another database: ![SQL Query](https://raw.githubusercontent.com/paganini2008/sqljam/master/docs/assets/sql-editor.png) @@ -155,8 +156,8 @@ flowchart LR D --> I[Import directly] --> TD[(Target DB)] D --> E[Export package
schema.sql · data*.sql · lob/ · manifest.json] E --> SI[ScriptImporter] --> TD - D --> P[Parquet or CSV package
DuckDB workspace · data/*.parquet or *.csv] - P --> PI[ParquetImporter · CsvImporter] --> TD + D --> P[Parquet, CSV or Excel package
DuckDB workspace · data/*.parquet, *.csv or *.xlsx] + P --> PI[ParquetImporter · CsvImporter · ExcelImporter] --> TD V[(Vector DB)] --> VC[VdbClient · REST API] --> VT[Collection tree] --> VD[Vdb dialect] --> TD ``` @@ -164,6 +165,7 @@ flowchart LR - **Generate for the target**: `DbType.createDialect(major, minor)` picks the version subclass. - **Stream rows**: count rows (percentage progress) → page by primary key → normalize values → batch insert or SQL literals. - **Parquet and CSV**: rows pass an embedded DuckDB workspace, `COPY ... TO` writes them, `read_parquet` or `read_csv` with the column types of `manifest.json` loads them back. +- **Excel**: the same workspace writes one sheet for each table with a frozen header row. A sheet is read back as CSV, so a workbook of any spreadsheet loads like a CSV file of another tool. - **Transactions**: an import runs in one transaction, committed when it succeeds or after your confirmation. MySQL, MariaDB, Oracle and H2 commit around DDL, so keys and identity values are set after the commit. - **Upserts and skips**: `ON CONFLICT`, `ON DUPLICATE KEY UPDATE` or `MERGE` of each database, kept tables, indexes and keys are skipped. - **Skipped errors**: a failed page is written row by row under savepoints, each bad row is logged with its key and the others are kept. @@ -207,6 +209,9 @@ parquet.exportDdlAndData(); // schema.sql, data/orders.parquet, constraints.sq CsvExporter csv = new CsvExporter(new File("export-csv")); csv.setDelimiter(";"); csv.exportDdlAndData(); // data/orders.csv, data/orders_2.csv ... + +ExcelExporter excel = new ExcelExporter(new File("export-excel")); +excel.exportDdlAndData(); // data/orders.xlsx, one sheet with a header row ``` ### Example 2: Oracle → SQL Server directly (schema created) @@ -321,7 +326,7 @@ schtasks /Create /TN "SqlJam sync" /SC MINUTE /MO 15 /TR "C:\SqlJam\sqljam.bat s Environment: Apple M2 Max, 32 GB, JDK 17. The databases run in Docker on a server of the local network (about 100 Mbit/s), H2, DuckDB and the packages are local. Default settings. Each scenario is measured by `TransferBenchmark`. -**Quality**: a full cross-database import matrix with every column type of every database, SQL, Parquet and CSV package round trips, commit and roll back verified on every database, copies in the same schema, old-version SQL executed on real servers, UI and boundary tests. +**Quality**: a full cross-database import matrix with every column type of every database, SQL, Parquet, CSV and Excel package round trips, commit and roll back verified on every database, copies in the same schema, old-version SQL executed on real servers, UI and boundary tests. ## 9. Design Trade-offs @@ -346,7 +351,7 @@ Environment: Apple M2 Max, 32 GB, JDK 17. The databases run in Docker on a serve 6. Timestamps, unsigned numbers, bits, money, UUID and JSON survive the trip. 7. Pooled connections and batch inserts: 40k to 95k rows/s for direct imports. 8. A mainstream dark UI with 7 themes, percentage progress and cancel. -9. Parquet and CSV packages and files of other tools, DuckDB and ClickHouse as OLAP data sources, imports in one transaction and rows updated by key. +9. Parquet, CSV and Excel packages and files of other tools, DuckDB and ClickHouse as OLAP data sources, imports in one transaction and rows updated by key. 10. A SQL Query editor exports the rows of any query through the same exits, columns of tables keep their types. 11. Query the rows of a table, export just those rows, or copy tables inside the same schema. 12. Collections of Milvus, Qdrant, Weaviate, Pinecone, Elasticsearch, OpenSearch and Chroma go straight into a database with vectors, previewed by conditions, native filters or nearest neighbor searches. diff --git a/docs/blogger/sqljam-medium.md b/docs/blogger/sqljam-medium.md index 29ced3e..32cb23f 100644 --- a/docs/blogger/sqljam-medium.md +++ b/docs/blogger/sqljam-medium.md @@ -8,7 +8,7 @@ Tables, indexes, constraints, sequences, partitions and rows, in one go. ## Overview -**SqlJam** is a Java 17 + JavaFX desktop tool that copies tables between relational and OLAP databases (**MySQL, MariaDB, PostgreSQL, Oracle, SQL Server, Db2, H2, SQLite, Microsoft Access, DuckDB, ClickHouse** and more) in any direction. Import directly into a target database or into the same schema as copies, or save a self-describing **export package** of SQL, **Parquet** or **CSV** files and import it later. Imports into a database run in **one transaction** which an error rolls back, and rows are **inserted, updated or skipped by key**. +**SqlJam** is a Java 17 + JavaFX desktop tool that copies tables between relational and OLAP databases (**MySQL, MariaDB, PostgreSQL, Oracle, SQL Server, Db2, H2, SQLite, Microsoft Access, DuckDB, ClickHouse** and more) in any direction. Import directly into a target database or into the same schema as copies, or save a self-describing **export package** of SQL, **Parquet**, **CSV** or **Excel** files and import it later. Imports into a database run in **one transaction** which an error rolls back, and rows are **inserted, updated or skipped by key**. Source: https://github.com/paganini2008/sqljam @@ -26,6 +26,7 @@ SqlJam reads one metadata tree and generates SQL with a dialect chosen by target - **Scripts without context** → manifest.json with source, target, options, SHA-256 per file and row counts - **Analytics needs Parquet** → Parquet packages through an embedded DuckDB, Parquet files of other tools loaded into any table - **Spreadsheets need CSV** → CSV packages with your delimiter, quote, NULL text, header, encoding and date format, exact types kept in manifest.json, CSV files of other tools loaded too +- **Business teams use Excel** → Excel packages with one .xlsx workbook for each table, real number and date cells, exact types kept in manifest.json, workbooks of other tools loaded without manifest.json from the sheet you choose - **An import went wrong** → one transaction by default, rolled back on any error, or commit every N rows. Skip rows with errors goes on and logs each skipped row. Confirm before commit reviews a successful import first - **Did every row arrive?** → a migration report for every import and export, also when it fails or is cancelled: rows per table, skipped rows with their errors, target rows counted afterwards, created objects and where it stopped. Import History lists every report, Markdown, HTML or JSON on export - **A copy has to stay up to date** → Sync Tasks copy the changed rows by an update time or an increasing key, every N minutes or every day, run by SqlJam while it is open or by your own scheduler through its command line, vector collections included, a report for every run @@ -75,7 +76,7 @@ Step 4. narrow the rows of a table on the Data tab and export just those rows. R ![Data query](https://raw.githubusercontent.com/paganini2008/sqljam/master/docs/assets/table-data.png) -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 or another database: +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: ![SQL Query](https://raw.githubusercontent.com/paganini2008/sqljam/master/docs/assets/sql-editor.png) @@ -148,6 +149,7 @@ Vector databases (sources only): - **Generate for the target**: DbType.createDialect(major, minor) picks the version subclass. - **Stream rows**: count rows for percentage progress, page by primary key, normalize values, then batch insert or write SQL literals. - **Parquet and CSV**: rows pass an embedded DuckDB workspace, COPY TO writes the files, read_parquet or read_csv with the column types of manifest.json loads them back. +- **Excel**: the same workspace writes one sheet for each table with a frozen header row, a sheet is read back as CSV, so a workbook of any spreadsheet loads like a CSV file of another tool. - **Transactions**: an import runs in one transaction, committed when it succeeds or after your confirmation. MySQL, MariaDB, Oracle and H2 commit around DDL, so keys and identity values are set after the commit. - **Upserts and skips**: ON CONFLICT, ON DUPLICATE KEY UPDATE or MERGE of each database, kept tables, indexes and keys are skipped. - **Skipped errors**: a failed page is written row by row under savepoints, each bad row is logged with its key and the others are kept. @@ -194,6 +196,9 @@ parquet.exportDdlAndData(); CsvExporter csv = new CsvExporter(new File("export-csv")); csv.setDelimiter(";"); csv.exportDdlAndData(); // data/orders.csv, data/orders_2.csv ... + +ExcelExporter excel = new ExcelExporter(new File("export-excel")); +excel.exportDdlAndData(); // data/orders.xlsx, one sheet with a header row ``` ### Example 2: Oracle → SQL Server directly @@ -291,7 +296,7 @@ Sync tasks run without the window too. Copy Command in Transfer > Sync Tasks cop - SQL package → PostgreSQL: 10.1 s, 19.8k rows/s - Qdrant → PostgreSQL (20,000 points, 256-d vectors and payload): 18.3 s, 1.1k rows/s -Quality: a full cross-database import matrix with every column type of every database, SQL, Parquet and CSV package round trips, commit and roll back verified on every database, copies in the same schema, old-version SQL executed on real servers, UI and boundary tests. +Quality: a full cross-database import matrix with every column type of every database, SQL, Parquet, CSV and Excel package round trips, commit and roll back verified on every database, copies in the same schema, old-version SQL executed on real servers, UI and boundary tests. ## Design Trade-offs @@ -316,7 +321,7 @@ Quality: a full cross-database import matrix with every column type of every dat 6. Timestamps, unsigned numbers, bits, money, UUID and JSON survive the trip. 7. Pooled connections and batch inserts: 40k to 95k rows/s for direct imports. 8. A mainstream dark UI with 7 themes, percentage progress and cancel. -9. Parquet and CSV packages and files of other tools, DuckDB and ClickHouse as OLAP data sources, imports in one transaction and rows updated or skipped by key. +9. Parquet, CSV and Excel packages and files of other tools, DuckDB and ClickHouse as OLAP data sources, imports in one transaction and rows updated or skipped by key. 10. A SQL Query editor exports the rows of any query through the same exits, columns of tables keep their types. 11. Query the rows of a table, export just those rows, or copy tables inside the same schema. 12. Collections of Milvus, Qdrant, Weaviate, Pinecone, Elasticsearch, OpenSearch and Chroma go straight into a database with vectors, previewed by conditions, native filters or nearest neighbor searches. diff --git a/docs/blogger/sqljam-zh.md b/docs/blogger/sqljam-zh.md index 2e83fbd..9699876 100644 --- a/docs/blogger/sqljam-zh.md +++ b/docs/blogger/sqljam-zh.md @@ -9,7 +9,7 @@ **SqlJam**:*Move tables across databases. Schema, data and all.* 一个 Java 17 + JavaFX 的桌面导入导出工具,支持关系型与 OLAP 数据库(**MySQL、MariaDB、PostgreSQL、Oracle、SQL Server、Db2、H2、SQLite、Microsoft Access、DuckDB、ClickHouse** 等)任意互导: -可以**直接导入目标库**,也可以在同一个 schema 里复制表,或者导出为带描述文件的 **SQL / Parquet / CSV 导出包**,之后再成对导入。导入目标库默认在**一个事务**里完成,出错整体回滚,数据可以**按主键更新、插入或跳过**。 +可以**直接导入目标库**,也可以在同一个 schema 里复制表,或者导出为带描述文件的 **SQL / Parquet / CSV / Excel 导出包**,之后再成对导入。导入目标库默认在**一个事务**里完成,出错整体回滚,数据可以**按主键更新、插入或跳过**。 ![SqlJam 主界面](https://raw.githubusercontent.com/paganini2008/sqljam/master/docs/assets/main-dark.png) @@ -29,6 +29,7 @@ SqlJam 用**一棵元数据树 + 按目标库和版本选择的方言**,把这 | 脚本没有上下文 | `manifest.json`:源、目标、选项、文件 SHA-256、行数 | | 分析要 Parquet | 内置 DuckDB 生成 Parquet 导出包,也能把其他工具产出的 Parquet 文件加载进任意表 | | 表格工具要 CSV | CSV 导出包可选分隔符、引号、NULL 表示、表头、编码(Excel 用的 UTF-8 BOM、GBK 等)和日期格式,`manifest.json` 记录每列类型,导回时精确还原,也能加载其他工具的 CSV 文件 | +| 业务同事只用 Excel | Excel 导出包每张表一个 `.xlsx` 工作簿,数字、日期、布尔是真正的单元格,`manifest.json` 记录每列类型,导回时精确还原。其他工具的 Excel 文件不需要 `manifest.json`,选好工作表,第一行作为列名,类型自动识别 | | 导错了怎么办 | 默认**一个事务**:出错整体回滚,也可以**每 N 行提交一次**。勾选**跳过出错的行**则继续导入,每条跳过的记录都写进日志,可筛选、可保存。勾选**提交前确认**,导入成功后先看结果再 **Commit** 或 **Roll Back** | | 数据到底全过去了没有 | 每次导入导出都有**迁移报告**,成功、失败、取消或回滚都有:每张表的源行数、写入行数、跳过行数,结束后重新统计的目标行数和 ✓ / ✗ 核对结果,创建了哪些对象,每条跳过的行和原因,停在哪张表的第几行,以及中断的错误。**View Report** 单独一页打开,**Transfer → Import History** 列出全部历史报告,可导出 Markdown、HTML、JSON | | 副本要一直保持最新 | **Sync Tasks** 定时同步:按更新时间列或递增主键找出上次之后变化的行,每 N 分钟或每天定点运行。首次全量,提交成功后才移动水位,连接类错误自动重试,数据类错误不重试。SqlJam 打开时自动运行,关着时可以复制任务的命令行,自己填进 crontab 或 Windows 任务计划,SqlJam 不会改动系统。向量库集合同样可以同步,每次同步都有迁移报告 | @@ -77,7 +78,7 @@ bin/ 右键数据源选 **Connect**,连上之后同一个菜单变成 **Disconnect**,断开时它的表页签一起关闭。导入导出选目标数据源时,旁边的 **+** 按钮可以当场新建一个。工具栏最右边是 **Exit**。**Help → About SqlJam** 里有版本、主页、仓库地址和作者联系方式,右下角的 GitHub 图标点一下直接打开仓库。 -工具栏的 **SQL Query** 为选中的数据源打开查询器。**Ctrl+Enter**(macOS 上是 **⌘+Enter**)执行光标所在的语句,**Ctrl+Shift+Enter** 执行全部,**Export…** 把查询的全部结果导出为 SQL、Parquet、CSV 或导入另一个数据库: +工具栏的 **SQL Query** 为选中的数据源打开查询器。**Ctrl+Enter**(macOS 上是 **⌘+Enter**)执行光标所在的语句,**Ctrl+Shift+Enter** 执行全部,**Export…** 把查询的全部结果导出为 SQL、Parquet、CSV、Excel 或导入另一个数据库: ![SQL Query](https://raw.githubusercontent.com/paganini2008/sqljam/master/docs/assets/sql-editor.png) @@ -155,8 +156,8 @@ flowchart LR D --> I[直接导入] --> TD[(目标库)] D --> E[导出包
schema.sql · data*.sql · lob/ · manifest.json] E --> SI[ScriptImporter] --> TD - D --> P[Parquet / CSV 导出包
DuckDB 中转 · data/*.parquet 或 *.csv] - P --> PI[ParquetImporter · CsvImporter] --> TD + D --> P[Parquet / CSV / Excel 导出包
DuckDB 中转 · data/*.parquet、*.csv 或 *.xlsx] + P --> PI[ParquetImporter · CsvImporter · ExcelImporter] --> TD V[(向量数据库)] --> VC[VdbClient · REST API] --> VT[集合树] --> VD[Vdb 方言] --> TD ``` @@ -164,6 +165,7 @@ flowchart LR - **按目标生成 SQL**:`DbType.createDialect(major, minor)` 选出版本子类。 - **数据流**:先统计行数(百分比进度)→ 按主键分页读取 → 值归一化 → 批量写入或生成字面量。 - **Parquet 与 CSV**:数据经过内置的 DuckDB 中转,`COPY ... TO` 写出,`read_parquet` 或按 `manifest.json` 中列类型的 `read_csv` 读回。 +- **Excel**:同一个 DuckDB 中转,每张表写成一个带冻结表头的工作表。读回时工作表先转成 CSV,所以任何表格软件的工作簿都能像外部 CSV 文件一样加载。 - **事务**:导入在一个事务里完成,成功自动提交或经你确认后提交。MySQL、MariaDB、Oracle、H2 执行 DDL 会隐式提交,外键和自增值等语句延后到提交之后执行。 - **按主键更新或跳过**:使用各库的 `ON CONFLICT`、`ON DUPLICATE KEY UPDATE` 或 `MERGE`,已存在的表、索引、键自动跳过。 - **跳过出错的行**:出错的一页在 savepoint 保护下逐行重写,每条坏行连同主键和错误写进日志,其余行照常保留。 @@ -207,6 +209,9 @@ parquet.exportDdlAndData(); // schema.sql、data/orders.parquet、constraints. CsvExporter csv = new CsvExporter(new File("export-csv")); csv.setDelimiter(";"); csv.exportDdlAndData(); // data/orders.csv、data/orders_2.csv ... + +ExcelExporter excel = new ExcelExporter(new File("export-excel")); +excel.exportDdlAndData(); // data/orders.xlsx,一个带表头的工作表 ``` ### Example 2:Oracle 直接导入 SQL Server(自动建 schema) @@ -321,7 +326,7 @@ schtasks /Create /TN "SqlJam sync" /SC MINUTE /MO 15 /TR "C:\SqlJam\sqljam.bat s 环境:Apple M2 Max / 32 GB / JDK 17。数据库在局域网服务器的 Docker 中(约 100 Mbit/s),H2、DuckDB 和导出包在本机。默认配置。每个场景由 `TransferBenchmark` 测得。 -**质量**:覆盖每种数据库全部字段类型的跨库互导矩阵,SQL、Parquet、CSV 导出包回放,事务提交与回滚、按主键更新或插入在每种数据库上验证,同 schema 复制,旧版本语法在真实库上执行,界面功能与边界测试。 +**质量**:覆盖每种数据库全部字段类型的跨库互导矩阵,SQL、Parquet、CSV、Excel 导出包回放,事务提交与回滚、按主键更新或插入在每种数据库上验证,同 schema 复制,旧版本语法在真实库上执行,界面功能与边界测试。 ## 9. 设计取舍(Design Trade-offs) @@ -346,7 +351,7 @@ schtasks /Create /TN "SqlJam sync" /SC MINUTE /MO 15 /TR "C:\SqlJam\sqljam.bat s 6. 时间、无符号、bit、money、UUID、JSON 等值跨库不失真。 7. 连接池 + 批量写入,直接导入 4 万 ~ 9.5 万行/秒。 8. 暗色主流界面,7 种主题,百分比进度与取消。 -9. Parquet、CSV 导出包与外部文件加载,DuckDB、ClickHouse 作为 OLAP 数据源,导入默认一个事务、出错整体回滚,支持按主键更新或插入。 +9. Parquet、CSV、Excel 导出包与外部文件加载,DuckDB、ClickHouse 作为 OLAP 数据源,导入默认一个事务、出错整体回滚,支持按主键更新或插入。 10. SQL Query 查询器的任意查询结果都能走同样的导出出口,来自表的列保留原类型。 11. 表数据可查询,只导出查询结果,也能在同一 schema 内复制表。 12. Milvus、Qdrant、Weaviate、Pinecone、Elasticsearch、OpenSearch、Chroma 的集合直接导入支持向量的数据库,导入前可按条件、原生过滤或最近邻搜索预览。 diff --git a/docs/developer-guide.md b/docs/developer-guide.md index 5cd53ea..f314893 100644 --- a/docs/developer-guide.md +++ b/docs/developer-guide.md @@ -2,7 +2,7 @@ **Use the engine of SqlJam from your own Java code.** -The desktop application is a thin layer over the `com.github.sqljam.impexp` API. Every export, import and copy that the UI runs is a few lines of Java: configure a source, pick an exit, call `export`. This guide shows those lines for each task. +The desktop application is a thin layer over the `com.github.sqljam.impexp` API (CSV and Excel classes in `com.github.sqljam.impexp.fs`). Every export, import and copy that the UI runs is a few lines of Java: configure a source, pick an exit, call `export`. This guide shows those lines for each task. --- @@ -13,10 +13,10 @@ The desktop application is a thin layer over the `com.github.sqljam.impexp` API. | [Add SqlJam to a project](#add-sqljam-to-a-project) | Maven coordinates | | [Core classes](#core-classes) | Overview of the API | | [1. Export tables as a SQL package](#1-export-tables-as-a-sql-package) | `ScriptExporter` | -| [2. Export Parquet and CSV packages](#2-export-parquet-and-csv-packages) | `ParquetExporter`, `CsvExporter`, `CsvOptions` | +| [2. Export Parquet and CSV packages](#2-export-parquet-and-csv-packages) | `ParquetExporter`, `CsvExporter`, `CsvOptions`, `ExcelExporter` | | [3. Copy tables into another database](#3-copy-tables-into-another-database) | `ImportExporter` | | [4. Import an export package](#4-import-an-export-package) | `AbstractFileImporter` | -| [5. Load Parquet and CSV files of other tools](#5-load-parquet-and-csv-files-of-other-tools) | `ParquetImporter`, `CsvImporter` | +| [5. Load Parquet and CSV files of other tools](#5-load-parquet-and-csv-files-of-other-tools) | `ParquetImporter`, `CsvImporter`, `ExcelImporter` | | [6. Export the rows of a query](#6-export-the-rows-of-a-query) | `ExportConfiguration.queries` | | [7. Export part of a table](#7-export-part-of-a-table) | `TableQuery` | | [8. Transactions and errors](#8-transactions-and-errors) | `ManualTransaction`, `SharedConnectionFactory` | @@ -59,10 +59,10 @@ flowchart LR S[(Source database)] --> E[Exporter
metadata, pages of rows] Q[Free query] --> E E --> H1[ScriptExportHandler
SQL package] - E --> H2[DuckDB workspace
Parquet / CSV package] + E --> H2[DuckDB workspace
Parquet / CSV / Excel package] E --> H3[ImportExportHandler
target database] P[Export package] --> I[AbstractFileImporter] --> T[(Target database)] - F[Parquet / CSV files] --> D[DataFileImporter] --> T + F[Parquet / CSV / Excel files] --> D[DataFileImporter] --> T H3 --> T ``` @@ -70,10 +70,10 @@ flowchart LR |---|---| | `Exporter.ExportConfiguration` | Source: database, catalogs, schemas, tables, queries and options | | `ScriptExporter` | Writes a SQL package: `schema.sql`, data files, LOB files, `constraints.sql`, `manifest.json` | -| `ParquetExporter` / `CsvExporter` | Write Parquet or CSV packages through an embedded DuckDB | +| `ParquetExporter` / `CsvExporter` / `ExcelExporter` | Write Parquet, CSV or Excel packages through an embedded DuckDB | | `ImportExporter` | Copies tables straight into another database | -| `AbstractFileImporter` | Imports any package: SQL, Parquet or CSV, chosen by its `manifest.json` | -| `ParquetImporter` / `CsvImporter` | Load files of other tools into a table | +| `AbstractFileImporter` | Imports any package: SQL, Parquet, CSV or Excel, chosen by its `manifest.json` | +| `ParquetImporter` / `CsvImporter` / `ExcelImporter` | Load files of other tools into a table, no `manifest.json` needed | | `ManualTransaction` | One transaction for a whole import, committed or rolled back by you | | `ExportListener` | Progress, messages, errors and cancel | | `Dialect` / `MetaDataOperations` | Everything special to one database, one subclass per database and version | @@ -162,6 +162,15 @@ csv.exportDdlAndData(); The column types are kept in `manifest.json`, so an import of the package restores every value with its type. +An Excel package has one `.xlsx` workbook for each table, numbers, dates and booleans are cells of their types and longer values (more than 15 digits, microseconds, binaries) are text: + +```java +ExcelExporter excel = new ExcelExporter(new File("export/excel")); +configureSource(excel.getConfiguration()); +excel.setMaxRows(500_000); // orders.xlsx, orders_2.xlsx … (1,048,575 at most) +excel.exportDdlAndData(); +``` + --- ## 3. Copy tables into another database @@ -220,7 +229,7 @@ SshUtils.close("pg-prod"); ## 4. Import an export package -The package decides the importer: SQL, Parquet or CSV. +The package decides the importer: SQL, Parquet, CSV or Excel. ```java try (Connection connection = DriverManager.getConnection( @@ -253,6 +262,14 @@ try (Connection connection = DriverManager.getConnection("jdbc:h2:./warehouse", } ``` +A workbook of a spreadsheet needs no `manifest.json` either. The first row of the sheet names the columns, the types are detected: + +```java +ExcelImporter importer = new ExcelImporter(connection, DbType.H2); +importer.setSheet("Orders 2024"); // the first sheet if not set +long rows = importer.importFiles(List.of(new File("orders.xlsx")), "ORDERS", DataFileImporter.Mode.CREATE); +``` + | `DataFileImporter.Mode` | Target table | |---|---| | `CREATE` | Dropped and created from the columns of the files | diff --git a/docs/index.html b/docs/index.html index ee0a9a9..bb90a48 100644 --- a/docs/index.html +++ b/docs/index.html @@ -4,7 +4,7 @@ SqlJam · Move tables across databases - + @@ -187,7 +187,7 @@

SqlJam

Move tables across databases. Schema, data and all.

-

A desktop import/export tool that copies tables, indexes, constraints, sequences, partitions and rows between relational and OLAP databases, directly, as copies in the same schema, or through a self-describing SQL, Parquet or CSV export package you can import later. Imports into a database run in one transaction which an error rolls back, and rows are inserted, updated or skipped by key.

+

A desktop import/export tool that copies tables, indexes, constraints, sequences, partitions and rows between relational and OLAP databases, directly, as copies in the same schema, or through a self-describing SQL, Parquet, CSV or Excel export package you can import later. Imports into a database run in one transaction which an error rolls back, and rows are inserted, updated or skipped by key.

MySQLMariaDBPostgreSQLOracle SQL ServerDb2H2SQLite @@ -233,13 +233,13 @@

Everything a table needs on the other side

Version-aware

Dialects picked by detected or selected server version, vector types and indexes by the features detected on the target.

Keys & constraints

Primary keys, indexes, foreign keys, comments and sequences.

Partitions

Range, list, hash, interval, composite, reference and nested partitions kept for the same database type, partitioned tables marked in the tree.

-

Export packages

SQL, Parquet or CSV files, LOB files and manifest.json, split by size and imported in order.

+

Export packages

SQL, Parquet, CSV or Excel files, LOB files and manifest.json, split by size and imported in order.

One transaction

Checked by status, type and SHA-256, all or nothing or bad rows skipped and logged, confirmed before the commit if you want.

Progress you can see

Overall percentage, per-table progress, error log and cancel.

Migration reports

Every import and export leaves a report, also when it fails or is cancelled: rows per table checked against the target, skipped rows, objects and where it stopped, kept in the import history.

Scheduled sync

Changed rows by an update time or an increasing key, every N minutes or every day, run by SqlJam or by your own scheduler through its command line, vector collections too, a report for every run.

Dark by default

A modern JavaFX UI with 7 switchable themes.

-

Parquet & CSV

Columnar or text packages and files of other tools, exact types, through an embedded DuckDB.

+

Parquet, CSV & Excel

Columnar, text or spreadsheet packages and files of other tools, exact types, through an embedded DuckDB.

OLAP sources

DuckDB and ClickHouse next to the relational databases.

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.

@@ -263,7 +263,7 @@

Read once, generate for any target

1

Metadata: per-database operations read tables, keys, indexes, comments, partitions and sequences.

2

Dialect: DbType.createDialect(major, minor) picks e.g. Oracle11gDialect.

-
3

Rows: counted, paged by primary key, normalized and written in batches, or written to Parquet or CSV by an embedded DuckDB.

+
3

Rows: counted, paged by primary key, normalized and written in batches, or written to Parquet, CSV or Excel by an embedded DuckDB.

4

Vector databases: a line of its own. REST clients read the collections, a visitor builds the tables and the pages go into a target whose vector features are probed first.

@@ -316,7 +316,7 @@

Ways to move a table

- + @@ -352,11 +352,12 @@

Ways to move a table

Package viewer with a Parquet file -

Export packages of Parquet or CSV files, look inside them with sizes, times and previews, and load Parquet or CSV files of other tools into any table.

+

Export packages of Parquet, CSV or Excel files, look inside them with sizes, times and previews, and load Parquet, CSV or Excel files of other tools into any table, an Excel sheet without manifest.json too.

parquet.setCompression("ZSTD");
 parquet.exportDdlAndData();   // data/<table>.parquet
 csv.setDelimiter(";");
 csv.exportDdlAndData();       // data/<table>.csv, <table>_2.csv ...
+excel.exportDdlAndData();     // data/<table>.xlsx, one sheet with a header row
 importer.importFiles(files, "sales", ParquetImporter.Mode.CREATE);
diff --git a/pom.xml b/pom.xml index f6ea738..fa959a4 100644 --- a/pom.xml +++ b/pom.xml @@ -27,6 +27,7 @@ 0.11.7 12.1.5.0 1.5.6.0 + 0.20.2 5.1.8 0.10.0 1.18.48 @@ -180,6 +181,17 @@ duckdb_jdbc ${duckdb.version} + + + org.dhatim + fastexcel + ${fastexcel.version} + + + org.dhatim + fastexcel-reader + ${fastexcel.version} + io.github.spannm diff --git a/src/main/java/com/github/sqljam/face/model/TransferRequest.java b/src/main/java/com/github/sqljam/face/model/TransferRequest.java index 6989ad6..ba88695 100644 --- a/src/main/java/com/github/sqljam/face/model/TransferRequest.java +++ b/src/main/java/com/github/sqljam/face/model/TransferRequest.java @@ -23,7 +23,7 @@ import java.util.Map; import com.github.sqljam.impexp.ColumnMapping; -import com.github.sqljam.impexp.CsvOptions; +import com.github.sqljam.impexp.fs.CsvOptions; import com.github.sqljam.impexp.DataFileStrategy; import com.github.sqljam.impexp.DataFormat; import com.github.sqljam.impexp.DbType; diff --git a/src/main/java/com/github/sqljam/face/service/DatabaseSession.java b/src/main/java/com/github/sqljam/face/service/DatabaseSession.java index 3fa59bf..a728ac0 100644 --- a/src/main/java/com/github/sqljam/face/service/DatabaseSession.java +++ b/src/main/java/com/github/sqljam/face/service/DatabaseSession.java @@ -56,7 +56,7 @@ import com.github.sqljam.impexp.TableMetaData; import com.github.sqljam.impexp.TableQuery; import com.github.sqljam.jdbc.ConnectionFactory; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import com.github.sqljam.utils.SshUtils; /** diff --git a/src/main/java/com/github/sqljam/face/service/TransferService.java b/src/main/java/com/github/sqljam/face/service/TransferService.java index ab1f4fa..880a86c 100644 --- a/src/main/java/com/github/sqljam/face/service/TransferService.java +++ b/src/main/java/com/github/sqljam/face/service/TransferService.java @@ -22,6 +22,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; @@ -36,14 +37,16 @@ import com.github.sqljam.face.model.TransferReport; import com.github.sqljam.face.model.TransferRequest; import com.github.sqljam.impexp.AbstractFileImporter; -import com.github.sqljam.impexp.CsvExporter; -import com.github.sqljam.impexp.CsvImporter; -import com.github.sqljam.impexp.CsvOptions; +import com.github.sqljam.impexp.fs.CsvExporter; +import com.github.sqljam.impexp.fs.CsvImporter; +import com.github.sqljam.impexp.fs.CsvOptions; import com.github.sqljam.impexp.DataFileImporter; import com.github.sqljam.impexp.DataFormat; import com.github.sqljam.impexp.DbType; import com.github.sqljam.impexp.Dialect; import com.github.sqljam.impexp.DuckDBWorkspace; +import com.github.sqljam.impexp.fs.ExcelExporter; +import com.github.sqljam.impexp.fs.ExcelImporter; import com.github.sqljam.impexp.ExportListener; import com.github.sqljam.impexp.Exporter; import com.github.sqljam.impexp.ImportExportHandler; @@ -53,7 +56,8 @@ import com.github.sqljam.impexp.ScriptExporter; import com.github.sqljam.impexp.SqlScriptRunner; import com.github.sqljam.impexp.WriteMode; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.ExcelUtils; +import com.github.sqljam.utils.JdbcUtils; import com.github.sqljam.jdbc.ManualTransaction; import com.github.sqljam.jdbc.SharedConnectionFactory; @@ -281,6 +285,10 @@ private void exportScripts(TransferRequest request, ExportListener listener) thr exportCsv(request, listener); return; } + if (request.getDataFormat() == DataFormat.EXCEL) { + exportExcel(request, listener); + return; + } ScriptExporter scriptExporter = new ScriptExporter(request.getOutputDirectory(), request.getDataFileStrategy(), request.getMaxFileSize()); configureSource(scriptExporter.getConfiguration(), request); @@ -335,6 +343,24 @@ private void exportCsv(TransferRequest request, ExportListener listener) throws csvExporter.export(request.getExportMode()); } + /** + * Export package with Excel workbooks: schema.sql and constraints.sql for the target database type, a workbook + * of one sheet for each table (split at the rows of a sheet), the types of the columns are kept in manifest.json + */ + private void exportExcel(TransferRequest request, ExportListener listener) throws Exception { + ExcelExporter excelExporter = new ExcelExporter(request.getOutputDirectory()); + configureSource(excelExporter.getConfiguration(), request); + excelExporter.setTargetDbType(request.getScriptDbType()); + excelExporter.setTargetSchemaName(request.getScriptSchema()); + excelExporter.setIdentifierCase(request.getIdentifierCase()); + int[] version = parseVersion(request.getScriptDbVersion()); + if (version != null) { + excelExporter.setTargetVersion(version[0], version[1]); + } + excelExporter.setExportListener(listener); + excelExporter.export(request.getExportMode()); + } + /** * Imports Parquet files of other tools into a table: a new table created from the Parquet schema, or rows * appended to an existing table @@ -370,10 +396,27 @@ public DataFileImporter importFiles(ConnectionProfile target, String catalog, St String tableName, DataFileImporter.Mode mode, List keyColumns, CsvOptions csvOptions, boolean skipErrors, int commitRows, ManualTransaction transaction, ExportListener listener) throws Exception { + return importFiles(target, catalog, schema, files, tableName, mode, keyColumns, csvOptions, null, skipErrors, + commitRows, transaction, listener); + } + + /** + * Imports Parquet, CSV or Excel files of other tools into a table (Excel when all files are .xlsx) + * + * @param sheet sheet of Excel workbooks, null for the first sheet + */ + public DataFileImporter importFiles(ConnectionProfile target, String catalog, String schema, List files, + String tableName, DataFileImporter.Mode mode, List keyColumns, + CsvOptions csvOptions, String sheet, boolean skipErrors, int commitRows, + ManualTransaction transaction, ExportListener listener) throws Exception { Connection connection = transaction != null ? transaction.getConnection() : connect(target, catalog, schema); try { DataFileImporter importer; - if (files.stream().allMatch(DuckDBWorkspace::isCsv)) { + if (files.stream().allMatch(ExcelUtils::isExcel)) { + ExcelImporter excelImporter = new ExcelImporter(connection, target.getDbType()); + excelImporter.setSheet(sheet); + importer = excelImporter; + } else if (files.stream().allMatch(DuckDBWorkspace::isCsv)) { CsvImporter csvImporter = new CsvImporter(connection, target.getDbType()); csvImporter.setOptions(csvOptions); importer = csvImporter; @@ -415,7 +458,28 @@ public ParquetPreview previewParquet(List files, int rowLimit) throws Exce * Columns, rows and first rows of Parquet or CSV files, CSV files are read with the options (null to detect) */ public ParquetPreview previewParquet(List files, int rowLimit, CsvOptions csvOptions) throws Exception { + return previewParquet(files, rowLimit, csvOptions, null); + } + + /** + * Columns, rows and first rows of Parquet, CSV or Excel files, a sheet of workbooks is read as a CSV file + * + * @param sheet sheet of Excel workbooks, null for the first sheet + */ + public ParquetPreview previewParquet(List files, int rowLimit, CsvOptions csvOptions, String sheet) + throws Exception { try (DuckDBWorkspace workspace = new DuckDBWorkspace(null)) { + if (!files.isEmpty() && files.stream().allMatch(ExcelUtils::isExcel)) { + List csvFiles = new ArrayList<>(); + for (File file : files) { + File csv = new File(workspace.getFile().getParentFile(), "excel-" + (csvFiles.size() + 1) + + ".csv"); + ExcelUtils.toCsv(file, sheet, csv); + csvFiles.add(csv); + } + files = csvFiles; + csvOptions = new CsvOptions(); + } List> firstRows = rowLimit > 0 ? workspace.readRows(files, rowLimit, csvOptions) : Collections.emptyList(); return new ParquetPreview(workspace.describeFiles(files, csvOptions), workspace.countFileRows(files, diff --git a/src/main/java/com/github/sqljam/face/vdb/VdbImportDialog.java b/src/main/java/com/github/sqljam/face/vdb/VdbImportDialog.java index 912d051..51635de 100644 --- a/src/main/java/com/github/sqljam/face/vdb/VdbImportDialog.java +++ b/src/main/java/com/github/sqljam/face/vdb/VdbImportDialog.java @@ -27,7 +27,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; - import org.apache.commons.lang3.StringUtils; import com.github.sqljam.face.model.ConnectionProfile; import com.github.sqljam.face.model.TransferReport; diff --git a/src/main/java/com/github/sqljam/face/view/CsvOptionsPane.java b/src/main/java/com/github/sqljam/face/view/CsvOptionsPane.java index e655768..d4882ca 100644 --- a/src/main/java/com/github/sqljam/face/view/CsvOptionsPane.java +++ b/src/main/java/com/github/sqljam/face/view/CsvOptionsPane.java @@ -19,8 +19,8 @@ import java.util.function.Function; import org.apache.commons.lang3.StringUtils; -import com.github.sqljam.impexp.CsvExporter; -import com.github.sqljam.impexp.CsvOptions; +import com.github.sqljam.impexp.fs.CsvExporter; +import com.github.sqljam.impexp.fs.CsvOptions; import javafx.scene.Node; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; 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 9516a35..ac1744b 100644 --- a/src/main/java/com/github/sqljam/face/view/ExportDialog.java +++ b/src/main/java/com/github/sqljam/face/view/ExportDialog.java @@ -32,8 +32,8 @@ import com.github.sqljam.face.model.TransferRequest; import com.github.sqljam.face.service.DatabaseSession; import com.github.sqljam.impexp.ColumnMapping; -import com.github.sqljam.impexp.CsvExporter; -import com.github.sqljam.impexp.CsvOptions; +import com.github.sqljam.impexp.fs.CsvExporter; +import com.github.sqljam.impexp.fs.CsvOptions; import com.github.sqljam.impexp.DataFileStrategy; import com.github.sqljam.impexp.DataFormat; import com.github.sqljam.impexp.DbType; @@ -45,6 +45,7 @@ import com.github.sqljam.impexp.ParquetExporter; import com.github.sqljam.impexp.TableQuery; import com.github.sqljam.impexp.WriteMode; +import com.github.sqljam.utils.ExcelUtils; import javafx.beans.InvalidationListener; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; @@ -148,6 +149,7 @@ public class ExportDialog extends Dialog { private final RadioButton sqlFormatRadio = new RadioButton(Messages.get("export.format.sql")); private final RadioButton parquetFormatRadio = new RadioButton(Messages.get("export.format.parquet")); private final RadioButton csvFormatRadio = new RadioButton(Messages.get("export.format.csv")); + private final RadioButton excelFormatRadio = new RadioButton(Messages.get("export.format.excel")); private final ComboBox compressionCombo = new ComboBox<>(); private CsvOptionsPane csvOptionsPane; private TransactionOption transactionOption; @@ -257,6 +259,7 @@ private ExportDialog(Window owner, AppContext context, DbNode node, TableQuery q parquetFormatRadio.setId("parquetFormatRadio"); compressionCombo.setId("compressionCombo"); csvFormatRadio.setId("csvFormatRadio"); + excelFormatRadio.setId("excelFormatRadio"); layoutHint.setId("layoutHint"); targetCombo.setId("targetCombo"); targetCatalogCombo.setId("targetCatalogCombo"); @@ -548,6 +551,7 @@ private Node createTargetPane() { sqlFormatRadio.setToggleGroup(formatGroup); parquetFormatRadio.setToggleGroup(formatGroup); csvFormatRadio.setToggleGroup(formatGroup); + excelFormatRadio.setToggleGroup(formatGroup); sqlFormatRadio.setSelected(true); compressionCombo.getItems().setAll(ParquetExporter.COMPRESSIONS); compressionCombo.setValue(ParquetExporter.DEFAULT_COMPRESSION); @@ -561,6 +565,8 @@ private Node createTargetPane() { singleFileRadio.disableProperty().bind(sqlFormatRadio.selectedProperty().not()); perTableRadio.disableProperty().bind(sqlFormatRadio.selectedProperty().not()); lobSeparatedCheck.disableProperty().bind(sqlFormatRadio.selectedProperty().not()); + // Workbooks are split at the rows of a sheet, not at a size + maxFileSizeSpinner.disableProperty().bind(excelFormatRadio.selectedProperty()); formatGroup.selectedToggleProperty().addListener((obs, oldToggle, toggle) -> { // Parquet files are split at their own size, sql scripts and CSV files share one boolean wasParquet = oldToggle == parquetFormatRadio; @@ -591,7 +597,7 @@ private Node createTargetPane() { scriptGrid.addRow(row++, new Label(Messages.get("export.script.version")), scriptVersionCombo); scriptGrid.addRow(row++, new Label(Messages.get("export.script.schema")), scriptSchemaField); scriptGrid.addRow(row++, new Label(Messages.get("export.format")), new HBox(16, sqlFormatRadio, - parquetFormatRadio, csvFormatRadio)); + parquetFormatRadio, csvFormatRadio, excelFormatRadio)); scriptGrid.addRow(row++, new Label(Messages.get("export.format.compression")), compressionCombo); scriptGrid.addRow(row++, new Label(Messages.get("csv.options")), csvOptionsPane.getNode()); scriptGrid.addRow(row++, new Label(Messages.get("export.script.strategy")), new HBox(16, singleFileRadio, @@ -680,6 +686,13 @@ static String delimiterName(String delimiter) { private void updateLayoutHint() { boolean split = maxFileSizeSpinner.getValue() != null && maxFileSizeSpinner.getValue() > 0; + if (excelFormatRadio.isSelected()) { + String extension = ExcelUtils.EXCEL_EXTENSION; + layoutHint.setText("schema.sql\ndata/
" + extension + ",
_2" + extension + " " + + Messages.format("export.format.excel.split", String.format("%,d", ExcelUtils.MAX_ROWS)) + + "\nconstraints.sql\nmanifest.json"); + return; + } if (!sqlFormatRadio.isSelected()) { String extension = parquetFormatRadio.isSelected() ? ParquetExporter.PARQUET_EXTENSION : CsvExporter.CSV_EXTENSION; @@ -1167,13 +1180,13 @@ TransferRequest buildRequest() { request.setMaxFileSize(maxFileSizeSpinner.getValue() * MB); request.setLobSeparated(lobSeparatedCheck.isSelected()); request.setDataFormat(parquetFormatRadio.isSelected() ? DataFormat.PARQUET : csvFormatRadio.isSelected() - ? DataFormat.CSV : DataFormat.SQL); + ? DataFormat.CSV : excelFormatRadio.isSelected() ? DataFormat.EXCEL : DataFormat.SQL); request.setCompression(compressionCombo.getValue()); request.setCsvOptions(csvOptionsPane.getOptions()); context.getSettings().setLastExportDirectory(directory.getAbsolutePath()); if (parquetFormatRadio.isSelected()) { context.getSettings().setParquetMaxFileSize(maxFileSizeSpinner.getValue() * MB); - } else { + } else if (!excelFormatRadio.isSelected()) { context.getSettings().setMaxDataFileSize(maxFileSizeSpinner.getValue() * MB); } if (csvFormatRadio.isSelected()) { diff --git a/src/main/java/com/github/sqljam/face/view/ImportPackageDialog.java b/src/main/java/com/github/sqljam/face/view/ImportPackageDialog.java index badec75..dc27b47 100644 --- a/src/main/java/com/github/sqljam/face/view/ImportPackageDialog.java +++ b/src/main/java/com/github/sqljam/face/view/ImportPackageDialog.java @@ -24,13 +24,14 @@ import org.apache.commons.lang3.StringUtils; import com.github.sqljam.config.Config; import com.github.sqljam.face.model.ConnectionProfile; -import com.github.sqljam.impexp.CsvExporter; +import com.github.sqljam.impexp.fs.CsvExporter; import com.github.sqljam.impexp.DataFormat; import com.github.sqljam.impexp.DbType; import com.github.sqljam.impexp.ExportManifest; import com.github.sqljam.impexp.ParquetExporter; import com.github.sqljam.impexp.SqlScriptRunner; import com.github.sqljam.impexp.WriteMode; +import com.github.sqljam.utils.ExcelUtils; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.event.ActionEvent; import javafx.geometry.Insets; @@ -339,7 +340,7 @@ static boolean isScriptDirectory(File directory) { } /** - * Directory with Parquet or CSV files (directly or in data/) but without manifest.json + * Directory with Parquet, CSV or Excel files (directly or in data/) but without manifest.json */ static boolean isParquetDirectory(File directory) { return hasDataFiles(directory) || hasDataFiles(new File(directory, "data")); @@ -348,7 +349,8 @@ static boolean isParquetDirectory(File directory) { private static boolean hasDataFiles(File directory) { File[] files = directory.listFiles((parent, name) -> name.toLowerCase(Locale.ENGLISH) .endsWith(ParquetExporter.PARQUET_EXTENSION) || name.toLowerCase(Locale.ENGLISH) - .endsWith(CsvExporter.CSV_EXTENSION)); + .endsWith(CsvExporter.CSV_EXTENSION) || name.toLowerCase(Locale.ENGLISH) + .endsWith(ExcelUtils.EXCEL_EXTENSION)); return files != null && files.length > 0; } @@ -382,7 +384,8 @@ private void showSummary(ExportManifest manifest, boolean valid) { writeModeValue.setText(Messages.get(writeMode == WriteMode.UPSERT ? "export.writeMode.upsert" : writeMode == WriteMode.SKIP_EXISTING ? "export.writeMode.skip" : "export.writeMode.insert")); formatValue.setText(Messages.get(manifest.getDataFormat() == DataFormat.PARQUET ? "export.format.parquet" - : manifest.getDataFormat() == DataFormat.CSV ? "export.format.csv" : "export.format.sql")); + : manifest.getDataFormat() == DataFormat.CSV ? "export.format.csv" + : manifest.getDataFormat() == DataFormat.EXCEL ? "export.format.excel" : "export.format.sql")); tableView.getItems().setAll(manifest.getTables()); filterTargets(); } diff --git a/src/main/java/com/github/sqljam/face/view/ImportParquetDialog.java b/src/main/java/com/github/sqljam/face/view/ImportParquetDialog.java index 504e1f2..0bde699 100644 --- a/src/main/java/com/github/sqljam/face/view/ImportParquetDialog.java +++ b/src/main/java/com/github/sqljam/face/view/ImportParquetDialog.java @@ -27,10 +27,11 @@ import com.github.sqljam.impexp.ParquetExporter; import javafx.scene.control.CheckBox; import com.github.sqljam.impexp.DuckDBWorkspace; -import com.github.sqljam.impexp.CsvSplitter; -import com.github.sqljam.impexp.CsvExporter; -import com.github.sqljam.impexp.CsvOptions; +import com.github.sqljam.impexp.fs.CsvSplitter; +import com.github.sqljam.impexp.fs.CsvExporter; +import com.github.sqljam.impexp.fs.CsvOptions; import com.github.sqljam.impexp.ParquetImporter; +import com.github.sqljam.utils.ExcelUtils; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.event.ActionEvent; import javafx.geometry.Insets; @@ -87,6 +88,16 @@ public class ImportParquetDialog extends Dialog sheetCombo = new ComboBox<>(); + private HBox sheetBox; + /** + * Workbook whose sheets are listed, they are read again for another first file + */ + private File sheetsOf; + private boolean loadingSheets; private final ComboBox targetCombo = new ComboBox<>(); private final TransactionOption transactionOption; private final ComboBox catalogCombo = new ComboBox<>(); @@ -110,9 +121,13 @@ public static class ParquetRequest { */ private final List keyColumns; /** - * Options of CSV files, null for Parquet files + * Options of CSV files, null for Parquet and Excel files */ private final CsvOptions csvOptions; + /** + * Sheet of Excel workbooks, null for other files + */ + private final String sheet; private final ConnectionProfile target; private final String catalog; private final String schema; @@ -134,13 +149,14 @@ public static class ParquetRequest { private final int commitRows; ParquetRequest(List files, String tableName, ParquetImporter.Mode mode, List keyColumns, - CsvOptions csvOptions, ConnectionProfile target, String catalog, String schema, + CsvOptions csvOptions, String sheet, ConnectionProfile target, String catalog, String schema, boolean oneTransaction, boolean confirmCommit, boolean skipErrors, int commitRows) { this.files = files; this.tableName = tableName; this.mode = mode; this.keyColumns = keyColumns; this.csvOptions = csvOptions; + this.sheet = sheet; this.target = target; this.catalog = catalog; this.schema = schema; @@ -229,7 +245,19 @@ protected void updateItem(File file, boolean empty) { csvOptionsBox.setVisible(false); csvOptionsBox.setManaged(false); csvOptionsPane.setOnChange(this::loadPreview); - VBox filesPane = new VBox(8, filesTitle, fileBox, csvOptionsBox, previewLabel, previewTable); + sheetCombo.setId("sheetCombo"); + sheetCombo.valueProperty().addListener((obs, oldSheet, sheet) -> { + if (!loadingSheets && sheet != null) { + loadPreview(); + } + }); + Label sheetLabel = new Label(Messages.get("parquet.sheet")); + sheetBox = new HBox(8, sheetLabel, sheetCombo); + sheetBox.setAlignment(javafx.geometry.Pos.CENTER_LEFT); + sheetBox.setId("sheetBox"); + sheetBox.setVisible(false); + sheetBox.setManaged(false); + VBox filesPane = new VBox(8, filesTitle, fileBox, csvOptionsBox, sheetBox, previewLabel, previewTable); filesPane.getStyleClass().add("form-section"); ToggleGroup modeGroup = new ToggleGroup(); @@ -331,11 +359,14 @@ private void chooseFiles() { FileChooser chooser = new FileChooser(); chooser.setTitle(Messages.get("parquet.files.add")); chooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter(Messages.get("parquet.files.filter"), - "*" + ParquetExporter.PARQUET_EXTENSION, "*" + CsvExporter.CSV_EXTENSION, "*.tsv", "*.txt"), + "*" + ParquetExporter.PARQUET_EXTENSION, "*" + CsvExporter.CSV_EXTENSION, "*.tsv", "*.txt", + "*" + ExcelUtils.EXCEL_EXTENSION), new FileChooser.ExtensionFilter(Messages.get("parquet.files.filter.parquet"), "*" + ParquetExporter.PARQUET_EXTENSION), new FileChooser.ExtensionFilter(Messages.get("parquet.files.filter.csv"), - "*" + CsvExporter.CSV_EXTENSION, "*.tsv", "*.txt")); + "*" + CsvExporter.CSV_EXTENSION, "*.tsv", "*.txt"), + new FileChooser.ExtensionFilter(Messages.get("parquet.files.filter.excel"), + "*" + ExcelUtils.EXCEL_EXTENSION)); String lastDirectory = context.getSettings().getLastImportDirectory(); if (StringUtils.isNotBlank(lastDirectory) && new File(lastDirectory).isDirectory()) { chooser.setInitialDirectory(new File(lastDirectory)); @@ -392,12 +423,16 @@ private void loadPreview() { validate(); return; } - // Files of one table are all Parquet or all CSV + // Files of one table are all Parquet, all CSV or all Excel long csvFiles = files.stream().filter(DuckDBWorkspace::isCsv).count(); + long excelFiles = files.stream().filter(ExcelUtils::isExcel).count(); boolean csv = csvFiles > 0 && csvFiles == files.size(); + boolean excel = excelFiles > 0 && excelFiles == files.size(); csvOptionsBox.setVisible(csv); csvOptionsBox.setManaged(csv); - if (csvFiles > 0 && csvFiles < files.size()) { + sheetBox.setVisible(excel); + sheetBox.setManaged(excel); + if (csvFiles > 0 && csvFiles < files.size() || excelFiles > 0 && excelFiles < files.size()) { showPreview(null); validate(); warningLabel.setText(Messages.get("parquet.error.mixed")); @@ -408,7 +443,11 @@ private void loadPreview() { previewTable.getItems().clear(); validate(); CsvOptions csvOptions = csv ? csvOptionsPane.getOptions() : null; - TaskRunner.run(() -> context.getTransferService().previewParquet(files, PREVIEW_ROWS, csvOptions), + if (excel && !loadSheets(files.get(0))) { + return; + } + String sheet = excel ? sheetCombo.getValue() : null; + TaskRunner.run(() -> context.getTransferService().previewParquet(files, PREVIEW_ROWS, csvOptions, sheet), preview -> { if (version == previewVersion) { filesValid = true; @@ -425,6 +464,34 @@ private void loadPreview() { }); } + /** + * Lists the sheets of the first workbook, the first sheet is chosen + * + * @return whether the sheets are read + */ + private boolean loadSheets(File workbook) { + if (workbook.equals(sheetsOf) && !sheetCombo.getItems().isEmpty()) { + return true; + } + loadingSheets = true; + try { + sheetCombo.getItems().setAll(ExcelUtils.sheetNames(workbook)); + sheetCombo.getSelectionModel().selectFirst(); + sheetsOf = workbook; + return true; + } catch (Exception e) { + sheetCombo.getItems().clear(); + sheetsOf = null; + showPreview(null); + warningLabel.setText(Messages.format("parquet.error.read", StringUtils.defaultIfBlank(e.getMessage(), + e.getClass().getSimpleName()))); + startButton.setDisable(true); + return false; + } finally { + loadingSheets = false; + } + } + private void showPreview(TransferService.ParquetPreview preview) { previewTable.getColumns().clear(); previewTable.getItems().clear(); @@ -510,7 +577,7 @@ ParquetRequest buildRequest() { ? ParquetImporter.Mode.SKIP_EXISTING : appendRadio.isSelected() ? ParquetImporter.Mode.APPEND : ParquetImporter.Mode.CREATE, KeyColumnsDialog.parse( keyColumnsField.getText()), csvOptionsBox.isVisible() ? csvOptionsPane.getOptions() : null, - targetCombo.getValue(), catalogCombo.isDisabled() ? null : catalogCombo.getValue(), + sheetBox.isVisible() ? sheetCombo.getValue() : null, targetCombo.getValue(), catalogCombo.isDisabled() ? null : catalogCombo.getValue(), schemaCombo.isDisabled() ? null : StringUtils.trimToNull(schemaCombo.getEditor().getText()), transactionOption.isOneTransaction(), transactionOption.isConfirmCommit(), transactionOption.isSkipErrors(), transactionOption.isOneTransaction() ? 0 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 ca9f542..d5a40ec 100644 --- a/src/main/java/com/github/sqljam/face/view/MainView.java +++ b/src/main/java/com/github/sqljam/face/view/MainView.java @@ -101,7 +101,6 @@ public class MainView extends BorderPane { static final double TREE_WIDTH = 0.24; static final double MIN_SPLIT_WIDTH = 200; - private final AppContext context; private final ConnectionTree connectionTree; private final TabPane tabPane = new TabPane(); @@ -1014,8 +1013,8 @@ ProgressDialog startFileImport(ImportParquetDialog.ParquetRequest parquetRequest return context.getTransferService().importFiles(parquetRequest.getTarget(), parquetRequest .getCatalog(), parquetRequest.getSchema(), parquetRequest.getFiles(), parquetRequest .getTableName(), parquetRequest.getMode(), parquetRequest.getKeyColumns(), parquetRequest - .getCsvOptions(), parquetRequest.isSkipErrors(), parquetRequest.getCommitRows(), transaction.get(), - progress.getListener()); + .getCsvOptions(), parquetRequest.getSheet(), parquetRequest.isSkipErrors(), parquetRequest + .getCommitRows(), transaction.get(), progress.getListener()); }, (DataFileImporter importer) -> Messages.format("parquet.summary", importer.getImportedRows(), parquetRequest.getTableName()), transaction::get, parquetRequest.isConfirmCommit(), () -> context.getSessionManager().closeSession(parquetRequest.getTarget().getId())); 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 6f5091b..6b8a775 100644 --- a/src/main/java/com/github/sqljam/face/view/SqlTab.java +++ b/src/main/java/com/github/sqljam/face/view/SqlTab.java @@ -33,7 +33,7 @@ import com.github.sqljam.face.service.SqlStatements; import com.github.sqljam.impexp.DbType; import com.github.sqljam.impexp.Dialect; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.collections.ObservableList; import javafx.geometry.Orientation; diff --git a/src/main/java/com/github/sqljam/impexp/AbstractFileImporter.java b/src/main/java/com/github/sqljam/impexp/AbstractFileImporter.java index 0929e42..7d8d8eb 100644 --- a/src/main/java/com/github/sqljam/impexp/AbstractFileImporter.java +++ b/src/main/java/com/github/sqljam/impexp/AbstractFileImporter.java @@ -21,6 +21,8 @@ import java.sql.SQLException; import org.apache.commons.lang3.StringUtils; +import com.github.sqljam.impexp.fs.CsvImporter; +import com.github.sqljam.impexp.fs.ExcelImporter; /** * @Description: AbstractFileImporter imports files of an export package into a database by a connection: @@ -58,8 +60,8 @@ protected AbstractFileImporter(Connection connection, DbType dbType) { /** * Importer of an export directory by the data format of its manifest: Parquet packages are imported by - * {@link ParquetImporter}, CSV packages by {@link CsvImporter}, sql scripts (with or without manifest) by - * {@link ScriptImporter} + * {@link ParquetImporter}, CSV packages by {@link CsvImporter}, Excel packages by {@link ExcelImporter}, sql + * scripts (with or without manifest) by {@link ScriptImporter} */ public static AbstractFileImporter forDirectory(File dir, Connection connection, DbType dbType) throws IOException { @@ -70,6 +72,9 @@ public static AbstractFileImporter forDirectory(File dir, Connection connection, if (manifest != null && manifest.getDataFormat() == DataFormat.CSV) { return new CsvImporter(connection, dbType); } + if (manifest != null && manifest.getDataFormat() == DataFormat.EXCEL) { + return new ExcelImporter(connection, dbType); + } return new ScriptImporter(connection, dbType); } diff --git a/src/main/java/com/github/sqljam/impexp/DataFileExporter.java b/src/main/java/com/github/sqljam/impexp/DataFileExporter.java index 092b576..87277a7 100644 --- a/src/main/java/com/github/sqljam/impexp/DataFileExporter.java +++ b/src/main/java/com/github/sqljam/impexp/DataFileExporter.java @@ -30,6 +30,7 @@ import com.github.sqljam.impexp.db.DuckDBMetaDataOperations; import com.github.sqljam.jdbc.SharedConnectionFactory; import lombok.extern.slf4j.Slf4j; +import com.github.sqljam.impexp.fs.CsvExporter; /** * @Description: DataFileExporter exports tables as an export package with data files: schema.sql and diff --git a/src/main/java/com/github/sqljam/impexp/DataFileImporter.java b/src/main/java/com/github/sqljam/impexp/DataFileImporter.java index 7b047da..a7a15aa 100644 --- a/src/main/java/com/github/sqljam/impexp/DataFileImporter.java +++ b/src/main/java/com/github/sqljam/impexp/DataFileImporter.java @@ -34,6 +34,8 @@ import org.apache.commons.lang3.Validate; import com.github.sqljam.jdbc.SharedConnectionFactory; import lombok.extern.slf4j.Slf4j; +import com.github.sqljam.impexp.fs.CsvImporter; +import com.github.sqljam.impexp.fs.CsvSplitter; /** * @Description: DataFileImporter imports data files into a database by a connection. Packages exported by diff --git a/src/main/java/com/github/sqljam/impexp/DataFormat.java b/src/main/java/com/github/sqljam/impexp/DataFormat.java index 64e1ec4..b6cb00c 100644 --- a/src/main/java/com/github/sqljam/impexp/DataFormat.java +++ b/src/main/java/com/github/sqljam/impexp/DataFormat.java @@ -17,8 +17,8 @@ /** * @Description: DataFormat of rows in an export package: SQL insert statements, Parquet files (one file per - * table) for analytical tools, or CSV files (one file per table with a header row) for spreadsheets - * and text tools + * table) for analytical tools, CSV files (one file per table with a header row) for spreadsheets + * and text tools, or Excel workbooks (one .xlsx file per table with a header row) * @Author: Fred Feng * @Date: 26/03/2023 * @Version 1.0.0 @@ -29,5 +29,7 @@ public enum DataFormat { PARQUET, - CSV + CSV, + + EXCEL } diff --git a/src/main/java/com/github/sqljam/impexp/DdlScripter.java b/src/main/java/com/github/sqljam/impexp/DdlScripter.java index 269e777..4ec3a1f 100644 --- a/src/main/java/com/github/sqljam/impexp/DdlScripter.java +++ b/src/main/java/com/github/sqljam/impexp/DdlScripter.java @@ -21,6 +21,7 @@ import java.util.Map; import org.apache.commons.lang3.StringUtils; +import com.github.sqljam.utils.SqlTextUtils; import com.github.sqljam.utils.MapUtils; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/com/github/sqljam/impexp/Dialect.java b/src/main/java/com/github/sqljam/impexp/Dialect.java index e4fb5ec..438fe0d 100644 --- a/src/main/java/com/github/sqljam/impexp/Dialect.java +++ b/src/main/java/com/github/sqljam/impexp/Dialect.java @@ -52,7 +52,8 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.SqlTextUtils; +import com.github.sqljam.utils.JdbcUtils; import com.github.sqljam.utils.MapUtils; /** diff --git a/src/main/java/com/github/sqljam/impexp/DuckDBWorkspace.java b/src/main/java/com/github/sqljam/impexp/DuckDBWorkspace.java index 883e87a..29c42d7 100644 --- a/src/main/java/com/github/sqljam/impexp/DuckDBWorkspace.java +++ b/src/main/java/com/github/sqljam/impexp/DuckDBWorkspace.java @@ -33,8 +33,10 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import lombok.extern.slf4j.Slf4j; +import com.github.sqljam.impexp.fs.CsvOptions; +import com.github.sqljam.impexp.fs.CsvSplitter; /** * @Description: DuckDBWorkspace is a temporary DuckDB database used to write and read Parquet and CSV files. Rows diff --git a/src/main/java/com/github/sqljam/impexp/ExportManifest.java b/src/main/java/com/github/sqljam/impexp/ExportManifest.java index 5f7870e..53443c2 100644 --- a/src/main/java/com/github/sqljam/impexp/ExportManifest.java +++ b/src/main/java/com/github/sqljam/impexp/ExportManifest.java @@ -80,7 +80,12 @@ public enum FileType { /** * Rows of a table in a CSV file with a header row */ - CSV + CSV, + + /** + * Rows of a table in the sheet of an Excel workbook with a header row + */ + EXCEL } private String format = FORMAT; diff --git a/src/main/java/com/github/sqljam/impexp/Exporter.java b/src/main/java/com/github/sqljam/impexp/Exporter.java index 49f40ad..4e9b591 100644 --- a/src/main/java/com/github/sqljam/impexp/Exporter.java +++ b/src/main/java/com/github/sqljam/impexp/Exporter.java @@ -30,7 +30,7 @@ import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import com.github.sqljam.jdbc.ConnectionFactory; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import com.github.sqljam.jdbc.SimpleConnectionFactory; import com.github.sqljam.page.EachPage; import com.github.sqljam.page.MapBasedPageReader; diff --git a/src/main/java/com/github/sqljam/impexp/ImportExportHandler.java b/src/main/java/com/github/sqljam/impexp/ImportExportHandler.java index b2e3f91..03bcece 100644 --- a/src/main/java/com/github/sqljam/impexp/ImportExportHandler.java +++ b/src/main/java/com/github/sqljam/impexp/ImportExportHandler.java @@ -42,10 +42,11 @@ import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; +import com.github.sqljam.utils.SqlTextUtils; import com.github.sqljam.impexp.DdlScripter.Catalog; import com.github.sqljam.impexp.DdlScripter.Schema; import com.github.sqljam.jdbc.ConnectionFactory; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import com.github.sqljam.jdbc.ManualTransaction; import com.github.sqljam.jdbc.SimpleConnectionFactory; import com.github.sqljam.page.EachPage; diff --git a/src/main/java/com/github/sqljam/impexp/MetaDataOperations.java b/src/main/java/com/github/sqljam/impexp/MetaDataOperations.java index 02ae8ec..145850d 100644 --- a/src/main/java/com/github/sqljam/impexp/MetaDataOperations.java +++ b/src/main/java/com/github/sqljam/impexp/MetaDataOperations.java @@ -22,7 +22,7 @@ import java.util.Map; import java.util.stream.Collectors; import com.github.sqljam.jdbc.Cursor; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; /** * @Description: MetaDataOperations reads metadata by jdbc DatabaseMetaData, subclasses of each database fix and complete it diff --git a/src/main/java/com/github/sqljam/impexp/PooledConnectionFactory.java b/src/main/java/com/github/sqljam/impexp/PooledConnectionFactory.java index e94b7f2..092556a 100644 --- a/src/main/java/com/github/sqljam/impexp/PooledConnectionFactory.java +++ b/src/main/java/com/github/sqljam/impexp/PooledConnectionFactory.java @@ -20,7 +20,7 @@ import javax.sql.DataSource; import com.github.sqljam.jdbc.ConnectionFactory; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; /** * @Description: PooledConnectionFactory provides connections of a DataSource diff --git a/src/main/java/com/github/sqljam/impexp/ScriptExportHandler.java b/src/main/java/com/github/sqljam/impexp/ScriptExportHandler.java index d94bdb1..68de39e 100644 --- a/src/main/java/com/github/sqljam/impexp/ScriptExportHandler.java +++ b/src/main/java/com/github/sqljam/impexp/ScriptExportHandler.java @@ -37,6 +37,7 @@ import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; +import com.github.sqljam.utils.SqlTextUtils; import com.github.sqljam.impexp.DdlScripter.Catalog; import com.github.sqljam.impexp.DdlScripter.Schema; import com.github.sqljam.jdbc.ConnectionFactory; diff --git a/src/main/java/com/github/sqljam/impexp/ScriptImporter.java b/src/main/java/com/github/sqljam/impexp/ScriptImporter.java index 690fb68..dba6b6f 100644 --- a/src/main/java/com/github/sqljam/impexp/ScriptImporter.java +++ b/src/main/java/com/github/sqljam/impexp/ScriptImporter.java @@ -39,8 +39,10 @@ import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import lombok.extern.slf4j.Slf4j; +import com.github.sqljam.impexp.fs.CsvImporter; +import com.github.sqljam.impexp.fs.ExcelImporter; /** * @Description: ScriptImporter imports a directory exported by {@link ScriptExporter} into a database: schema.sql, @@ -127,7 +129,7 @@ protected void importManifest(File dir, ExportManifest manifest) throws IOExcept if (manifest.getDataFormat() != null && manifest.getDataFormat() != DataFormat.SQL) { throw new ImpExpException(String.format("Packages of %s files are imported by %s", manifest.getDataFormat(), manifest.getDataFormat() == DataFormat.CSV ? "CsvImporter" - : "ParquetImporter")); + : manifest.getDataFormat() == DataFormat.EXCEL ? "ExcelImporter" : "ParquetImporter")); } for (ExportManifest.FileEntry fileEntry : manifest.getFiles()) { File file = new File(dir, fileEntry.getPath()); diff --git a/src/main/java/com/github/sqljam/impexp/SqlScriptRunner.java b/src/main/java/com/github/sqljam/impexp/SqlScriptRunner.java index bc1e8c9..2aa4031 100644 --- a/src/main/java/com/github/sqljam/impexp/SqlScriptRunner.java +++ b/src/main/java/com/github/sqljam/impexp/SqlScriptRunner.java @@ -34,7 +34,7 @@ import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import lombok.Getter; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/com/github/sqljam/impexp/db/ClickHouseMetaDataOperations.java b/src/main/java/com/github/sqljam/impexp/db/ClickHouseMetaDataOperations.java index a57af7a..aaca30f 100644 --- a/src/main/java/com/github/sqljam/impexp/db/ClickHouseMetaDataOperations.java +++ b/src/main/java/com/github/sqljam/impexp/db/ClickHouseMetaDataOperations.java @@ -38,7 +38,7 @@ import com.github.sqljam.impexp.TableMetaData; import com.github.sqljam.impexp.VectorIndex; import com.github.sqljam.impexp.VectorType; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import com.github.sqljam.utils.CaseInsensitiveMap; /** diff --git a/src/main/java/com/github/sqljam/impexp/db/Db2MetaDataOperations.java b/src/main/java/com/github/sqljam/impexp/db/Db2MetaDataOperations.java index 376ca98..40a0400 100644 --- a/src/main/java/com/github/sqljam/impexp/db/Db2MetaDataOperations.java +++ b/src/main/java/com/github/sqljam/impexp/db/Db2MetaDataOperations.java @@ -32,7 +32,7 @@ import com.github.sqljam.impexp.TableMetaData; import com.github.sqljam.impexp.VectorIndex; import com.github.sqljam.impexp.VectorType; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import com.github.sqljam.utils.CaseInsensitiveMap; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/com/github/sqljam/impexp/db/DuckDBDialect.java b/src/main/java/com/github/sqljam/impexp/db/DuckDBDialect.java index 21f9647..7767f39 100644 --- a/src/main/java/com/github/sqljam/impexp/db/DuckDBDialect.java +++ b/src/main/java/com/github/sqljam/impexp/db/DuckDBDialect.java @@ -57,7 +57,6 @@ public class DuckDBDialect extends Dialect { */ static final int ROWS_PER_INSERT = 256; - /** * Max precision of DECIMAL */ diff --git a/src/main/java/com/github/sqljam/impexp/db/DuckDBMetaDataOperations.java b/src/main/java/com/github/sqljam/impexp/db/DuckDBMetaDataOperations.java index 32b7f64..bbf77c1 100644 --- a/src/main/java/com/github/sqljam/impexp/db/DuckDBMetaDataOperations.java +++ b/src/main/java/com/github/sqljam/impexp/db/DuckDBMetaDataOperations.java @@ -35,7 +35,7 @@ import com.github.sqljam.impexp.MetaDataOperations; import com.github.sqljam.impexp.TableMetaData; import com.github.sqljam.impexp.VectorType; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; /** * @Description: DuckDBMetaDataOperations reads tables of the database file (internal databases and schemas are diff --git a/src/main/java/com/github/sqljam/impexp/db/H2MetaDataOperations.java b/src/main/java/com/github/sqljam/impexp/db/H2MetaDataOperations.java index c582f6a..25479fe 100644 --- a/src/main/java/com/github/sqljam/impexp/db/H2MetaDataOperations.java +++ b/src/main/java/com/github/sqljam/impexp/db/H2MetaDataOperations.java @@ -24,7 +24,7 @@ import org.apache.commons.lang3.StringUtils; import com.github.sqljam.impexp.MetaDataOperations; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; /** * @Description: H2MetaDataOperations reads tables, generated columns and sequences of H2 diff --git a/src/main/java/com/github/sqljam/impexp/db/MariaDBMetaDataOperations.java b/src/main/java/com/github/sqljam/impexp/db/MariaDBMetaDataOperations.java index 974a45a..f6b31c1 100644 --- a/src/main/java/com/github/sqljam/impexp/db/MariaDBMetaDataOperations.java +++ b/src/main/java/com/github/sqljam/impexp/db/MariaDBMetaDataOperations.java @@ -31,7 +31,7 @@ import org.apache.commons.lang3.StringUtils; import com.github.sqljam.impexp.VectorIndex; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import lombok.extern.slf4j.Slf4j; /** diff --git a/src/main/java/com/github/sqljam/impexp/db/MySQLMetaDataOperations.java b/src/main/java/com/github/sqljam/impexp/db/MySQLMetaDataOperations.java index 2f15f8f..a5a221d 100644 --- a/src/main/java/com/github/sqljam/impexp/db/MySQLMetaDataOperations.java +++ b/src/main/java/com/github/sqljam/impexp/db/MySQLMetaDataOperations.java @@ -29,7 +29,7 @@ import com.github.sqljam.impexp.MetaDataOperations; import com.github.sqljam.impexp.TableMetaData; import com.github.sqljam.impexp.VectorType; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; /** * @Description: MySQLMetaDataOperations completes column types, default values, generated columns and partitions of MySQL diff --git a/src/main/java/com/github/sqljam/impexp/db/OracleMetaDataOperations.java b/src/main/java/com/github/sqljam/impexp/db/OracleMetaDataOperations.java index d04de27..97eeb8c 100644 --- a/src/main/java/com/github/sqljam/impexp/db/OracleMetaDataOperations.java +++ b/src/main/java/com/github/sqljam/impexp/db/OracleMetaDataOperations.java @@ -38,7 +38,7 @@ import com.github.sqljam.impexp.MetaDataOperations; import com.github.sqljam.impexp.VectorIndex; import com.github.sqljam.impexp.VectorType; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import com.github.sqljam.utils.CaseInsensitiveMap; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/com/github/sqljam/impexp/db/PostgreSQLDialect.java b/src/main/java/com/github/sqljam/impexp/db/PostgreSQLDialect.java index 0c986ad..0467da8 100644 --- a/src/main/java/com/github/sqljam/impexp/db/PostgreSQLDialect.java +++ b/src/main/java/com/github/sqljam/impexp/db/PostgreSQLDialect.java @@ -15,7 +15,6 @@ */ package com.github.sqljam.impexp.db; - import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; diff --git a/src/main/java/com/github/sqljam/impexp/db/PostgreSQLMetaDataOperations.java b/src/main/java/com/github/sqljam/impexp/db/PostgreSQLMetaDataOperations.java index 20caa40..0521e34 100644 --- a/src/main/java/com/github/sqljam/impexp/db/PostgreSQLMetaDataOperations.java +++ b/src/main/java/com/github/sqljam/impexp/db/PostgreSQLMetaDataOperations.java @@ -37,7 +37,7 @@ import com.github.sqljam.impexp.MetaDataOperations; import com.github.sqljam.impexp.VectorIndex; import com.github.sqljam.impexp.VectorType; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import com.github.sqljam.utils.MapUtils; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/com/github/sqljam/impexp/db/SQLServerMetaDataOperations.java b/src/main/java/com/github/sqljam/impexp/db/SQLServerMetaDataOperations.java index e925c61..e7e8e0e 100644 --- a/src/main/java/com/github/sqljam/impexp/db/SQLServerMetaDataOperations.java +++ b/src/main/java/com/github/sqljam/impexp/db/SQLServerMetaDataOperations.java @@ -30,7 +30,7 @@ import com.github.sqljam.impexp.MetaDataOperations; import com.github.sqljam.impexp.TableMetaData; import com.github.sqljam.impexp.VectorType; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import lombok.extern.slf4j.Slf4j; /** diff --git a/src/main/java/com/github/sqljam/impexp/db/SQLiteMetaDataOperations.java b/src/main/java/com/github/sqljam/impexp/db/SQLiteMetaDataOperations.java index 485ecef..c3cdcef 100644 --- a/src/main/java/com/github/sqljam/impexp/db/SQLiteMetaDataOperations.java +++ b/src/main/java/com/github/sqljam/impexp/db/SQLiteMetaDataOperations.java @@ -29,7 +29,7 @@ import org.apache.commons.lang3.StringUtils; import com.github.sqljam.impexp.MetaDataOperations; import com.github.sqljam.impexp.TableMetaData; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import com.github.sqljam.utils.CaseInsensitiveMap; /** diff --git a/src/main/java/com/github/sqljam/impexp/CsvExporter.java b/src/main/java/com/github/sqljam/impexp/fs/CsvExporter.java similarity index 94% rename from src/main/java/com/github/sqljam/impexp/CsvExporter.java rename to src/main/java/com/github/sqljam/impexp/fs/CsvExporter.java index 646412a..8fd7c72 100644 --- a/src/main/java/com/github/sqljam/impexp/CsvExporter.java +++ b/src/main/java/com/github/sqljam/impexp/fs/CsvExporter.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.github.sqljam.impexp; +package com.github.sqljam.impexp.fs; import java.io.File; import java.nio.charset.StandardCharsets; @@ -21,6 +21,10 @@ import java.util.Map; import org.apache.commons.lang3.StringUtils; +import com.github.sqljam.impexp.DataFileExporter; +import com.github.sqljam.impexp.DataFormat; +import com.github.sqljam.impexp.DuckDBWorkspace; +import com.github.sqljam.impexp.ExportManifest; /** * @Description: CsvExporter exports tables as an export package with CSV files: schema.sql and constraints.sql for diff --git a/src/main/java/com/github/sqljam/impexp/CsvImporter.java b/src/main/java/com/github/sqljam/impexp/fs/CsvImporter.java similarity index 91% rename from src/main/java/com/github/sqljam/impexp/CsvImporter.java rename to src/main/java/com/github/sqljam/impexp/fs/CsvImporter.java index 3351cfe..c9e1cf4 100644 --- a/src/main/java/com/github/sqljam/impexp/CsvImporter.java +++ b/src/main/java/com/github/sqljam/impexp/fs/CsvImporter.java @@ -13,13 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.github.sqljam.impexp; +package com.github.sqljam.impexp.fs; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.List; +import com.github.sqljam.impexp.DataFileImporter; +import com.github.sqljam.impexp.DataFormat; +import com.github.sqljam.impexp.DbType; +import com.github.sqljam.impexp.DuckDBWorkspace; +import com.github.sqljam.impexp.ExportManifest; /** * @Description: CsvImporter imports CSV files with a header row into a database by a connection: packages exported diff --git a/src/main/java/com/github/sqljam/impexp/CsvOptions.java b/src/main/java/com/github/sqljam/impexp/fs/CsvOptions.java similarity index 98% rename from src/main/java/com/github/sqljam/impexp/CsvOptions.java rename to src/main/java/com/github/sqljam/impexp/fs/CsvOptions.java index 79cc4eb..ddfa6aa 100644 --- a/src/main/java/com/github/sqljam/impexp/CsvOptions.java +++ b/src/main/java/com/github/sqljam/impexp/fs/CsvOptions.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.github.sqljam.impexp; +package com.github.sqljam.impexp.fs; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -24,6 +24,7 @@ import org.apache.commons.lang3.StringUtils; import lombok.Getter; import lombok.Setter; +import com.github.sqljam.impexp.DuckDBWorkspace; /** * @Description: CsvOptions of CSV files like the CSV settings of spreadsheets: delimiter, quote character (doubled diff --git a/src/main/java/com/github/sqljam/impexp/CsvSplitter.java b/src/main/java/com/github/sqljam/impexp/fs/CsvSplitter.java similarity index 99% rename from src/main/java/com/github/sqljam/impexp/CsvSplitter.java rename to src/main/java/com/github/sqljam/impexp/fs/CsvSplitter.java index 2079790..a750126 100644 --- a/src/main/java/com/github/sqljam/impexp/CsvSplitter.java +++ b/src/main/java/com/github/sqljam/impexp/fs/CsvSplitter.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.github.sqljam.impexp; +package com.github.sqljam.impexp.fs; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -40,6 +40,7 @@ import java.util.regex.Pattern; import org.apache.commons.io.FilenameUtils; +import com.github.sqljam.impexp.ImpExpException; /** * @Description: CsvSplitter splits a large CSV file into parts of a maximum size, named like data files of sql diff --git a/src/main/java/com/github/sqljam/impexp/fs/ExcelExporter.java b/src/main/java/com/github/sqljam/impexp/fs/ExcelExporter.java new file mode 100644 index 0000000..99cd57c --- /dev/null +++ b/src/main/java/com/github/sqljam/impexp/fs/ExcelExporter.java @@ -0,0 +1,118 @@ +/* + * 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.impexp.fs; + +import java.io.File; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.github.sqljam.utils.ExcelUtils; +import com.github.sqljam.impexp.DataFileExporter; +import com.github.sqljam.impexp.DataFormat; +import com.github.sqljam.impexp.DuckDBWorkspace; +import com.github.sqljam.impexp.ExportManifest; + +/** + * @Description: ExcelExporter exports tables as an export package with Excel workbooks: schema.sql and + * constraints.sql for the target database (the same as SQL packages), data/<table>.xlsx with one + * sheet and a header row for rows, and manifest.json with the type of each column, so that + * {@link ExcelImporter} reads the values back exactly. A table of more rows than a sheet holds is + * split into orders.xlsx, orders_2.xlsx ... + * @Author: Fred Feng + * @Date: 24/10/2026 + * @Version 1.0.0 + */ +public final class ExcelExporter extends DataFileExporter { + + /** + * Types which are cells of their own types, others are written as their text of DuckDB, e.g. binary values, + * times, intervals and timestamps with time zones + */ + private static final Set CELL_TYPES = Set.of("BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", + "UTINYINT", "USMALLINT", "UINTEGER", "UBIGINT", "HUGEINT", "UHUGEINT", "FLOAT", "DOUBLE", "DATE", + "TIMESTAMP", "TIMESTAMP_S", "TIMESTAMP_MS"); + + private int maxRows = ExcelUtils.MAX_ROWS; + + public ExcelExporter(File root) { + super(root); + } + + /** + * Rows of a workbook, the rows of a sheet (1,048,575 without the header) at most + */ + public void setMaxRows(int maxRows) { + this.maxRows = maxRows > 0 ? Math.min(maxRows, ExcelUtils.MAX_ROWS) : ExcelUtils.MAX_ROWS; + } + + public int getMaxRows() { + return maxRows; + } + + @Override + protected DataFormat getDataFormat() { + return DataFormat.EXCEL; + } + + @Override + protected String getExtension() { + return ExcelUtils.EXCEL_EXTENSION; + } + + @Override + protected ExportManifest.FileType getFileType() { + return ExportManifest.FileType.EXCEL; + } + + @Override + protected List writeFile(DuckDBWorkspace workspace, String schema, String table, File file, + Map metadata) throws Exception { + List columns = workspace.describeTable(schema, table); + String select = columns.stream().map(column -> isCellType(column[1]) ? DuckDBWorkspace.quote(column[0]) + : String.format("CAST(%s AS VARCHAR)", DuckDBWorkspace.quote(column[0]))) + .collect(Collectors.joining(", ")); + try (Statement statement = workspace.getConnection().createStatement(); + ResultSet rs = statement.executeQuery(String.format("SELECT %s FROM %s", select, + DuckDBWorkspace.qualify(schema, table)))) { + return ExcelUtils.write(rs, columns.stream().map(column -> column[0]).collect(Collectors.toList()), + table, file, maxRows); + } + } + + static boolean isCellType(String duckdbType) { + String type = duckdbType.toUpperCase(Locale.ENGLISH); + return CELL_TYPES.contains(type) || type.startsWith("DECIMAL"); + } + + @Override + protected void describeTable(ExportManifest.TableEntry tableEntry, DuckDBWorkspace workspace, String schema, + String table) throws Exception { + tableEntry.getColumns().clear(); + for (String[] column : workspace.describeTable(schema, table)) { + tableEntry.getColumns().add(new ExportManifest.ColumnEntry(column[0], column[1])); + } + } + + @Override + protected void putOptions(Map options) { + options.put("maxRows", maxRows); + } +} diff --git a/src/main/java/com/github/sqljam/impexp/fs/ExcelImporter.java b/src/main/java/com/github/sqljam/impexp/fs/ExcelImporter.java new file mode 100644 index 0000000..ba54ba7 --- /dev/null +++ b/src/main/java/com/github/sqljam/impexp/fs/ExcelImporter.java @@ -0,0 +1,123 @@ +/* + * 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.impexp.fs; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.github.sqljam.utils.ExcelUtils; +import com.github.sqljam.impexp.DataFileImporter; +import com.github.sqljam.impexp.DataFormat; +import com.github.sqljam.impexp.DbType; +import com.github.sqljam.impexp.DuckDBWorkspace; +import com.github.sqljam.impexp.ExportManifest; +import com.github.sqljam.impexp.ImpExpException; + +/** + * @Description: ExcelImporter imports Excel workbooks (.xlsx) into a database by a connection: packages exported by + * {@link ExcelExporter}, whose values are read with the column types of manifest.json, or workbooks of + * other tools without manifest.json, whose first row names the columns and whose column types are + * detected, into a new table or appended to an existing table. A sheet is read as a CSV file in the + * workspace, then it is loaded like the CSV files of other tools. + * @Author: Fred Feng + * @Date: 24/10/2026 + * @Version 1.0.0 + */ +public class ExcelImporter extends DataFileImporter { + + /** + * Sheet of workbooks of other tools, null for the first sheet + */ + private String sheet; + /** + * CSV files of the sheets in the workspace, read once for counting and loading + */ + private final Map csvFiles = new HashMap<>(); + + public ExcelImporter(Connection connection, DbType dbType) { + super(connection, dbType); + } + + /** + * Sheet of the workbooks, the first sheet if null + */ + public void setSheet(String sheet) { + this.sheet = sheet; + } + + public String getSheet() { + return sheet; + } + + @Override + protected DataFormat getDataFormat() { + return DataFormat.EXCEL; + } + + @Override + protected ExportManifest.FileType getFileType() { + return ExportManifest.FileType.EXCEL; + } + + @Override + protected long countRows(DuckDBWorkspace workspace, List files) throws SQLException, IOException { + return workspace.countFileRows(toCsv(workspace, files), new CsvOptions()); + } + + @Override + protected void prepare(ExportManifest manifest) { + // A package has one sheet in each workbook + sheet = null; + } + + @Override + protected void load(DuckDBWorkspace workspace, String schema, String table, List files, + List identityColumns, ExportManifest.TableEntry tableEntry) throws SQLException, + IOException { + workspace.loadCsv(schema, table, toCsv(workspace, files), tableEntry != null ? tableEntry.getColumns() : null, + identityColumns, new CsvOptions()); + } + + /** + * CSV files of the sheets of the workbooks in the directory of the workspace, deleted with it. They have the + * default options of CSV files: comma, double quotes, a header row, NULL is an empty field + */ + private List toCsv(DuckDBWorkspace workspace, List files) throws IOException { + File directory = workspace.getFile().getParentFile(); + List converted = new ArrayList<>(); + for (File file : files) { + String key = directory.getPath() + File.pathSeparator + file.getAbsolutePath(); + File csv = csvFiles.get(key); + if (csv == null) { + csv = new File(directory, "excel-" + (csvFiles.size() + 1) + ".csv"); + try { + ExcelUtils.toCsv(file, sheet, csv); + } catch (IllegalArgumentException e) { + throw new ImpExpException(e.getMessage(), e); + } + csvFiles.put(key, csv); + } + converted.add(csv); + } + return converted; + } +} diff --git a/src/main/java/com/github/sqljam/jdbc/ConnectionFactory.java b/src/main/java/com/github/sqljam/jdbc/ConnectionFactory.java index f9eecb0..9a757e4 100644 --- a/src/main/java/com/github/sqljam/jdbc/ConnectionFactory.java +++ b/src/main/java/com/github/sqljam/jdbc/ConnectionFactory.java @@ -17,6 +17,7 @@ import java.sql.Connection; import java.sql.SQLException; +import com.github.sqljam.utils.JdbcUtils; /** * @Description: ConnectionFactory provides jdbc connections diff --git a/src/main/java/com/github/sqljam/jdbc/ManualTransaction.java b/src/main/java/com/github/sqljam/jdbc/ManualTransaction.java index d26e617..4f69c79 100644 --- a/src/main/java/com/github/sqljam/jdbc/ManualTransaction.java +++ b/src/main/java/com/github/sqljam/jdbc/ManualTransaction.java @@ -31,6 +31,7 @@ import java.util.regex.Pattern; import lombok.extern.slf4j.Slf4j; +import com.github.sqljam.utils.JdbcUtils; /** * @Description: ManualTransaction runs an import in one transaction which is committed or rolled back by the user diff --git a/src/main/java/com/github/sqljam/jdbc/SimpleConnectionFactory.java b/src/main/java/com/github/sqljam/jdbc/SimpleConnectionFactory.java index 5f2a832..fad403c 100644 --- a/src/main/java/com/github/sqljam/jdbc/SimpleConnectionFactory.java +++ b/src/main/java/com/github/sqljam/jdbc/SimpleConnectionFactory.java @@ -17,6 +17,7 @@ import java.sql.Connection; import java.sql.SQLException; +import com.github.sqljam.utils.JdbcUtils; import com.github.sqljam.impexp.TransactionIsolationLevel; /** diff --git a/src/main/java/com/github/sqljam/page/MapBasedPageReader.java b/src/main/java/com/github/sqljam/page/MapBasedPageReader.java index 273f70f..8b2deac 100644 --- a/src/main/java/com/github/sqljam/page/MapBasedPageReader.java +++ b/src/main/java/com/github/sqljam/page/MapBasedPageReader.java @@ -29,7 +29,7 @@ import com.github.sqljam.impexp.Dialect; import com.github.sqljam.impexp.PooledConnectionFactory; import com.github.sqljam.jdbc.ConnectionFactory; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; import com.github.sqljam.utils.CaseInsensitiveMap; /** diff --git a/src/main/java/com/github/sqljam/utils/ExcelUtils.java b/src/main/java/com/github/sqljam/utils/ExcelUtils.java new file mode 100644 index 0000000..25cadda --- /dev/null +++ b/src/main/java/com/github/sqljam/utils/ExcelUtils.java @@ -0,0 +1,417 @@ +/* + * 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.utils; + +import java.io.BufferedOutputStream; +import java.io.BufferedWriter; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Writer; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.io.FilenameUtils; +import org.dhatim.fastexcel.Workbook; +import org.dhatim.fastexcel.Worksheet; +import org.dhatim.fastexcel.reader.Cell; +import org.dhatim.fastexcel.reader.CellType; +import org.dhatim.fastexcel.reader.ReadableWorkbook; +import org.dhatim.fastexcel.reader.ReadingOptions; +import org.dhatim.fastexcel.reader.Row; +import org.dhatim.fastexcel.reader.Sheet; + +import lombok.extern.slf4j.Slf4j; + +/** + * @Description: ExcelUtils writes rows of a result set into Excel workbooks (.xlsx, one sheet with a header row, + * split into orders.xlsx, orders_2.xlsx ... at a number of rows) and reads a sheet of a workbook as a + * CSV file. Numbers, booleans, dates and timestamps are cells of their types, values which a cell + * would change (more than 15 digits, microseconds, days before 1900-03-01) are text, so that the values are read back exactly. + * @Author: Fred Feng + * @Date: 24/10/2026 + * @Version 1.0.0 + */ +@Slf4j +public final class ExcelUtils { + + public static final String EXCEL_EXTENSION = ".xlsx"; + /** + * Rows of a sheet without its header row + */ + public static final int MAX_ROWS = Worksheet.MAX_ROWS - 1; + /** + * Characters of a cell which Excel shows, longer values are kept but cut by Excel + */ + public static final int MAX_CELL_LENGTH = 32767; + + private static final int MAX_SHEET_NAME = 31; + private static final int DIGITS_OF_DOUBLE = 15; + private static final int FLUSHED_ROWS = 10000; + private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + /** + * The first day which a date cell keeps: Excel counts days from 1900 and takes 1900 for a leap year, so earlier + * days are text + */ + private static final LocalDate FIRST_CELL_DATE = LocalDate.of(1900, 3, 1); + private static final DateTimeFormatter TIMESTAMP = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"); + + private ExcelUtils() { + } + + public static boolean isExcel(File file) { + return file.getName().toLowerCase(Locale.ENGLISH).endsWith(EXCEL_EXTENSION); + } + + /** + * Writes the rows of the result set into workbooks of at most maxRows rows each, the first one is the file + * + * @param columns names of the columns of the result set, the header row + * @param sheetName name of the sheet, made acceptable to Excel + * @return the written files: orders.xlsx, orders_2.xlsx ... + */ + public static List write(ResultSet rs, List columns, String sheetName, File file, int maxRows) + throws SQLException, IOException { + int rowsPerFile = maxRows > 0 ? Math.min(maxRows, MAX_ROWS) : MAX_ROWS; + List files = new ArrayList<>(); + boolean more = rs.next(); + do { + File part = files.isEmpty() ? file : new File(file.getParentFile(), FilenameUtils.getBaseName(file + .getName()) + "_" + (files.size() + 1) + EXCEL_EXTENSION); + more = writePart(rs, more, columns, sheetName, part, rowsPerFile); + files.add(part); + } while (more); + return files; + } + + /** + * Writes rows into one workbook, the current row of the result set is the first one + * + * @return whether rows are left for the next workbook + */ + private static boolean writePart(ResultSet rs, boolean more, List columns, String table, File file, + int rowsPerFile) throws SQLException, IOException { + Files.createDirectories(file.getAbsoluteFile().getParentFile().toPath()); + boolean hasRows = more; + try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) { + Workbook workbook = new Workbook(out, "SqlJam", null); + Worksheet sheet = workbook.newWorksheet(sheetName(table)); + for (int c = 0; c < columns.size(); c++) { + sheet.inlineString(0, c, columns.get(c)); + sheet.style(0, c).bold().set(); + } + sheet.freezePane(0, 1); + int r = 0; + boolean warned = false; + while (hasRows && r < rowsPerFile) { + r++; + for (int c = 0; c < columns.size(); c++) { + warned |= writeCell(sheet, r, c, valueOf(rs, c + 1), warned, table, columns.get(c)); + } + if (r % FLUSHED_ROWS == 0) { + sheet.flush(); + } + hasRows = rs.next(); + } + workbook.finish(); + } + return hasRows; + } + + /** + * A value of the result set, dates and timestamps as java.time values: java.sql.Date and Timestamp take the + * Julian calendar for days before 1582, e.g. 0001-01-01 would be two days off + */ + private static Object valueOf(ResultSet rs, int column) throws SQLException { + Object value = rs.getObject(column); + try { + if (value instanceof java.sql.Date) { + return rs.getObject(column, LocalDate.class); + } + if (value instanceof Timestamp) { + return rs.getObject(column, LocalDateTime.class); + } + } catch (SQLException e) { + // A driver without java.time values, the value as it is + } + return value; + } + + /** + * Writes a value as a cell of its type, null is no cell + * + * @return whether a value longer than Excel shows was written + */ + private static boolean writeCell(Worksheet sheet, int r, int c, Object value, boolean warned, String table, + String column) { + if (value == null) { + return false; + } + if (value instanceof Boolean) { + sheet.value(r, c, (Boolean) value); + } else if (value instanceof Double || value instanceof Float) { + double number = ((Number) value).doubleValue(); + if (Double.isFinite(number)) { + sheet.value(r, c, (Number) value); + } else { + // inf, -inf and nan as databases read them back + sheet.inlineString(r, c, value.toString().toLowerCase(Locale.ENGLISH).replace("infinity", "inf")); + } + } else if (value instanceof Number) { + BigDecimal number = value instanceof BigDecimal ? (BigDecimal) value : value instanceof BigInteger + ? new BigDecimal((BigInteger) value) : BigDecimal.valueOf(((Number) value).longValue()); + if (number.precision() <= DIGITS_OF_DOUBLE) { + sheet.value(r, c, number); + } else { + // A cell keeps 15 digits, larger numbers are text + sheet.inlineString(r, c, number.toPlainString()); + } + } else if (value instanceof LocalDate || value instanceof java.sql.Date) { + LocalDate date = value instanceof LocalDate ? (LocalDate) value : ((java.sql.Date) value).toLocalDate(); + if (date.isBefore(FIRST_CELL_DATE)) { + sheet.inlineString(r, c, date.format(DATE)); + } else { + sheet.value(r, c, date); + sheet.style(r, c).format("yyyy-mm-dd").set(); + } + } else if (value instanceof Timestamp || value instanceof LocalDateTime) { + LocalDateTime timestamp = value instanceof Timestamp ? ((Timestamp) value).toLocalDateTime() + : (LocalDateTime) value; + if (timestamp.getNano() % 1_000_000 == 0 && !timestamp.toLocalDate().isBefore(FIRST_CELL_DATE)) { + sheet.value(r, c, timestamp); + sheet.style(r, c).format(timestamp.getNano() == 0 ? "yyyy-mm-dd hh:mm:ss" + : "yyyy-mm-dd hh:mm:ss.000").set(); + } else { + // A cell keeps milliseconds and days from 1900-03-01, others are text + sheet.inlineString(r, c, timestamp.format(TIMESTAMP)); + } + } else { + String text = value.toString(); + sheet.inlineString(r, c, text); + if (text.length() > MAX_CELL_LENGTH && !warned) { + log.warn("{}.{} has values longer than the {} characters which Excel shows, they are kept", table, + column, MAX_CELL_LENGTH); + return true; + } + } + return false; + } + + /** + * A name which Excel accepts for a sheet: 31 characters at most, without : \ / ? * [ ] + */ + static String sheetName(String table) { + String name = table.replaceAll("[:\\\\/?*\\[\\]]", "_").replaceAll("^'+|'+$", ""); + name = name.isEmpty() ? "Sheet1" : name; + return name.length() > MAX_SHEET_NAME ? name.substring(0, MAX_SHEET_NAME) : name; + } + + /** + * Names of the sheets of a workbook in their order + */ + public static List sheetNames(File file) throws IOException { + try (ReadableWorkbook workbook = open(file)) { + return workbook.getSheets().map(Sheet::getName).collect(Collectors.toList()); + } + } + + /** + * Writes a sheet of a workbook as a CSV file in UTF-8 with the first row as its header: numbers in plain + * notation, dates as yyyy-MM-dd, timestamps as yyyy-MM-dd HH:mm:ss.SSS, booleans as true and false, formulas + * by their computed values. An empty cell is NULL, an empty text is "", errors (#DIV/0!) are NULL. + * + * @param sheetName name of the sheet, null for the first sheet + * @return rows written without the header row + */ + public static long toCsv(File file, String sheetName, File csv) throws IOException { + try (ReadableWorkbook workbook = open(file)) { + Sheet sheet = sheetName == null ? workbook.getFirstSheet() : workbook.findSheet(sheetName) + .orElseThrow(() -> new IllegalArgumentException(String.format("%s has no sheet %s", + file.getName(), sheetName))); + Files.createDirectories(csv.getAbsoluteFile().getParentFile().toPath()); + long rows = 0; + try (Stream stream = sheet.openStream(); + Writer writer = new BufferedWriter(Files.newBufferedWriter(csv.toPath(), StandardCharsets.UTF_8))) { + Iterator iterator = stream.iterator(); + int width = -1; + while (iterator.hasNext()) { + Row row = iterator.next(); + if (width < 0) { + // The first row is the header, its last named cell ends the columns + width = headerWidth(row); + if (width == 0) { + width = -1; + continue; + } + writeHeader(writer, row, width); + continue; + } + if (isEmpty(row, width)) { + continue; + } + for (int c = 0; c < width; c++) { + if (c > 0) { + writer.write(','); + } + writer.write(csvValue(row.getOptionalCell(c).orElse(null))); + } + writer.write('\n'); + rows++; + } + } + return rows; + } + } + + private static ReadableWorkbook open(File file) throws IOException { + byte[] header = new byte[8]; + try (InputStream in = Files.newInputStream(file.toPath())) { + int read = in.read(header); + if (read == header.length && ReadableWorkbook.isOLE2Header(header)) { + throw new IOException(String.format("%s is a workbook of Excel 97-2003, save it as .xlsx", + file.getName())); + } + } + return new ReadableWorkbook(file, new ReadingOptions(true, false)); + } + + private static int headerWidth(Row row) { + int width = 0; + for (int c = 0; c < row.getCellCount(); c++) { + Cell cell = row.getOptionalCell(c).orElse(null); + if (cell != null && cell.getType() != CellType.EMPTY && !cell.getText().isEmpty()) { + width = c + 1; + } + } + return width; + } + + private static void writeHeader(Writer writer, Row row, int width) throws IOException { + for (int c = 0; c < width; c++) { + if (c > 0) { + writer.write(','); + } + Cell cell = row.getOptionalCell(c).orElse(null); + String name = cell != null ? cell.getText().trim() : ""; + writer.write(quote(name.isEmpty() ? "column" + (c + 1) : name)); + } + writer.write('\n'); + } + + private static boolean isEmpty(Row row, int width) { + for (int c = 0; c < width; c++) { + Cell cell = row.getOptionalCell(c).orElse(null); + if (cell != null && cell.getType() != CellType.EMPTY) { + return false; + } + } + return true; + } + + /** + * A value of a cell in CSV, an empty field for NULL + */ + static String csvValue(Cell cell) { + if (cell == null) { + return ""; + } + Object value = cell.getValue(); + switch (cell.getType()) { + case EMPTY: + case ERROR: + return ""; + case BOOLEAN: + return String.valueOf(cell.asBoolean()); + case NUMBER: + return number(cell, (BigDecimal) value); + case FORMULA: + // The value computed by the spreadsheet, empty when it never computed it + if (value instanceof BigDecimal) { + return number(cell, (BigDecimal) value); + } + return value == null ? "" : quote(value.toString()); + default: + return quote(value == null ? "" : value.toString()); + } + } + + private static String number(Cell cell, BigDecimal value) { + if (value == null) { + return ""; + } + if (isDateFormat(cell.getDataFormatId(), cell.getDataFormatString())) { + LocalDateTime date = cell.asDate(); + if (date.toLocalTime().equals(LocalTime.MIDNIGHT) && !hasTime(cell.getDataFormatString())) { + return date.format(DATE); + } + String text = date.format(TIMESTAMP); + // Milliseconds at most, trailing zeros removed + return text.replaceAll("\\.?0+$", ""); + } + return value.toPlainString(); + } + + /** + * Whether a number format shows a date: the built-in formats of dates and times, or a format with days, + * months, years, hours or seconds outside of quotes, brackets and escapes, fractions of seconds included + */ + static boolean isDateFormat(Integer id, String format) { + if (id != null && (id >= 14 && id <= 22 || id >= 45 && id <= 47)) { + return true; + } + if (format == null || format.isEmpty() || "General".equalsIgnoreCase(format)) { + return false; + } + // Fractions of seconds (ss.000) are not digits of numbers + String plain = format.replaceAll("\"[^\"]*\"", "").replaceAll("\\[[^\\]]*\\]", "").replaceAll("\\\\.", "") + .toLowerCase(Locale.ENGLISH).replaceAll("s\\.0+", "s"); + return plain.matches(".*[dmyhs].*") && !plain.matches(".*[0#?].*"); + } + + private static boolean hasTime(String format) { + return format != null && format.replaceAll("\"[^\"]*\"", "").toLowerCase(Locale.ENGLISH).matches(".*[hs].*"); + } + + /** + * A field quoted when needed, an empty text is "" to keep it apart from NULL + */ + static String quote(String text) { + if (text.isEmpty()) { + return "\"\""; + } + if (text.indexOf(',') >= 0 || text.indexOf('"') >= 0 || text.indexOf('\n') >= 0 || text.indexOf('\r') >= 0 + || !text.trim().equals(text)) { + return '"' + text.replace("\"", "\"\"") + '"'; + } + return text; + } +} diff --git a/src/main/java/com/github/sqljam/jdbc/JdbcUtils.java b/src/main/java/com/github/sqljam/utils/JdbcUtils.java similarity index 99% rename from src/main/java/com/github/sqljam/jdbc/JdbcUtils.java rename to src/main/java/com/github/sqljam/utils/JdbcUtils.java index f3059df..b59972c 100644 --- a/src/main/java/com/github/sqljam/jdbc/JdbcUtils.java +++ b/src/main/java/com/github/sqljam/utils/JdbcUtils.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.github.sqljam.jdbc; +package com.github.sqljam.utils; import java.math.BigDecimal; import java.math.BigInteger; @@ -50,9 +50,8 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.lang3.StringUtils; -import com.github.sqljam.utils.CaseInsensitiveMap; -import com.github.sqljam.utils.ConvertUtils; -import com.github.sqljam.utils.Observable; +import com.github.sqljam.jdbc.Cursor; +import com.github.sqljam.jdbc.PreparedStatementCallback; import lombok.experimental.UtilityClass; /** diff --git a/src/main/java/com/github/sqljam/impexp/SqlTextUtils.java b/src/main/java/com/github/sqljam/utils/SqlTextUtils.java similarity index 98% rename from src/main/java/com/github/sqljam/impexp/SqlTextUtils.java rename to src/main/java/com/github/sqljam/utils/SqlTextUtils.java index f52c45b..70e079a 100644 --- a/src/main/java/com/github/sqljam/impexp/SqlTextUtils.java +++ b/src/main/java/com/github/sqljam/utils/SqlTextUtils.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.github.sqljam.impexp; +package com.github.sqljam.utils; import java.util.ArrayList; import java.util.Collection; diff --git a/src/main/resources/com/github/sqljam/face/messages.properties b/src/main/resources/com/github/sqljam/face/messages.properties index d7a10c3..1c8e19d 100644 --- a/src/main/resources/com/github/sqljam/face/messages.properties +++ b/src/main/resources/com/github/sqljam/face/messages.properties @@ -19,7 +19,7 @@ action.refresh=Refresh action.export=Export... action.import=Import... action.importScripts=Import Export Package... -action.importParquet=Import Parquet or CSV Files... +action.importParquet=Import Parquet, CSV or Excel Files... action.importVectorDatabase=Import from Vector Database... action.exit=Exit action.newTargetConnection=New data source as the target @@ -28,7 +28,7 @@ action.copy=Copy about.title=About SqlJam about.header=SqlJam {0} -about.message=Move tables across databases. Schema, data and all.\n\nCopies tables, indexes, constraints, sequences and partitions directly into another database, saves them as SQL, Parquet or CSV export packages, and imports collections of vector databases into databases with vectors. +about.message=Move tables across databases. Schema, data and all.\n\nCopies tables, indexes, constraints, sequences and partitions directly into another database, saves them as SQL, Parquet, CSV or Excel export packages, and imports collections of vector databases into databases with vectors. about.tab=About about.features=Features feature.reliability.title=Reliability @@ -43,7 +43,7 @@ feature.structure.items=Tables, primary keys, indexes and foreign keys|Sequences feature.rows.title=Rows feature.rows.items=Data viewer with columns, WHERE and ORDER BY|SQL Query with highlighting, its rows exported|Insert, update or insert, or skip existing by key|Column mapping: names, types, columns left out|Values in one line, whole values, rows copied as CSV, JSON or Markdown feature.transfer.title=Import and export -feature.transfer.items=Straight into another database|Export packages of SQL, Parquet or CSV|Packages imported in order, checked by SHA-256|Parquet and CSV files of other tools|Copies in the same schema|Package viewer +feature.transfer.items=Straight into another database|Export packages of SQL, Parquet, CSV or Excel|Packages imported in order, checked by SHA-256|Parquet, CSV and Excel files of other tools|Copies in the same schema|Package viewer about.version=Version about.homepage=Home page about.repository=Repository @@ -269,7 +269,7 @@ import.error.directory=Please choose a directory exported by SqlJam import.error.manifest=Unable to read manifest: {0} import.warning.status=The package is {0}, it can not be imported import.warning.noDataSource=The package is exported for {0}, please create a {0} data source first -import.warning.parquetFiles=The directory contains Parquet or CSV files without manifest.json, please use Import Parquet or CSV Files +import.warning.parquetFiles=The directory contains Parquet, CSV or Excel files without manifest.json, please use Import Parquet, CSV or Excel Files import.summary=Executed {0} statements, restored {1} LOB values, {2} failed report.view=View Report @@ -366,6 +366,8 @@ export.format=Data format export.format.sql=SQL scripts export.format.parquet=Parquet export.format.csv=CSV +export.format.excel=Excel +export.format.excel.split=... above {0} rows export.format.delimiter=CSV delimiter export.format.delimiter.comma=Comma ( , ) export.format.delimiter.semicolon=Semicolon ( ; ) @@ -387,16 +389,17 @@ package.truncated=... the first {0} of {1} are shown package.column.name=Name package.column.size=Size package.column.modified=Modified -parquet.title=Import Parquet or CSV Files -parquet.header=Load Parquet or CSV files into a table of a database +parquet.title=Import Parquet, CSV or Excel Files +parquet.header=Load Parquet, CSV or Excel files into a table of a database parquet.section.files=Data files parquet.files.add=Add Files... parquet.files.remove=Remove -parquet.files.filter=Parquet and CSV files +parquet.files.filter=Parquet, CSV and Excel files parquet.files.filter.parquet=Parquet files parquet.files.filter.csv=CSV files -parquet.files.empty=No files, add Parquet or CSV files of one table -parquet.files.hint=Files of one table are loaded together in this order, columns and the first rows are previewed. Delimiters and column types of CSV files are detected +parquet.files.filter.excel=Excel workbooks +parquet.files.empty=No files, add Parquet, CSV or Excel files of one table +parquet.files.hint=Files of one table are loaded together in this order, columns and the first rows are previewed. Delimiters and column types of CSV files are detected, the first row of an Excel sheet names its columns parquet.preview={0} columns, {1} rows, the first {2} are shown parquet.table=Table parquet.table.prompt=Name of the target table @@ -408,7 +411,8 @@ parquet.mode.skip=Insert rows, skip existing ones by key parquet.keys.prompt=Key columns, the primary key of the table if empty parquet.keys.tooltip=Columns of a unique index or the primary key of the target table, separated by commas: MySQL and MariaDB match rows by their unique indexes, PostgreSQL, SQLite and DuckDB require such an index. parquet.error.read=Unable to read the files: {0} -parquet.error.mixed=Files of one table must be all Parquet or all CSV +parquet.error.mixed=Files of one table must be all Parquet, all CSV or all Excel +parquet.sheet=Sheet parquet.error.table=Please enter the name of the target table parquet.summary=Loaded {0} rows into {1} data.query.allColumns=All columns diff --git a/src/test/java/com/github/sqljam/face/service/TransferServiceTest.java b/src/test/java/com/github/sqljam/face/service/TransferServiceTest.java index 14bf38a..91470a5 100644 --- a/src/test/java/com/github/sqljam/face/service/TransferServiceTest.java +++ b/src/test/java/com/github/sqljam/face/service/TransferServiceTest.java @@ -34,7 +34,7 @@ import com.github.sqljam.face.model.TransferRequest; import com.github.sqljam.face.model.TransferReport; import com.github.sqljam.face.view.UiDatabase; -import com.github.sqljam.impexp.CsvImporter; +import com.github.sqljam.impexp.fs.CsvImporter; import com.github.sqljam.impexp.DataFileImporter; import com.github.sqljam.impexp.DataFormat; import com.github.sqljam.impexp.DbType; diff --git a/src/test/java/com/github/sqljam/face/view/DocScreenshots.java b/src/test/java/com/github/sqljam/face/view/DocScreenshots.java index 46148e0..7f0c8a8 100644 --- a/src/test/java/com/github/sqljam/face/view/DocScreenshots.java +++ b/src/test/java/com/github/sqljam/face/view/DocScreenshots.java @@ -20,7 +20,6 @@ import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -202,7 +201,6 @@ void dataSource() throws IOException { snapshotDialog(dialog, 640, 760, "data-source.png"); } - /** * Node of a fixture table of the MySQL test database */ 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 8ab3301..d91af34 100644 --- a/src/test/java/com/github/sqljam/face/view/ExportDialogTest.java +++ b/src/test/java/com/github/sqljam/face/view/ExportDialogTest.java @@ -528,6 +528,25 @@ void mapsCsvFormat() { FxTestSupport.run(next::close); } + /** + * Excel workbooks are split at the rows of a sheet, the size of files does not apply + */ + @Test + void mapsExcelFormat() { + open(schemaNode()); + setText("directoryField", dir.getAbsolutePath()); + FxTestSupport.run(() -> ((RadioButton) node("excelFormatRadio")).setSelected(true)); + for (String id : new String[]{"singleFileRadio", "perTableRadio", "lobSeparatedCheck", "compressionCombo", + "csvDelimiterCombo", "maxFileSizeSpinner"}) { + assertTrue(FxTestSupport.call(() -> node(id).isDisabled()), id); + } + assertEquals("schema.sql\ndata/
.xlsx,
_2.xlsx ... above 1,048,575 rows\nconstraints.sql" + + "\nmanifest.json", FxTestSupport.call(() -> ((Label) node("layoutHint")).getText())); + assertEquals(DataFormat.EXCEL, build().getDataFormat()); + // The size of text files is kept + assertEquals(10L * 1024 * 1024, context.getSettings().getMaxDataFileSize()); + } + /** * Parquet files are split at their own size, sql scripts and CSV files share one */ diff --git a/src/test/java/com/github/sqljam/face/view/ImportPackageDialogTest.java b/src/test/java/com/github/sqljam/face/view/ImportPackageDialogTest.java index ea36fac..0d3ea34 100644 --- a/src/test/java/com/github/sqljam/face/view/ImportPackageDialogTest.java +++ b/src/test/java/com/github/sqljam/face/view/ImportPackageDialogTest.java @@ -19,7 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import com.github.sqljam.impexp.CsvImporter; +import com.github.sqljam.impexp.fs.CsvImporter; import com.github.sqljam.jdbc.ManualTransaction; import java.io.File; import java.nio.file.Files; @@ -425,9 +425,8 @@ void guidesParquetFilesWithoutManifest() throws Exception { assertTrue(new File(parquetDir, ExportManifest.FILE_NAME).delete()); open(parquetDir); assertTrue(startDisabled()); - assertEquals("The directory contains Parquet or CSV files without manifest.json, please use Import Parquet or CSV" - + " Files", - text("warningLabel")); + assertEquals("The directory contains Parquet, CSV or Excel files without manifest.json, please use Import" + + " Parquet, CSV or Excel Files", text("warningLabel")); assertTrue(ImportPackageDialog.isParquetDirectory(parquetDir)); assertFalse(ImportPackageDialog.isParquetDirectory(dir)); } diff --git a/src/test/java/com/github/sqljam/face/view/ImportParquetDialogTest.java b/src/test/java/com/github/sqljam/face/view/ImportParquetDialogTest.java index 4e3ccd7..999876c 100644 --- a/src/test/java/com/github/sqljam/face/view/ImportParquetDialogTest.java +++ b/src/test/java/com/github/sqljam/face/view/ImportParquetDialogTest.java @@ -21,6 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; +import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.file.Files; import java.sql.Connection; @@ -31,6 +32,8 @@ import java.util.stream.Collectors; import javafx.scene.control.CheckBox; +import org.dhatim.fastexcel.Workbook; +import org.dhatim.fastexcel.Worksheet; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -162,7 +165,8 @@ void requiresFilesAndTable() throws Exception { open(null); assertTrue(startDisabled()); assertEquals("Files of one table are loaded together in this order, columns and the first rows are previewed." - + " Delimiters and column types of CSV files are detected", + + " Delimiters and column types of CSV files are detected, the first row of an Excel sheet names its" + + " columns", text("parquetPreviewLabel")); // The only data source is the target assertEquals("Target H2", FxTestSupport.call(() -> { @@ -259,7 +263,7 @@ void loadsCsvPartsInOrder() throws Exception { void rejectsMixedFormats() throws Exception { open(null); addFiles(writeParquet("orders.parquet", 0, 10), writeCsv("orders.csv", 10, 20)); - assertEquals("Files of one table must be all Parquet or all CSV", text("warningLabel")); + assertEquals("Files of one table must be all Parquet, all CSV or all Excel", text("warningLabel")); assertTrue(startDisabled()); assertTrue(FxTestSupport.call(() -> preview().getColumns().isEmpty())); } @@ -392,4 +396,60 @@ void previewsCsvWithOptions() throws Exception { assertEquals("北京", FxTestSupport.call(() -> preview().getItems().get(0).get(1))); assertEquals("GBK", FxTestSupport.call(dialog::buildRequest).getCsvOptions().getEncoding()); } + + /** + * Workbooks of a spreadsheet: their sheets are listed, the first one is previewed, another sheet is previewed + * when it is chosen and loaded into the table without manifest.json + */ + @Test + void previewsAndLoadsSheetsOfWorkbooks() throws Exception { + open(DbNode.connection(target)); + File file = new File(dir, "orders.xlsx"); + try (OutputStream out = Files.newOutputStream(file.toPath())) { + Workbook workbook = new Workbook(out, "Spreadsheet", "1.0"); + Worksheet summary = workbook.newWorksheet("Summary"); + summary.value(0, 0, "total"); + summary.value(1, 0, 3); + Worksheet orders = workbook.newWorksheet("Orders"); + orders.value(0, 0, "ID"); + orders.value(0, 1, "NAME"); + for (int i = 1; i <= 3; i++) { + orders.value(i, 0, i); + orders.value(i, 1, "name " + i); + } + workbook.finish(); + } + addFiles(file); + waitForPreview(); + assertTrue(FxTestSupport.call(() -> node("sheetBox").isVisible())); + assertFalse(FxTestSupport.call(() -> node("csvOptionsBox").isVisible())); + ComboBox sheets = FxTestSupport.call(() -> (ComboBox) node("sheetCombo")); + assertEquals(List.of("Summary", "Orders"), FxTestSupport.call(() -> List.copyOf(sheets.getItems()))); + assertEquals("1 columns, 1 rows, the first 1 are shown", text("parquetPreviewLabel")); + FxTestSupport.run(() -> sheets.setValue("Orders")); + FxTestSupport.waitUntil(() -> text("parquetPreviewLabel").startsWith("2 columns, 3 rows")); + assertEquals("name 1", FxTestSupport.call(() -> preview().getItems().get(0).get(1))); + ImportParquetDialog.ParquetRequest request = FxTestSupport.call(dialog::buildRequest); + assertEquals("Orders", request.getSheet()); + assertNull(request.getCsvOptions()); + + ProgressDialog progress = FxTestSupport.call(() -> new ProgressDialog(stage, context, "Import", 1)); + FxTestSupport.run(() -> progress.run(() -> context.getTransferService().importFiles(target, null, null, + request.getFiles(), "ORDERS", ParquetImporter.Mode.CREATE, List.of(), null, request.getSheet(), false, + 0, null, progress.getListener()), (DataFileImporter importer) -> String.valueOf(importer + .getImportedRows()), null)); + FxTestSupport.waitUntil(progress::isFinished); + assertEquals("Completed", status(progress)); + assertEquals(3, countRows()); + } + + @Test + void reportsUnreadableWorkbooks() throws Exception { + open(null); + File file = new File(dir, "broken.xlsx"); + Files.writeString(file.toPath(), "not a workbook"); + addFiles(file); + FxTestSupport.waitUntil(() -> text("warningLabel").startsWith("Unable to read the files")); + assertTrue(startDisabled()); + } } 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 6ac5705..b2d43e8 100644 --- a/src/test/java/com/github/sqljam/face/view/MainViewTest.java +++ b/src/test/java/com/github/sqljam/face/view/MainViewTest.java @@ -349,11 +349,11 @@ private MenuItem fileMenuItem(String id) { @Test void opensParquetImportFromMenuAndTree() { MenuItem importParquet = fileMenuItem("importParquetMenuItem"); - assertEquals("Import Parquet or CSV Files...", importParquet.getText()); + assertEquals("Import Parquet, CSV or Excel Files...", importParquet.getText()); assertEquals("Open Export Package...", fileMenuItem("openPackageMenuItem").getText()); Platform.runLater(importParquet::fire); DialogPane pane = FxTestSupport.waitForDialogPane(); - assertEquals("Load Parquet or CSV files into a table of a database", FxTestSupport.call(pane::getHeaderText)); + assertEquals("Load Parquet, CSV or Excel files into a table of a database", FxTestSupport.call(pane::getHeaderText)); assertTrue(FxTestSupport.call(() -> pane.lookupButton(ButtonType.OK).isDisabled())); FxTestSupport.closeDialog(ButtonType.CANCEL); // The context menu of a data source offers both imports @@ -368,7 +368,7 @@ void opensParquetImportFromMenuAndTree() { .flatMap(cell -> cell.getContextMenu().getItems().stream()).map(MenuItem::getText) .filter(text -> text != null).collect(Collectors.toList()); }); - assertTrue(items.containsAll(List.of("Import Export Package...", "Import Parquet or CSV Files...")), + assertTrue(items.containsAll(List.of("Import Export Package...", "Import Parquet, CSV or Excel Files...")), items.toString()); } diff --git a/src/test/java/com/github/sqljam/face/view/ReportBoundaryTest.java b/src/test/java/com/github/sqljam/face/view/ReportBoundaryTest.java index 4037dfa..d9e1b4e 100644 --- a/src/test/java/com/github/sqljam/face/view/ReportBoundaryTest.java +++ b/src/test/java/com/github/sqljam/face/view/ReportBoundaryTest.java @@ -428,8 +428,8 @@ void reportsImportsOfPackagesAndFiles() throws Exception { List files = manifest.getTables().get(0).getDataFiles().stream().map(path -> new File(packageDir, path)).toList(); ProgressDialog files2 = FxTestSupport.call(() -> mainView.startFileImport(new ImportParquetDialog - .ParquetRequest(files, "BIG_COPY", DataFileImporter.Mode.CREATE, List.of(), null, target, null, null, - true, false, false, 0))); + .ParquetRequest(files, "BIG_COPY", DataFileImporter.Mode.CREATE, List.of(), null, null, target, null, + null, true, false, false, 0))); TransferReport fileReport = saved(context, files2); assertEquals(TransferReport.Status.COMPLETED, fileReport.getStatus(), fileReport.getFailure()); assertEquals(TransferReport.Kind.FILE_IMPORT, fileReport.getKind()); diff --git a/src/test/java/com/github/sqljam/impexp/DataFileBoundaryTest.java b/src/test/java/com/github/sqljam/impexp/DataFileBoundaryTest.java index 4833885..f35ae0a 100644 --- a/src/test/java/com/github/sqljam/impexp/DataFileBoundaryTest.java +++ b/src/test/java/com/github/sqljam/impexp/DataFileBoundaryTest.java @@ -34,6 +34,9 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import com.github.sqljam.impexp.fs.CsvExporter; +import com.github.sqljam.impexp.fs.CsvImporter; +import com.github.sqljam.impexp.fs.CsvOptions; /** * @Description: DataFileBoundaryTest verifies CSV and Parquet packages at their boundaries with H2 databases: empty diff --git a/src/test/java/com/github/sqljam/impexp/QueryExportTest.java b/src/test/java/com/github/sqljam/impexp/QueryExportTest.java index 6d70dfb..896df2a 100644 --- a/src/test/java/com/github/sqljam/impexp/QueryExportTest.java +++ b/src/test/java/com/github/sqljam/impexp/QueryExportTest.java @@ -31,6 +31,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import com.github.sqljam.it.CollectingListener; +import com.github.sqljam.impexp.fs.CsvExporter; /** * @Description: QueryExportTest exports free queries like tables at their boundaries with H2: a join whose columns diff --git a/src/test/java/com/github/sqljam/impexp/CsvSplitterTest.java b/src/test/java/com/github/sqljam/impexp/fs/CsvSplitterTest.java similarity index 99% rename from src/test/java/com/github/sqljam/impexp/CsvSplitterTest.java rename to src/test/java/com/github/sqljam/impexp/fs/CsvSplitterTest.java index 2c982b0..1d6bce8 100644 --- a/src/test/java/com/github/sqljam/impexp/CsvSplitterTest.java +++ b/src/test/java/com/github/sqljam/impexp/fs/CsvSplitterTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.github.sqljam.impexp; +package com.github.sqljam.impexp.fs; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/src/test/java/com/github/sqljam/impexp/fs/ExcelPackageTest.java b/src/test/java/com/github/sqljam/impexp/fs/ExcelPackageTest.java new file mode 100644 index 0000000..abc2601 --- /dev/null +++ b/src/test/java/com/github/sqljam/impexp/fs/ExcelPackageTest.java @@ -0,0 +1,247 @@ +/* + * 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.impexp.fs; + +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.io.File; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.nio.file.Files; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +import org.dhatim.fastexcel.Workbook; +import org.dhatim.fastexcel.Worksheet; +import org.dhatim.fastexcel.reader.ReadableWorkbook; +import org.dhatim.fastexcel.reader.Row; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import com.github.sqljam.utils.ExcelUtils; +import com.github.sqljam.impexp.AbstractFileImporter; +import com.github.sqljam.impexp.DataFileImporter; +import com.github.sqljam.impexp.DataFormat; +import com.github.sqljam.impexp.DbType; +import com.github.sqljam.impexp.ExportManifest; +import com.github.sqljam.impexp.Exporter; +import com.github.sqljam.impexp.ImpExpException; + +/** + * @Description: ExcelPackageTest verifies Excel packages and workbooks of other tools with H2 databases: the values + * of every common type read back exactly (NULL and empty strings apart, 15 digits and more, microseconds), + * names with delimiters and quotes, an empty table, a table split into workbooks of a number of rows, + * and workbooks without manifest.json whose sheets, header, dates, formulas and empty rows are read + * @Author: Fred Feng + * @Date: 24/10/2026 + * @Version 1.0.0 + */ +class ExcelPackageTest { + + @TempDir + File dir; + + private static String newUrl() { + return "jdbc:h2:mem:xl" + UUID.randomUUID().toString().replace("-", "") + ";DB_CLOSE_DELAY=-1"; + } + + private static void execute(String url, String... sqls) throws Exception { + try (Connection connection = DriverManager.getConnection(url, "sa", ""); + Statement statement = connection.createStatement()) { + for (String sql : sqls) { + statement.execute(sql); + } + } + } + + private static List> rows(String url, String sql) throws Exception { + List> rows = new ArrayList<>(); + try (Connection connection = DriverManager.getConnection(url, "sa", ""); + Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) { + int columns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + List row = new ArrayList<>(); + for (int i = 1; i <= columns; i++) { + row.add(rs.getString(i)); + } + rows.add(row); + } + } + return rows; + } + + private static String sourceUrl() throws Exception { + String url = newUrl(); + execute(url, "CREATE TABLE \"EMPTY\" (ID INT PRIMARY KEY, NAME VARCHAR(20))", + "CREATE TABLE TYPES (ID INT PRIMARY KEY, BIG BIGINT, AMOUNT DECIMAL(20, 4), RATE DOUBLE PRECISION," + + " FLAG BOOLEAN, SOLD_DAY DATE, SOLD_AT TIMESTAMP(6), CLOCK TIME, NOTE VARCHAR(100), BODY CLOB," + + " BYTES VARBINARY(10), CODE UUID)", + "INSERT INTO TYPES VALUES (1, 9223372036854775807, 1234567890123456.7891, 0.1, TRUE," + + " DATE '2024-02-29', TIMESTAMP '2024-02-29 13:14:15.123456', TIME '23:59:58', '', 'long'," + + " X'00FF10', '123e4567-e89b-12d3-a456-426614174000')", + "INSERT INTO TYPES VALUES (2, 42, 10.5, -1.5E300, FALSE, DATE '1900-01-01'," + + " TIMESTAMP '2024-01-02 03:04:05', TIME '00:00:00', 'a,b \"q\"\nline', NULL, NULL, NULL)", + "INSERT INTO TYPES VALUES (3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)", + "CREATE TABLE \"ODD, \"\"NAMES\"\"\" (ID INT PRIMARY KEY, \"A;B|C\" VARCHAR(50))", + "INSERT INTO \"ODD, \"\"NAMES\"\"\" VALUES (1, ' spaced '), (2, NULL)", + "CREATE TABLE MANY (ID INT PRIMARY KEY, NOTE VARCHAR(100))", + "INSERT INTO MANY SELECT X, 'row ' || X FROM SYSTEM_RANGE(1, 2500)"); + return url; + } + + private static void configure(Exporter.ExportConfiguration configuration, String url) { + configuration.setDbType(DbType.H2); + configuration.setUrl(url); + configuration.setUsername("sa"); + configuration.setPassword(""); + configuration.setIncludedSchemaNames(new String[]{"PUBLIC"}); + configuration.setIdReused(true); + configuration.setConnectionPoolEnabled(false); + } + + private static ExportManifest.TableEntry table(ExportManifest manifest, String name) { + return manifest.getTables().stream().filter(entry -> name.equals(entry.getName())).findFirst() + .orElseThrow(); + } + + @Test + void excelPackageReadsBackExactly() throws Exception { + String source = sourceUrl(); + File packageDir = new File(dir, "excel"); + ExcelExporter exporter = new ExcelExporter(packageDir); + configure(exporter.getConfiguration(), source); + exporter.setMaxRows(1000); + exporter.exportDdlAndData(); + ExportManifest manifest = ExportManifest.read(packageDir); + assertEquals(DataFormat.EXCEL, manifest.getDataFormat()); + assertEquals(1000, ((Number) manifest.getOptions().get("maxRows")).intValue()); + assertEquals(1, table(manifest, "EMPTY").getDataFiles().size()); + List manyFiles = List.copyOf(table(manifest, "MANY").getDataFiles()); + assertEquals(3, manyFiles.size(), manyFiles.toString()); + assertTrue(manyFiles.get(2).endsWith("MANY_3.xlsx"), manyFiles.toString()); + + // Cells of their types: numbers, booleans and dates are cells for spreadsheets, 19 digits are text + File types = new File(packageDir, table(manifest, "TYPES").getDataFiles().iterator().next()); + try (ReadableWorkbook workbook = new ReadableWorkbook(types)) { + assertEquals("TYPES", workbook.getFirstSheet().getName()); + List sheet = workbook.getFirstSheet().read(); + assertEquals("ID", sheet.get(0).getCellText(0)); + assertEquals("9223372036854775807", sheet.get(1).getCellText(1)); + assertEquals(new BigDecimal("42"), sheet.get(2).getCellAsNumber(1).orElseThrow()); + assertEquals(Boolean.TRUE, sheet.get(1).getCellAsBoolean(4).orElseThrow()); + assertEquals(LocalDateTime.of(2024, 2, 29, 0, 0), sheet.get(1).getCellAsDate(5).orElseThrow()); + } + + String target = newUrl(); + try (Connection connection = DriverManager.getConnection(target, "sa", "")) { + AbstractFileImporter importer = AbstractFileImporter.forDirectory(packageDir, connection, DbType.H2); + assertTrue(importer instanceof ExcelImporter); + importer.importDirectory(packageDir); + assertEquals(0, importer.getFailedCount()); + } + for (String sql : new String[]{"SELECT * FROM TYPES ORDER BY ID", "SELECT * FROM MANY ORDER BY ID", + "SELECT * FROM \"ODD, \"\"NAMES\"\"\" ORDER BY ID", "SELECT * FROM \"EMPTY\""}) { + assertEquals(rows(source, sql), rows(target, sql), sql); + } + // NULL and empty strings stay apart + assertEquals("", rows(target, "SELECT NOTE FROM TYPES WHERE ID = 1").get(0).get(0)); + assertNull(rows(target, "SELECT NOTE FROM TYPES WHERE ID = 3").get(0).get(0)); + } + + /** + * A workbook of a spreadsheet without manifest.json: the first row names the columns, the types are detected + */ + @Test + void importsWorkbookOfOtherTools() throws Exception { + File file = new File(dir, "sales.xlsx"); + try (OutputStream out = Files.newOutputStream(file.toPath())) { + Workbook workbook = new Workbook(out, "Spreadsheet", "1.0"); + Worksheet notes = workbook.newWorksheet("Notes"); + notes.value(0, 0, "not the first table"); + Worksheet sales = workbook.newWorksheet("Sales 2024"); + String[] header = {"id", "city", "amount", "sold on", "paid", "total", "", "comment"}; + for (int c = 0; c < header.length; c++) { + sales.value(0, c, header[c]); + } + sales.value(1, 0, 1); + sales.value(1, 1, "北京"); + sales.value(1, 2, 10.5); + sales.value(1, 3, LocalDate.of(2024, 3, 1)); + sales.style(1, 3).format("yyyy-mm-dd").set(); + sales.value(1, 4, true); + sales.formula(1, 5, "C2*2"); + sales.value(1, 7, ""); + sales.value(2, 0, 2); + sales.value(2, 1, "Paris, \"FR\""); + sales.value(2, 3, LocalDate.of(2024, 3, 2)); + sales.style(2, 3).format("d/m/yy").set(); + sales.value(2, 4, false); + // An empty row in the middle and empty rows at the end are skipped + sales.value(4, 0, 3); + sales.value(4, 1, "Rome"); + sales.value(4, 2, 7); + workbook.finish(); + } + assertEquals(List.of("Notes", "Sales 2024"), ExcelUtils.sheetNames(file)); + String target = newUrl(); + try (Connection connection = DriverManager.getConnection(target, "sa", "")) { + ExcelImporter importer = new ExcelImporter(connection, DbType.H2); + importer.setSheet("Sales 2024"); + assertEquals("Sales 2024", importer.getSheet()); + assertEquals(3, importer.importFiles(List.of(file), "SALES", DataFileImporter.Mode.CREATE)); + } + List> rows = rows(target, "SELECT * FROM SALES ORDER BY 1"); + assertEquals(Arrays.asList("1", "北京", "10.5", "2024-03-01", "TRUE", null, null, ""), rows.get(0)); + assertEquals(Arrays.asList("2", "Paris, \"FR\"", null, "2024-03-02", "FALSE", null, null, null), rows.get(1)); + assertEquals("Rome", rows.get(2).get(1)); + // Detected types, the names of the columns in the case of the target, a column without a name is numbered + assertEquals(List.of(List.of("ID", "BIGINT"), List.of("CITY", "CHARACTER LARGE OBJECT"), + List.of("AMOUNT", "DOUBLE PRECISION"), List.of("SOLD ON", "DATE"), List.of("PAID", "BOOLEAN"), + List.of("TOTAL", "CHARACTER LARGE OBJECT"), List.of("COLUMN7", "CHARACTER LARGE OBJECT"), + List.of("COMMENT", "CHARACTER LARGE OBJECT")), rows(target, "SELECT COLUMN_NAME, DATA_TYPE FROM" + + " INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SALES' ORDER BY ORDINAL_POSITION")); + + // The first sheet by default, a missing sheet is told + String other = newUrl(); + try (Connection connection = DriverManager.getConnection(other, "sa", "")) { + ExcelImporter importer = new ExcelImporter(connection, DbType.H2); + assertEquals(0, importer.importFiles(List.of(file), "NOTES", DataFileImporter.Mode.CREATE)); + importer.setSheet("Missing"); + assertThrows(ImpExpException.class, () -> importer.importFiles(List.of(file), "MISSING", + DataFileImporter.Mode.CREATE)); + } + } + + @Test + void typesOfCells() { + assertTrue(ExcelExporter.isCellType("DECIMAL(20,4)")); + assertTrue(ExcelExporter.isCellType("timestamp")); + assertFalse(ExcelExporter.isCellType("TIMESTAMP WITH TIME ZONE")); + assertFalse(ExcelExporter.isCellType("BLOB")); + } +} diff --git a/src/test/java/com/github/sqljam/it/AbstractParquetIT.java b/src/test/java/com/github/sqljam/it/AbstractParquetIT.java index 5c7d476..2ff2690 100644 --- a/src/test/java/com/github/sqljam/it/AbstractParquetIT.java +++ b/src/test/java/com/github/sqljam/it/AbstractParquetIT.java @@ -34,9 +34,9 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import com.github.sqljam.impexp.AbstractFileImporter; -import com.github.sqljam.impexp.CsvExporter; -import com.github.sqljam.impexp.CsvImporter; -import com.github.sqljam.impexp.CsvOptions; +import com.github.sqljam.impexp.fs.CsvExporter; +import com.github.sqljam.impexp.fs.CsvImporter; +import com.github.sqljam.impexp.fs.CsvOptions; import com.github.sqljam.impexp.DataFileExporter; import com.github.sqljam.impexp.DataFileImporter; import com.github.sqljam.impexp.DataFormat; @@ -45,6 +45,8 @@ import com.github.sqljam.impexp.ParquetExporter; import com.github.sqljam.impexp.ParquetImporter; import com.github.sqljam.impexp.ScriptExportHandler; +import com.github.sqljam.impexp.fs.ExcelExporter; +import com.github.sqljam.impexp.fs.ExcelImporter; /** * @Description: AbstractParquetIT exports fixture tables of a source database as Parquet and CSV packages (split @@ -61,6 +63,10 @@ public abstract class AbstractParquetIT { */ private static final long CSV_PART_SIZE = 8 * 1024; private static final long PARQUET_PART_SIZE = 16 * 1024; + /** + * Few rows of a workbook, so that tables of the fixture are split: emp.xlsx, emp_2.xlsx ... + */ + private static final int EXCEL_PART_ROWS = 100; protected final ItDatabase source; @@ -91,6 +97,10 @@ private DataFileExporter newExporter(File dir, ItDatabase target, DataFormat for csvExporter.setOptions(options); csvExporter.setMaxFileSize(CSV_PART_SIZE); exporter = csvExporter; + } else if (format == DataFormat.EXCEL) { + ExcelExporter excelExporter = new ExcelExporter(dir); + excelExporter.setMaxRows(EXCEL_PART_ROWS); + exporter = excelExporter; } else { ParquetExporter parquetExporter = new ParquetExporter(dir); // Compressions are rotated over the matrix @@ -119,6 +129,12 @@ void exportAndImportCsv(ItDatabase target) throws Exception { exportAndImport(target, DataFormat.CSV); } + @ParameterizedTest(name = "excel for {0}") + @EnumSource(ItDatabase.class) + void exportAndImportExcel(ItDatabase target) throws Exception { + exportAndImport(target, DataFormat.EXCEL); + } + private void exportAndImport(ItDatabase target, DataFormat format) throws Exception { // Test users of Oracle and MariaDB have one schema, the same database type is verified by copyIntoSameSchema assumeTrue(!(source == target && source.isSingleSchema())); @@ -150,13 +166,17 @@ private void exportAndImport(ItDatabase target, DataFormat format) throws Except // ClickHouse has no identity columns assertEquals(source == ItDatabase.CLICKHOUSE ? 0 : 1, emp.getIdentityColumns().size(), "Identity column of emp"); ExportManifest.FileType fileType = format == DataFormat.CSV ? ExportManifest.FileType.CSV - : ExportManifest.FileType.PARQUET; + : format == DataFormat.EXCEL ? ExportManifest.FileType.EXCEL : ExportManifest.FileType.PARQUET; assertTrue(manifest.getFiles().stream().anyMatch(f -> f.getType() == fileType)); assertEquals(ExportManifest.FileType.SCHEMA, manifest.getFiles().get(0).getType()); List empFiles = List.copyOf(emp.getDataFiles()); for (String path : empFiles) { assertTrue(new File(dir, path).isFile(), "Data file of emp: " + path); } + if (format == DataFormat.EXCEL) { + assertTrue(empFiles.size() > 1, "emp is split: " + empFiles); + assertTrue(empFiles.get(1).toLowerCase().endsWith("emp_2.xlsx"), empFiles.toString()); + } if (format == DataFormat.CSV) { // Every column with its type, parts named like data files of sql scripts, each with the header CsvOptions options = CsvOptions.fromMap(manifest.getOptions()); @@ -174,7 +194,8 @@ private void exportAndImport(ItDatabase target, DataFormat format) throws Except try (Connection connection = target.getTargetConnection()) { AbstractFileImporter importer = AbstractFileImporter.forDirectory(dir, connection, target.getDbType()); - assertEquals(format == DataFormat.CSV ? CsvImporter.class : ParquetImporter.class, importer.getClass()); + assertEquals(format == DataFormat.CSV ? CsvImporter.class : format == DataFormat.EXCEL + ? ExcelImporter.class : ParquetImporter.class, importer.getClass()); listener = new CollectingListener(); importer.setExportListener(listener); try { @@ -217,6 +238,15 @@ void loadCsvFiles() throws Exception { loadFiles(DataFormat.CSV); } + /** + * Excel workbooks without manifest.json are loaded into a new table (the first row names the columns, types + * detected) and appended to it, parts in order + */ + @Test + void loadExcelFiles() throws Exception { + loadFiles(DataFormat.EXCEL); + } + private void loadFiles(DataFormat format) throws Exception { ItDatabase target = ItDatabase.H2; assumeTrue(source.isAvailable() && target.isAvailable()); @@ -237,7 +267,8 @@ private void loadFiles(DataFormat format) throws Exception { // The parts are given in any order, they are imported in the order of their numbers Collections.reverse(files); - String tableName = source.getPrefix() + (format == DataFormat.CSV ? "csv_emp" : "pq_emp"); + String tableName = source.getPrefix() + (format == DataFormat.CSV ? "csv_emp" : format == DataFormat.EXCEL + ? "xl_emp" : "pq_emp"); try (Connection connection = target.getTargetConnection()) { DataFileImporter importer; if (format == DataFormat.CSV) { @@ -247,6 +278,8 @@ private void loadFiles(DataFormat format) throws Exception { options.setDelimiter(""); csvImporter.setOptions(options); importer = csvImporter; + } else if (format == DataFormat.EXCEL) { + importer = new ExcelImporter(connection, target.getDbType()); } else { importer = new ParquetImporter(connection, target.getDbType()); } diff --git a/src/test/java/com/github/sqljam/it/ItDatabase.java b/src/test/java/com/github/sqljam/it/ItDatabase.java index 5cf246b..f5bd0c4 100644 --- a/src/test/java/com/github/sqljam/it/ItDatabase.java +++ b/src/test/java/com/github/sqljam/it/ItDatabase.java @@ -43,7 +43,7 @@ import com.github.sqljam.impexp.Exporter; import com.github.sqljam.impexp.ImportExportHandler; import com.github.sqljam.impexp.SqlScriptRunner; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; /** * @Description: ItDatabase holds the databases used by integration tests. Each database has its own fixture tables diff --git a/src/test/java/com/github/sqljam/it/ManualCommitIT.java b/src/test/java/com/github/sqljam/it/ManualCommitIT.java index 4986cb3..68d9746 100644 --- a/src/test/java/com/github/sqljam/it/ManualCommitIT.java +++ b/src/test/java/com/github/sqljam/it/ManualCommitIT.java @@ -31,7 +31,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import com.github.sqljam.impexp.AbstractFileImporter; -import com.github.sqljam.impexp.CsvExporter; +import com.github.sqljam.impexp.fs.CsvExporter; import com.github.sqljam.impexp.DataFileStrategy; import com.github.sqljam.impexp.DataFormat; import com.github.sqljam.impexp.Exporter; diff --git a/src/test/java/com/github/sqljam/it/PartitionIT.java b/src/test/java/com/github/sqljam/it/PartitionIT.java index 9f743f6..6b89183 100644 --- a/src/test/java/com/github/sqljam/it/PartitionIT.java +++ b/src/test/java/com/github/sqljam/it/PartitionIT.java @@ -55,7 +55,7 @@ import com.github.sqljam.impexp.ScriptExporter; import com.github.sqljam.impexp.ScriptImporter; import com.github.sqljam.impexp.SqlScriptRunner; -import com.github.sqljam.jdbc.JdbcUtils; +import com.github.sqljam.utils.JdbcUtils; /** * @Description: PartitionIT backs up and restores partitioned tables of every partitioning type of each database diff --git a/src/test/java/com/github/sqljam/it/QueryExportIT.java b/src/test/java/com/github/sqljam/it/QueryExportIT.java index 29fcfbd..1ac37dc 100644 --- a/src/test/java/com/github/sqljam/it/QueryExportIT.java +++ b/src/test/java/com/github/sqljam/it/QueryExportIT.java @@ -30,7 +30,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import com.github.sqljam.impexp.AbstractFileImporter; -import com.github.sqljam.impexp.CsvExporter; +import com.github.sqljam.impexp.fs.CsvExporter; import com.github.sqljam.impexp.DbType; import com.github.sqljam.impexp.ImportExporter; diff --git a/src/test/java/com/github/sqljam/it/TransferBenchmark.java b/src/test/java/com/github/sqljam/it/TransferBenchmark.java index 7673d65..83176b9 100644 --- a/src/test/java/com/github/sqljam/it/TransferBenchmark.java +++ b/src/test/java/com/github/sqljam/it/TransferBenchmark.java @@ -42,7 +42,7 @@ import com.github.sqljam.face.view.DocImages; import com.github.sqljam.face.view.FxTestSupport; import com.github.sqljam.impexp.AbstractFileImporter; -import com.github.sqljam.impexp.CsvExporter; +import com.github.sqljam.impexp.fs.CsvExporter; import com.github.sqljam.impexp.DataFileStrategy; import com.github.sqljam.impexp.DbType; import com.github.sqljam.impexp.Exporter; diff --git a/src/test/java/com/github/sqljam/it/UpsertIT.java b/src/test/java/com/github/sqljam/it/UpsertIT.java index afb8857..eecb6fe 100644 --- a/src/test/java/com/github/sqljam/it/UpsertIT.java +++ b/src/test/java/com/github/sqljam/it/UpsertIT.java @@ -33,7 +33,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import com.github.sqljam.impexp.AbstractFileImporter; -import com.github.sqljam.impexp.CsvExporter; +import com.github.sqljam.impexp.fs.CsvExporter; import com.github.sqljam.impexp.DataFileStrategy; import com.github.sqljam.impexp.DataFormat; import com.github.sqljam.impexp.DbType; diff --git a/src/test/java/com/github/sqljam/it/VectorIT.java b/src/test/java/com/github/sqljam/it/VectorIT.java index a3c2778..6f3f762 100644 --- a/src/test/java/com/github/sqljam/it/VectorIT.java +++ b/src/test/java/com/github/sqljam/it/VectorIT.java @@ -50,7 +50,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import com.github.sqljam.impexp.AbstractFileImporter; -import com.github.sqljam.impexp.CsvExporter; +import com.github.sqljam.impexp.fs.CsvExporter; import com.github.sqljam.impexp.DataFileExporter; import com.github.sqljam.impexp.DataFileStrategy; import com.github.sqljam.impexp.DatabaseFeature; diff --git a/src/test/java/com/github/sqljam/utils/ExcelUtilsTest.java b/src/test/java/com/github/sqljam/utils/ExcelUtilsTest.java new file mode 100644 index 0000000..fbc71b1 --- /dev/null +++ b/src/test/java/com/github/sqljam/utils/ExcelUtilsTest.java @@ -0,0 +1,118 @@ +/* + * 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.utils; + +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.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * @Description: ExcelUtilsTest verifies workbooks written from a result set and read back as CSV: the header row, + * values of every common type, NULL and empty texts, inf and nan, long numbers and microseconds as + * text, parts of a number of rows, an empty result, sheet names and number formats of dates, and + * workbooks of Excel 97-2003 which are refused + * @Author: Fred Feng + * @Date: 24/10/2026 + * @Version 1.0.0 + */ +class ExcelUtilsTest { + + @TempDir + File dir; + + @Test + void writesAndReadsBackRows() throws Exception { + File file = new File(dir, "out/notes.xlsx"); + try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:"); + Statement statement = connection.createStatement()) { + statement.execute("CREATE TABLE T (ID INT, BIG DECIMAL(20, 2), R DOUBLE PRECISION, F BOOLEAN, D DATE," + + " TS TIMESTAMP(6), MS TIMESTAMP(3), NOTE VARCHAR(50))"); + statement.execute("INSERT INTO T VALUES (1, 123456789012345678.91, 1.5, TRUE, DATE '2024-02-29'," + + " TIMESTAMP '2024-02-29 01:02:03.000004', TIMESTAMP '2024-02-29 01:02:03.250', 'a,\"b\"')," + + " (2, 12.5, 'Infinity', FALSE, DATE '0001-01-01', TIMESTAMP '1899-12-31 23:00:00', NULL, '')," + + " (3, NULL, 'NaN', NULL, NULL, NULL, NULL, NULL)"); + try (ResultSet rs = statement.executeQuery("SELECT * FROM T ORDER BY ID")) { + List files = ExcelUtils.write(rs, List.of("ID", "BIG", "R", "F", "D", "TS", "MS", "NOTE"), + "T:1", file, 2); + assertEquals(List.of(file, new File(dir, "out/notes_2.xlsx")), files); + } + try (ResultSet rs = statement.executeQuery("SELECT * FROM T WHERE ID < 0")) { + File empty = new File(dir, "empty.xlsx"); + assertEquals(List.of(empty), ExcelUtils.write(rs, List.of("ID"), "T", empty, 0)); + File csv = new File(dir, "empty.csv"); + assertEquals(0, ExcelUtils.toCsv(empty, null, csv)); + assertEquals("ID\n", Files.readString(csv.toPath(), StandardCharsets.UTF_8)); + } + } + assertEquals(List.of("T_1"), ExcelUtils.sheetNames(file)); + File csv = new File(dir, "notes.csv"); + assertEquals(2, ExcelUtils.toCsv(file, "T_1", csv)); + assertEquals("ID,BIG,R,F,D,TS,MS,NOTE\n" + + "1,123456789012345678.91,1.5,true,2024-02-29,2024-02-29 01:02:03.000004,2024-02-29 01:02:03.25," + + "\"a,\"\"b\"\"\"\n" + + "2,12.50,inf,false,0001-01-01,1899-12-31 23:00:00.000000,,\"\"\n", Files.readString(csv.toPath(), + StandardCharsets.UTF_8)); + File second = new File(dir, "second.csv"); + assertEquals(1, ExcelUtils.toCsv(new File(dir, "out/notes_2.xlsx"), null, second)); + assertEquals("ID,BIG,R,F,D,TS,MS,NOTE\n3,,nan,,,,,\n", Files.readString(second.toPath(), + StandardCharsets.UTF_8)); + assertThrows(IllegalArgumentException.class, () -> ExcelUtils.toCsv(file, "missing", csv)); + } + + @Test + void refusesWorkbooksOfExcel97() throws Exception { + File file = new File(dir, "old.xlsx"); + Files.write(file.toPath(), new byte[]{(byte) 0xD0, (byte) 0xCF, 0x11, (byte) 0xE0, (byte) 0xA1, (byte) 0xB1, + 0x1A, (byte) 0xE1, 0, 0}); + IOException e = assertThrows(IOException.class, () -> ExcelUtils.sheetNames(file)); + assertTrue(e.getMessage().contains("Excel 97-2003"), e.getMessage()); + } + + @Test + void namesAndFormats() { + assertTrue(ExcelUtils.isExcel(new File("A.XLSX"))); + assertFalse(ExcelUtils.isExcel(new File("a.xls"))); + assertEquals("a_b_c_d_", ExcelUtils.sheetName("a:b/c[d]")); + assertEquals("Sheet1", ExcelUtils.sheetName("''")); + assertEquals(31, ExcelUtils.sheetName("x".repeat(40)).length()); + assertTrue(ExcelUtils.isDateFormat(14, null)); + assertTrue(ExcelUtils.isDateFormat(200, "yyyy\\-mm\\-dd hh:mm")); + assertTrue(ExcelUtils.isDateFormat(200, "[$-409]d-mmm-yy")); + assertTrue(ExcelUtils.isDateFormat(200, "yyyy-mm-dd hh:mm:ss.000")); + assertFalse(ExcelUtils.isDateFormat(0, "General")); + assertFalse(ExcelUtils.isDateFormat(200, "0.00\"days\"")); + assertFalse(ExcelUtils.isDateFormat(200, "#,##0")); + assertFalse(ExcelUtils.isDateFormat(null, null)); + assertEquals("\"\"", ExcelUtils.quote("")); + assertEquals("\" a\"", ExcelUtils.quote(" a")); + assertEquals("\"x\ny\"", ExcelUtils.quote("x\ny")); + assertEquals("plain", ExcelUtils.quote("plain")); + } +} diff --git a/src/test/java/com/github/sqljam/jdbc/JdbcUtilsTest.java b/src/test/java/com/github/sqljam/utils/JdbcUtilsTest.java similarity index 99% rename from src/test/java/com/github/sqljam/jdbc/JdbcUtilsTest.java rename to src/test/java/com/github/sqljam/utils/JdbcUtilsTest.java index 60fa219..ceda016 100644 --- a/src/test/java/com/github/sqljam/jdbc/JdbcUtilsTest.java +++ b/src/test/java/com/github/sqljam/utils/JdbcUtilsTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.github.sqljam.jdbc; +package com.github.sqljam.utils; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -41,6 +41,8 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import com.github.sqljam.jdbc.Cursor; +import com.github.sqljam.jdbc.SimpleConnectionFactory; import com.github.sqljam.impexp.TransactionIsolationLevel; import com.github.sqljam.impexp.db.H2Dialect; import com.github.sqljam.page.EachPage; diff --git a/src/test/java/com/github/sqljam/impexp/SqlTextUtilsTest.java b/src/test/java/com/github/sqljam/utils/SqlTextUtilsTest.java similarity index 98% rename from src/test/java/com/github/sqljam/impexp/SqlTextUtilsTest.java rename to src/test/java/com/github/sqljam/utils/SqlTextUtilsTest.java index 2c90fc2..1dead1a 100644 --- a/src/test/java/com/github/sqljam/impexp/SqlTextUtilsTest.java +++ b/src/test/java/com/github/sqljam/utils/SqlTextUtilsTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.github.sqljam.impexp; +package com.github.sqljam.utils; import static org.junit.jupiter.api.Assertions.assertEquals;