CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-jooq--jooq

jOOQ is an internal DSL and source code generator, modelling the SQL language as a type safe Java API to help you write better SQL

Pending
Overview
Eval results
Files

utilities.mddocs/

Utilities and Tools

Comprehensive utility classes for JDBC operations, JSON processing, CSV handling, reflection, and R2DBC integration. Includes testing utilities and mock database providers.

Capabilities

JDBC Utilities

Essential utilities for working with JDBC connections, result sets, and database metadata.

public class JDBCUtils {
    /**
     * Safely close a JDBC connection, ignoring any exceptions
     * @param connection Connection to close
     */
    public static void safeClose(Connection connection);
    
    /**
     * Safely close a JDBC statement, ignoring any exceptions
     * @param statement Statement to close
     */
    public static void safeClose(Statement statement);
    
    /**
     * Safely close a JDBC result set, ignoring any exceptions
     * @param resultSet ResultSet to close
     */
    public static void safeClose(ResultSet resultSet);
    
    /**
     * Safely close multiple JDBC resources, ignoring any exceptions
     * @param closeables Resources to close
     */
    public static void safeClose(AutoCloseable... closeables);
    
    /**
     * Detect the SQL dialect from a JDBC connection
     * @param connection JDBC connection to analyze
     * @return SQLDialect detected from the connection
     */
    public static SQLDialect dialect(Connection connection);
    
    /**
     * Detect the SQL dialect from a database URL
     * @param url JDBC URL to analyze
     * @return SQLDialect detected from the URL
     */
    public static SQLDialect dialect(String url);
    
    /**
     * Check if a connection is still valid
     * @param connection Connection to test
     * @param timeout Timeout in seconds for the test
     * @return true if connection is valid
     */
    public static boolean isValid(Connection connection, int timeout);
    
    /**
     * Get database product name from connection metadata
     * @param connection JDBC connection
     * @return Database product name
     */
    public static String getDatabaseProductName(Connection connection);
    
    /**
     * Get database product version from connection metadata
     * @param connection JDBC connection
     * @return Database product version
     */
    public static String getDatabaseProductVersion(Connection connection);
    
    /**
     * Create a data source from a JDBC URL
     * @param url JDBC connection URL
     * @param username Database username
     * @param password Database password
     * @return DataSource instance
     */
    public static DataSource dataSource(String url, String username, String password);
}

Usage Examples:

// Safe resource cleanup
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
    conn = DriverManager.getConnection("jdbc:h2:mem:test");
    stmt = conn.createStatement();
    rs = stmt.executeQuery("SELECT * FROM users");
    
    // Process results...
    
} catch (SQLException e) {
    // Handle error
} finally {
    // Safe cleanup - no exceptions thrown
    JDBCUtils.safeClose(rs, stmt, conn);
}

// Dialect detection
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/test");
SQLDialect dialect = JDBCUtils.dialect(conn);
System.out.println("Detected dialect: " + dialect); // POSTGRES

// Connection validation
if (JDBCUtils.isValid(conn, 5)) {
    // Connection is still good, use it
    DSLContext create = using(conn, dialect);
} else {
    // Connection is stale, get a new one
    conn = dataSource.getConnection();
}

Mock Testing Utilities

Utilities for creating mock databases and testing jOOQ code without real database connections.

public interface MockDataProvider {
    /**
     * Provide mock results for a SQL execution
     * @param ctx Mock execution context with SQL and parameters
     * @return Array of mock results
     * @throws SQLException if mock execution should simulate an error
     */
    MockResult[] execute(MockExecuteContext ctx) throws SQLException;
}

public class MockConnection implements Connection {
    /**
     * Create a mock connection with a data provider
     * @param provider MockDataProvider for generating results
     */
    public MockConnection(MockDataProvider provider);
    
    /**
     * Create a mock connection with multiple data providers
     * @param providers Array of MockDataProvider instances
     */
    public MockConnection(MockDataProvider... providers);
}

public class MockResult {
    /**
     * Create a mock result for a query
     * @param rows Number of rows affected/returned
     * @param data Result data as jOOQ Result
     */
    public MockResult(int rows, Result<? extends Record> data);
    
    /**
     * Create a mock result for DML operations
     * @param rows Number of rows affected
     */
    public MockResult(int rows);
    
    /**
     * Get the number of rows affected
     * @return Row count
     */
    public int rows();
    
    /**
     * Get the result data
     * @return Result data or null for DML operations
     */
    public Result<? extends Record> data();
}

public interface MockExecuteContext {
    /**
     * Get the SQL being executed
     * @return SQL string
     */
    String sql();
    
    /**
     * Get the bind values
     * @return Array of parameter values
     */
    Object[] bindings();
    
    /**
     * Get the SQL with inlined parameters
     * @return SQL with parameters substituted
     */
    String sqlInlined();
}

Usage Examples:

// Simple mock data provider
MockDataProvider provider = new MockDataProvider() {
    @Override
    public MockResult[] execute(MockExecuteContext ctx) throws SQLException {
        String sql = ctx.sql();
        
        if (sql.toUpperCase().startsWith("SELECT")) {
            // Mock SELECT results
            DSLContext create = using(SQLDialect.H2);
            Result<Record> result = create.newResult(
                field("id", Integer.class),
                field("name", String.class)
            );
            
            result.add(create.newRecord(result.fields())
                .values(1, "John Doe"));
            result.add(create.newRecord(result.fields())
                .values(2, "Jane Smith"));
                
            return new MockResult[] { new MockResult(2, result) };
            
        } else if (sql.toUpperCase().startsWith("INSERT")) {
            // Mock INSERT result
            return new MockResult[] { new MockResult(1) };
            
        } else {
            throw new SQLException("Unexpected SQL: " + sql);
        }
    }
};

// Use mock connection in tests
Connection mockConn = new MockConnection(provider);
DSLContext create = using(mockConn, SQLDialect.H2);

// This will use the mock provider
Result<Record> authors = create.select()
    .from("authors")
    .fetch();

assertEquals(2, authors.size());
assertEquals("John Doe", authors.get(0).get("name"));

Type Conversion Utilities

Utilities for converting between Java types and database values.

public class Convert {
    /**
     * Convert a value to a specific type
     * @param from Value to convert
     * @param toClass Target type class
     * @return Converted value
     */
    public static <T> T convert(Object from, Class<T> toClass);
    
    /**
     * Convert a value using a specific converter
     * @param from Value to convert
     * @param converter Converter instance
     * @return Converted value
     */
    public static <T, U> U convert(T from, Converter<T, U> converter);
    
    /**
     * Check if conversion is possible between two types
     * @param from Source type
     * @param to Target type
     * @return true if conversion is supported
     */
    public static boolean canConvert(Class<?> from, Class<?> to);
    
    /**
     * Convert an array of values to a specific type
     * @param from Array of values to convert
     * @param toClass Target component type
     * @return Array with converted values
     */
    public static <T> T[] convertArray(Object[] from, Class<T> toClass);
    
    /**
     * Convert a collection to a list of specific type
     * @param from Collection to convert
     * @param toClass Target element type
     * @return List with converted elements
     */
    public static <T> List<T> convertCollection(Collection<?> from, Class<T> toClass);
}

JSON Processing Utilities

Utilities for working with JSON data in database operations.

public class JSONObject {
    /**
     * Create an empty JSON object
     */
    public JSONObject();
    
    /**
     * Create a JSON object from a string
     * @param json JSON string to parse
     */
    public JSONObject(String json);
    
    /**
     * Put a key-value pair in the JSON object
     * @param key JSON key
     * @param value JSON value
     * @return This JSONObject for chaining
     */
    public JSONObject put(String key, Object value);
    
    /**
     * Get a value by key
     * @param key JSON key
     * @return Value or null if not found
     */
    public Object get(String key);
    
    /**
     * Get a typed value by key
     * @param key JSON key
     * @param type Expected value type
     * @return Typed value or null if not found
     */
    public <T> T get(String key, Class<T> type);
    
    /**
     * Convert to JSON string
     * @return JSON string representation
     */
    public String toJSONString();
}

public class JSONArray {
    /**
     * Create an empty JSON array
     */
    public JSONArray();
    
    /**
     * Create a JSON array from a string
     * @param json JSON array string to parse
     */
    public JSONArray(String json);
    
    /**
     * Add a value to the array
     * @param value Value to add
     * @return This JSONArray for chaining
     */
    public JSONArray add(Object value);
    
    /**
     * Get a value by index
     * @param index Array index
     * @return Value at index
     */
    public Object get(int index);
    
    /**
     * Get array size
     * @return Number of elements
     */
    public int size();
    
    /**
     * Convert to JSON string
     * @return JSON array string representation
     */
    public String toJSONString();
}

public class JSONParser {
    /**
     * Parse a JSON string into an object
     * @param json JSON string to parse
     * @return JSONObject or JSONArray
     */
    public static Object parse(String json);
    
    /**
     * Parse a JSON string into a JSONObject
     * @param json JSON object string
     * @return JSONObject instance
     */
    public static JSONObject parseObject(String json);
    
    /**
     * Parse a JSON string into a JSONArray
     * @param json JSON array string
     * @return JSONArray instance
     */
    public static JSONArray parseArray(String json);
}

Usage Examples:

// Working with JSON data
JSONObject author = new JSONObject()
    .put("id", 1)
    .put("firstName", "John")
    .put("lastName", "Doe")
    .put("active", true);

String jsonString = author.toJSONString();
// {"id":1,"firstName":"John","lastName":"Doe","active":true}

// Parse JSON from database
Result<Record1<String>> jsonResults = create
    .select(field("author_data", String.class))
    .from("authors")
    .fetch();

for (Record1<String> record : jsonResults) {
    JSONObject authorData = JSONParser.parseObject(record.value1());
    String name = authorData.get("firstName", String.class);
    Integer id = authorData.get("id", Integer.class);
}

// Type conversion with JSON
Object value = "123";
Integer intValue = Convert.convert(value, Integer.class);
String stringValue = Convert.convert(intValue, String.class);

CSV Processing Utilities

Utilities for reading and writing CSV data for bulk operations.

public class CSVReader {
    /**
     * Create a CSV reader from a file
     * @param file CSV file to read
     */
    public CSVReader(File file);
    
    /**
     * Create a CSV reader from an input stream
     * @param inputStream Stream containing CSV data
     */
    public CSVReader(InputStream inputStream);
    
    /**
     * Read the next CSV record
     * @return Array of field values or null if end of file
     */
    public String[] readNext();
    
    /**
     * Read all CSV records
     * @return List of string arrays representing records
     */
    public List<String[]> readAll();
    
    /**
     * Close the CSV reader
     */
    public void close();
}

public class CSVParser {
    /**
     * Parse a CSV line into fields
     * @param csvLine CSV line to parse
     * @return Array of field values
     */
    public static String[] parseLine(String csvLine);
    
    /**
     * Parse CSV line with custom separator
     * @param csvLine CSV line to parse
     * @param separator Field separator character
     * @return Array of field values
     */
    public static String[] parseLine(String csvLine, char separator);
}

Reflection Utilities

Enhanced reflection utilities for working with Java objects and jOOQ records.

public class Reflect {
    /**
     * Create a Reflect wrapper around an object
     * @param object Object to wrap
     * @return Reflect instance
     */
    public static Reflect on(Object object);
    
    /**
     * Create a Reflect wrapper around a class
     * @param clazz Class to wrap
     * @return Reflect instance
     */
    public static Reflect on(Class<?> clazz);
    
    /**
     * Create a new instance of the wrapped class
     * @param args Constructor arguments
     * @return New Reflect instance wrapping the created object
     */
    public Reflect create(Object... args);
    
    /**
     * Call a method on the wrapped object
     * @param name Method name
     * @param args Method arguments
     * @return Reflect instance wrapping the method result
     */
    public Reflect call(String name, Object... args);
    
    /**
     * Get a field value from the wrapped object
     * @param name Field name
     * @return Reflect instance wrapping the field value
     */
    public Reflect field(String name);
    
    /**
     * Set a field value on the wrapped object
     * @param name Field name
     * @param value New field value
     * @return This Reflect instance for chaining
     */
    public Reflect set(String name, Object value);
    
    /**
     * Get the wrapped object
     * @return The underlying object
     */
    public <T> T get();
    
    /**
     * Get the wrapped object as a specific type
     * @param type Target type class
     * @return The underlying object cast to the target type
     */
    public <T> T get(Class<T> type);
}

Usage Examples:

// Reflection utilities for POJO mapping
public class AuthorPojo {
    private String firstName;
    private String lastName;
    
    // getters and setters...
}

// Use reflection to create and populate POJO
Reflect authorReflect = Reflect.on(AuthorPojo.class).create();
authorReflect
    .set("firstName", "John")
    .set("lastName", "Doe");

AuthorPojo author = authorReflect.get(AuthorPojo.class);

// Call methods via reflection
String fullName = Reflect.on(author)
    .call("getFirstName")
    .get(String.class) + " " + 
    Reflect.on(author)
    .call("getLastName")
    .get(String.class);

// CSV bulk loading example
try (CSVReader reader = new CSVReader(new File("authors.csv"))) {
    List<String[]> records = reader.readAll();
    
    for (String[] record : records) {
        create.insertInto(AUTHOR)
            .set(AUTHOR.FIRST_NAME, record[0])
            .set(AUTHOR.LAST_NAME, record[1])
            .set(AUTHOR.EMAIL, record[2])
            .execute();
    }
}

R2DBC Integration Utilities

Utilities for reactive database access using R2DBC with jOOQ.

public class R2DBCUtils {
    /**
     * Convert a reactive R2DBC result to jOOQ Result
     * @param publisher R2DBC result publisher
     * @param recordType Target record type
     * @return CompletableFuture with jOOQ Result
     */
    public static <R extends Record> CompletableFuture<Result<R>> 
        collect(Publisher<R> publisher, Class<R> recordType);
    
    /**
     * Execute a jOOQ query reactively with R2DBC
     * @param query jOOQ query to execute
     * @param connection R2DBC connection
     * @return Publisher of records
     */
    public static <R extends Record> Publisher<R> 
        executeAsync(Query query, io.r2dbc.spi.Connection connection);
}

Usage Examples:

// Reactive query execution
io.r2dbc.spi.ConnectionFactory factory = 
    ConnectionFactories.get("r2dbc:postgresql://localhost/test");

DSLContext create = using(factory);

// Reactive SELECT
Publisher<AuthorRecord> authorsPublisher = create
    .selectFrom(AUTHOR)
    .where(AUTHOR.ACTIVE.eq(true))
    .fetchPublisher();

// Convert to CompletableFuture
CompletableFuture<Result<AuthorRecord>> authorsFuture = 
    R2DBCUtils.collect(authorsPublisher, AuthorRecord.class);

authorsFuture.thenAccept(authors -> {
    System.out.println("Found " + authors.size() + " active authors");
});

Install with Tessl CLI

npx tessl i tessl/maven-org-jooq--jooq

docs

configuration.md

exceptions.md

index.md

query-building.md

query-execution.md

records.md

schema-objects.md

utilities.md

tile.json