Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
* Copyright 2003 Draagon Software LLC. All Rights Reserved.
*
* This software is the proprietary information of Draagon Software LLC.
* Use is subject to license terms.
*/
package com.draagon.meta.manager.db.driver;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.draagon.meta.MetaClass;
import com.draagon.meta.MetaException;
import com.draagon.meta.MetaField;
import com.draagon.meta.manager.QueryOptions;
import com.draagon.meta.manager.db.DatabaseDriver;
import com.draagon.meta.manager.db.ObjectManagerDB;
import com.draagon.meta.manager.db.ObjectMappingDB;
import com.draagon.meta.manager.db.SubSelectValue;
import com.draagon.meta.manager.db.defs.BaseDef;
import com.draagon.meta.manager.db.defs.BaseTableDef;
import com.draagon.meta.manager.db.defs.ColumnDef;
import com.draagon.meta.manager.db.defs.ForeignKeyDef;
import com.draagon.meta.manager.db.defs.IndexDef;
import com.draagon.meta.manager.db.defs.InheritenceDef;
import com.draagon.meta.manager.db.defs.NameDef;
import com.draagon.meta.manager.db.defs.SequenceDef;
import com.draagon.meta.manager.db.defs.TableDef;
import com.draagon.meta.manager.db.defs.ViewDef;
import com.draagon.meta.manager.exp.Expression;
import com.draagon.meta.manager.exp.ExpressionGroup;
import com.draagon.meta.manager.exp.ExpressionOperator;
import com.draagon.meta.manager.exp.Range;
import com.draagon.meta.manager.exp.SortOrder;
/**
* The Object Manager Base is able to add, update, delete, and retrieve objects
* of those types from a datastore.
*/
public class GenericSQLDriver implements DatabaseDriver {
private static Log log = LogFactory.getLog(GenericSQLDriver.class);
private ObjectManagerDB mManager = null;
/**
* This is to handle arguments for the constructed SQL query to ensure proper type conversion
* @author Doug
*/
public class SQLArg {
private MetaField metaField = null;
private Object value = null;
public SQLArg( MetaField f, Object value ) {
this.metaField = f;
this.value = value;
}
public MetaField getMetaField() { return metaField; }
public Object getValue() { return value; }
}
public GenericSQLDriver() {
}
public void setManager(ObjectManagerDB man) {
mManager = man;
}
/**
* Returns the Object Manager
*/
public ObjectManagerDB getManager() {
return mManager;
}
// /**
// * Returns whether the auto id is retrieved prior to creation
// */
// @Override
// public int getAutoType() {
// return AUTO_PRIOR;
// }
@Override
public boolean checkTable(Connection c, TableDef table) throws SQLException {
return checkBaseTable(c, table);
}
@Override
public boolean checkView(Connection c, ViewDef view) throws SQLException {
return checkBaseTable(c, view);
}
/**
* Checks for the existence of the base table and optionally creates it if
* it doesn't exist
*
* @param c
* Database connection to use
* @param baseTable
* Base Table Definition (Table or View)
* @param autoCreate
* Whether to auto create the table or view
* @return Whether the table or view exists
* @throws SQLException
* Exception if it exists in an invalid format
*/
protected boolean checkBaseTable(Connection c, BaseTableDef baseTable)
throws SQLException {
String schema = baseTable.getNameDef().getSchema();
String name = baseTable.getNameDef().getName();
// VALIDATE TABLE OR VIEW
ResultSet rs = c.getMetaData().getTables(null, schema, name, null);
try {
boolean found = false;
while (rs.next()) {
if (name.equalsIgnoreCase(rs.getString(3))) {
found = true;
break;
}
}
if (!found) {
// throw new TableDoesNotExistException( "Table or View [" +
// baseTable.getNameDef() + "] does not exist" );
return false;
}
} finally {
rs.close();
}
// VALIDATE THE COLUMNS
for (ColumnDef col : baseTable.getColumns()) {
rs = c.getMetaData().getColumns(null, schema, name, col.getName());
try {
boolean found = false;
while (rs.next()) {
if (col.getName().equalsIgnoreCase(rs.getString(4))) {
found = true;
break;
}
}
if (!found)
throw new SQLException("Table or View ["
+ baseTable.getNameDef()
+ "] does not have a Column [" + col.getName()
+ "]");
} finally {
rs.close();
}
}
return true;
}
/**
* Gets the next sequence for a given MetaClass
*/
protected String getNextAutoId(Connection conn, ColumnDef col) throws SQLException {
// String table = getManager().getTableName( mc );
// if ( table == null )
// throw new MetaException( "MetaClass [" + mc + "] has no table
// defined" );
// String col = getManager().getColumnName( mf );
// if ( col == null )
// throw new MetaException( "MetaField [" + mf + "] has no column
// defined" );
StringBuilder query = new StringBuilder();
try {
// Get next next MAX() sequence
Statement s = conn.createStatement();
try {
query.append("SELECT MAX( ").append(col.getName()).append(" )")
.append("FROM ").append(
getProperName(col.getBaseTable().getNameDef()));
ResultSet rs = s.executeQuery(query.toString());
try {
if (!rs.next())
return "1";
String tmp = rs.getString(1);
if (tmp == null)
return "1";
int i = Integer.parseInt(tmp) + 1;
return "" + i;
} finally {
rs.close();
}
} finally {
s.close();
}
} catch (SQLException e) {
log.error("Unable to get next id for column [" + col
+ "] with query [" + query + "]: " + e.getMessage(), e);
throw new SQLException("Unable to get next id for column [" + col
+ "]: " + e.getMessage(), e);
}
}
/**
* Creates a table in the database
*/
@Override
public void createTable(Connection c, TableDef tableDef)
throws SQLException {
throw new UnsupportedOperationException("CREATE TABLE NOT IMPLEMENTED!");
}
/**
* Deletes a table from the database
*/
@Override
public void deleteTable(Connection c, TableDef tableDef)
throws SQLException {
throw new UnsupportedOperationException("DELETE TABLE NOT IMPLEMENTED!");
}
/**
* Creates a view in the database
*/
@Override
public void createView(Connection c, ViewDef viewDef) throws SQLException {
throw new UnsupportedOperationException("CREATE VIEW NOT IMPLEMENTED!");
}
/**
* Creates the sequence in the database
*/
public void createSequence(Connection c, SequenceDef sequenceDef)
throws SQLException {
throw new UnsupportedOperationException(
"CREATE SEQUENCE NOT IMPLEMENTED!");
}
/**
* Creates the index in the database
*/
public void createIndex(Connection c, IndexDef indexDef)
throws SQLException {
// Do Nothing
}
/**
* Creates the foreign keys for the table in the database
*/
@Override
public void createForeignKey(Connection c, ForeignKeyDef foreignKeyDef)
throws SQLException {
// DO Nothing
}
/**
* Returns the proper name of the table or view
*
* @param nameDef
* @return
*/
public String getProperName(NameDef nameDef) {
return nameDef.getFullname();
}
@Override
public boolean create(Connection c, MetaClass mc, ObjectMappingDB omdb,
Object o) throws SQLException {
// Check if there is table inheritence going on, and if so create the super table first
BaseDef base = omdb.getDBDef();
if ( base instanceof TableDef ) {
TableDef table = (TableDef) base;
InheritenceDef inheritence = table.getInheritence();
if ( inheritence != null ) {
ObjectMappingDB smom = (ObjectMappingDB) omdb.getSuperMapping();
// Set the discriminator values
if ( inheritence.getDiscriminatorName() != null ) {
MetaField df = omdb.getField( inheritence.getDiscriminatorName() );
df.setString( o, inheritence.getDiscriminatorValue() );
}
// Create the super classes table entry
if ( !create( c, mc, smom, o )) {
throw new SQLException( "Super table entry could not be created for mapping [" + smom + "]" );
}
// Set the mapping field
MetaField rf = omdb.getField( inheritence.getRefColumn() );
MetaField f = omdb.getField( inheritence.getColumnName() );
f.setObject( o, rf.getObject( o ));
}
}
// Now create the entry for this object
PreparedStatement s = getInsertStatement(c, mc, omdb, o);
try {
s.execute();
if (s.getUpdateCount() < 1) {
return false;
} else {
return true;
}
} finally {
s.close();
}
}
@Override
public boolean read(Connection c, MetaClass mc, ObjectMappingDB mapping,
Object o, Expression exp) throws SQLException {
// Get the fields to read
Collection fields = mapping.getMetaFields();
QueryOptions qo = new QueryOptions(exp);
qo.setRange(1, 1);
PreparedStatement s = getSelectStatementWhere(c, mc, mapping, fields, qo);
try {
ResultSet rs = s.executeQuery();
try {
if (rs.next()) {
// Parse the Object
parseObject(rs, fields, mc, o);
return true;
}
return false;
} finally {
rs.close();
}
} finally {
s.close();
}
}
@Override
public boolean update( Connection c, MetaClass mc, ObjectMappingDB omdb,
Object o, Collection fields, Collection keys,
MetaField dirtyField, Object dirtyValue ) throws SQLException {
Expression exp = null;
// Check if there is table inheritence going on, and if so delete the super table first
BaseDef base = omdb.getDBDef();
if ( base instanceof TableDef ) {
TableDef table = (TableDef) base;
InheritenceDef inheritence = table.getInheritence();
if ( inheritence != null ) {
ObjectMappingDB smom = (ObjectMappingDB) omdb.getSuperMapping();
// Setup the key
MetaField rf = omdb.getField( inheritence.getRefColumn() );
Collection pkeys = new ArrayList();
pkeys.add( rf );
// Create the super classes table entry
if ( !update( c, mc, smom, o, fields, pkeys, dirtyField, dirtyValue )) {
return false;
// throw new SQLException( "Super table entry could not be updated for mapping [" + smom + "]" );
}
// Set the mapping field
MetaField f = omdb.getField( inheritence.getColumnName() );
// Set the expression to delete
exp = new Expression( f.getName(), rf.getObject( o ));
// Can only have dirty fields on the highest level of inheritence
dirtyField = null;
dirtyValue = null;
}
}
// If there wasn't inheritence, then generate the delete where clause
if ( exp == null ) {
// Generate the keys expression
for( MetaField mf : keys ) {
//if ( omdb.isInThisMap( mf )) {
Expression e = new Expression( mf.getName(), mf.getObject( o ));
if ( exp == null ) exp = e;
else exp = exp.and( e );
//}
}
}
// Add the dirty field expression
if ( dirtyField != null ) {
Expression e = new Expression( dirtyField.getName(), dirtyValue );
if ( exp == null ) exp = e;
else exp = exp.and( e );
}
//setAutoFields( c, mc, omdb, fields, o, ObjectManager.UPDATE );
Collection fieldsInMap = new ArrayList();
for ( MetaField mf : fields ) {
if ( omdb.isInThisMap( mf )) {
fieldsInMap.add( mf );
}
}
if ( fieldsInMap.size() == 0 ) return true;
PreparedStatement s = getUpdateStatement(c, omdb, fieldsInMap, mc, o, exp);
try {
int rc = s.executeUpdate();
if ( rc > 0 ) return true;
else return false;
} finally {
s.close();
}
}
@Override
public boolean delete( Connection c, MetaClass mc, ObjectMappingDB omdb,
Object o, Collection keys )
throws SQLException {
// Check if there is table inheritence going on, and if so delete the super table first
BaseDef base = omdb.getDBDef();
if ( base instanceof TableDef ) {
TableDef table = (TableDef) base;
InheritenceDef inheritence = table.getInheritence();
if ( inheritence != null ) {
ObjectMappingDB smom = (ObjectMappingDB) omdb.getSuperMapping();
MetaField rf = omdb.getField( inheritence.getRefColumn() );
Collection pkeys = new ArrayList();
pkeys.add( rf );
// Set the mapping field
MetaField f = omdb.getField( inheritence.getColumnName() );
// Set the expression to delete
Expression exp = new Expression( f.getName(), rf.getObject( o ));
// Delete the higher level table first
boolean result = executeDelete( c, mc, omdb, exp );
// Return a false if it was not deleteable
if ( result == false ) return false;
// Delete the super classes table entry
if ( !delete( c, mc, smom, o, pkeys )) {
throw new SQLException( "Super table entry could not be deleted for mapping [" + smom + "]" );
}
return result;
}
}
// If there wasn't inheritence, then generate the delete where clause
// Generate the keys expression
Expression exp = null;
for( MetaField mf : keys ) {
Expression e = new Expression( mf.getName(), mf.getObject( o ));
if ( exp == null ) exp = e;
else exp = exp.and( e );
}
//setAutoFields( c, mc, omdb, fields, o, ObjectManager.UPDATE );
return executeDelete( c, mc, omdb, exp );
}
/** Perform the actual delete call */
protected boolean executeDelete( Connection c, MetaClass mc, ObjectMappingDB omdb, Expression exp ) throws MetaException, SQLException {
PreparedStatement s = getDeleteStatementWhere(c, mc, omdb, exp);
try {
int rc = s.executeUpdate();
if ( rc == 1 ) return true;
else return false;
} finally {
s.close();
}
}
@Override
public long getCount(Connection c, MetaClass mc,
ObjectMappingDB mapping, Expression exp ) throws SQLException {
PreparedStatement s = getCountStatementWhere(c, mc, mapping, exp );
try {
ResultSet rs = s.executeQuery();
try {
if (rs.next()) {
return rs.getLong( 1 );
} else {
return 0;
}
} finally {
rs.close();
}
} finally {
s.close();
}
}
@Override
public Collection