Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,52 @@ default String dropView(TableReference view, boolean ifExists) {
return sb.toString();
}

// -------------------- DDL — materialized views --------------------

/**
* {@code CREATE MATERIALIZED VIEW [IF NOT EXISTS] schema.view AS select}: a view whose rows the
* database computes when the view is created and keeps until it is refreshed. With
* {@code ifNotExists} an existing view is no error where the dialect can say so; elsewhere the
* statement fails on it.
*
* @return empty where the database has no materialized views
* ({@link #supportsMaterializedViews()} is false)
*/
default Optional<String> createMaterializedView(TableReference view, String selectSql, boolean ifNotExists) {
if (!supportsMaterializedViews()) {
return Optional.empty();
}
if (selectSql == null || selectSql.isBlank()) {
throw new IllegalArgumentException("selectSql must not be blank for CREATE MATERIALIZED VIEW");
}
return Optional.of("CREATE MATERIALIZED VIEW " + (ifNotExists ? "IF NOT EXISTS " : "") + qualified(view)
+ " AS " + selectSql);
}

/**
* {@code DROP MATERIALIZED VIEW [IF EXISTS] schema.view}. With {@code ifExists} a missing view is
* no error where the dialect can say so; elsewhere the statement fails on it.
*
* @return empty where the database has no materialized views
* ({@link #supportsMaterializedViews()} is false)
*/
default Optional<String> dropMaterializedView(TableReference view, boolean ifExists) {
if (!supportsMaterializedViews()) {
return Optional.empty();
}
return Optional.of("DROP MATERIALIZED VIEW " + (ifExists ? "IF EXISTS " : "") + qualified(view));
}

/**
* @return true if {@code createMaterializedView} / {@code dropMaterializedView} render
* statements. An indexed view (SQL Server) is a view with an index, and a ClickHouse
* materialized view feeds a table from the rows inserted into another; neither keeps the
* result of its query, so neither is one.
*/
default boolean supportsMaterializedViews() {
return false;
}

// -------------------- DDL — sequences --------------------

record SequenceDefinition(String schemaName, String name, Long startWith, Long incrementBy, Long minValue,
Expand Down
12 changes: 12 additions & 0 deletions dialect/db/consistency-test/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,18 @@
<version>${revision}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.daanse</groupId>
<artifactId>org.eclipse.daanse.sql.dialect.db.hive</artifactId>
<version>${revision}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.daanse</groupId>
<artifactId>org.eclipse.daanse.sql.dialect.db.impala</artifactId>
<version>${revision}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
* 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.Optional;
import java.util.stream.Stream;

import org.eclipse.daanse.sql.dialect.api.Dialect;
import org.eclipse.daanse.sql.dialect.api.DialectInitData;
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.eclipse.daanse.sql.model.schema.SchemaReference;
import org.eclipse.daanse.sql.model.schema.TableReference;
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;

/**
* What each dialect writes to create and drop the materialized view {@code s.mv}. A dialect whose
* database keeps no query result as a view writes nothing and says so by
* {@link DdlGenerator#supportsMaterializedViews()}.
*/
class MaterializedViewStatementsTest {

private static final TableReference VIEW = new TableReference(
Optional.of(new SchemaReference(Optional.empty(), "s")), "mv", TableReference.TYPE_VIEW);

private static final String QUERY = "SELECT a FROM t";

/** The statements expected of a dialect; all null where it has no materialized views. */
record Expected(String create, String createIfNotExists, String drop, String dropIfExists) {

static Expected none() {
return new Expected(null, null, null, null);
}
}

static Stream<Arguments> dialects() {
return Stream.of(
of("postgresql", new PostgreSqlDialect(), new Expected(
"CREATE MATERIALIZED VIEW \"s\".\"mv\" AS " + QUERY,
"CREATE MATERIALIZED VIEW IF NOT EXISTS \"s\".\"mv\" AS " + QUERY,
"DROP MATERIALIZED VIEW \"s\".\"mv\"", "DROP MATERIALIZED VIEW IF EXISTS \"s\".\"mv\"")),
of("oracle, no version", new OracleDialect(), new Expected(
"CREATE MATERIALIZED VIEW \"s\".\"mv\" AS " + QUERY,
"CREATE MATERIALIZED VIEW \"s\".\"mv\" AS " + QUERY,
"DROP MATERIALIZED VIEW \"s\".\"mv\"", "DROP MATERIALIZED VIEW \"s\".\"mv\"")),
of("oracle 23", new OracleDialect(version(23, 0)), new Expected(
"CREATE MATERIALIZED VIEW \"s\".\"mv\" AS " + QUERY,
"CREATE MATERIALIZED VIEW IF NOT EXISTS \"s\".\"mv\" AS " + QUERY,
"DROP MATERIALIZED VIEW \"s\".\"mv\"", "DROP MATERIALIZED VIEW IF EXISTS \"s\".\"mv\"")),
of("mssql", new MicrosoftSqlServerDialect(), Expected.none()),
of("mysql", new MySqlDialect(), Expected.none()),
of("mariadb", new MariaDBDialect(), Expected.none()),
of("h2", new H2Dialect(), Expected.none()),
of("clickhouse", new ClickHouseDialect(), Expected.none()),
of("duckdb", new DuckDbDialect(), Expected.none()),
of("sqlite", new SqliteDialect(), Expected.none()),
of("derby", new DerbyDialect(), Expected.none()),
of("hive", new HiveDialect(), Expected.none()),
of("impala", new ImpalaDialect(), Expected.none()),
of("ansi", new AnsiDialect(), Expected.none()));
}

@ParameterizedTest(name = "{0}")
@MethodSource("dialects")
void createAndDropAMaterializedView(Dialect dialect, Expected expected) {
DdlGenerator ddl = dialect.ddlGenerator();

assertThat(ddl.supportsMaterializedViews()).as("supportsMaterializedViews")
.isEqualTo(expected.create() != null);
assertThat(ddl.createMaterializedView(VIEW, QUERY, false)).isEqualTo(Optional.ofNullable(expected.create()));
assertThat(ddl.createMaterializedView(VIEW, QUERY, true))
.isEqualTo(Optional.ofNullable(expected.createIfNotExists()));
assertThat(ddl.dropMaterializedView(VIEW, false)).isEqualTo(Optional.ofNullable(expected.drop()));
assertThat(ddl.dropMaterializedView(VIEW, true)).isEqualTo(Optional.ofNullable(expected.dropIfExists()));
}

private static Arguments of(String name, Dialect dialect, Expected expected) {
return Arguments.of(Named.of(name, dialect), expected);
}

private static DialectInitData version(int major, int minor) {
return DialectInitData.ansiDefaults().withVersion(major, minor);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -877,4 +877,24 @@ public Optional<String> dropUser(String userName, boolean ifExists) {
return Optional.of("DROP USER " + (ifExists && dialectVersion.atLeast(23, 0) ? "IF EXISTS " : "")
+ quoteIdentifier(userName));
}

/**
* Oracle builds a materialized view's rows when it is created and refreshes them on demand, its
* defaults. {@code IF [NOT] EXISTS} from Oracle 23; before, and for an unknown version, it is left
* out.
*/
@Override
public boolean supportsMaterializedViews() {
return true;
}

@Override
public Optional<String> createMaterializedView(TableReference view, String selectSql, boolean ifNotExists) {
return super.createMaterializedView(view, selectSql, ifNotExists && dialectVersion.atLeast(23, 0));
}

@Override
public Optional<String> dropMaterializedView(TableReference view, boolean ifExists) {
return super.dropMaterializedView(view, ifExists && dialectVersion.atLeast(23, 0));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import static org.assertj.core.api.Assertions.assertThat;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertExecuteUpdateAffected;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertFirstIntEquals;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertFirstStringEquals;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertSelectIdRowCountAndFirst;
import static org.eclipse.daanse.sql.dialect.db.testsupport.RoundTripAssertions.assertSelectIdRowCountAndFirstWithParams;
Expand Down Expand Up @@ -135,4 +136,39 @@ void user_is_created_given_a_role_and_dropped() throws SQLException {
DatabasePrincipal.KIND_USER, users, "rt_user", "rt_role");
}
}

/**
* A materialized view the dialect writes holds the rows of its query and is read back as a
* materialized view with its query; dropped, it is gone. Before Oracle 23 the dialect has no
* {@code IF [NOT] EXISTS}, and the statements with and without it are alike.
*/
@Test
void materialized_view_is_created_read_back_and_dropped() throws SQLException {
String schema = CONTAINER.getUsername().toUpperCase();
TableReference view = new TableReference(Optional.of(new SchemaReference(Optional.empty(), schema)),
"MV_USERS", TableReference.TYPE_VIEW);
String query = "SELECT id, name FROM \"" + schema + "\".\"USERS\" WHERE id <= 5";
OracleMetadataProvider provider = new OracleMetadataProvider();
String create = dialect.ddlGenerator().createMaterializedView(view, query, false).orElseThrow();
String createIfNotExists = dialect.ddlGenerator().createMaterializedView(view, query, true).orElseThrow();
String drop = dialect.ddlGenerator().dropMaterializedView(view, false).orElseThrow();
String dropIfExists = dialect.ddlGenerator().dropMaterializedView(view, true).orElseThrow();
try (Statement s = conn.createStatement()) {
s.execute(create);
if (!createIfNotExists.equals(create)) {
s.execute(createIfNotExists);
}
assertFirstIntEquals(conn, "SELECT COUNT(*) FROM \"" + schema + "\".\"MV_USERS\"", 5);
assertThat(provider.getAllMaterializedViews(conn, null, schema))
.filteredOn(mv -> mv.view().name().equals("MV_USERS")).singleElement()
.satisfies(mv -> assertThat(mv.viewBody().orElseThrow()).containsIgnoringCase("users"));

s.execute(drop);
if (!dropIfExists.equals(drop)) {
s.execute(dropIfExists);
}
assertThat(provider.getAllMaterializedViews(conn, null, schema))
.noneMatch(mv -> mv.view().name().equals("MV_USERS"));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -556,4 +556,10 @@ public Optional<String> createUser(String userName, boolean ifNotExists) {
return Optional.of("DO " + quote + " BEGIN " + create + "; EXCEPTION WHEN duplicate_object THEN NULL; END "
+ quote);
}

/** PostgreSQL keeps a materialized view's rows from its creation on, until it is refreshed. */
@Override
public boolean supportsMaterializedViews() {
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,29 @@ void user_is_created_given_a_role_and_dropped() throws SQLException {
UserRoundTrip.assertUserRoundTrip(conn, dialect.ddlGenerator(), new PostgreSqlMetadataProvider(),
DatabasePrincipal.KIND_USER, USERS, "rt_user", "rt_role");
}

/**
* A materialized view the dialect writes holds the rows of its query and is read back as a
* materialized view with its query; dropped, it is gone.
*/
@Test
void materialized_view_is_created_read_back_and_dropped() throws SQLException {
TableReference view = new TableReference(Optional.of(new SchemaReference(Optional.empty(), "public")),
"mv_users", TableReference.TYPE_VIEW);
String query = "SELECT id, name FROM \"public\".\"users\" WHERE id <= 5";
PostgreSqlMetadataProvider provider = new PostgreSqlMetadataProvider();
try (Statement s = conn.createStatement()) {
s.execute(dialect.ddlGenerator().createMaterializedView(view, query, false).orElseThrow());
s.execute(dialect.ddlGenerator().createMaterializedView(view, query, true).orElseThrow());
assertFirstIntEquals(conn, "SELECT COUNT(*) FROM \"public\".\"mv_users\"", 5);
assertThat(provider.getAllMaterializedViews(conn, null, "public"))
.filteredOn(mv -> mv.view().name().equals("mv_users")).singleElement()
.satisfies(mv -> assertThat(mv.viewBody().orElseThrow()).containsIgnoringCase("users"));

s.execute(dialect.ddlGenerator().dropMaterializedView(view, false).orElseThrow());
s.execute(dialect.ddlGenerator().dropMaterializedView(view, true).orElseThrow());
assertThat(provider.getAllMaterializedViews(conn, null, "public"))
.noneMatch(mv -> mv.view().name().equals("mv_users"));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
* sales.child_indexed
* PK (id), INDEX ix_child_indexed (orders_id), then FK fk_child_indexed (orders_id)
* sales.v_orders a view on orders
* sales.mv_orders a materialized view on orders, where the database has them
* sales.seq_unlimited, sales.seq_limited (1 to 999)
* sales.f_total two overloads, where a schema may hold several routines of a name
* sales.f_answer a function without parameters, with a comment, where the provider reads it
Expand Down Expand Up @@ -165,6 +166,14 @@ protected boolean keepsConstraintNames() {
return true;
}

/**
* The statements that create the materialized view {@code mv_orders} on the orders in their
* schema; none where the database has no materialized views.
*/
protected List<String> createMaterializedView() {
return List.of();
}

/** Whether the database makes an index of its own for a foreign key whose columns have none. */
protected boolean makesForeignKeyIndexes() {
return false;
Expand Down Expand Up @@ -273,6 +282,7 @@ private List<String> fixture() {
sql.add("CREATE UNIQUE INDEX " + indexName(sales, "ux_orders_product_day") + " ON " + sales
+ ".orders (product_id, ordered_on)");
sql.add("CREATE VIEW " + sales + ".v_orders AS SELECT id, qty FROM " + sales + ".orders");
sql.addAll(createMaterializedView());
sql.addAll(createChildren());
if (sequences()) {
sql.add(createSequence(sales + ".seq_unlimited", false));
Expand Down Expand Up @@ -419,6 +429,17 @@ void viewWithItsQuery() throws SQLException {
.containsIgnoringCase("orders"));
}

/** A materialized view is reported as one, with its query, where the database has them. */
@Test
void materializedViewWithItsQuery() throws SQLException {
assumeFalse(createMaterializedView().isEmpty(), "the database has no materialized views");

assertThat(provider.getAllMaterializedViews(connection, null, sales()))
.filteredOn(mv -> is(mv.view(), sales(), "mv_orders")).singleElement()
.satisfies(mv -> assertThat(mv.viewBody().or(mv::fullDefinition).orElseThrow())
.containsIgnoringCase("orders"));
}

@Test
void sequencesWithAndWithoutLimits() throws SQLException {
assumeTrue(sequences(), "the database has no sequences");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ protected Connection fixtureConnection() {
return system;
}

/** SYSTEM creates it; its owner needs the rights to own one. */
@Override
protected List<String> createMaterializedView() {
return List.of("GRANT CREATE MATERIALIZED VIEW, CREATE TABLE TO " + sales(),
"CREATE MATERIALIZED VIEW " + sales() + ".mv_orders AS SELECT id, qty FROM " + sales() + ".orders");
}

@Override
protected MetadataProvider provider() {
return new OracleMetadataProvider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ protected Connection open() throws Exception {
return DriverManager.getConnection(container.getJdbcUrl(), container.getUsername(), container.getPassword());
}

@Override
protected List<String> createMaterializedView() {
return List.of("CREATE MATERIALIZED VIEW sales.mv_orders AS SELECT id, qty FROM sales.orders");
}

@Override
protected MetadataProvider provider() {
return new PostgreSqlMetadataProvider();
Expand Down
Loading