Class Database

  • All Implemented Interfaces:
    com.d3x.core.util.LifeCycle

    public class Database
    extends com.d3x.core.util.LifeCycle.Base
    A light weight SQL database abstraction layer using an Object / Functional approach to JDBC
    Author:
    Xavier Witdouck
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      private static class  Database.BasicMapping<T>
      A generic mapping class for single type
      static interface  Database.ConnectionHandler<R>
      An interface to a component to implement bespoke functionality against a database
      • Nested classes/interfaces inherited from interface com.d3x.core.util.LifeCycle

        com.d3x.core.util.LifeCycle.Base
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      int count​(java.lang.String sql, java.lang.Object... args)
      Returns the record count from a select count(*) type query
      <T> DatabaseUpdate<T> delete​(java.lang.Class<T> type)
      Returns a new delete operation for the type specified
      protected void doStart()  
      protected void doStop()  
      DatabaseExecute exec​(java.lang.String sql)  
      com.d3x.core.util.Option<java.lang.Integer> execute​(java.lang.String sql)
      Executes the sql definition using java.sql.Statement.execute()
      com.d3x.core.util.Option<java.lang.Integer> execute​(java.lang.String sql, com.d3x.core.util.Option<java.util.function.Consumer<java.sql.ResultSet>> handler)
      Executes the sql definition using java.sql.Statement.execute()
      int executeUpdate​(java.lang.String sql, java.lang.Object... args)
      Performs a SQL executeUpdate() given the parameterized SQL and arguments
      int executeUpdate​(java.lang.String sql, java.util.TimeZone timeZone, java.lang.Object... args)
      Performs a SQL executeUpdate() given the parameterized SQL and arguments
      DatabaseConfig getConfig()
      Returns the configuration for this database
      (package private) java.sql.Connection getConnection()
      Returns a reference to a database connection from the pool
      javax.sql.DataSource getDataSource()
      Returns a reference to the DataSource
      (package private) static java.util.concurrent.Executor getExecutor()
      Returns the Executor thread pool for Database
      <T> DatabaseUpdate<T> insert​(java.lang.Class<T> type)
      Returns a new insert operation for the type specified
      (package private) <T> DatabaseMapping<T> mapping​(java.lang.Class<T> type)
      Returns the mapping for the type specified
      static Database of​(DatabaseConfig config)
      Returns a newly created Database instance based on args provided
      static Database of​(DatabaseConfig config, java.util.function.Consumer<Database> setup)
      Returns a newly created Database instance based on args provided
      Database onStart​(java.util.function.Consumer<Database> onStart)
      Adds a onStart consumer to be called when the Database starts up
      private java.sql.Connection proxy​(java.sql.Connection connection)
      Returns a dynamic proxy over a connection to avoid closing to allow for multiple operations on same connection
      <T> void register​(DatabaseMapping<T> mapping)
      Registers a database mapping for a data type
      <T> DatabaseSelect<T> select​(java.lang.Class<T> type)
      Returns a new select operation for the type specified
      static void setDataSourceAdapter​(DataSourceAdapter dataSourceAdapter)
      Sets the data source adapter used to create DataSource objects
      static void setExecutor​(java.util.concurrent.ExecutorService executor)
      Sets the default executor for running async database operations
      (package private) <R> java.util.concurrent.Future<R> submit​(java.util.concurrent.Callable<R> callable)
      Submits the Callable to the Database assigned ExecutorService
      boolean supports​(java.lang.Class<?> type)
      Returns true if a mapping for the type exists
      boolean tableExists​(java.lang.String tableName)
      Returns true if the specified table exists
      <T> DatabaseUpdate<T> update​(java.lang.Class<T> type)
      Returns a new update operation for the type specified
      <R> R withConnection​(Database.ConnectionHandler<R> handler)
      Freestyle function to execute some logic against a database using the connection directly
      <R> R withTransaction​(Database.ConnectionHandler<R> handler)
      Freestyle function to execute some logic against a database within a transaction
      • Methods inherited from class com.d3x.core.util.LifeCycle.Base

        isStarted, start, stop
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
      • Methods inherited from interface com.d3x.core.util.LifeCycle

        startAsync, stopAsync
    • Field Detail

      • log

        private static final org.slf4j.Logger log
      • executor

        private static com.d3x.core.util.Lazy<java.util.concurrent.ExecutorService> executor
      • dataSource

        private javax.sql.DataSource dataSource
      • onStart

        private com.d3x.core.util.Consumers<Database> onStart
      • mappingsMap

        private java.util.Map<java.lang.reflect.Type,​DatabaseMapping<?>> mappingsMap
      • connectionThreadLocal

        private java.lang.ThreadLocal<java.sql.Connection> connectionThreadLocal
    • Constructor Detail

      • Database

        public Database​(DatabaseConfig config)
        Constructor
        Parameters:
        config - the config supplier
    • Method Detail

      • of

        public static Database of​(DatabaseConfig config)
        Returns a newly created Database instance based on args provided
        Parameters:
        config - the database config
        Returns:
        the newly created database
      • of

        public static Database of​(DatabaseConfig config,
                                  java.util.function.Consumer<Database> setup)
        Returns a newly created Database instance based on args provided
        Parameters:
        config - the database config
        setup - the consumer to perform additional setup
        Returns:
        the newly created database
      • getExecutor

        static java.util.concurrent.Executor getExecutor()
        Returns the Executor thread pool for Database
        Returns:
        the Executor thread pool
      • setExecutor

        public static void setExecutor​(java.util.concurrent.ExecutorService executor)
        Sets the default executor for running async database operations
        Parameters:
        executor - the executor reference
      • setDataSourceAdapter

        public static void setDataSourceAdapter​(DataSourceAdapter dataSourceAdapter)
        Sets the data source adapter used to create DataSource objects
        Parameters:
        dataSourceAdapter - the data source adapter
      • getConfig

        public DatabaseConfig getConfig()
        Returns the configuration for this database
        Returns:
        the database configuration
      • getDataSource

        public javax.sql.DataSource getDataSource()
        Returns a reference to the DataSource
        Returns:
        the DataSource reference
      • getConnection

        java.sql.Connection getConnection()
                                   throws java.sql.SQLException
        Returns a reference to a database connection from the pool
        Returns:
        the database connection
        Throws:
        java.sql.SQLException - if fails to get a connection
      • onStart

        public Database onStart​(java.util.function.Consumer<Database> onStart)
        Adds a onStart consumer to be called when the Database starts up
        Parameters:
        onStart - the on-start consumer to call before startup
        Returns:
        this database
      • doStart

        protected void doStart()
                        throws java.lang.RuntimeException
        Specified by:
        doStart in class com.d3x.core.util.LifeCycle.Base
        Throws:
        java.lang.RuntimeException
      • doStop

        protected void doStop()
                       throws java.lang.RuntimeException
        Overrides:
        doStop in class com.d3x.core.util.LifeCycle.Base
        Throws:
        java.lang.RuntimeException
      • supports

        public boolean supports​(java.lang.Class<?> type)
        Returns true if a mapping for the type exists
        Parameters:
        type - the data type
        Returns:
        true if a mapping exists
      • register

        public <T> void register​(DatabaseMapping<T> mapping)
        Registers a database mapping for a data type
        Type Parameters:
        T - the type for mapping
        Parameters:
        mapping - the mapping reference
      • tableExists

        public boolean tableExists​(java.lang.String tableName)
        Returns true if the specified table exists
        Parameters:
        tableName - the table name
        Returns:
        true if the table exists
      • count

        public int count​(java.lang.String sql,
                         java.lang.Object... args)
        Returns the record count from a select count(*) type query
        Parameters:
        sql - the SQL statement or path to classpath resource with SQL
        args - the args if the SQL is a parameterized statement
        Returns:
        the record count
      • execute

        public com.d3x.core.util.Option<java.lang.Integer> execute​(java.lang.String sql)
                                                            throws DatabaseException
        Executes the sql definition using java.sql.Statement.execute()
        Parameters:
        sql - the SQL statement or path to classpath resource with SQL
        Returns:
        the update count if applicable
        Throws:
        DatabaseException - if fails to execute sql
      • execute

        public com.d3x.core.util.Option<java.lang.Integer> execute​(java.lang.String sql,
                                                                   com.d3x.core.util.Option<java.util.function.Consumer<java.sql.ResultSet>> handler)
                                                            throws DatabaseException
        Executes the sql definition using java.sql.Statement.execute()
        Parameters:
        sql - the SQL statement or path to classpath resource with SQL
        handler - the optional handler for any ResultSets that may be produced
        Returns:
        the update count if applicable
        Throws:
        DatabaseException - if fails to execute sql
      • executeUpdate

        public int executeUpdate​(java.lang.String sql,
                                 java.lang.Object... args)
        Performs a SQL executeUpdate() given the parameterized SQL and arguments
        Parameters:
        sql - the SQL statement or path to classpath resource with SQL
        args - the arguments to apply to the expression
        Returns:
        the number of records affected
      • executeUpdate

        public int executeUpdate​(java.lang.String sql,
                                 java.util.TimeZone timeZone,
                                 java.lang.Object... args)
        Performs a SQL executeUpdate() given the parameterized SQL and arguments
        Parameters:
        sql - the SQL statement or path to classpath resource with SQL
        timeZone - the time zone to use to store timestamp related fields
        args - the arguments to apply to the expression
        Returns:
        the number of records affected
      • withConnection

        public <R> R withConnection​(Database.ConnectionHandler<R> handler)
                             throws DatabaseException
        Freestyle function to execute some logic against a database using the connection directly
        Type Parameters:
        R - the result type for function
        Parameters:
        handler - the function to take connection and do something
        Returns:
        the result of the function
        Throws:
        DatabaseException
      • withTransaction

        public <R> R withTransaction​(Database.ConnectionHandler<R> handler)
                              throws DatabaseException
        Freestyle function to execute some logic against a database within a transaction
        Type Parameters:
        R - the result type for function
        Parameters:
        handler - the function to take connection and do something
        Returns:
        the result of the function
        Throws:
        DatabaseException
      • select

        public <T> DatabaseSelect<T> select​(java.lang.Class<T> type)
        Returns a new select operation for the type specified
        Parameters:
        type - the data type for operation
        Returns:
        the database operation
      • insert

        public <T> DatabaseUpdate<T> insert​(java.lang.Class<T> type)
        Returns a new insert operation for the type specified
        Parameters:
        type - the data type for operation
        Returns:
        the database operation
      • update

        public <T> DatabaseUpdate<T> update​(java.lang.Class<T> type)
        Returns a new update operation for the type specified
        Parameters:
        type - the data type for operation
        Returns:
        the database operation
      • delete

        public <T> DatabaseUpdate<T> delete​(java.lang.Class<T> type)
        Returns a new delete operation for the type specified
        Parameters:
        type - the data type for operation
        Returns:
        the database operation
      • mapping

        <T> DatabaseMapping<T> mapping​(java.lang.Class<T> type)
        Returns the mapping for the type specified
        Parameters:
        type - the data type for mapping
        Returns:
        the mapping
        Throws:
        DatabaseException - if no mapping for type
      • submit

        <R> java.util.concurrent.Future<R> submit​(java.util.concurrent.Callable<R> callable)
        Submits the Callable to the Database assigned ExecutorService
        Type Parameters:
        R - the type for callable
        Parameters:
        callable - the callable to execute
        Returns:
        the future returned by ExecutorService
      • proxy

        private java.sql.Connection proxy​(java.sql.Connection connection)
        Returns a dynamic proxy over a connection to avoid closing to allow for multiple operations on same connection
        Parameters:
        connection - the connection to wrap with a dynamic proxy
        Returns:
        the dynamic proxy wrapper over the connection