org.melati.poem
Class Database

Package class diagram package Database
java.lang.Object
  extended by org.melati.poem.Database
All Implemented Interfaces:
TransactionPool
Direct Known Subclasses:
PoemDatabaseBase

public abstract class Database
extends Object
implements TransactionPool

An RDBMS database. Don't instantiate (or subclass) this class, but rather PoemDatabase, which includes the boilerplate code for the standard tables such as user and columninfo which all POEM databases must contain. If the database is predefined by a Data Structure Definition Bar.dsd, there will be an application-specialised subclass of PoemDatabase called BarDatabase which provides named methods for accessing application-specialised objects representing the predefined tables.

See Also:
PoemDatabase

Nested Class Summary
 class Database.ConnectingException
          Thrown when a request is made whilst the connection to the underlying database is still in progress.
 
Constructor Summary
Database()
          Don't subclass this, subclass PoemDatabase.
 
Method Summary
 void addConstraints()
          Add database constraints.
 Table addTableAndCommit(TableInfo info, String troidName)
          Add a Table to this Databse and commit the Transaction.
 Capability administerCapability()
           
 User administratorUser()
           
 void beginExclusiveLock()
          Acquire a lock on the database.
 void beginSession(AccessToken accessToken)
          Start a db session.
 Enumeration<Column> columns()
           
 void connect(String nameIn, String dbmsclass, String url, String username, String password, int transactionsMaxP)
          Connect to an RDBMS database.
protected  void defineTable(Table table)
          Don't call this.
 void deleteTableAndCommit(TableInfo info)
           
 void disconnect()
          Releases database connections.
 void dump()
          Print information about the structure of the database to stdout.
 void dumpCacheAnalysis()
          Print some diagnostic information about the contents and consistency of POEM's cache to stderr.
 void endExclusiveLock()
          Release lock.
 void endSession()
          End a db session.
 Capability getCanAdminister()
          By default, anyone can administer a database.
abstract  CapabilityTable getCapabilityTable()
          The table of capabilities (required for reading and/or writing records) defined for the database.
abstract  ColumnInfoTable getColumnInfoTable()
           
 Connection getCommittedConnection()
           
 Dbms getDbms()
           
 String getDisplayName()
           
 Enumeration<Table> getDisplayTables()
          All the tables in the database in DisplayOrder order, using current transaction if there is one.
 Enumeration<Table> getDisplayTables(PoemTransaction transaction)
          Currently all the tables in the database in DisplayOrder order.
 int getFreeTransactionsCount()
          
abstract  GroupCapabilityTable getGroupCapabilityTable()
          The table containing group-capability records.
abstract  GroupMembershipTable getGroupMembershipTable()
          A user is a member of a group iff there is a record in this table to say so.
abstract  GroupTable getGroupTable()
           
 String getLastQuery()
           
 String getName()
           
 int getQueryCount()
          Used in testing to check if the cache is being used or a new query is being issued.
abstract  SettingTable getSettingTable()
           
 Table getTable(String tableName)
          Retrieve the table with a given name.
abstract  TableCategoryTable getTableCategoryTable()
           
abstract  TableInfoTable getTableInfoTable()
           
 int getTransactionsCount()
          
abstract  UserTable getUserTable()
           
 String givesCapabilitySQL(User user, Capability capability)
          Get the raw SQL statement for this database's DBMS for Capability check for a User.
 AccessToken guestAccessToken()
           
 User guestUser()
           
 boolean hasCapability(User user, Capability capability)
          Check if a user has the specified Capability.
 void inCommittedTransaction(AccessToken accessToken, PoemTask task)
          Perform a task with the database, but not in an insulated transaction.
 void incrementQueryCount(String sql)
          Increment query count.
 void inSession(AccessToken accessToken, PoemTask task)
          Perform a task with the database.
 void inSessionAsRoot(PoemTask task)
           
 boolean isFree(PoemTransaction trans)
           
 boolean logCommits()
           
 boolean logSQL()
           
 PoemTransaction poemTransaction(int index)
          Find a transaction by its index.
 String quotedName(String nameIn)
          Quote a name in the DBMS' specific dialect.
protected  void redefineTable(Table table)
           
 Enumeration<Persistent> referencesTo(Persistent object)
          Find all references to specified object in all tables.
 Enumeration<Column> referencesTo(Table tableIn)
           
 void setCanAdminister()
          Set administrator capability to default.
 void setCanAdminister(String capabilityName)
          Set administrator capability to named Capability.
 void setDisplayName(String displayName)
           
 void setLogCommits(boolean value)
          Toggle commit logging.
 void setLogSQL(boolean value)
          Toggle logging.
 void setTransactionsMax(int t)
          Set the maximum number of transactions.
 ResultSet sqlQuery(String sql)
          Run an arbitrary SQL query against the database.
 int sqlUpdate(String sql)
          Run an arbitrary SQL update against the database.
 Enumeration<Table> tables()
          All the tables in the database.
 String toString()
          Returns the connection url.
 Transaction transaction(int index)
          Get a Transaction by its index.
 int transactionsMax()
          The number of transactions available for concurrent use on the database.
 void trimCache(int maxSize)
          Trim POEM's cache to a given size.
 void uncache()
          Set the contents of the cache to empty.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Database

public Database()
Don't subclass this, subclass PoemDatabase.

See Also:
PoemDatabase
Method Detail

connect

public void connect(String nameIn,
                    String dbmsclass,
                    String url,
                    String username,
                    String password,
                    int transactionsMaxP)
             throws PoemException
Connect to an RDBMS database. This should be called once when the application starts up; it will

Parameters:
dbmsclass - The Melati DBMS class (see org/melati/poem/dbms) to use, usually specified in org.melati.LogicalDatabase.properties.
url - The JDBC URL for the database; for instance jdbc:postgresql:williamc. It is the programmer's responsibility to make sure that an appropriate driver has been loaded.
username - The username under which to establish JDBC connections to the database. This has nothing to do with the user/group/capability authentication performed by Melati.
password - The password to go with the username.
transactionsMaxP - The maximum number of concurrent Transactions allowed, usually specified in org.melati.LogicalDatabase.properties.
Throws:
PoemException
See Also:
transactionsMax()

disconnect

public void disconnect()
                throws PoemException
Releases database connections.

Throws:
PoemException

defineTable

protected void defineTable(Table table)
                    throws DuplicateTableNamePoemException
Don't call this. Tables should be defined either in the DSD (in which case the boilerplate code generated by the preprocessor will call this method), or directly in the RDBMS (in which case the initialisation code will), or using addTableAndCommit.

Throws:
DuplicateTableNamePoemException
See Also:
addTableAndCommit(org.melati.poem.TableInfo, java.lang.String)

redefineTable

protected void redefineTable(Table table)

addTableAndCommit

public Table addTableAndCommit(TableInfo info,
                               String troidName)
                        throws PoemException
Add a Table to this Databse and commit the Transaction.

Parameters:
info - Table metadata object
troidName - name of troidColumn
Returns:
new minted Table
Throws:
PoemException

deleteTableAndCommit

public void deleteTableAndCommit(TableInfo info)
Parameters:
info - the tableInfo for the table to delete

addConstraints

public void addConstraints()
Add database constraints. The only constraints POEM expects are uniqueness and nullability. POEM assumes that the db will exploit indexes where present. However if you wish to export the db to a more DB oriented application or wish to use schema interrogation or visualisation tools then constraints can be added. Whether constraints are added is controlled in org.melati.LogicalDatabase.properties.


transactionsMax

public final int transactionsMax()
The number of transactions available for concurrent use on the database. This is the number of JDBC Connections opened when the database was connected, this can be set via LogicalDatabase.properties, but defaults to 8 if not set.

Specified by:
transactionsMax in interface TransactionPool
Returns:
the maximum number of Transactions we can store.
See Also:
TransactionPool.transactionsMax()

setTransactionsMax

public final void setTransactionsMax(int t)
Set the maximum number of transactions. Note that this does not resize the transaction pool so should be called before the db is connected to. Set the maximum number of transactions in this pool.

Specified by:
setTransactionsMax in interface TransactionPool
Parameters:
t - maximum number of transactions to set
See Also:
TransactionPool.setTransactionsMax(int)

getTransactionsCount

public int getTransactionsCount()

Specified by:
getTransactionsCount in interface TransactionPool
Returns:
Returns the total number of transactions.
See Also:
TransactionPool.getTransactionsCount()

getFreeTransactionsCount

public int getFreeTransactionsCount()

Specified by:
getFreeTransactionsCount in interface TransactionPool
Returns:
the number of free transactions.
See Also:
TransactionPool.getFreeTransactionsCount()

poemTransaction

public PoemTransaction poemTransaction(int index)
Find a transaction by its index.

transaction(i).index() == i

Parameters:
index - the index of the Transaction to return
Returns:
the Transaction with that index

transaction

public final Transaction transaction(int index)
Get a Transaction by its index.

Specified by:
transaction in interface TransactionPool
Parameters:
index - the Transaction index to retrieve
Returns:
the found Transaction
See Also:
TransactionPool.transaction(int)

isFree

public boolean isFree(PoemTransaction trans)
Parameters:
trans - a PoemTransaction
Returns:
whether the Transaction is free

beginExclusiveLock

public void beginExclusiveLock()
Acquire a lock on the database.


endExclusiveLock

public void endExclusiveLock()
Release lock.


inSession

public void inSession(AccessToken accessToken,
                      PoemTask task)
Perform a task with the database. Every access to a POEM database must be made in the context of a `transaction' established using this method (note that Melati programmers don't have to worry about this, because the PoemServlet will have done this by the time they get control).

Parameters:
accessToken - A token determining the Capabilitys available to the task, which in turn determine what data it can attempt to read and write without triggering an AccessPoemException. Note that a User can be an AccessToken.
task - What to do: its run() is invoked, in the current Java thread; until run() returns, all POEM accesses made by the thread are taken to be performed with the capabilities given by accessToken, and in a private transaction. No changes made to the database by other transactions will be visible to it (in the sense that once it has seen a particular version of a record, it will always subsequently see the same one), and its own changes will not be made permanent until it completes successfully or performs an explicit PoemThread.commit(). If it terminates with an exception or issues a PoemThread.rollback() its changes will be lost. (The task is allowed to continue after either a commit() or a rollback().)
See Also:
PoemThread, PoemThread.commit(), PoemThread.rollback(), User

inSessionAsRoot

public void inSessionAsRoot(PoemTask task)
Parameters:
task - the task to run

beginSession

public void beginSession(AccessToken accessToken)
Start a db session. This is the very manual way of doing db work - not reccomended - use inSession.


endSession

public void endSession()
End a db session.

This is the very manual way of doing db work - not recommended - use inSession.


inCommittedTransaction

public void inCommittedTransaction(AccessToken accessToken,
                                   PoemTask task)
Perform a task with the database, but not in an insulated transaction. The effect is the same as inSession, except that the task will see changes to the database made by other transactions as they are committed, and it is not allowed to make any changes of its own.

A modification will trigger a WriteCommittedException, however a create operation will trigger a NullPointerException, as we have no Transaction.

Not recommended; why exactly do you want to sidestep the Transaction handling?

See Also:
inSession(org.melati.poem.AccessToken, org.melati.poem.PoemTask)

getTable

public final Table getTable(String tableName)
                     throws NoSuchTablePoemException
Retrieve the table with a given name.

Parameters:
tableName - The name of the table to return, as in the RDBMS database. It's case-sensitive, and some RDBMSs such as Postgres 6.4.2 (and perhaps other versions) treat upper case letters in identifiers inconsistently, so the name is forced to lowercase.
Returns:
the Table of that name
Throws:
NoSuchTablePoemException - if no table with the given name exists in the RDBMS

tables

public final Enumeration<Table> tables()
All the tables in the database. NOTE This will include any deleted tables

Returns:
an Enumeration of Tables, in no particular order.

getDisplayTables

public Enumeration<Table> getDisplayTables()
All the tables in the database in DisplayOrder order, using current transaction if there is one.

Returns:
an Enumeration of Tables

getDisplayTables

public Enumeration<Table> getDisplayTables(PoemTransaction transaction)
Currently all the tables in the database in DisplayOrder order.

Returns:
an Enumeration of Tables

columns

public Enumeration<Column> columns()
Returns:
All the Columns in the whole Database

getTableInfoTable

public abstract TableInfoTable getTableInfoTable()
Returns:
The metadata table with information about all tables in the database.

getTableCategoryTable

public abstract TableCategoryTable getTableCategoryTable()
Returns:
The Table Category Table.

getColumnInfoTable

public abstract ColumnInfoTable getColumnInfoTable()
Returns:
The metadata table with information about all columns in all tables in the database.

getCapabilityTable

public abstract CapabilityTable getCapabilityTable()
The table of capabilities (required for reading and/or writing records) defined for the database. Users acquire capabilities in virtue of being members of groups.

Returns:
the CapabilityTable
See Also:
Persistent#getCanRead, Persistent#getCanWrite, Persistent#getCanDelete, JdbcTable.getDefaultCanRead(), JdbcTable.getDefaultCanWrite(), User, getUserTable(), Group, getGroupTable()

getUserTable

public abstract UserTable getUserTable()
Returns:
the table of known users of the database

getGroupTable

public abstract GroupTable getGroupTable()
Returns:
the table of defined user groups for the database

getGroupMembershipTable

public abstract GroupMembershipTable getGroupMembershipTable()
A user is a member of a group iff there is a record in this table to say so.

Returns:
the table containing group-membership records

getGroupCapabilityTable

public abstract GroupCapabilityTable getGroupCapabilityTable()
The table containing group-capability records. A group has a certain capability iff there is a record in this table to say so.

Returns:
the GroupCapability table

getSettingTable

public abstract SettingTable getSettingTable()
Returns:
the Setting Table.

sqlQuery

public ResultSet sqlQuery(String sql)
                   throws SQLPoemException
Run an arbitrary SQL query against the database. This is a low-level java.sql.Statement.executeQuery, intended for fiddly queries for which the higher-level methods are too clunky or inflexible. Note that it bypasses the access control mechanism!

Returns:
the ResultSet resulting from running the query
Throws:
SQLPoemException
See Also:
Table.selection(), Table.selection(java.lang.String), Column.selectionWhereEq(java.lang.Object)

sqlUpdate

public int sqlUpdate(String sql)
              throws SQLPoemException
Run an arbitrary SQL update against the database. This is a low-level java.sql.Statement.executeUpdate, intended for fiddly updates for which the higher-level methods are too clunky or inflexible.

NOTE This bypasses the access control mechanism. Furthermore, the cache will be left out of sync with the database and must be cleared out (explicitly, manually) after the current transaction has been committed or completed.

Returns:
either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing
Throws:
SQLPoemException
See Also:
Table.selection(), Table.selection(java.lang.String), Column.selectionWhereEq(java.lang.Object), uncache()

guestUser

public User guestUser()
Returns:
the guest

administratorUser

public User administratorUser()
Returns:
the administrator

givesCapabilitySQL

public String givesCapabilitySQL(User user,
                                 Capability capability)
Get the raw SQL statement for this database's DBMS for Capability check for a User.

Parameters:
user -
capability -
Returns:
the raw SQL appropriate for this db

hasCapability

public boolean hasCapability(User user,
                             Capability capability)
Check if a user has the specified Capability.

Parameters:
user - the User to check
capability - the Capability required
Returns:
whether User has Capability

guestAccessToken

public AccessToken guestAccessToken()
Returns:
the guest token.

administerCapability

public Capability administerCapability()
Returns:
the Capability required to administer this db.

getCanAdminister

public Capability getCanAdminister()
By default, anyone can administer a database.

Returns:
the required Capability to administer the db (null unless overridden)

setCanAdminister

public void setCanAdminister()
Set administrator capability to default.

NOTE Once a database has had its canAdminister capability set there is no mechanism to set it back to null.


setCanAdminister

public void setCanAdminister(String capabilityName)
Set administrator capability to named Capability.

Parameters:
capabilityName - name of Capability

trimCache

public void trimCache(int maxSize)
Trim POEM's cache to a given size.

Parameters:
maxSize - The data for all but this many records per table will be dropped from POEM's cache, on a least-recently-used basis.

uncache

public void uncache()
Set the contents of the cache to empty.


referencesTo

public Enumeration<Persistent> referencesTo(Persistent object)
Find all references to specified object in all tables.

Parameters:
object - the object being referred to
Returns:
an Enumeration of Persistents

referencesTo

public Enumeration<Column> referencesTo(Table tableIn)
Returns:
An Enumeration of Columns referring to the specified Table.

dumpCacheAnalysis

public void dumpCacheAnalysis()
Print some diagnostic information about the contents and consistency of POEM's cache to stderr.


dump

public void dump()
Print information about the structure of the database to stdout.


getDbms

public Dbms getDbms()
Returns:
the Database Management System class of this db

quotedName

public final String quotedName(String nameIn)
Quote a name in the DBMS' specific dialect.

Parameters:
nameIn -
Returns:
name quoted.

toString

public String toString()
Returns the connection url. If you want a simple name see LogicalDatabase.

Overrides:
toString in class Object
See Also:
Object.toString()

getCommittedConnection

public Connection getCommittedConnection()
Returns:
the non-transactioned jdbc Connection

logSQL

public boolean logSQL()
Returns:
whether logging is switched on

setLogSQL

public void setLogSQL(boolean value)
Toggle logging.


logCommits

public boolean logCommits()
Returns:
whether database commits should be logged

setLogCommits

public void setLogCommits(boolean value)
Toggle commit logging.


getQueryCount

public int getQueryCount()
Used in testing to check if the cache is being used or a new query is being issued.

Returns:
Returns the queryCount.

incrementQueryCount

public void incrementQueryCount(String sql)
Increment query count.


getLastQuery

public String getLastQuery()
Returns:
the most recent query

getName

public String getName()
Returns:
the name

getDisplayName

public String getDisplayName()
Returns:
the displayName

setDisplayName

public void setDisplayName(String displayName)
Parameters:
displayName - the displayName to set


Copyright © 2000-2010 PanEris. All Rights Reserved.