Class DatabaseFactory

java.lang.Object
com.tccc.kos.commons.db.DatabaseFactory

public class DatabaseFactory extends Object
System component used to create a DataSource or Jdbi instance for a SQLite database. This will handle creation of the database file and migration of the schema using the supplied DatabaseMigrator. The result can be either a DataSoruce or Jdbi instance to the resulting database.
Since:
1.0
Version:
2022-10-21
See Also:
  • Constructor Details

    • DatabaseFactory

      public DatabaseFactory()
  • Method Details

    • setDefaultDir

      public void setDefaultDir(File dir)
      Set the default directory
    • getDefaultDir

      public File getDefaultDir()
      Return the default directory.
    • migrate

      public DatabaseMigrator migrate(DatabaseMigrator migrator, String name, File dir)
      This is a convenience method that simply calls getDataSource() and then returns the migrator. When a database only has a single DAO, then this is typically used by passing in a new instance of the DAO, migrating it, and then returning the DAO instance so it can be added to the context, all in one line of code.
      Parameters:
      migrator - used to migrate the database
      name - the database's name
      dir - the directory the database is located
      Returns:
      the migrator that was passed in
    • getDataSource

      public DataSource getDataSource(DatabaseMigrator migrator, String name, File dir)
      Creates a DataSource for the specified database file in the specified directory. The supplied migrator is used to migrate the database to the latest schema before the data source is returned. If migration needs to occur, it is performed with a temporary data source until everything is ready, and then setDataSource() is called on the migrator to indicate that things are stable and ready for use.

      When this method is called, the database is in one of the following states:

      1. It exists and its schema version is correct/current (most of the time)
      2. It exists but its schema version is older (needs updating)
      3. It exists but its schema version is newer (needs rolling-back)
      4. It does not exist
      When this method exits, the database schema is up-to-date and ready to access
      Parameters:
      migrator - used to migrate the database
      name - the database's name
      dir - the directory the database is located
      Returns:
      the resulting datasource
    • getJdbi

      public Jdbi getJdbi(DatabaseMigrator migrator, String name, File dir)
      Wrapper for getDataSource that returns Jdbi instance instead. This will be the same Jdbi instance used to call setJdbi on the migrator when migration is complete.
      Parameters:
      migrator - used to migrate the database
      name - the database's name
      dir - the directory the database is located
      Returns:
      the resulting jdbi instance