Add compatible DataGrid, filter editors, themes and JDBC example
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
# Optional JDBC DataGrid source
|
||||
|
||||
`data-grid-jdbc` depends only on the neutral `data-grid` contracts and the JDK JDBC API. It adds no driver or JavaFX dependency. The application supplies a DataSource, executor, approved simple table/key/column identifiers and a row mapper. The stable key must be unique and non-null. The initial dialect is H2, qualified with **2.5.252**; other databases are not claimed compatible.
|
||||
|
||||
```java
|
||||
var source = new JdbcGridSource<Long, Product>(
|
||||
dataSource, applicationExecutor, JdbcDialect.h2(), "products", "id",
|
||||
List.of(JdbcColumn.text("name", "name", "name_key"),
|
||||
JdbcColumn.decimal("price", "price", 12, 2)),
|
||||
rs -> new GridRow<>(rs.getLong("id"), mapProduct(rs)), 250, 10);
|
||||
```
|
||||
|
||||
The projection includes the stable key and all mapped physical columns. Identifiers accept only simple ASCII names, supplied by developers; SQL expressions, arbitrary joins and user-provided identifiers are intentionally unavailable. Filter operands and paging values use bound parameters. Custom conditions without a translator are explicitly rejected, never dropped. Date/time and boolean mappings are outside this initial adapter.
|
||||
|
||||
## Matching and consistency
|
||||
|
||||
Text mappings require a companion key column maintained with Java `Locale.ROOT` lowercasing whenever original values change. Store original text unchanged; checklist equality uses it. The adapter does not repair inconsistent application data or use SQL LOWER. Text sorting uses comparison keys; nulls sort last in either direction, followed by the stable key ascending. The H2 dialect rejects configured linguistic collation; default OFF collation is qualified against Java String comparison, including supplementary Unicode and combining marks. LIKE escapes `%`, `_` and the escape character `!`; all operands remain literal.
|
||||
|
||||
Integer operands must fit a signed long exactly. Decimal mappings enforce precision and scale with no rounding; numerically equal values with extra trailing zeros remain valid. The application must use matching SQL types (the example uses BIGINT and DECIMAL(12,2)). Missing/present, exact checklist membership and AND-combined filters are supported. The translator validates both condition type and column type before borrowing a connection.
|
||||
|
||||
Each request borrows one idle auto-commit connection, checks H2/collation, starts H2's vendor SNAPSHOT isolation (6), counts and fetches in the same transaction, commits before returning, and restores isolation/auto-commit before close. A non-auto-commit borrowed connection is rejected rather than committing an application transaction. The mapper must not mutate connection settings or execute writes. The application owns transaction cleanliness and pool reset policy. Close failures fail the request; cleanup errors are retained as suppressed exceptions.
|
||||
|
||||
All-mode checks its warning threshold after counting and before selecting rows. If approval is required, it rolls back and releases all borrowed resources before completing with `AllRowsConfirmationRequired`. Approval starts a fresh snapshot and recounts: it acknowledges an unpaged load, not a fixed maximum number of rows. The existing coordinator handles query-scoped approval and stale completions. Never save approval in a setup.
|
||||
|
||||
Every prepared query has the configured JDBC timeout. Cancellation attempts `Statement.cancel`, marks the request cancelled and stops mapping; cancellation is best effort and does not interrupt embedded driver threads. A cancelled future can complete before worker cleanup finishes, so application shutdown must drain the executor before disposing the DataSource. Closing a DataGrid does not own either resource.
|
||||
|
||||
The example explicitly supplies current-page checklist candidates; the adapter does not pretend a page is a complete source-wide candidate set. Applications needing source-wide candidates supply their own `FilterCandidates.Provider`, independently of SQL condition execution.
|
||||
|
||||
See [the complete runnable example](../fx-example/docs/product-grid.md) for fixture parity, fault controls, saved setups and limitations.
|
||||
@@ -0,0 +1,5 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0-SNAPSHOT</version></parent>
|
||||
<artifactId>data-grid-jdbc</artifactId><description>Optional mapped JDBC grid source</description>
|
||||
<dependencies><dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
|
||||
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.5.252</version><scope>test</scope></dependency></dependencies></project>
|
||||
@@ -0,0 +1,65 @@
|
||||
package de.neitzel.grid.jdbc;
|
||||
|
||||
import de.neitzel.grid.*;
|
||||
|
||||
import java.math.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Approved physical identifier and scalar domain. Text keys are maintained by the application. */
|
||||
public record JdbcColumn(
|
||||
String id, String sqlName, Kind kind, String comparisonKey, int precision, int scale) {
|
||||
public enum Kind {
|
||||
TEXT,
|
||||
INTEGER,
|
||||
DECIMAL
|
||||
}
|
||||
|
||||
public JdbcColumn {
|
||||
if (id == null || id.isBlank())
|
||||
throw new IllegalArgumentException("Missing column identity");
|
||||
identifier(sqlName);
|
||||
Objects.requireNonNull(kind);
|
||||
if (kind == Kind.TEXT) identifier(comparisonKey);
|
||||
else if (comparisonKey != null)
|
||||
throw new IllegalArgumentException("Only text has comparison keys");
|
||||
if (kind == Kind.DECIMAL && (precision < 1 || scale < 0 || scale > precision))
|
||||
throw new IllegalArgumentException("Invalid decimal domain");
|
||||
}
|
||||
|
||||
public static JdbcColumn text(String id, String column, String key) {
|
||||
return new JdbcColumn(id, column, Kind.TEXT, key, 0, 0);
|
||||
}
|
||||
|
||||
public static JdbcColumn integer(String id, String column) {
|
||||
return new JdbcColumn(id, column, Kind.INTEGER, null, 0, 0);
|
||||
}
|
||||
|
||||
public static JdbcColumn decimal(String id, String column, int precision, int scale) {
|
||||
return new JdbcColumn(id, column, Kind.DECIMAL, null, precision, scale);
|
||||
}
|
||||
|
||||
static String identifier(String name) {
|
||||
if (name == null || !name.matches("[A-Za-z_][A-Za-z0-9_]*"))
|
||||
throw new IllegalArgumentException("Expected an approved simple SQL identifier");
|
||||
return name;
|
||||
}
|
||||
|
||||
void number(BigDecimal value) {
|
||||
if (kind == Kind.INTEGER) value.longValueExact();
|
||||
else if (kind == Kind.DECIMAL) {
|
||||
if (value.setScale(scale, RoundingMode.UNNECESSARY).precision() > precision)
|
||||
throw new IllegalArgumentException("Decimal exceeds " + precision + "," + scale);
|
||||
} else
|
||||
throw new IllegalArgumentException("Numeric condition requires numeric column " + id);
|
||||
}
|
||||
|
||||
Object value(FilterValue value) {
|
||||
if (kind == Kind.TEXT && value instanceof FilterValue.Text t) return t.value();
|
||||
if (kind == Kind.INTEGER && value instanceof FilterValue.IntegerValue n) return n.value();
|
||||
if (kind == Kind.DECIMAL && value instanceof FilterValue.Decimal n) {
|
||||
number(n.value());
|
||||
return n.value();
|
||||
}
|
||||
throw new IllegalArgumentException("Checklist type does not match " + id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package de.neitzel.grid.jdbc;
|
||||
|
||||
import java.sql.*;
|
||||
|
||||
/** Explicit dialect boundary; only H2 is qualified by this delivery. */
|
||||
public interface JdbcDialect {
|
||||
String executionId();
|
||||
|
||||
void beginSnapshot(Connection connection, int timeoutSeconds) throws SQLException;
|
||||
|
||||
String paging();
|
||||
|
||||
private static ResultSet execute(PreparedStatement statement, int timeoutSeconds)
|
||||
throws SQLException {
|
||||
statement.setQueryTimeout(timeoutSeconds);
|
||||
return statement.executeQuery();
|
||||
}
|
||||
|
||||
/** H2 default binary/Java-string collation and its vendor snapshot isolation level. */
|
||||
static JdbcDialect h2() {
|
||||
return new JdbcDialect() {
|
||||
public String executionId() {
|
||||
return "jdbc-h2";
|
||||
}
|
||||
|
||||
public void beginSnapshot(Connection connection, int timeoutSeconds)
|
||||
throws SQLException {
|
||||
if (!connection.getMetaData().getDatabaseProductName().equals("H2"))
|
||||
throw new SQLException("H2 dialect requires H2");
|
||||
try (var s =
|
||||
connection.prepareStatement(
|
||||
"SELECT SETTING_VALUE FROM INFORMATION_SCHEMA.SETTINGS"
|
||||
+ " WHERE SETTING_NAME = 'COLLATION'");
|
||||
var rs = execute(s, timeoutSeconds)) {
|
||||
if (rs.next() && !rs.getString(1).equals("OFF"))
|
||||
throw new SQLException("Only H2 OFF collation is qualified");
|
||||
}
|
||||
connection.setTransactionIsolation(
|
||||
6); // H2 TRANSACTION_SNAPSHOT, not JDBC REPEATABLE_READ.
|
||||
connection.setAutoCommit(false);
|
||||
}
|
||||
|
||||
public String paging() {
|
||||
return " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package de.neitzel.grid.jdbc;
|
||||
|
||||
import de.neitzel.grid.*;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
/** Mapped, parameterized queries. The application owns the DataSource and executor. */
|
||||
public final class JdbcGridSource<K, T> implements GridSource<K, T> {
|
||||
@FunctionalInterface
|
||||
public interface RowMapper<K, T> {
|
||||
GridRow<K, T> read(ResultSet result) throws SQLException;
|
||||
}
|
||||
|
||||
private final DataSource dataSource;
|
||||
private final Executor executor;
|
||||
private final JdbcDialect dialect;
|
||||
private final String table, key, projection;
|
||||
private final Map<String, JdbcColumn> columns;
|
||||
private final RowMapper<K, T> mapper;
|
||||
private final int timeoutSeconds;
|
||||
private final SourceCapabilities capabilities;
|
||||
|
||||
public JdbcGridSource(
|
||||
DataSource dataSource,
|
||||
Executor executor,
|
||||
JdbcDialect dialect,
|
||||
String table,
|
||||
String key,
|
||||
List<JdbcColumn> columns,
|
||||
RowMapper<K, T> mapper,
|
||||
int maximumPageSize,
|
||||
int timeoutSeconds) {
|
||||
this.dataSource = Objects.requireNonNull(dataSource);
|
||||
this.executor = Objects.requireNonNull(executor);
|
||||
this.dialect = Objects.requireNonNull(dialect);
|
||||
this.table = JdbcColumn.identifier(table);
|
||||
this.key = JdbcColumn.identifier(key);
|
||||
this.mapper = Objects.requireNonNull(mapper);
|
||||
if (timeoutSeconds < 1)
|
||||
throw new IllegalArgumentException("A positive query timeout is required");
|
||||
this.timeoutSeconds = timeoutSeconds;
|
||||
capabilities = new SourceCapabilities(true, true, maximumPageSize);
|
||||
var mapped = new LinkedHashMap<String, JdbcColumn>();
|
||||
var selected = new LinkedHashSet<String>();
|
||||
selected.add(key);
|
||||
for (var c : columns) {
|
||||
if (mapped.put(c.id(), c) != null)
|
||||
throw new IllegalArgumentException("Duplicate column");
|
||||
selected.add(c.sqlName());
|
||||
}
|
||||
this.columns = Map.copyOf(mapped);
|
||||
projection = String.join(",", selected);
|
||||
}
|
||||
|
||||
public SourceCapabilities capabilities() {
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
public String filterExecutionId() {
|
||||
return dialect.executionId();
|
||||
}
|
||||
|
||||
private JdbcColumn column(String id) {
|
||||
var c = columns.get(id);
|
||||
if (c == null) throw new IllegalArgumentException("Unknown column: " + id);
|
||||
return c;
|
||||
}
|
||||
|
||||
public void validateFilter(FilterCondition filter) {
|
||||
compile(filter, new ArrayList<>());
|
||||
}
|
||||
|
||||
public QueryExecution<K, T> query(GridQuery query) {
|
||||
return query(query, QueryOptions.defaults());
|
||||
}
|
||||
|
||||
public QueryExecution<K, T> query(GridQuery query, QueryOptions options) {
|
||||
Objects.requireNonNull(query);
|
||||
Objects.requireNonNull(options);
|
||||
var execution = new Execution();
|
||||
try {
|
||||
capabilities.validate(query.page());
|
||||
var parameters = new ArrayList<Object>();
|
||||
String where = where(query.filters(), parameters);
|
||||
var order = new ArrayList<String>();
|
||||
for (var sort : query.sort()) {
|
||||
var c = column(sort.columnId());
|
||||
order.add(
|
||||
(c.kind() == JdbcColumn.Kind.TEXT ? c.comparisonKey() : c.sqlName())
|
||||
+ (sort.direction() == SortKey.Direction.ASCENDING
|
||||
? " ASC"
|
||||
: " DESC")
|
||||
+ " NULLS LAST");
|
||||
}
|
||||
order.add(key + " ASC");
|
||||
String rows =
|
||||
"SELECT "
|
||||
+ projection
|
||||
+ " FROM "
|
||||
+ table
|
||||
+ where
|
||||
+ " ORDER BY "
|
||||
+ String.join(",", order)
|
||||
+ (query.page() instanceof PageRequest.Paged ? dialect.paging() : "");
|
||||
executor.execute(
|
||||
() -> {
|
||||
try {
|
||||
execution.check();
|
||||
execution.result.complete(
|
||||
execute(execution, query, options, where, rows, parameters));
|
||||
} catch (Exception failure) {
|
||||
execution.result.completeExceptionally(failure);
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException failure) {
|
||||
execution.result.completeExceptionally(failure);
|
||||
}
|
||||
return execution;
|
||||
}
|
||||
|
||||
private PageResult<K, T> execute(
|
||||
Execution execution,
|
||||
GridQuery query,
|
||||
QueryOptions options,
|
||||
String where,
|
||||
String sql,
|
||||
List<Object> parameters)
|
||||
throws SQLException {
|
||||
try (var connection = dataSource.getConnection()) {
|
||||
boolean auto = connection.getAutoCommit();
|
||||
int isolation = connection.getTransactionIsolation();
|
||||
if (!auto)
|
||||
throw new SQLException("Borrowed connection must be idle with autoCommit=true");
|
||||
Throwable primary = null;
|
||||
try {
|
||||
dialect.beginSnapshot(connection, timeoutSeconds);
|
||||
execution.check();
|
||||
long count;
|
||||
try (var statement =
|
||||
execution.prepare(
|
||||
connection,
|
||||
"SELECT COUNT(*) FROM " + table + where,
|
||||
parameters);
|
||||
var rs = statement.executeQuery()) {
|
||||
rs.next();
|
||||
count = rs.getLong(1);
|
||||
}
|
||||
execution.active.set(null);
|
||||
execution.check();
|
||||
if (query.page() instanceof PageRequest.All
|
||||
&& count > options.allWarningThreshold()
|
||||
&& !options.allApproved()) throw new AllRowsConfirmationRequired(count);
|
||||
var values = new ArrayList<>(parameters);
|
||||
if (query.page() instanceof PageRequest.Paged p) {
|
||||
values.add(p.offset());
|
||||
values.add(p.pageSize());
|
||||
}
|
||||
var result = new ArrayList<GridRow<K, T>>();
|
||||
try (var statement = execution.prepare(connection, sql, values);
|
||||
var rs = statement.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
execution.check();
|
||||
result.add(mapper.read(rs));
|
||||
}
|
||||
}
|
||||
execution.active.set(null);
|
||||
execution.check();
|
||||
var page =
|
||||
new PageResult<>(
|
||||
query.page(),
|
||||
result,
|
||||
OptionalLong.of(count),
|
||||
query.page() instanceof PageRequest.Paged p
|
||||
&& count - p.offset() > p.pageSize());
|
||||
connection.commit();
|
||||
return page;
|
||||
} catch (SQLException | RuntimeException | Error failure) {
|
||||
primary = failure;
|
||||
throw failure;
|
||||
} finally {
|
||||
execution.active.set(null);
|
||||
SQLException cleanup = null;
|
||||
try {
|
||||
connection.rollback();
|
||||
} catch (SQLException ex) {
|
||||
cleanup = ex;
|
||||
}
|
||||
try {
|
||||
connection.setTransactionIsolation(isolation);
|
||||
} catch (SQLException ex) {
|
||||
if (cleanup == null) cleanup = ex;
|
||||
else cleanup.addSuppressed(ex);
|
||||
}
|
||||
try {
|
||||
connection.setAutoCommit(auto);
|
||||
} catch (SQLException ex) {
|
||||
if (cleanup == null) cleanup = ex;
|
||||
else cleanup.addSuppressed(ex);
|
||||
}
|
||||
if (cleanup != null) {
|
||||
if (primary != null) primary.addSuppressed(cleanup);
|
||||
else throw cleanup;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String where(List<FilterCondition> filters, List<Object> args) {
|
||||
if (filters.isEmpty()) return "";
|
||||
return " WHERE "
|
||||
+ String.join(
|
||||
" AND ", filters.stream().map(f -> "(" + compile(f, args) + ")").toList());
|
||||
}
|
||||
|
||||
private String compile(FilterCondition f, List<Object> args) {
|
||||
var c = column(f.columnId());
|
||||
String field = c.sqlName();
|
||||
if (f instanceof MissingFilter m)
|
||||
return field + (m.missing() ? " IS NULL" : " IS NOT NULL");
|
||||
if (f instanceof TextFilter t) {
|
||||
if (c.kind() != JdbcColumn.Kind.TEXT)
|
||||
throw new IllegalArgumentException("Text filter requires text column");
|
||||
field = t.caseSensitive() ? field : c.comparisonKey();
|
||||
String operand = t.caseSensitive() ? t.operand() : t.operand().toLowerCase(Locale.ROOT);
|
||||
if (t.operator() == TextFilter.Operator.EQUALS) {
|
||||
args.add(operand);
|
||||
return field + " = ?";
|
||||
}
|
||||
operand = operand.replace("!", "!!").replace("%", "!%").replace("_", "!_");
|
||||
args.add(
|
||||
switch (t.operator()) {
|
||||
case CONTAINS -> "%" + operand + "%";
|
||||
case STARTS_WITH -> operand + "%";
|
||||
case ENDS_WITH -> "%" + operand;
|
||||
default -> throw new IllegalStateException();
|
||||
});
|
||||
return field + " LIKE ? ESCAPE '!'";
|
||||
}
|
||||
if (f instanceof NumericFilter n) {
|
||||
c.number(n.operand());
|
||||
args.add(n.operand());
|
||||
if (n.operator() == NumericFilter.Operator.RANGE) {
|
||||
c.number(n.upper());
|
||||
args.add(n.upper());
|
||||
return field + " BETWEEN ? AND ?";
|
||||
}
|
||||
return field
|
||||
+ switch (n.operator()) {
|
||||
case EQUALS -> " = ?";
|
||||
case LESS -> " < ?";
|
||||
case LESS_OR_EQUAL -> " <= ?";
|
||||
case GREATER -> " > ?";
|
||||
case GREATER_OR_EQUAL -> " >= ?";
|
||||
default -> throw new IllegalStateException();
|
||||
};
|
||||
}
|
||||
if (f instanceof ValueFilter v) {
|
||||
var marks = new ArrayList<String>();
|
||||
for (var value : v.values()) {
|
||||
args.add(c.value(value));
|
||||
marks.add("?");
|
||||
}
|
||||
String membership =
|
||||
marks.isEmpty() ? "1=0" : field + " IN (" + String.join(",", marks) + ")";
|
||||
return membership + (v.includeMissing() ? " OR " + field + " IS NULL" : "");
|
||||
}
|
||||
throw new UnsupportedOperationException("JDBC does not support filter: " + f.typeId());
|
||||
}
|
||||
|
||||
private final class Execution implements QueryExecution<K, T> {
|
||||
final CompletableFuture<PageResult<K, T>> result = new CompletableFuture<>();
|
||||
final AtomicBoolean cancelled = new AtomicBoolean();
|
||||
final AtomicReference<Statement> active = new AtomicReference<>();
|
||||
|
||||
public CompletionStage<PageResult<K, T>> result() {
|
||||
return result;
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
cancelled.set(true);
|
||||
var statement = active.get();
|
||||
if (statement != null)
|
||||
try {
|
||||
statement.cancel();
|
||||
} catch (SQLException ignored) {
|
||||
/* Best effort; obsolete publication is independently rejected. */
|
||||
}
|
||||
result.cancel(false);
|
||||
}
|
||||
|
||||
void check() {
|
||||
if (cancelled.get()) throw new CancellationException("JDBC request cancelled");
|
||||
}
|
||||
|
||||
PreparedStatement prepare(Connection connection, String sql, List<Object> parameters)
|
||||
throws SQLException {
|
||||
check();
|
||||
var statement = connection.prepareStatement(sql);
|
||||
try {
|
||||
statement.setQueryTimeout(timeoutSeconds);
|
||||
for (int i = 0; i < parameters.size(); i++)
|
||||
statement.setObject(i + 1, parameters.get(i));
|
||||
active.set(statement);
|
||||
check();
|
||||
return statement;
|
||||
} catch (SQLException | RuntimeException failure) {
|
||||
try {
|
||||
statement.close();
|
||||
} catch (SQLException close) {
|
||||
failure.addSuppressed(close);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user