Class SQLManager

java.lang.Object
net.blockhost.commons.database.core.SQLManager

public final class SQLManager extends Object

Generic SQL connection manager with HikariCP connection pooling.

This class provides a complete solution for managing database connections in plugins, including connection pooling, configuration reloads, reconnection handling, and table creation/migration support.

Features

  • Connection Pooling: Uses HikariCP for efficient connection management
  • Config Reloads: Supports hot-reloading database configuration
  • Auto-Reconnect: Automatically attempts to reconnect on connection loss
  • Table Management: Built-in support for table creation and migrations
  • Thread Safety: All operations are thread-safe
// Using MariaDbConfig from commons-database-mariadb
MariaDbConfig dbConfig = config.database();

SQLManager sqlManager = SQLManager.create(dbConfig)
    .poolName("MyPlugin-Pool")
    .logger(plugin.getLogger())
    .build();

// Register tables to create on connect
sqlManager.registerTable("""
    CREATE TABLE IF NOT EXISTS players (
        uuid VARCHAR(36) PRIMARY KEY,
        name VARCHAR(16) NOT NULL
    )
""");

// Connect and create tables
sqlManager.connect();

// Use connections safely with callbacks
sqlManager.withConnection(connection -> {
    // Use connection safely
});

// Shutdown when done
sqlManager.shutdown();

Using Withers for Config Overrides

// Create a modified config for a specific use case
MariaDbConfig authMeConfig = config.database()
    .withDatabase("authme")
    .withMaxPoolSize(5);

SQLManager authMeManager = SQLManager.create(authMeConfig)
    .poolName("AuthMe-Pool")
    .build();
See Also:
  • Method Details

    • create

      public static SQLManager.Builder create(PooledDatabaseConfig config)

      Creates a new builder for SQLManager using a pooled database configuration.

      This is the recommended way to create an SQLManager. The configuration provides credentials, pool size, and idle connection settings.

      Parameters:
      config - the pooled database configuration
      Returns:
      a new builder instance with config applied
    • connect

      public void connect()

      Connects to the database and initializes the connection pool.

      This method will create the HikariCP connection pool using the current configuration. If already connected, this method does nothing.

      After connecting, all registered table creation statements and migrations will be executed.

    • getConnection

      public @Nullable Connection getConnection()

      Gets a connection from the pool.

      This method returns null instead of throwing an exception when unable to get a connection. This allows for easier error handling in calling code.

      Important: The returned connection must be closed after use. Use try-with-resources for automatic cleanup.

      Returns:
      a database connection, or null if unavailable
    • withConnection

      public boolean withConnection(SQLManager.ConnectionConsumer action)

      Executes an action with a database connection.

      This is a convenience method that handles connection retrieval and automatic cleanup. The connection is automatically closed after the action completes.

      Parameters:
      action - the action to execute with the connection
      Returns:
      true if the action executed successfully, false if no connection was available
    • withConnectionResult

      public <T> @Nullable T withConnectionResult(SQLManager.ConnectionFunction<T> action)
      Executes an action with a database connection and returns a result.
      Type Parameters:
      T - the type of result
      Parameters:
      action - the action to execute with the connection
      Returns:
      the result, or null if no connection was available or an error occurred
    • reconnect

      public void reconnect()

      Attempts to reconnect to the database.

      This method closes the existing connection pool (if any) and creates a new one with the current configuration.

    • reload

      public void reload(DatabaseCredentials newCredentials)

      Reloads the database configuration and reconnects.

      This method allows hot-reloading of database configuration. The existing connection pool is closed and a new one is created with the new configuration.

      Parameters:
      newCredentials - the new database credentials
    • registerTable

      public void registerTable(String createTableSql)

      Registers a table creation SQL statement.

      These statements are executed when connect() is called. Use CREATE TABLE IF NOT EXISTS to make statements idempotent.

      Parameters:
      createTableSql - the SQL statement to create the table
    • registerMigration

      public void registerMigration(int version, String description, String sql)

      Registers a database migration.

      Migrations are executed in order of their version number when connect() is called. Each migration runs only once, tracked by a migrations table.

      Parameters:
      version - the migration version (must be unique and sequential)
      description - a description of what the migration does
      sql - the SQL statement(s) to execute
    • shutdown

      public void shutdown()

      Shuts down the connection pool.

      This method should be called when the plugin is disabled to properly release database resources.

    • isConnected

      public boolean isConnected()
      Checks if the manager is currently connected to the database.
      Returns:
      true if connected, false otherwise
    • getCredentials

      public DatabaseCredentials getCredentials()
      Gets the current database credentials.
      Returns:
      the current credentials