From 5d8ad58df84f8bd0508c163576141efac36a85e3 Mon Sep 17 00:00:00 2001 From: dbulahov Date: Wed, 25 Nov 2026 18:07:42 +0300 Subject: [PATCH] dialect(sqlite): version checks and fixes, tested with the sqlite3 CLI in Docker SQLite is embedded and serves no connection, and the JDBC driver brings an SQLite of its own: the tests run the sqlite3 CLI of each version in Docker (3.22.0 to 3.51.0) on the SQL the dialect writes, the dialect built for the version the CLI reports. DdlGenerator (dialect api): - supportsSchemas: whether createSchema / dropSchema write a statement; null from both where it says no SqliteDialect: - supportsRenameColumn: from 3.25; 3.22 refuses RENAME COLUMN - supportsNullsLast, supportsNullsOrdering: from 3.30, one answer; generateOrderByNulls wrote NULLS FIRST/LAST on every version, a syntax error before 3.30, now a CASE there - supportsListAgg, generateListAgg: group_concat(x, sep), on every version; ORDER BY inside it from 3.44, an ordered list refused before; DISTINCT with any separator through json_group_array, as a DISTINCT aggregate takes one argument; DISTINCT in the order of another column refused - supportsNthValue, generateNthValueAgg: from 3.44, the n-th element of json_group_array(v ORDER BY ...), NULL past the end - supportsPercentileDisc/Cont, generatePercentileDisc/Cont: from 3.44, on the sorted json_group_array, core functions only; percentile_cont and ceil are in some builds only - supportsAddUniqueConstraint, supportsAddCheckConstraint, supportsAddForeignKeyConstraint: false, no ALTER TABLE ... ADD CONSTRAINT in any version - foreignKeyClause: the referenced table by its name alone; REFERENCES "main"."t" was a syntax error - mergeGenerator: DO NOTHING where no column is to be updated; an empty DO UPDATE SET was a syntax error - supportsSchemas: false, createSchema / dropSchema null; CREATE and DROP SCHEMA are syntax errors in every version - createTrigger: no FOR EACH STATEMENT, a syntax error in SQLite: UnsupportedOperationException, as in MySQL - supportsRenameTable, supportsRenameView: documented; views and triggers follow a renamed table from 3.25 only CsvDataImporter: - a directory below the base is no schema where the dialect has none; on SQLite its tables go into the connection's own schema Container tests, sqlite3 CLI in Docker: - SqliteCli: keinos/sqlite3 from 3.38, ubuntu:18.04 (3.22.0), alpine:3.8 (3.25.3), alpine:3.12 (3.32.1), alpine:3.14 (3.35.5), built once into images of their own name - SqliteRenameColumnTest, SqliteNullsOrderTest, SqliteListAggTest, SqliteNthValueTest, SqlitePercentileTest, SqliteAddConstraintTest, SqliteReturningTest (3.35), SqliteUpsertTest (3.24), SqliteSchemaTest, SqliteRenameTableTest, SqliteTriggerTest - SchemaStatementsTest (consistency): supportsSchemas of every dialect Signed-off-by: --- .../dialect/api/generator/DdlGenerator.java | 15 +- .../consistencytest/SchemaStatementsTest.java | 70 +++++ dialect/db/sqlite/pom.xml | 13 + .../sql/dialect/db/sqlite/SqliteDialect.java | 271 +++++++++++++++++- .../container/SqliteAddConstraintTest.java | 133 +++++++++ .../db/sqlite/container/SqliteCli.java | 106 +++++++ .../sqlite/container/SqliteListAggTest.java | 136 +++++++++ .../sqlite/container/SqliteNthValueTest.java | 126 ++++++++ .../container/SqliteNullsOrderTest.java | 79 +++++ .../container/SqlitePercentileTest.java | 114 ++++++++ .../container/SqliteRenameColumnTest.java | 96 +++++++ .../container/SqliteRenameTableTest.java | 104 +++++++ .../sqlite/container/SqliteReturningTest.java | 77 +++++ .../db/sqlite/container/SqliteSchemaTest.java | 65 +++++ .../sqlite/container/SqliteTriggerTest.java | 96 +++++++ .../db/sqlite/container/SqliteUpsertTest.java | 97 +++++++ .../importer/csv/impl/CsvDataImporter.java | 8 + 17 files changed, 1602 insertions(+), 4 deletions(-) create mode 100644 dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/SchemaStatementsTest.java create mode 100644 dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteAddConstraintTest.java create mode 100644 dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteCli.java create mode 100644 dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteListAggTest.java create mode 100644 dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteNthValueTest.java create mode 100644 dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteNullsOrderTest.java create mode 100644 dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqlitePercentileTest.java create mode 100644 dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteRenameColumnTest.java create mode 100644 dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteRenameTableTest.java create mode 100644 dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteReturningTest.java create mode 100644 dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteSchemaTest.java create mode 100644 dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteTriggerTest.java create mode 100644 dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteUpsertTest.java diff --git a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java index 71b728b1..fdcc72d6 100644 --- a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java +++ b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java @@ -44,17 +44,28 @@ public interface DdlGenerator extends IdentifierQuoter, DialectCapabilitiesProvi /** * @param ifExists whether to include IF NOT EXISTS clause - * @return SQL statement to create the schema + * @return SQL statement to create the schema, {@code null} where the database has no schemas to create + * ({@link #supportsSchemas()} is false) */ String createSchema(String schemaName, boolean ifExists); /** * @param ifExists whether to include IF EXISTS clause * @param cascade whether to include CASCADE clause - * @return SQL statement to drop the schema + * @return SQL statement to drop the schema, {@code null} where the database has no schemas to drop + * ({@link #supportsSchemas()} is false) */ String dropSchema(String schemaName, boolean ifExists, boolean cascade); + /** + * @return true if {@code createSchema} / {@code dropSchema} render statements: the database keeps schemas, name + * spaces of tables inside one database, created and dropped by SQL. SQLite has none: its schemas are the + * database files attached to a connection, and it refuses {@code CREATE SCHEMA}. + */ + default boolean supportsSchemas() { + return true; + } + // -------------------- DDL — descriptor-based -------------------- default String createTable(TableReference table, List columns, PrimaryKey primaryKey, diff --git a/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/SchemaStatementsTest.java b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/SchemaStatementsTest.java new file mode 100644 index 00000000..2bdc7543 --- /dev/null +++ b/dialect/db/consistency-test/src/test/java/org/eclipse/daanse/sql/dialect/db/consistencytest/SchemaStatementsTest.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.consistencytest; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.stream.Stream; + +import org.eclipse.daanse.sql.dialect.api.Dialect; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator; +import org.eclipse.daanse.sql.dialect.db.clickhouse.ClickHouseDialect; +import org.eclipse.daanse.sql.dialect.db.common.AnsiDialect; +import org.eclipse.daanse.sql.dialect.db.derby.DerbyDialect; +import org.eclipse.daanse.sql.dialect.db.duckdb.DuckDbDialect; +import org.eclipse.daanse.sql.dialect.db.h2.H2Dialect; +import org.eclipse.daanse.sql.dialect.db.hive.HiveDialect; +import org.eclipse.daanse.sql.dialect.db.impala.ImpalaDialect; +import org.eclipse.daanse.sql.dialect.db.mariadb.MariaDBDialect; +import org.eclipse.daanse.sql.dialect.db.mssqlserver.MicrosoftSqlServerDialect; +import org.eclipse.daanse.sql.dialect.db.mysql.MySqlDialect; +import org.eclipse.daanse.sql.dialect.db.oracle.OracleDialect; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.junit.jupiter.api.Named; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Which dialect has schemas to create and drop: {@link DdlGenerator#supportsSchemas()}, and a statement from + * {@code createSchema} and {@code dropSchema} where it says yes, none where it says no. SQLite alone has no schemas + * inside a database. What the statements of the others say is left to the tests of each dialect. + */ +class SchemaStatementsTest { + + static Stream dialects() { + return Stream.of(of("postgresql", new PostgreSqlDialect(), true), of("h2", new H2Dialect(), true), + of("duckdb", new DuckDbDialect(), true), of("ansi", new AnsiDialect(), true), + of("oracle", new OracleDialect(), true), of("mssql", new MicrosoftSqlServerDialect(), true), + of("mysql", new MySqlDialect(), true), of("mariadb", new MariaDBDialect(), true), + of("clickhouse", new ClickHouseDialect(), true), of("hive", new HiveDialect(), true), + of("impala", new ImpalaDialect(), true), of("derby", new DerbyDialect(), true), + of("sqlite", new SqliteDialect(), false)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("dialects") + void createsAndDropsASchema(Dialect dialect, boolean schemas) { + DdlGenerator ddl = dialect.ddlGenerator(); + assertThat(ddl.supportsSchemas()).as("supportsSchemas").isEqualTo(schemas); + if (schemas) { + assertThat(ddl.createSchema("s", true)).as("createSchema").isNotBlank(); + assertThat(ddl.dropSchema("s", true, true)).as("dropSchema").isNotBlank(); + } else { + assertThat(ddl.createSchema("s", true)).as("no createSchema").isNull(); + assertThat(ddl.dropSchema("s", true, true)).as("no dropSchema").isNull(); + } + } + + private static Arguments of(String name, Dialect dialect, boolean schemas) { + return Arguments.of(Named.of(name, dialect), schemas); + } +} diff --git a/dialect/db/sqlite/pom.xml b/dialect/db/sqlite/pom.xml index ed83151a..23e11433 100644 --- a/dialect/db/sqlite/pom.xml +++ b/dialect/db/sqlite/pom.xml @@ -49,6 +49,19 @@ 3.45.3.0 test + + org.eclipse.daanse + org.eclipse.daanse.sql.jdbc.record + ${project.version} + test + + + + org.testcontainers + junit-jupiter + 1.21.4 + test + org.eclipse.daanse org.eclipse.daanse.sql.dialect.db.test-support diff --git a/dialect/db/sqlite/src/main/java/org/eclipse/daanse/sql/dialect/db/sqlite/SqliteDialect.java b/dialect/db/sqlite/src/main/java/org/eclipse/daanse/sql/dialect/db/sqlite/SqliteDialect.java index dafb37c4..dfde5e57 100644 --- a/dialect/db/sqlite/src/main/java/org/eclipse/daanse/sql/dialect/db/sqlite/SqliteDialect.java +++ b/dialect/db/sqlite/src/main/java/org/eclipse/daanse/sql/dialect/db/sqlite/SqliteDialect.java @@ -22,6 +22,7 @@ package org.eclipse.daanse.sql.dialect.db.sqlite; import org.eclipse.daanse.sql.model.schema.TableReference; +import org.eclipse.daanse.sql.model.schema.Trigger; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; @@ -75,6 +76,228 @@ public SqliteDialect(org.eclipse.daanse.sql.dialect.api.DialectInitData init) { super(init); } + /** + * {@code ALTER TABLE … RENAME COLUMN} from 3.25.0, which renames the column in the table's indexes, triggers and + * views too; 3.22 refuses it with a syntax error, and {@code renameColumn} then gives {@code null}. A dialect made + * without a connection takes such a version. + */ + @Override + public boolean supportsRenameColumn() { + return dialectVersion.isUnknownOrAtLeast(3, 25); + } + + /** + * Yes, on every version: {@code group_concat(x, sep)}, which leaves the NULLs out. An order inside it, + * {@code group_concat(x, sep ORDER BY …)}, comes with 3.44.0; before, no expression of a grouped query lists the + * values in an order (a sorted subquery over the group is a misuse of the aggregate), and an ordered list is + * refused. A DISTINCT aggregate takes one argument only, on every version: a DISTINCT list with any separator is + * the values of {@code json_group_array(DISTINCT x)} joined in a subquery. A DISTINCT list in the order of + * another column SQLite puts in no order of the values' first places, and is refused, as PostgreSQL refuses it. + */ + @Override + public boolean supportsListAgg() { + return true; + } + + @Override + public java.util.Optional generateListAgg(CharSequence operand, boolean distinct, String separator, + String coalesce, String onOverflowTruncate, List columns) { + boolean ordered = columns != null && !columns.isEmpty(); + if (ordered && !dialectVersion.isUnknownOrAtLeast(3, 44)) { + return java.util.Optional.empty(); + } + if (ordered && distinct && !columns.stream().allMatch(c -> c.tableName() == null + && (operand.toString().equals(c.columnName()) + || operand.toString().equals(quoteIdentifier(c.columnName()).toString())))) { + return java.util.Optional.empty(); + } + StringBuilder sep = new StringBuilder(); + quoteStringLiteral(sep, separator == null ? "," : separator); + String order = ordered ? " ORDER BY " + buildOrderedColumnsClause(columns) : ""; + if (distinct) { + return java.util.Optional.of("(SELECT group_concat(value, " + sep + + ") FROM json_each(json_group_array(DISTINCT " + operand + order + ")))"); + } + return java.util.Optional.of("group_concat(" + operand + ", " + sep + order + ")"); + } + + /** + * From 3.44.0: the n-th element of {@code json_group_array(v ORDER BY …)}, the NULL values left out with + * {@code FILTER (WHERE v IS NOT NULL)} where asked; an aggregate over the rows of the group, not the window + * {@code nth_value … OVER}, which in a grouped query runs over the groups (V-82). Before 3.44 an aggregate takes + * no ORDER BY, and the n-th value is refused. n counts from 1, below 1 is 1; past the end it is NULL. A dialect + * made without a connection takes such a version. + */ + @Override + public boolean supportsNthValue() { + return dialectVersion.isUnknownOrAtLeast(3, 44); + } + + @Override + public boolean supportsNthValueIgnoreNulls() { + return supportsNthValue(); + } + + @Override + public java.util.Optional generateNthValueAgg(CharSequence operand, boolean ignoreNulls, Integer n, + List columns) { + if (!supportsNthValue()) { + return java.util.Optional.empty(); + } + StringBuilder sb = new StringBuilder("json_extract(json_group_array(").append(operand); + if (columns != null && !columns.isEmpty()) { + sb.append(" ORDER BY ").append(buildOrderedColumnsClause(columns)); + } + sb.append(')'); + if (ignoreNulls) { + sb.append(" FILTER (WHERE ").append(operand).append(" IS NOT NULL)"); + } + sb.append(", "); + int index = org.eclipse.daanse.sql.dialect.api.generator.AggregationGenerator.nthIndex(n) - 1; + quoteStringLiteral(sb, "$[" + index + "]"); + return java.util.Optional.of(sb.append(')').toString()); + } + + /** + * From 3.44.0, computed on the group's values sorted in {@code json_group_array(c ORDER BY c) FILTER (WHERE c IS + * NOT NULL)}: SQLite has no {@code WITHIN GROUP}, and its own {@code percentile_cont(c, p)} and + * {@code percentile_disc(c, p)} are in some builds only (3.47 and 3.50 of keinos/sqlite3, not 3.46 or 3.51), as + * {@code ceil} and {@code floor} are; the expression takes neither, {@code CAST(x AS INTEGER)} rounds down. Before + * 3.44 an aggregate takes no ORDER BY. A dialect made without a connection takes such a version. + */ + @Override + public boolean supportsPercentileDisc() { + return dialectVersion.isUnknownOrAtLeast(3, 44); + } + + @Override + public boolean supportsPercentileCont() { + return supportsPercentileDisc(); + } + + /** The {@code max(1, ceil(p n))}-th value: the first whose cumulative share reaches p; NULL for no value. */ + @Override + public java.util.Optional generatePercentileDisc(double percentile, boolean desc, String tableName, + String columnName) { + if (!supportsPercentileDisc()) { + return java.util.Optional.empty(); + } + String col = column(tableName, columnName); + String pn = "(" + percentile + " * count(" + col + "))"; + String ceil = "(CAST(" + pn + " AS INTEGER) + (" + pn + " > CAST(" + pn + " AS INTEGER)))"; + return java.util.Optional.of("json_extract(" + sortedArray(col, desc) + ", '$[' || (max(1, " + ceil + + ") - 1) || ']')"); + } + + /** The value at {@code p (n - 1)} of the sorted values counted from 0, interpolated; NULL for no value. */ + @Override + public java.util.Optional generatePercentileCont(double percentile, boolean desc, String tableName, + String columnName) { + if (!supportsPercentileCont()) { + return java.util.Optional.empty(); + } + String col = column(tableName, columnName); + String array = sortedArray(col, desc); + String r = "(" + percentile + " * (count(" + col + ") - 1))"; + String lo = "CAST(" + r + " AS INTEGER)"; + String frac = "(" + r + " - " + lo + ")"; + String atLo = "json_extract(" + array + ", '$[' || " + lo + " || ']')"; + String atHi = "json_extract(" + array + ", '$[' || (" + lo + " + (" + frac + " > 0)) || ']')"; + return java.util.Optional.of("(" + atLo + " + " + frac + " * (" + atHi + " - " + atLo + "))"); + } + + private String column(String tableName, String columnName) { + StringBuilder col = new StringBuilder(); + if (tableName != null) { + quoteIdentifier(col, tableName, columnName); + } else { + quoteIdentifier(col, columnName); + } + return col.toString(); + } + + private static String sortedArray(String col, boolean desc) { + return "json_group_array(" + col + " ORDER BY " + col + (desc ? " DESC" : "") + ") FILTER (WHERE " + col + + " IS NOT NULL)"; + } + + /** + * SQLite has no {@code ALTER TABLE … ADD CONSTRAINT}, in any version (a syntax error): its unique constraints, + * checks and foreign keys are declared in {@code CREATE TABLE}. + */ + @Override + public boolean supportsAddUniqueConstraint() { + return false; + } + + @Override + public boolean supportsAddCheckConstraint() { + return false; + } + + @Override + public boolean supportsAddForeignKeyConstraint() { + return false; + } + + /** + * The referenced table by its name alone: {@code REFERENCES "main"."t"} is a syntax error, a foreign key refers + * to a table of its own schema. SQLite checks foreign keys only on a connection that turned them on + * ({@code PRAGMA foreign_keys = ON}); without, the key is declared and not kept. + */ + @Override + public String foreignKeyClause(String constraintName, List fkColumns, TableReference referencedTable, + List referencedColumns, String onDelete, String onUpdate) { + TableReference unqualified = referencedTable == null ? null + : new TableReference(java.util.Optional.empty(), referencedTable.name(), referencedTable.type()); + return super.foreignKeyClause(constraintName, fkColumns, unqualified, referencedColumns, onDelete, onUpdate); + } + + /** + * No: SQLite keeps no schemas inside a database. Its schemas are {@code main}, {@code temp} and the database files + * a connection attaches ({@code ATTACH DATABASE 'file' AS s}), for that connection only, with no IF [NOT] EXISTS; + * {@code CREATE SCHEMA} and {@code DROP SCHEMA} are syntax errors in every version. {@code createSchema} and + * {@code dropSchema} give {@code null}. + */ + @Override + public boolean supportsSchemas() { + return false; + } + + @Override + public String createSchema(String schemaName, boolean ifNotExists) { + return null; + } + + @Override + public String dropSchema(String schemaName, boolean ifExists, boolean cascade) { + return null; + } + + @Override + public boolean supportsDropSchemaIfExists() { + return false; + } + + /** + * {@code CREATE TRIGGER name timing event ON table FOR EACH ROW [WHEN (condition)] BEGIN …; END}, in every + * version: SQLite reads WHEN itself, and takes the table with its schema. SQLite has row triggers only: + * {@code FOR EACH STATEMENT} is a syntax error, and a row trigger does not fire once for a statement (not at all + * for one of no rows), so none is written. The body names its tables without a schema: SQLite refuses a qualified + * table name in a statement of a trigger. {@code OR REPLACE} SQLite has not, and it is left out. + * + * @throws UnsupportedOperationException of {@link Trigger.TriggerScope#STATEMENT} + */ + @Override + public String createTrigger(String triggerName, Trigger.TriggerTiming timing, Trigger.TriggerEvent event, + TableReference table, Trigger.TriggerScope scope, String whenCondition, String body, boolean orReplace) { + if (scope == Trigger.TriggerScope.STATEMENT) { + throw new UnsupportedOperationException( + "SQLite has row triggers only: FOR EACH STATEMENT of " + triggerName + " cannot be written"); + } + return super.createTrigger(triggerName, timing, event, table, scope, whenCondition, body, orReplace); + } + @Override public boolean supportsSequences() { return false; @@ -103,12 +326,26 @@ public boolean supportsRenameConstraint() { return false; } - /** SQLite has no {@code ALTER VIEW ... RENAME}. */ + /** + * SQLite has no {@code ALTER VIEW ... RENAME}, and {@code ALTER TABLE v RENAME TO w} refuses a view ("view v may + * not be altered"), in every version. + */ @Override public boolean supportsRenameView() { return false; } + /** + * {@code ALTER TABLE t RENAME TO u}, the new name by itself ({@code RENAME TO "main"."u"} is a syntax error), in + * every version. The foreign keys of other tables follow the table in every version; its views and triggers from + * 3.25.0 on. Before, the rename is done and leaves them naming the old table, which fails when they run + * ("no such table"). A connection that turns {@code PRAGMA legacy_alter_table} on gets that behaviour back. + */ + @Override + public boolean supportsRenameTable() { + return true; + } + @Override public boolean supportsDropTableCascade() { return false; @@ -126,9 +363,28 @@ public StringBuilder generateInline(java.util.List columnNames, java.uti return generateInlineGeneric(columnNames, columnTypes, valueList, null, false); } + /** + * {@code NULLS FIRST} / {@code NULLS LAST} from 3.30.0; 3.25 refuses them with a syntax error, and the NULLs are + * then ranked with a CASE. SQLite itself puts NULLs first ascending and last descending. A dialect made without a + * connection takes such a version. + */ + @Override + public boolean supportsNullsLast() { + return supportsNullsOrdering(); + } + + @Override + protected boolean supportsNullsOrdering() { + return dialectVersion.isUnknownOrAtLeast(3, 30); + } + + /** {@code x ASC NULLS LAST} from 3.30, before {@code CASE WHEN x IS NULL THEN 1 ELSE 0 END, x ASC}. */ @Override public StringBuilder generateOrderByNulls(CharSequence expr, boolean ascending, boolean collateNullsLast) { - return generateOrderByNullsAnsi(expr, ascending, collateNullsLast); + if (supportsNullsOrdering()) { + return generateOrderByNullsAnsi(expr, ascending, collateNullsLast); + } + return super.generateOrderByNulls(expr, ascending, collateNullsLast); } /** @@ -265,6 +521,13 @@ public java.util.Optional returning(java.util.List columns) { return local; } + /** + * {@code INSERT … ON CONFLICT (key) DO UPDATE SET c = excluded.c} from 3.24.0, which updates the row in place, + * its key and the columns not listed kept; with no column to update {@code DO NOTHING}, insert-or-ignore. 3.22 + * knows no {@code ON CONFLICT} after {@code INSERT} (a syntax error), and {@code INSERT OR REPLACE} is no + * stand-in: it deletes the row and inserts a new one, the columns not listed lost. The key must be a PRIMARY KEY + * or a UNIQUE constraint. A dialect made without a connection takes such a version. + */ @Override public org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator mergeGenerator() { var local = cachedMergeGenerator; @@ -296,6 +559,10 @@ public java.util.Optional upsert(UpsertSpec spec, java.util.List } sb.append(") ON CONFLICT ("); appendQuotedCsv(sb, spec.keyColumns()); + if (spec.updateColumns().isEmpty()) { + // insert-or-ignore: an empty DO UPDATE SET is a syntax error + return java.util.Optional.of(sb.append(") DO NOTHING").toString()); + } sb.append(") DO UPDATE SET "); for (int i = 0; i < spec.updateColumns().size(); i++) { if (i > 0) diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteAddConstraintTest.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteAddConstraintTest.java new file mode 100644 index 00000000..40258333 --- /dev/null +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteAddConstraintTest.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.sqlite.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.JDBCType; +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; + +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator; +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.eclipse.daanse.sql.jdbc.record.schema.ColumnDefinitionRecord; +import org.eclipse.daanse.sql.jdbc.record.schema.ColumnMetaDataRecord; +import org.eclipse.daanse.sql.jdbc.record.schema.PrimaryKeyRecord; +import org.eclipse.daanse.sql.model.schema.ColumnDefinition; +import org.eclipse.daanse.sql.model.schema.ColumnMetaData; +import org.eclipse.daanse.sql.model.schema.ColumnReference; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * SQLite adds no unique constraint, no check and no foreign key to an existing table, in any version (a syntax error + * near CONSTRAINT): the dialect adds none of them later and declares them in {@code CREATE TABLE}. SQLite is embedded: + * the CLI of each version runs what the dialect writes, in Docker, and the dialect is built for the version the CLI + * reports. The {@code CREATE TABLE} with a unique constraint, a check and a foreign key holds the rows that keep them + * and refuses those that break them; the foreign key refers to its table by its name alone, as SQLite asks of a table + * named with its schema, keeps ON DELETE CASCADE, and is kept only where the connection turns foreign keys on. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class SqliteAddConstraintTest { + + private static final Optional MAIN = Optional.of(new SchemaReference(Optional.empty(), "main")); + private static final TableReference CUSTOMER = new TableReference(MAIN, "customer"); + private static final TableReference ORDERS = new TableReference(MAIN, "orders"); + + private static final String FOREIGN_KEYS = "PRAGMA foreign_keys = ON;\n"; + + @ParameterizedTest(name = "sqlite {0}") + @ValueSource(strings = { "3.22.0", "3.25.3", "3.32.1", "3.40.1", "3.46.1", "3.51.0" }) + void addConstraint(String version) { + SqliteDialect dialect = SqliteCli.dialect(version); + DdlGenerator ddl = dialect.ddlGenerator(); + + assertThat(ddl.supportsAddForeignKeyConstraint()).as("supportsAddForeignKeyConstraint").isFalse(); + assertThat(ddl.supportsAddUniqueConstraint()).as("supportsAddUniqueConstraint").isFalse(); + assertThat(ddl.supportsAddCheckConstraint()).as("supportsAddCheckConstraint").isFalse(); + assertThat(ddl.addForeignKeyConstraint(ORDERS, "fk", List.of("cid"), CUSTOMER, List.of("id"), null, null, + DdlGenerator.Deferrability.NOT_DEFERRABLE)).as("no foreign key added later").isEmpty(); + + // declared in CREATE TABLE, the constraints hold + String customer = ddl.createTable(CUSTOMER, List.of(column(CUSTOMER, "id", JDBCType.INTEGER), + column(CUSTOMER, "email", JDBCType.VARCHAR), column(CUSTOMER, "n", JDBCType.INTEGER)), + pk(CUSTOMER), + List.of(ddl.uniqueConstraintClause("uc_email", List.of("email")), + ddl.checkConstraintClause("ck_n", "\"n\" > 0")), + false); + String fk = ddl.foreignKeyClause("fk_orders_customer", List.of("cid"), CUSTOMER, List.of("id"), "CASCADE", + "NO ACTION"); + assertThat(fk).as("the referenced table by its name alone").contains("REFERENCES \"customer\" (") + .doesNotContain("\"main\".").endsWith(" ON DELETE CASCADE ON UPDATE NO ACTION"); + String orders = ddl.createTable(ORDERS, List.of(column(ORDERS, "id", JDBCType.INTEGER), + column(ORDERS, "cid", JDBCType.INTEGER)), pk(ORDERS), List.of(fk), false); + String setup = customer + ";\n" + orders + ";\nINSERT INTO customer VALUES (1, 'a@x', 1), (2, 'b@x', 2);\n" + + "INSERT INTO orders VALUES (10, 1), (11, NULL), (12, 2);\n"; + + SqliteCli.Result kept = SqliteCli.run(version, FOREIGN_KEYS + setup + + "SELECT 'customers ' || count(*) FROM customer; SELECT 'orders ' || count(*) FROM orders;"); + assertThat(kept.failed()).as(kept.err() + " in " + setup).isFalse(); + assertThat(kept.out()).as("the rows that keep the constraints").containsExactly("customers 2", "orders 3"); + + assertRefused(version, FOREIGN_KEYS + setup + "INSERT INTO customer VALUES (3, 'a@x', 3);", "UNIQUE", + "a second email"); + assertRefused(version, FOREIGN_KEYS + setup + "INSERT INTO customer VALUES (3, 'c@x', 0);", "CHECK", + "n not above 0"); + assertRefused(version, FOREIGN_KEYS + setup + "INSERT INTO orders VALUES (13, 99);", "FOREIGN KEY", + "an order of no customer"); + + SqliteCli.Result cascade = SqliteCli.run(version, FOREIGN_KEYS + setup + + "DELETE FROM customer WHERE id = 1; SELECT 'orders ' || count(*) FROM orders;"); + assertThat(cascade.failed()).as(cascade.err()).isFalse(); + assertThat(cascade.out()).as("ON DELETE CASCADE takes the customer's orders").containsExactly("orders 2"); + + SqliteCli.Result off = SqliteCli.run(version, setup + + "INSERT INTO orders VALUES (13, 99); SELECT 'orders ' || count(*) FROM orders;"); + assertThat(off.failed()).as(off.err()).isFalse(); + assertThat(off.out()).as("without PRAGMA foreign_keys the key is not kept").containsExactly("orders 4"); + + assertRefused(version, "CREATE TABLE customer(id INTEGER PRIMARY KEY);" + + " CREATE TABLE r(cid INTEGER, FOREIGN KEY (cid) REFERENCES \"main\".\"customer\" (id));", + "syntax error", "REFERENCES a table named with its schema"); + + // ALTER TABLE … ADD: none in any version + String plain = "CREATE TABLE customer(id INTEGER PRIMARY KEY, email TEXT, n INTEGER);" + + " CREATE TABLE orders(id INTEGER, cid INTEGER);\n"; + assertRefused(version, plain + ddl.addUniqueConstraint(CUSTOMER, "uc_email", List.of("email")) + ";", + "syntax error", "ADD UNIQUE"); + assertRefused(version, plain + ddl.addCheckConstraint(CUSTOMER, "ck_n", "\"n\" > 0") + ";", "syntax error", + "ADD CHECK"); + assertRefused(version, plain + ddl.addForeignKeyConstraint(ORDERS, "fk_orders_customer", List.of("cid"), + CUSTOMER, List.of("id"), null, null) + ";", "syntax error", "ADD FOREIGN KEY"); + } + + private static void assertRefused(String version, String sql, String error, String what) { + SqliteCli.Result r = SqliteCli.run(version, sql); + assertThat(r.failed()).as(what + " is refused: " + sql).isTrue(); + assertThat(r.err()).as(what).contains(error); + } + + private static PrimaryKeyRecord pk(TableReference table) { + return new PrimaryKeyRecord(table, List.of(new ColumnReference(Optional.of(table), "id")), Optional.empty()); + } + + private static ColumnDefinition column(TableReference table, String name, JDBCType type) { + return new ColumnDefinitionRecord(new ColumnReference(Optional.of(table), name), + new ColumnMetaDataRecord(type, type.getName(), + type == JDBCType.VARCHAR ? OptionalInt.of(50) : OptionalInt.empty(), OptionalInt.empty(), + OptionalInt.empty(), ColumnMetaData.Nullability.NULLABLE, OptionalInt.empty(), + Optional.empty(), Optional.empty(), ColumnMetaData.AutoIncrement.UNKNOWN, + ColumnMetaData.GeneratedColumn.UNKNOWN)); + } +} diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteCli.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteCli.java new file mode 100644 index 00000000..696e8b48 --- /dev/null +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteCli.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.sqlite.container; + +import java.time.Duration; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.output.OutputFrame.OutputType; +import org.testcontainers.containers.startupcheck.StartupCheckStrategy; +import org.testcontainers.images.builder.ImageFromDockerfile; + +import com.github.dockerjava.api.DockerClient; + +/** + * The sqlite3 CLI of a given version, run in Docker. SQLite is embedded and serves no connection, and the JDBC driver + * brings an SQLite of its own: the version is the CLI's. A version is named by the image that has it: + * {@code keinos/sqlite3:} from 3.38, and before, a release of a distribution whose package is that version, + * built once into an image of its own name and kept ({@code ubuntu:18.04} with 3.22.0, {@code alpine:3.8} with 3.25.3, + * {@code alpine:3.12} with 3.32.1, {@code alpine:3.14} with 3.35.5). Each call runs its statements in a database in + * memory and exits, stopping at the first that fails ({@code -bail}). + */ +final class SqliteCli { + + private static final Pattern VERSION = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)"); + + /** What a call printed, and how it exited. */ + record Result(long exitCode, List out, String err) { + + /** Whether a statement failed: {@code Error:} in older CLIs, {@code Parse error} or the like in newer. */ + boolean failed() { + return exitCode != 0 || err.toLowerCase(java.util.Locale.ROOT).contains("error"); + } + } + + private SqliteCli() { + } + + /** Runs the statements and gives the lines of their rows, the values split by {@code |}, no header. */ + static Result run(String version, String sql) { + try (GenericContainer cli = container(version) + .withCommand("sqlite3", "-batch", "-bail", "-noheader", "-list", ":memory:", sql) + .withStartupCheckStrategy(new Exited())) { + cli.start(); + long exitCode = cli.getCurrentContainerInfo().getState().getExitCodeLong(); + List out = cli.getLogs(OutputType.STDOUT).lines().toList(); + return new Result(exitCode, out, cli.getLogs(OutputType.STDERR)); + } + } + + /** The dialect for the version the CLI reports, checked against the one asked for. */ + static SqliteDialect dialect(String version) { + Result r = run(version, "SELECT sqlite_version();"); + String reported = r.out().isEmpty() ? "" : r.out().get(0); + Matcher m = VERSION.matcher(reported); + if (r.failed() || !m.matches() || !reported.equals(version)) { + throw new IllegalStateException("sqlite " + version + " reports " + r.out() + r.err()); + } + return new SqliteDialect(DialectInitData.ansiDefaults().withVersion(Integer.parseInt(m.group(1)), + Integer.parseInt(m.group(2)))); + } + + private static GenericContainer container(String version) { + String base = switch (version) { + case "3.22.0" -> "ubuntu:18.04"; + case "3.25.3" -> "alpine:3.8"; + case "3.32.1" -> "alpine:3.12"; + case "3.35.5" -> "alpine:3.14"; + default -> null; + }; + if (base == null) { + return new GenericContainer<>("keinos/sqlite3:" + version); + } + String install = base.startsWith("ubuntu") + ? "apt-get update && apt-get install -y --no-install-recommends sqlite3 && rm -rf /var/lib/apt/lists/*" + : "apk add --no-cache sqlite"; + // named and not deleted: built once, then taken from Docker's cache + return new GenericContainer<>(new ImageFromDockerfile("daanse-sqlite3:" + version, false) + .withDockerfileFromBuilder(b -> b.from(base).run(install).build())); + } + + /** Started once the container has exited, whatever its exit code: a failed statement is a result too. */ + private static final class Exited extends StartupCheckStrategy { + + Exited() { + withTimeout(Duration.ofMinutes(5)); + } + + @Override + public StartupStatus checkStartupState(DockerClient dockerClient, String containerId) { + return "exited".equals(getCurrentState(dockerClient, containerId).getStatus()) ? StartupStatus.SUCCESSFUL + : StartupStatus.NOT_YET_KNOWN; + } + } +} diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteListAggTest.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteListAggTest.java new file mode 100644 index 00000000..cb42d97b --- /dev/null +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteListAggTest.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.sqlite.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.eclipse.daanse.sql.model.sql.NullsOrder; +import org.eclipse.daanse.sql.model.sql.OrderedColumn; +import org.eclipse.daanse.sql.model.sql.SortDirection; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** + * SQLite lists the values of a group with {@code group_concat(x, sep)} on every version, with an order inside it + * from 3.44.0; a DISTINCT aggregate takes one argument only, on every version. SQLite is embedded: the CLI of each + * version runs the statements in Docker, and the dialect is built for the version the CLI reports. The list it writes + * must leave the NULL values out, keep DISTINCT with any separator, take a quote and a backslash as a separator, list + * a column of any type and per group; from 3.44 on in the order asked for, the NULLs of an order column first or last + * as asked. Before 3.44 an ordered list, and on every version a DISTINCT one in the order of another column, it does + * not write. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class SqliteListAggTest { + + /** Group a: alice 20, bob 30, bob 10, a NULL name of 40; group b: dave 5. */ + private static final String SETUP = "CREATE TABLE emp(dept TEXT, name TEXT, salary INTEGER);" + + " INSERT INTO emp VALUES ('a', 'bob', 30), ('a', NULL, 40), ('a', 'alice', 20), ('a', 'bob', 10)," + + " ('b', 'dave', 5);\n"; + + @ParameterizedTest(name = "sqlite {0} -> ordered {1}") + @CsvSource({ "3.22.0, false", "3.32.1, false", "3.43.1, false", "3.44.0, true", "3.46.1, true", + "3.51.0, true" }) + void list_agg(String version, boolean ordered) { + SqliteDialect d = SqliteCli.dialect(version); + assertThat(d.supportsListAgg()).as("supportsListAgg").isTrue(); + + Map lists = new LinkedHashMap<>(); + lists.put("no order", agg(d, "name", false, ",", List.of())); + lists.put("DISTINCT, no order", agg(d, "name", true, ";", List.of())); + lists.put("a quote as separator", agg(d, "name", false, "'", List.of())); + lists.put("a backslash as separator", agg(d, "name", false, "\\", List.of())); + lists.put("no separator is a comma", agg(d, "name", false, null, List.of())); + lists.put("an INTEGER column", agg(d, "salary", false, ",", List.of())); + if (ordered) { + lists.put("ordered by the value", agg(d, "name", false, ", ", order("name", SortDirection.ASC))); + lists.put("ordered by another column", agg(d, "name", false, ", ", order("salary", SortDirection.DESC))); + lists.put("a column of the table", agg(d, "name", false, ", ", + List.of(new OrderedColumn("name", "emp", SortDirection.ASC)))); + lists.put("DISTINCT ordered by the value", agg(d, "name", true, ";", order("name", SortDirection.DESC))); + lists.put("NULLS FIRST, then a second column", agg(d, "salary", false, ",", + List.of(new OrderedColumn("name", null, Optional.of(SortDirection.ASC), + Optional.of(NullsOrder.FIRST)), new OrderedColumn("salary", null, SortDirection.ASC)))); + lists.put("NULLS LAST, then a second column", agg(d, "salary", false, ",", + List.of(new OrderedColumn("name", null, Optional.of(SortDirection.ASC), + Optional.of(NullsOrder.LAST)), new OrderedColumn("salary", null, SortDirection.ASC)))); + } else { + assertThat(d.generateListAgg("name", false, ",", null, null, order("name", SortDirection.ASC))) + .as("no ordered list before 3.44").isEmpty(); + } + assertThat(d.generateListAgg("name", true, ",", null, null, order("salary", SortDirection.ASC))) + .as("no DISTINCT list in the order of another column").isEmpty(); + + StringBuilder sql = new StringBuilder(SETUP); + lists.forEach((label, agg) -> sql.append("SELECT '").append(label).append("|' || ").append(agg) + .append(" FROM emp WHERE dept = 'a';\n")); + String perDept = agg(d, "name", false, ",", List.of()); + sql.append("SELECT 'per group|' || group_concat(dept || '=' || l, ' ') FROM (SELECT dept, ").append(perDept) + .append(" AS l FROM emp GROUP BY dept ORDER BY dept);\n"); + String distinctPerDept = agg(d, "name", true, ";", List.of()); + sql.append("SELECT 'DISTINCT per group|' || group_concat(dept || '=' || l, ' ') FROM (SELECT dept, ") + .append(distinctPerDept).append(" AS l FROM emp GROUP BY dept ORDER BY dept);\n"); + SqliteCli.Result r = SqliteCli.run(version, sql.toString()); + assertThat(r.failed()).as("every list runs: " + r.err() + " in " + sql).isFalse(); + Map got = new LinkedHashMap<>(); + for (String line : r.out()) { + int bar = line.indexOf('|'); + if (bar > 0) { + got.put(line.substring(0, bar), line.substring(bar + 1)); + } + } + + assertThat(sorted(got.get("no order"), ",")).as("the NULL left out").containsExactly("alice", "bob", "bob"); + assertThat(sorted(got.get("DISTINCT, no order"), ";")).as(lists.get("DISTINCT, no order")) + .containsExactly("alice", "bob"); + assertThat(sorted(got.get("a quote as separator"), "'")).containsExactly("alice", "bob", "bob"); + assertThat(sorted(got.get("a backslash as separator"), "\\\\")).containsExactly("alice", "bob", "bob"); + assertThat(sorted(got.get("no separator is a comma"), ",")).containsExactly("alice", "bob", "bob"); + assertThat(sorted(got.get("an INTEGER column"), ",")).containsExactly("10", "20", "30", "40"); + assertThat(got.get("per group")).as("per group") + .matches("a=(alice,bob,bob|bob,alice,bob|bob,bob,alice) b=dave"); + assertThat(got.get("DISTINCT per group")).as("DISTINCT per group").matches("a=(alice;bob|bob;alice) b=dave"); + if (!ordered) { + SqliteCli.Result refused = SqliteCli.run(version, + SETUP + "SELECT group_concat(name, ',' ORDER BY name) FROM emp;"); + assertThat(refused.failed()).as("the server knows no ORDER BY in an aggregate before 3.44").isTrue(); + return; + } + assertThat(got.get("ordered by the value")).as(lists.get("ordered by the value")) + .isEqualTo("alice, bob, bob"); + assertThat(got.get("ordered by another column")).isEqualTo("bob, alice, bob"); + assertThat(got.get("a column of the table")).isEqualTo("alice, bob, bob"); + assertThat(got.get("DISTINCT ordered by the value")).as(lists.get("DISTINCT ordered by the value")) + .isEqualTo("bob;alice"); + assertThat(got.get("NULLS FIRST, then a second column")).isEqualTo("40,20,10,30"); + assertThat(got.get("NULLS LAST, then a second column")).isEqualTo("20,10,30,40"); + } + + private static String agg(SqliteDialect d, String operand, boolean distinct, String separator, + List columns) { + return d.generateListAgg(operand, distinct, separator, null, null, columns).orElseThrow(); + } + + private static List order(String column, SortDirection direction) { + return List.of(new OrderedColumn(column, null, direction)); + } + + private static List sorted(String list, String separatorRegex) { + assertThat(list).isNotNull(); + return Arrays.stream(list.split(separatorRegex)).sorted().toList(); + } +} diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteNthValueTest.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteNthValueTest.java new file mode 100644 index 00000000..9c874f49 --- /dev/null +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteNthValueTest.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.sqlite.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.eclipse.daanse.sql.model.sql.NullsOrder; +import org.eclipse.daanse.sql.model.sql.OrderedColumn; +import org.eclipse.daanse.sql.model.sql.SortDirection; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** + * SQLite gives the n-th value of a group as the n-th element of {@code json_group_array(v ORDER BY …)} from 3.44.0, + * where an aggregate takes an ORDER BY: an aggregate over the rows of the group, not the window {@code nth_value … + * OVER} (V-82). SQLite is embedded: the CLI of each version runs the statements in Docker, and the dialect is built for + * the version the CLI reports. From 3.44 on the n-th value must follow the order asked for, ascending, descending, + * NULLs of an order column first or last, a column named with its table; count the NULL values or leave them out as + * asked; n below 1 is 1; past the end it is NULL; a text keeps its quotes; and it is per group. Before, the dialect + * offers none. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class SqliteNthValueTest { + + /** Group a in the order of o: NULL, 20, 30, NULL, 50; group b: 7; group c: a NULL o of 9, then 8. */ + private static final String SETUP = "CREATE TABLE t(g TEXT, o INTEGER, v INTEGER, s TEXT);" + + " INSERT INTO t VALUES ('a', 3, 30, 'it''s'), ('a', 1, NULL, NULL), ('a', 5, 50, 'x')," + + " ('a', 2, 20, 'y'), ('a', 4, NULL, NULL), ('b', 1, 7, 'z'), ('c', NULL, 9, NULL), ('c', 1, 8, NULL);\n"; + + private static final List BY_O = List.of(new OrderedColumn("o", null, SortDirection.ASC)); + private static final List BY_O_DESC = List.of(new OrderedColumn("o", null, SortDirection.DESC)); + + @ParameterizedTest(name = "sqlite {0} -> nth value {1}") + @CsvSource({ "3.22.0, false", "3.43.1, false", "3.44.0, true", "3.46.1, true", "3.51.0, true" }) + void nth_value(String version, boolean expected) { + SqliteDialect d = SqliteCli.dialect(version); + assertThat(d.supportsNthValue()).as("supportsNthValue").isEqualTo(expected); + assertThat(d.supportsNthValueIgnoreNulls()).as("supportsNthValueIgnoreNulls").isEqualTo(expected); + if (!expected) { + assertThat(d.generateNthValueAgg("v", true, 1, BY_O)).as("none before 3.44").isEmpty(); + SqliteCli.Result refused = SqliteCli.run(version, + SETUP + "SELECT json_group_array(v ORDER BY o) FROM t;"); + assertThat(refused.failed()).as("the server takes no ORDER BY in an aggregate before 3.44").isTrue(); + return; + } + + Map nth = new LinkedHashMap<>(); + nth.put("1st", nth(d, false, 1, BY_O)); + nth.put("1st ignoring NULLs", nth(d, true, 1, BY_O)); + nth.put("2nd", nth(d, false, 2, BY_O)); + nth.put("2nd ignoring NULLs", nth(d, true, 2, BY_O)); + nth.put("5th", nth(d, false, 5, BY_O)); + nth.put("3rd ignoring NULLs", nth(d, true, 3, BY_O)); + nth.put("4th ignoring NULLs, past the end", nth(d, true, 4, BY_O)); + nth.put("6th, past the end", nth(d, false, 6, BY_O)); + nth.put("0th is the 1st", nth(d, true, 0, BY_O)); + nth.put("no n is the 1st", nth(d, true, null, BY_O)); + nth.put("1st descending", nth(d, false, 1, BY_O_DESC)); + nth.put("2nd descending ignoring NULLs", nth(d, true, 2, BY_O_DESC)); + nth.put("1st by a column of the table", nth(d, true, 1, List.of(new OrderedColumn("o", "t", + SortDirection.ASC)))); + nth.put("a text with a quote", d.generateNthValueAgg("s", true, 2, BY_O).orElseThrow()); + + StringBuilder sql = new StringBuilder(SETUP); + nth.forEach((label, agg) -> sql.append("SELECT '").append(label).append("|' || ifnull(").append(agg) + .append(", 'null') FROM t WHERE g = 'a';\n")); + nullsOrder(sql, d, "NULLS FIRST", NullsOrder.FIRST); + nullsOrder(sql, d, "NULLS LAST", NullsOrder.LAST); + sql.append("SELECT 'per group|' || group_concat(g || '=' || ifnull(x, 'null'), ' ') FROM (SELECT g, ") + .append(nth(d, true, 1, BY_O)).append(" AS x FROM t GROUP BY g ORDER BY g);\n"); + + SqliteCli.Result r = SqliteCli.run(version, sql.toString()); + assertThat(r.failed()).as("every n-th value runs: " + r.err() + " in " + nth).isFalse(); + Map got = new LinkedHashMap<>(); + for (String line : r.out()) { + int bar = line.indexOf('|'); + if (bar > 0) { + got.put(line.substring(0, bar), line.substring(bar + 1)); + } + } + + assertThat(got.get("1st")).as("the NULLs counted: " + nth.get("1st")).isEqualTo("null"); + assertThat(got.get("1st ignoring NULLs")).as(nth.get("1st ignoring NULLs")).isEqualTo("20"); + assertThat(got.get("2nd")).isEqualTo("20"); + assertThat(got.get("2nd ignoring NULLs")).isEqualTo("30"); + assertThat(got.get("5th")).isEqualTo("50"); + assertThat(got.get("3rd ignoring NULLs")).isEqualTo("50"); + assertThat(got.get("4th ignoring NULLs, past the end")).isEqualTo("null"); + assertThat(got.get("6th, past the end")).isEqualTo("null"); + assertThat(got.get("0th is the 1st")).isEqualTo("20"); + assertThat(got.get("no n is the 1st")).isEqualTo("20"); + assertThat(got.get("1st descending")).isEqualTo("50"); + assertThat(got.get("2nd descending ignoring NULLs")).isEqualTo("30"); + assertThat(got.get("1st by a column of the table")).isEqualTo("20"); + assertThat(got.get("a text with a quote")).as("the 2nd text, by o: y, then it's").isEqualTo("it's"); + assertThat(got.get("NULLS FIRST")).as("the row of a NULL order first").isEqualTo("9"); + assertThat(got.get("NULLS LAST")).as("the row of a NULL order last").isEqualTo("8"); + assertThat(got.get("per group")).as("per group; c by SQLite's own order, its NULL o first ascending") + .isEqualTo("a=20 b=7 c=9"); + } + + private static String nth(SqliteDialect d, boolean ignoreNulls, Integer n, List columns) { + return d.generateNthValueAgg("v", ignoreNulls, n, columns).orElseThrow(); + } + + private static void nullsOrder(StringBuilder sql, SqliteDialect d, String label, NullsOrder nulls) { + String agg = nth(d, false, 1, List.of(new OrderedColumn("o", null, Optional.of(SortDirection.ASC), + Optional.of(nulls)))); + sql.append("SELECT '").append(label).append("|' || ifnull(").append(agg) + .append(", 'null') FROM t WHERE g = 'c';\n"); + } +} diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteNullsOrderTest.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteNullsOrderTest.java new file mode 100644 index 00000000..cadf1555 --- /dev/null +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteNullsOrderTest.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.sqlite.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** + * SQLite has {@code NULLS FIRST} and {@code NULLS LAST} from 3.30.0, and puts NULLs first ascending and last + * descending by itself. SQLite is embedded: the CLI of each version runs the statements in Docker, and the dialect is + * built for the version the CLI reports. From 3.30 on the dialect orders with NULLS FIRST/LAST, before with a CASE + * that ranks the NULLs, which 3.25 runs where it refuses the other; on every version the order must put the NULLs + * where asked, ascending and descending, through generateOrderItem and generateOrderByNulls alike. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class SqliteNullsOrderTest { + + private static final String SETUP = "CREATE TABLE t(v INTEGER); INSERT INTO t VALUES (2), (NULL), (1), (3);\n"; + + @ParameterizedTest(name = "sqlite {0} -> NULLS FIRST/LAST {1}") + @CsvSource({ "3.22.0, false", "3.25.3, false", "3.32.1, true", "3.40.1, true", "3.46.1, true", + "3.51.0, true" }) + void nulls_order(String version, boolean nullsOrdering) { + SqliteDialect d = SqliteCli.dialect(version); + assertThat(d.supportsNullsLast()).as("supportsNullsLast").isEqualTo(nullsOrdering); + assertThat(d.getOrderByCapabilities().supportsNullsLast()).as("the capabilities say the same") + .isEqualTo(nullsOrdering); + assertThat(d.generateOrderItem("v", true, true, true).toString().contains("NULLS")) + .as("NULLS written").isEqualTo(nullsOrdering); + + Map orders = new LinkedHashMap<>(); + orders.put("asc nulls last", d.generateOrderItem("v", true, true, true).toString()); + orders.put("asc nulls first", d.generateOrderItem("v", true, true, false).toString()); + orders.put("desc nulls last", d.generateOrderItem("v", true, false, true).toString()); + orders.put("desc nulls first", d.generateOrderItem("v", true, false, false).toString()); + orders.put("by nulls, desc nulls last", d.generateOrderByNulls("v", false, true).toString()); + orders.put("not nullable, asc", d.generateOrderItem("v", false, true, true).toString()); + orders.put("not nullable, desc", d.generateOrderItem("v", false, false, true).toString()); + + StringBuilder sql = new StringBuilder(SETUP); + orders.forEach((label, order) -> sql.append("SELECT '").append(label) + .append("|' || group_concat(ifnull(v, 'null'), ',') FROM (SELECT v FROM t ORDER BY ").append(order) + .append(");\n")); + SqliteCli.Result r = SqliteCli.run(version, sql.toString()); + assertThat(r.failed()).as("every order runs: " + r.err() + " in " + orders).isFalse(); + Map got = new LinkedHashMap<>(); + for (String line : r.out()) { + int bar = line.indexOf('|'); + if (bar > 0) { + got.put(line.substring(0, bar), line.substring(bar + 1)); + } + } + + assertThat(got.get("asc nulls last")).as(orders.get("asc nulls last")).isEqualTo("1,2,3,null"); + assertThat(got.get("asc nulls first")).as(orders.get("asc nulls first")).isEqualTo("null,1,2,3"); + assertThat(got.get("desc nulls last")).as(orders.get("desc nulls last")).isEqualTo("3,2,1,null"); + assertThat(got.get("desc nulls first")).as(orders.get("desc nulls first")).isEqualTo("null,3,2,1"); + assertThat(got.get("by nulls, desc nulls last")).isEqualTo("3,2,1,null"); + assertThat(got.get("not nullable, asc")).as("SQLite's own: NULLs first ascending").isEqualTo("null,1,2,3"); + assertThat(got.get("not nullable, desc")).as("and last descending").isEqualTo("3,2,1,null"); + + SqliteCli.Result ansi = SqliteCli.run(version, SETUP + "SELECT v FROM t ORDER BY v ASC NULLS LAST;"); + assertThat(ansi.failed()).as("the server takes NULLS LAST: " + ansi.err()).isEqualTo(!nullsOrdering); + } +} diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqlitePercentileTest.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqlitePercentileTest.java new file mode 100644 index 00000000..a2c48468 --- /dev/null +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqlitePercentileTest.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.sqlite.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** + * SQLite has no {@code PERCENTILE_CONT … WITHIN GROUP}, and its own {@code percentile_cont} and + * {@code percentile_disc} are in some builds only, as {@code ceil} is. The dialect computes both on the sorted values + * of {@code json_group_array}, from 3.44.0, where an aggregate takes an ORDER BY. SQLite is embedded: the CLI of each + * version runs the statements in Docker, and the dialect is built for the version the CLI reports. From 3.44 on its + * percentiles must give what the standard says, on builds with and without the functions of their own: the discrete + * one a value of the group, the continuous one interpolated, ascending and descending, the NULLs left out, p at its + * ends, per group, and NULL for a group of no value. Before, it offers none. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class SqlitePercentileTest { + + /** Group a: 10, 20, 30, 40 and a NULL that every aggregate leaves out; group b: 5; group c: only a NULL. */ + private static final String SETUP = "CREATE TABLE nums(g TEXT, v INTEGER); INSERT INTO nums VALUES ('a', 30)," + + " ('a', 10), ('a', NULL), ('a', 40), ('a', 20), ('b', 5), ('c', NULL);\n"; + + /** + * 3.47.0 and 3.50.1 are builds with percentile_cont and ceil, 3.46.1 and 3.51.0 builds without; keinos/sqlite3's + * 3.49.0 holds 3.44.4 and is not run. + */ + @ParameterizedTest(name = "sqlite {0} -> percentiles {1}") + @CsvSource({ "3.22.0, false", "3.43.1, false", "3.44.0, true", "3.46.1, true", "3.47.0, true", "3.50.1, true", + "3.51.0, true" }) + void percentile(String version, boolean expected) { + SqliteDialect d = SqliteCli.dialect(version); + assertThat(d.supportsPercentileDisc()).as("supportsPercentileDisc").isEqualTo(expected); + assertThat(d.supportsPercentileCont()).as("supportsPercentileCont").isEqualTo(expected); + if (!expected) { + assertThat(d.generatePercentileDisc(0.5, false, "nums", "v")).as("none before 3.44").isEmpty(); + assertThat(d.generatePercentileCont(0.5, false, "nums", "v")).as("none before 3.44").isEmpty(); + return; + } + + Map p = new LinkedHashMap<>(); + p.put("disc 0.5", d.generatePercentileDisc(0.5, false, "nums", "v").orElseThrow()); + p.put("disc 0.25", d.generatePercentileDisc(0.25, false, null, "v").orElseThrow()); + p.put("disc 0.7", d.generatePercentileDisc(0.7, false, null, "v").orElseThrow()); + p.put("disc 0", d.generatePercentileDisc(0, false, null, "v").orElseThrow()); + p.put("disc 1", d.generatePercentileDisc(1, false, null, "v").orElseThrow()); + p.put("disc 0.5 desc", d.generatePercentileDisc(0.5, true, null, "v").orElseThrow()); + p.put("disc 0.25 desc", d.generatePercentileDisc(0.25, true, null, "v").orElseThrow()); + p.put("cont 0.5", d.generatePercentileCont(0.5, false, "nums", "v").orElseThrow()); + p.put("cont 0.25", d.generatePercentileCont(0.25, false, null, "v").orElseThrow()); + p.put("cont 0.7", d.generatePercentileCont(0.7, false, null, "v").orElseThrow()); + p.put("cont 0", d.generatePercentileCont(0, false, null, "v").orElseThrow()); + p.put("cont 1", d.generatePercentileCont(1, false, null, "v").orElseThrow()); + p.put("cont 0.25 desc", d.generatePercentileCont(0.25, true, null, "v").orElseThrow()); + p.put("cont 1 desc", d.generatePercentileCont(1, true, null, "v").orElseThrow()); + + StringBuilder sql = new StringBuilder(SETUP); + p.forEach((label, agg) -> sql.append("SELECT '").append(label).append("|' || ifnull(").append(agg) + .append(", 'null') FROM nums WHERE g = 'a';\n")); + String cont = d.generatePercentileCont(0.5, false, null, "v").orElseThrow(); + String disc = d.generatePercentileDisc(0.5, false, null, "v").orElseThrow(); + sql.append("SELECT 'cont per group|' || group_concat(g || '=' || ifnull(x, 'null'), ' ') FROM (SELECT g, ") + .append(cont).append(" AS x FROM nums GROUP BY g ORDER BY g);\n"); + sql.append("SELECT 'disc per group|' || group_concat(g || '=' || ifnull(x, 'null'), ' ') FROM (SELECT g, ") + .append(disc).append(" AS x FROM nums GROUP BY g ORDER BY g);\n"); + + SqliteCli.Result r = SqliteCli.run(version, sql.toString()); + assertThat(r.failed()).as("every percentile runs: " + r.err() + " in " + p).isFalse(); + Map got = new LinkedHashMap<>(); + for (String line : r.out()) { + int bar = line.indexOf('|'); + if (bar > 0) { + got.put(line.substring(0, bar), line.substring(bar + 1)); + } + } + + assertThat(num(got, "disc 0.5")).as(p.get("disc 0.5")).isEqualTo(20); + assertThat(num(got, "disc 0.25")).as("cume_dist of 10 is 0.25").isEqualTo(10); + assertThat(num(got, "disc 0.7")).isEqualTo(30); + assertThat(num(got, "disc 0")).as("the least").isEqualTo(10); + assertThat(num(got, "disc 1")).as("the greatest").isEqualTo(40); + assertThat(num(got, "disc 0.5 desc")).as("descending").isEqualTo(30); + assertThat(num(got, "disc 0.25 desc")).isEqualTo(40); + assertThat(num(got, "cont 0.5")).as(p.get("cont 0.5")).isEqualTo(25); + assertThat(num(got, "cont 0.25")).isEqualTo(17.5); + assertThat(num(got, "cont 0.7")).isCloseTo(31, within(1e-9)); + assertThat(num(got, "cont 0")).as("the least").isEqualTo(10); + assertThat(num(got, "cont 1")).as("the greatest").isEqualTo(40); + assertThat(num(got, "cont 0.25 desc")).as("descending").isEqualTo(32.5); + assertThat(num(got, "cont 1 desc")).as("descending, the end: the least").isEqualTo(10); + assertThat(got.get("cont per group")).as("one value, no value").matches("a=25(\\.0)? b=5(\\.0)? c=null"); + assertThat(got.get("disc per group")).as("one value, no value").isEqualTo("a=20 b=5 c=null"); + } + + private static double num(Map got, String label) { + assertThat(got.get(label)).as(label).isNotNull(); + return Double.parseDouble(got.get(label)); + } +} diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteRenameColumnTest.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteRenameColumnTest.java new file mode 100644 index 00000000..cc1e04eb --- /dev/null +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteRenameColumnTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.sqlite.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** + * SQLite renames a column with {@code ALTER TABLE … RENAME COLUMN} from 3.25.0, which changes the name only, and + * renames it in the table's indexes and views as well. SQLite is embedded and serves no connection: the CLI of each + * version runs the statements in Docker, and the dialect is built for the version the CLI reports. From 3.25 on the + * column it renames, the primary key too, keeps its type, its NOT NULL, its default and its values, an index and a view + * follow it; before, on 3.22, it writes no rename, for the server refuses it. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class SqliteRenameColumnTest { + + private static final TableReference T = new TableReference(Optional.empty(), "t", TableReference.TYPE_TABLE); + + private static final String SETUP = """ + CREATE TABLE t(id INTEGER PRIMARY KEY, note TEXT NOT NULL DEFAULT 'n/a', price REAL); + INSERT INTO t(id, note, price) VALUES (1, 'x', 1.5); + INSERT INTO t(id, price) VALUES (2, NULL); + CREATE INDEX t_note ON t(note); + CREATE VIEW v AS SELECT note FROM t; + """; + + @ParameterizedTest(name = "sqlite {0} -> RENAME COLUMN {1}") + @CsvSource({ "3.22.0, false", "3.25.3, true", "3.32.1, true", "3.40.1, true", "3.46.1, true", + "3.51.0, true" }) + void rename_column(String version, boolean renameColumn) { + SqliteDialect dialect = SqliteCli.dialect(version); + assertThat(dialect.supportsRenameColumn()).as("supportsRenameColumn").isEqualTo(renameColumn); + + if (!renameColumn) { + assertThat(dialect.renameColumn(T, "note", "remark")).as("no rename before 3.25").isNull(); + SqliteCli.Result r = SqliteCli.run(version, SETUP + "ALTER TABLE t RENAME COLUMN note TO remark;"); + assertThat(r.failed()).as("the server refuses it").isTrue(); + assertThat(r.err()).contains("syntax error"); + return; + } + + List renames = List.of(dialect.renameColumn(T, "note", "remark"), + dialect.renameColumn(T, "price", "cost"), dialect.renameColumn(T, "id", "key_id")); + assertThat(renames).allSatisfy(sql -> assertThat(sql).contains("RENAME COLUMN")); + + Map checks = new LinkedHashMap<>(); + checks.put("columns", "SELECT group_concat(name || ':' || type || ':' || \"notnull\" || ':'" + + " || ifnull(dflt_value, '-') || ':' || pk, ',') FROM pragma_table_info('t')"); + checks.put("values", "SELECT group_concat(key_id || ':' || remark || ':' || ifnull(cost, '-'), ',')" + + " FROM (SELECT * FROM t ORDER BY key_id)"); + checks.put("index", "SELECT group_concat(name, ',') FROM pragma_index_info('t_note')"); + checks.put("view", "SELECT (SELECT count(*) FROM v) || ':' || (instr((SELECT sql FROM sqlite_master" + + " WHERE name = 'v'), 'remark') > 0)"); + checks.put("default", "SELECT remark FROM t WHERE key_id = 3"); + + StringBuilder sql = new StringBuilder(SETUP); + renames.forEach(r -> sql.append(r).append(";\n")); + sql.append("INSERT INTO t(key_id) VALUES (3);\n"); + checks.forEach((label, query) -> sql.append("SELECT '").append(label).append("|' || (").append(query) + .append(");\n")); + SqliteCli.Result r = SqliteCli.run(version, sql.toString()); + assertThat(r.failed()).as("every rename and check runs: " + r.err() + " in " + sql).isFalse(); + Map got = new LinkedHashMap<>(); + for (String line : r.out()) { + int bar = line.indexOf('|'); + if (bar > 0) { + got.put(line.substring(0, bar), line.substring(bar + 1)); + } + } + + assertThat(got.get("columns")).as("each column renamed, and kept whole") + .isEqualTo("key_id:INTEGER:0:-:1,remark:TEXT:1:'n/a':0,cost:REAL:0:-:0"); + assertThat(got.get("values")).as("the values kept").isEqualTo("1:x:1.5,2:n/a:-,3:n/a:-"); + assertThat(got.get("index")).as("the index follows the column").isEqualTo("remark"); + assertThat(got.get("view")).as("the view follows the column, and reads").isEqualTo("3:1"); + assertThat(got.get("default")).as("the default kept").isEqualTo("n/a"); + } +} diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteRenameTableTest.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteRenameTableTest.java new file mode 100644 index 00000000..8227d560 --- /dev/null +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteRenameTableTest.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.sqlite.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.TableRename; +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** + * SQLite renames a table with {@code ALTER TABLE t RENAME TO u} in every version, the new name by itself. SQLite is + * embedded: the CLI of each version runs the statements in Docker, and the dialect is built for the version the CLI + * reports. The table the dialect renames, named with its schema, keeps its rows, and the foreign keys of other tables + * follow it in every version; its views and triggers follow it from 3.25.0 on, before they are left naming the old + * table and fail. Several renames are one statement each, which swap two tables through a third name; a view SQLite + * renames in no version, and the dialect writes no rename of one. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class SqliteRenameTableTest { + + private static final Optional MAIN = Optional.of(new SchemaReference(Optional.empty(), "main")); + + private static final String SETUP = """ + PRAGMA foreign_keys = ON; + CREATE TABLE t(id INTEGER PRIMARY KEY, a INTEGER); INSERT INTO t VALUES (1, 10); + CREATE TABLE c(tid INTEGER REFERENCES t(id)); INSERT INTO c VALUES (1); + CREATE VIEW v AS SELECT a FROM t; + CREATE TABLE log(x INTEGER); + CREATE TRIGGER tr AFTER INSERT ON c BEGIN INSERT INTO log SELECT a FROM t; END; + CREATE TABLE x(n TEXT); INSERT INTO x VALUES ('x'); CREATE TABLE y(n TEXT); INSERT INTO y VALUES ('y'); + """; + + @ParameterizedTest(name = "sqlite {0} -> views and triggers follow {1}") + @CsvSource({ "3.22.0, false", "3.25.3, true", "3.32.1, true", "3.46.1, true", "3.51.0, true" }) + void rename_table(String version, boolean dependentsFollow) { + SqliteDialect d = SqliteCli.dialect(version); + DdlGenerator ddl = d.ddlGenerator(); + assertThat(ddl.supportsRenameTable()).as("supportsRenameTable").isTrue(); + assertThat(ddl.supportsRenameView()).as("supportsRenameView").isFalse(); + assertThat(ddl.supportsAtomicMultiRenameTable()).as("supportsAtomicMultiRenameTable").isFalse(); + assertThat(ddl.renameView(table("v", TableReference.TYPE_VIEW), "w")).as("no rename of a view").isNull(); + + String rename = ddl.renameTable(table("t", TableReference.TYPE_TABLE), "u"); + assertThat(rename).as("the new name by itself").endsWith(" RENAME TO " + d.quoteIdentifier("u")); + List swap = ddl.renameTables(List.of(new TableRename(table("x", TableReference.TYPE_TABLE), "tmp"), + new TableRename(table("y", TableReference.TYPE_TABLE), "x"), + new TableRename(table("tmp", TableReference.TYPE_TABLE), "y"))); + assertThat(swap).as("one statement per rename").hasSize(3); + + StringBuilder sql = new StringBuilder(SETUP).append(rename).append(";\n"); + swap.forEach(s -> sql.append(s).append(";\n")); + sql.append("SELECT 'rows|' || (SELECT id || ':' || a FROM u);\n") + .append("SELECT 'fk|' || (instr((SELECT sql FROM sqlite_master WHERE name = 'c'), '\"u\"') > 0);\n") + .append("SELECT 'view sql|' || (instr((SELECT sql FROM sqlite_master WHERE name = 'v'), '\"u\"')" + + " > 0);\n") + .append("SELECT 'swap|' || (SELECT n FROM x) || (SELECT n FROM y);\n"); + if (dependentsFollow) { + sql.append("SELECT 'view|' || (SELECT a FROM v);\n") + .append("INSERT INTO c VALUES (1); SELECT 'trigger|' || count(*) FROM log;\n"); + } + SqliteCli.Result r = SqliteCli.run(version, sql.toString()); + assertThat(r.failed()).as(r.err() + " in " + sql).isFalse(); + List expected = dependentsFollow + ? List.of("rows|1:10", "fk|1", "view sql|1", "swap|yx", "view|10", "trigger|1") + : List.of("rows|1:10", "fk|1", "view sql|0", "swap|yx"); + assertThat(r.out()).as("the rows kept, the foreign key follows, the tables swapped") + .containsExactlyElementsOf(expected); + + if (!dependentsFollow) { + SqliteCli.Result view = SqliteCli.run(version, SETUP + rename + "; SELECT a FROM v;"); + assertThat(view.failed()).as("the view names the old table before 3.25").isTrue(); + assertThat(view.err()).contains("no such table"); + SqliteCli.Result trigger = SqliteCli.run(version, SETUP + rename + "; INSERT INTO c VALUES (1);"); + assertThat(trigger.failed()).as("so does the trigger").isTrue(); + assertThat(trigger.err()).contains("no such table"); + } + + SqliteCli.Result qualified = SqliteCli.run(version, SETUP + "ALTER TABLE t RENAME TO \"main\".\"u\";"); + assertThat(qualified.failed()).as("a new name with its schema is refused").isTrue(); + SqliteCli.Result view = SqliteCli.run(version, SETUP + "ALTER TABLE v RENAME TO w;"); + assertThat(view.failed()).as("a view is not renamed").isTrue(); + assertThat(view.err()).contains("may not be altered"); + } + + private static TableReference table(String name, String type) { + return new TableReference(MAIN, name, type); + } +} diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteReturningTest.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteReturningTest.java new file mode 100644 index 00000000..41d48dd5 --- /dev/null +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteReturningTest.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.sqlite.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.generator.ReturningGenerator; +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** + * SQLite has {@code RETURNING} from 3.35.0, on INSERT, UPDATE and DELETE, an upsert too, and no {@code RETURNING … + * INTO}. SQLite is embedded: the CLI of each version runs the statements in Docker, and the dialect is built for the + * version the CLI reports. From 3.35 on the clause it writes must bring back the rows the statement wrote: the key + * SQLite gave, a default it filled in, the values an UPDATE set, the row a DELETE took, every column with {@code *}, a + * column named by a keyword; before, it writes none, for the server refuses it. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class SqliteReturningTest { + + private static final String SETUP = "CREATE TABLE items(id INTEGER PRIMARY KEY, name TEXT UNIQUE," + + " qty INTEGER DEFAULT 1, \"order\" INTEGER);\n"; + + @ParameterizedTest(name = "sqlite {0} -> RETURNING {1}") + @CsvSource({ "3.22.0, false", "3.32.1, false", "3.35.5, true", "3.40.1, true", "3.46.1, true", + "3.51.0, true" }) + void returning(String version, boolean expected) { + SqliteDialect d = SqliteCli.dialect(version); + ReturningGenerator g = d.returningGenerator(); + assertThat(g.supportsReturning()).as("supportsReturning").isEqualTo(expected); + assertThat(g.supportsReturningInto()).as("no RETURNING … INTO").isFalse(); + assertThat(g.returningInto(List.of("id"))).isEmpty(); + assertThat(g.returning(List.of())).as("no columns, no clause").isEmpty(); + + if (!expected) { + assertThat(g.returning(List.of("id"))).as("none before 3.35").isEmpty(); + SqliteCli.Result refused = SqliteCli.run(version, + SETUP + "INSERT INTO items(name) VALUES ('a') RETURNING id;"); + assertThat(refused.failed()).as("the server refuses RETURNING before 3.35").isTrue(); + assertThat(refused.err()).contains("syntax error"); + return; + } + + String sql = SETUP + + "INSERT INTO items(name) VALUES ('a'), ('b')" + clause(g, "id", "name", "qty") + ";\n" + + "UPDATE items SET qty = qty + 5, \"order\" = 7 WHERE name = 'a'" + clause(g, "id", "qty", "order") + + ";\n" + + "DELETE FROM items WHERE id = 2" + clause(g, "*") + ";\n" + + "INSERT INTO items(name, qty) VALUES ('a', 9) ON CONFLICT(name) DO UPDATE SET qty = excluded.qty" + + clause(g, "id", "qty") + ";\n"; + SqliteCli.Result r = SqliteCli.run(version, sql); + assertThat(r.failed()).as(r.err() + " in " + sql).isFalse(); + assertThat(r.out()).as("the rows each statement wrote").containsExactly( + "1|a|1", "2|b|1", // the keys SQLite gave, the default it filled in + "1|6|7", // the values the UPDATE set, a column named by a keyword + "2|b|1|", // the row the DELETE took, every column + "1|9"); // the upsert's row + assertThat(g.returning(List.of("*")).orElseThrow()).isEqualTo(" RETURNING *"); + assertThat(g.returning(List.of("order")).orElseThrow()).as("a keyword quoted") + .isEqualTo(" RETURNING " + d.quoteIdentifier("order")); + } + + private static String clause(ReturningGenerator g, String... columns) { + return g.returning(List.of(columns)).orElseThrow(); + } +} diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteSchemaTest.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteSchemaTest.java new file mode 100644 index 00000000..d506ebad --- /dev/null +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteSchemaTest.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.sqlite.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator; +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * SQLite keeps no schemas inside a database, in any version: {@code CREATE SCHEMA} and {@code DROP SCHEMA} are syntax + * errors; its schemas are {@code main}, {@code temp} and the database files a connection attaches. SQLite is embedded: + * the CLI of each version runs the statements in Docker, and the dialect is built for the version the CLI reports. The + * dialect says it has no schemas and writes no statement to create or drop one; a table named with {@code main} or + * {@code temp} is still one SQLite has. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class SqliteSchemaTest { + + @ParameterizedTest(name = "sqlite {0}") + @ValueSource(strings = { "3.22.0", "3.32.1", "3.46.1", "3.51.0" }) + void schemas(String version) { + SqliteDialect d = SqliteCli.dialect(version); + DdlGenerator ddl = d.ddlGenerator(); + assertThat(ddl.supportsSchemas()).as("supportsSchemas").isFalse(); + assertThat(ddl.createSchema("s", true)).as("no CREATE SCHEMA").isNull(); + assertThat(ddl.createSchema("s", false)).as("no CREATE SCHEMA").isNull(); + assertThat(ddl.dropSchema("s", true, true)).as("no DROP SCHEMA").isNull(); + assertThat(ddl.dropSchema("s", false, false)).as("no DROP SCHEMA").isNull(); + assertThat(d.supportsDropSchemaIfExists()).as("supportsDropSchemaIfExists").isFalse(); + + for (String refused : new String[] { "CREATE SCHEMA \"s\";", "CREATE SCHEMA IF NOT EXISTS \"s\";", + "DROP SCHEMA \"main\";", "DROP SCHEMA IF EXISTS \"s\";" }) { + SqliteCli.Result r = SqliteCli.run(version, refused); + assertThat(r.failed()).as("the server refuses " + refused).isTrue(); + assertThat(r.err()).as(refused).contains("syntax error"); + } + + TableReference inMain = new TableReference(Optional.of(new SchemaReference(Optional.empty(), "main")), "t", + TableReference.TYPE_TABLE); + TableReference inTemp = new TableReference(Optional.of(new SchemaReference(Optional.empty(), "temp")), "u", + TableReference.TYPE_TABLE); + String sql = "CREATE TABLE " + d.qualified(inMain) + "(a INTEGER); CREATE TABLE " + d.qualified(inTemp) + + "(b INTEGER); INSERT INTO " + d.qualified(inMain) + " VALUES (1); INSERT INTO " + d.qualified(inTemp) + + " VALUES (2); SELECT (SELECT a FROM main.t) || ':' || (SELECT b FROM temp.u);\n" + + ddl.dropTable(inMain, true) + "; SELECT 'dropped';"; + SqliteCli.Result r = SqliteCli.run(version, sql); + assertThat(r.failed()).as(r.err() + " in " + sql).isFalse(); + assertThat(r.out()).as("main and temp are schemas SQLite has").containsExactly("1:2", "dropped"); + } +} diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteTriggerTest.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteTriggerTest.java new file mode 100644 index 00000000..5f3450ed --- /dev/null +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteTriggerTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.sqlite.container; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator; +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.eclipse.daanse.sql.model.schema.Trigger.TriggerEvent; +import org.eclipse.daanse.sql.model.schema.Trigger.TriggerScope; +import org.eclipse.daanse.sql.model.schema.Trigger.TriggerTiming; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * SQLite has row triggers with WHEN in every version, and no {@code FOR EACH STATEMENT} (a syntax error). SQLite is + * embedded: the CLI of each version runs the statements in Docker, and the dialect is built for the version the CLI + * reports. The triggers the dialect writes, on a table named with its schema, must fire once per row, where the WHEN + * condition holds only, read NEW and OLD, BEFORE, AFTER and INSTEAD OF on a view, and be dropped, IF EXISTS sparing an + * error; a statement trigger it does not write, for a row trigger would not fire once for a statement. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class SqliteTriggerTest { + + private static final Optional MAIN = Optional.of(new SchemaReference(Optional.empty(), "main")); + private static final TableReference T = new TableReference(MAIN, "t", TableReference.TYPE_TABLE); + private static final TableReference V = new TableReference(MAIN, "v", TableReference.TYPE_VIEW); + + private static final String SETUP = """ + CREATE TABLE t(id INTEGER PRIMARY KEY, a INTEGER); + CREATE TABLE log(what TEXT, x INTEGER); + CREATE VIEW v AS SELECT id, a FROM t; + """; + + @ParameterizedTest(name = "sqlite {0}") + @ValueSource(strings = { "3.22.0", "3.32.1", "3.46.1", "3.51.0" }) + void triggers(String version) { + SqliteDialect d = SqliteCli.dialect(version); + DdlGenerator ddl = d.ddlGenerator(); + + String insert = ddl.createTrigger("tr_ins", TriggerTiming.AFTER, TriggerEvent.INSERT, T, TriggerScope.ROW, + "NEW.a > 3", "BEGIN INSERT INTO log VALUES ('ins', NEW.a); END"); + assertThat(insert).contains(" FOR EACH ROW WHEN (NEW.a > 3) "); + String update = ddl.createTrigger("tr_upd", TriggerTiming.BEFORE, TriggerEvent.UPDATE, T, TriggerScope.ROW, + null, "BEGIN INSERT INTO log VALUES ('upd', OLD.a * 100 + NEW.a); END"); + String delete = ddl.createTrigger("tr_del", TriggerTiming.AFTER, TriggerEvent.DELETE, T, TriggerScope.ROW, + null, "BEGIN INSERT INTO log VALUES ('del', OLD.id); END"); + String instead = ddl.createTrigger("tr_v", TriggerTiming.INSTEAD_OF, TriggerEvent.INSERT, V, + TriggerScope.ROW, null, "BEGIN INSERT INTO t VALUES (NEW.id, NEW.a * 10); END"); + assertThat(instead).contains(" INSTEAD OF INSERT ON "); + + String sql = SETUP + insert + ";\n" + update + ";\n" + delete + ";\n" + instead + ";\n" + + "INSERT INTO t VALUES (1, 5), (2, 1), (3, 7);\n" // the WHEN holds for 5 and 7 + + "UPDATE t SET a = a + 1 WHERE id IN (1, 2);\n" // a row each: 506, 102 + + "DELETE FROM t WHERE id = 3;\n" + + "INSERT INTO v VALUES (4, 2);\n" // instead of the view, 20 into t; the WHEN holds for it + + "SELECT 'log|' || group_concat(what || ':' || x, ',') FROM (SELECT * FROM log ORDER BY rowid);\n" + + "SELECT 't|' || group_concat(id || ':' || a, ',') FROM (SELECT * FROM t ORDER BY id);\n" + + ddl.dropTrigger("tr_ins", false) + ";\n" + ddl.dropTrigger("tr_ins", true) + ";\n" + + "INSERT INTO t VALUES (5, 9);\n" + + "SELECT 'after drop|' || count(*) FROM log WHERE what = 'ins';\n"; + SqliteCli.Result r = SqliteCli.run(version, sql); + assertThat(r.failed()).as(r.err() + " in " + sql).isFalse(); + assertThat(r.out()).containsExactly( + "log|ins:5,ins:7,upd:506,upd:102,del:3,ins:20", + "t|1:6,2:2,4:20", + "after drop|3"); + + assertThatThrownBy(() -> ddl.createTrigger("tr_s", TriggerTiming.AFTER, TriggerEvent.INSERT, T, + TriggerScope.STATEMENT, null, "BEGIN INSERT INTO log VALUES ('s', 0); END")) + .as("no statement trigger").isInstanceOf(UnsupportedOperationException.class); + SqliteCli.Result statement = SqliteCli.run(version, SETUP + "CREATE TRIGGER tr_s AFTER INSERT ON t" + + " FOR EACH STATEMENT BEGIN INSERT INTO log VALUES ('s', 0); END;"); + assertThat(statement.failed()).as("the server refuses FOR EACH STATEMENT").isTrue(); + assertThat(statement.err()).contains("syntax error"); + + SqliteCli.Result twice = SqliteCli.run(version, SETUP + insert + ";\n" + + ddl.createTrigger("tr_ins", TriggerTiming.AFTER, TriggerEvent.INSERT, T, TriggerScope.ROW, null, + "BEGIN INSERT INTO log VALUES ('again', NEW.a); END", true) + ";"); + assertThat(twice.failed()).as("no OR REPLACE: a second one of the name fails").isTrue(); + assertThat(twice.err()).contains("already exists"); + } +} diff --git a/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteUpsertTest.java b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteUpsertTest.java new file mode 100644 index 00000000..603d435b --- /dev/null +++ b/dialect/db/sqlite/src/test/java/org/eclipse/daanse/sql/dialect/db/sqlite/container/SqliteUpsertTest.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.sqlite.container; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator.UpsertSpec; +import org.eclipse.daanse.sql.dialect.db.sqlite.SqliteDialect; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** + * SQLite has the upsert, {@code INSERT … ON CONFLICT (key) DO UPDATE | DO NOTHING}, from 3.24.0. SQLite is embedded: + * the CLI of each version runs the statements in Docker, and the dialect is built for the version the CLI reports. + * From 3.24 on the upsert it writes must insert a row of a new key, update in place the listed columns of a row of a + * key there, its other columns and its rowid kept, of a key of two columns too; and with no column to update leave the + * row there as it is. Before, on 3.22, it writes none, for the server refuses it; INSERT OR REPLACE, which it has, + * would lose the columns not listed. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class SqliteUpsertTest { + + private static final TableReference ITEMS = new TableReference(Optional.empty(), "items", + TableReference.TYPE_TABLE); + private static final TableReference STOCK = new TableReference(Optional.empty(), "stock", + TableReference.TYPE_TABLE); + + private static final String SETUP = """ + CREATE TABLE items(id INTEGER PRIMARY KEY, name TEXT, qty INTEGER, note TEXT DEFAULT 'none'); + INSERT INTO items VALUES (1, 'a', 1, 'kept'); + CREATE TABLE stock(store TEXT, item INTEGER, qty INTEGER, PRIMARY KEY (store, item)); + INSERT INTO stock VALUES ('x', 1, 5); + """; + + private static final UpsertSpec UPDATE = new UpsertSpec(ITEMS, List.of("id"), List.of("id", "name", "qty"), + List.of("name", "qty")); + private static final UpsertSpec IGNORE = new UpsertSpec(ITEMS, List.of("id"), List.of("id", "name", "qty"), + List.of()); + private static final UpsertSpec COMPOSITE = new UpsertSpec(STOCK, List.of("store", "item"), + List.of("store", "item", "qty"), List.of("qty")); + + @ParameterizedTest(name = "sqlite {0} -> upsert {1}") + @CsvSource({ "3.22.0, false", "3.25.3, true", "3.32.1, true", "3.35.5, true", "3.46.1, true", "3.51.0, true" }) + void upsert(String version, boolean expected) { + SqliteDialect d = SqliteCli.dialect(version); + MergeGenerator g = d.mergeGenerator(); + assertThat(g.supportsMerge()).as("supportsMerge").isEqualTo(expected); + + if (!expected) { + assertThat(g.upsert(UPDATE, List.of("1", "'b'", "2"))).as("no upsert before 3.24").isEmpty(); + SqliteCli.Result refused = SqliteCli.run(version, SETUP + + "INSERT INTO items (id, name, qty) VALUES (1, 'b', 2) ON CONFLICT (id) DO NOTHING;"); + assertThat(refused.failed()).as("the server refuses ON CONFLICT after INSERT before 3.24").isTrue(); + assertThat(refused.err()).contains("syntax error"); + SqliteCli.Result replace = SqliteCli.run(version, SETUP + + "INSERT OR REPLACE INTO items (id, name, qty) VALUES (1, 'b', 2);" + + " SELECT id || '|' || name || '|' || qty || '|' || note FROM items;"); + assertThat(replace.out()).as("INSERT OR REPLACE is no stand-in: the note not listed is lost") + .containsExactly("1|b|2|none"); + return; + } + + assertThat(g.upsert(IGNORE, List.of("1", "'b'", "2")).orElseThrow()).as("insert-or-ignore") + .endsWith(" DO NOTHING"); + String sql = SETUP + + g.upsert(UPDATE, List.of("2", "'n'", "7")).orElseThrow() + ";\n" + + g.upsert(UPDATE, List.of("1", "'b'", "2")).orElseThrow() + ";\n" + + g.upsert(IGNORE, List.of("2", "'ignored'", "99")).orElseThrow() + ";\n" + + g.upsert(IGNORE, List.of("3", "'c'", "3")).orElseThrow() + ";\n" + + g.upsert(COMPOSITE, List.of("'x'", "1", "8")).orElseThrow() + ";\n" + + g.upsert(COMPOSITE, List.of("'y'", "1", "4")).orElseThrow() + ";\n" + + "SELECT 'items|' || group_concat(r, ',') FROM (SELECT rowid || ':' || id || ':' || name || ':' || qty" + + " || ':' || note AS r FROM items ORDER BY id);\n" + + "SELECT 'stock|' || group_concat(r, ',') FROM (SELECT store || ':' || item || ':' || qty AS r" + + " FROM stock ORDER BY store, item);\n"; + SqliteCli.Result r = SqliteCli.run(version, sql); + assertThat(r.failed()).as(r.err() + " in " + sql).isFalse(); + assertThat(r.out()).containsExactly( + // 1 updated in place, its note and rowid kept; 2 inserted, then left by DO NOTHING; 3 inserted + "items|1:1:b:2:kept,2:2:n:7:none,3:3:c:3:none", + // a key of two columns: x/1 updated, y/1 inserted + "stock|x:1:8,y:1:4"); + } +} diff --git a/jdbc/importer/csv/src/main/java/org/eclipse/daanse/sql/jdbc/importer/csv/impl/CsvDataImporter.java b/jdbc/importer/csv/src/main/java/org/eclipse/daanse/sql/jdbc/importer/csv/impl/CsvDataImporter.java index 23a2ca30..56a5a42f 100644 --- a/jdbc/importer/csv/src/main/java/org/eclipse/daanse/sql/jdbc/importer/csv/impl/CsvDataImporter.java +++ b/jdbc/importer/csv/src/main/java/org/eclipse/daanse/sql/jdbc/importer/csv/impl/CsvDataImporter.java @@ -287,11 +287,19 @@ public void createTable(Connection connection, List headersTyp } + /** + * The schema of a file in a directory below the base: the directory's name. Where the database has no schemas + * (SQLite), none, and the table goes into the connection's own. + */ private Optional getSchemaFromPath(Path path) { Path parent = path.getParent(); if (basePath.equals(parent)) { return Optional.empty(); } + if (dialect != null && !dialect.ddlGenerator().supportsSchemas()) { + LOGGER.debug("No schemas in {}: {} goes into the default one", dialect.name(), path); + return Optional.empty(); + } String fileName = parent.getFileName().toString(); return Optional.of(new SchemaReference(fileName)); }