You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@empire-db.apache.org by do...@apache.org on 2024/07/12 16:01:24 UTC
(empire-db) branch master updated: EMPIREDB-433 Database RowSet access by alias and improved cloning
This is an automated email from the ASF dual-hosted git repository.
doebele pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/empire-db.git
The following commit(s) were added to refs/heads/master by this push:
new 6d6c5d26 EMPIREDB-433 Database RowSet access by alias and improved cloning
6d6c5d26 is described below
commit 6d6c5d262385510e31369d9ad167756aeec9506a
Author: Rainer Döbele <do...@apache.org>
AuthorDate: Fri Jul 12 18:01:20 2024 +0200
EMPIREDB-433
Database RowSet access by alias and improved cloning
---
.../org/apache/empire/commons/ObjectUtils.java | 17 ++++
.../java/org/apache/empire/db/DBCommandExpr.java | 7 ++
.../main/java/org/apache/empire/db/DBDatabase.java | 108 +++++++++++++++++++--
.../main/java/org/apache/empire/db/DBQuery.java | 6 ++
.../main/java/org/apache/empire/db/DBRowSet.java | 65 ++++++++++++-
.../main/java/org/apache/empire/db/DBTable.java | 75 +++++---------
.../src/main/java/org/apache/empire/db/DBView.java | 91 ++++++++++++++++-
.../empire/db/expr/compare/DBCompareColExpr.java | 17 +++-
8 files changed, 326 insertions(+), 60 deletions(-)
diff --git a/empire-db/src/main/java/org/apache/empire/commons/ObjectUtils.java b/empire-db/src/main/java/org/apache/empire/commons/ObjectUtils.java
index 57fa8c2e..062e2636 100644
--- a/empire-db/src/main/java/org/apache/empire/commons/ObjectUtils.java
+++ b/empire-db/src/main/java/org/apache/empire/commons/ObjectUtils.java
@@ -1200,4 +1200,21 @@ public final class ObjectUtils
System.arraycopy(right, 0, result, left.length, right.length);
return result;
}
+
+ /**
+ * appends an element to an array
+ * @param <T> the type of the array items
+ * @param array the array
+ * @param element the new element
+ * @return the combined array
+ */
+ public static <T> T[] append(T[] array, T element)
+ {
+ if (array==null)
+ throw new InvalidArgumentException("array", array);
+ // append element
+ T[] result = Arrays.copyOf(array, array.length + 1);
+ result[array.length] = element;
+ return result;
+ }
}
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBCommandExpr.java b/empire-db/src/main/java/org/apache/empire/db/DBCommandExpr.java
index 234e70aa..1fd013a8 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBCommandExpr.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBCommandExpr.java
@@ -147,6 +147,13 @@ public abstract class DBCommandExpr extends DBExpr
{
throw new NotSupportedException(this, "deleteRecord");
}
+
+ /** throws ERR_NOTSUPPORTED */
+ @Override
+ protected DBColumn cloneColumn(DBRowSet clone, DBColumn scourceColumn)
+ {
+ throw new NotSupportedException(this, "cloneColumn");
+ }
}
/**
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBDatabase.java b/empire-db/src/main/java/org/apache/empire/db/DBDatabase.java
index 64c49fbf..536b661e 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBDatabase.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBDatabase.java
@@ -27,8 +27,10 @@ import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.Collections;
import java.util.Date;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
@@ -37,6 +39,7 @@ import java.util.Set;
import org.apache.empire.commons.ObjectUtils;
import org.apache.empire.commons.Options;
+import org.apache.empire.commons.StringUtils;
import org.apache.empire.data.Column;
import org.apache.empire.data.DataType;
import org.apache.empire.db.DBDDLGenerator.DDLActionType;
@@ -55,10 +58,11 @@ import org.apache.empire.db.expr.compare.DBCompareExpr;
import org.apache.empire.dbms.DBMSHandler;
import org.apache.empire.dbms.DBSqlPhrase;
import org.apache.empire.exceptions.InvalidArgumentException;
+import org.apache.empire.exceptions.InvalidOperationException;
import org.apache.empire.exceptions.ItemExistsException;
import org.apache.empire.exceptions.NotSupportedException;
+import org.apache.empire.exceptions.ObjectNotValidException;
import org.apache.empire.exceptions.PropertyReadOnlyException;
-import org.apache.empire.exceptions.InvalidOperationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -150,6 +154,8 @@ public abstract class DBDatabase extends DBObject
protected final List<DBTable> tables = new ArrayList<DBTable>();
protected final List<DBRelation> relations = new ArrayList<DBRelation>();
protected final List<DBView> views = new ArrayList<DBView>();
+ // map of all Rowsets by alias
+ protected final Map<String, DBRowSet> rowsetAliasMap = new HashMap<String, DBRowSet>();
protected DBMSHandler dbms = null;
@@ -697,17 +703,23 @@ public abstract class DBDatabase extends DBObject
{ // find column by name
if (table == null || table.db != this)
throw new InvalidArgumentException("table", table);
- if (tables.contains(table)==true)
- throw new ItemExistsException(table.getName());
// Check for second instances
DBTable existing = getTable(table.getName());
+ if (existing==table)
+ return; // already there
if (existing!=null)
{ // Check classes
- if (existing.getClass().equals(table.getClass()))
- return; // Ignore other instances
+ if (isSameRowSet(existing, table))
+ { // Add instance to alias map
+ addRowsetToAliasMap(table);
+ // Ignore other instances
+ return;
+ }
// Table exists with different class
throw new ItemExistsException(table.getName());
}
+ // Add instance to alias map
+ addRowsetToAliasMap(table);
// add now
tables.add(table);
}
@@ -723,6 +735,8 @@ public abstract class DBDatabase extends DBObject
// remove
if (tables.contains(table))
tables.remove(table);
+ // Remove from RowSet map
+ removeRowsetFromAliasMap(table);
}
/**
@@ -766,6 +780,26 @@ public abstract class DBDatabase extends DBObject
return rset;
}
+ /**
+ * Finds a RowSet object by the alias name.
+ * <P>
+ * @param name the name of the table
+ * @return the located DBTable object
+ */
+ public DBRowSet getRowSetByAlias(String alias)
+ { // find table by name
+ return this.rowsetAliasMap.get(alias);
+ }
+
+ /**
+ * Returns all DBRowSet instances currently created for this database
+ * @return all DBRowSet instances
+ */
+ public Collection<DBRowSet> getAllRowSets()
+ { // find table by name
+ return this.rowsetAliasMap.values();
+ }
+
/**
* Adds a foreign key relation to the database.
* <P>
@@ -878,9 +912,24 @@ public abstract class DBDatabase extends DBObject
{ // find column by name
if (view == null || view.db != this)
throw new InvalidArgumentException("view", view);
- if (views.contains(view) == true)
+ // Check for second instances
+ DBView existing = getView(view.getName());
+ if (existing==view)
+ return; // already there
+ if (existing!=null)
+ { // Check classes
+ if (isSameRowSet(existing, view))
+ { // Add instance to alias map
+ addRowsetToAliasMap(view);
+ // Ignore other instances
+ return;
+ }
+ // Table exists with different class
throw new ItemExistsException(view.getName());
- // add now
+ }
+ // Add instance to alias map
+ addRowsetToAliasMap(view);
+ // add view
views.add(view);
}
@@ -895,6 +944,8 @@ public abstract class DBDatabase extends DBObject
// remove
if (views.contains(view))
views.remove(view);
+ // Remove from RowSet map
+ removeRowsetFromAliasMap(view);
}
/**
@@ -1261,4 +1312,47 @@ public abstract class DBDatabase extends DBObject
return new DBCaseMapExpr(column, cmpValue, trueValue, falseValue);
}
+
+ /**
+ * Checks if two Rowsets with the same name are equal and just another instance
+ * @param first the first rowset
+ * @param second the second rowset
+ * @return true if both are the same and are just another instance
+ */
+ protected boolean isSameRowSet(DBRowSet first, DBRowSet second)
+ {
+ return first.getClass().equals(second.getClass());
+ }
+
+ /**
+ * adds a DBRowSet to the alias map
+ * @param rowset
+ */
+ protected void addRowsetToAliasMap(DBRowSet rowset)
+ {
+ String alias = rowset.getAlias();
+ if (StringUtils.isEmpty(alias))
+ throw new ObjectNotValidException(rowset); // alias must be valid
+ // find existing
+ DBRowSet existing = rowsetAliasMap.get(alias);
+ if (existing==rowset)
+ return; // already there
+ if (existing!=null) {
+ log.error("Rowset alias \"{}\" must be unqiue, but has alreaedy been used for {}", alias, existing.getClass().getName());
+ throw new ItemExistsException(alias); // Alias must be unique!
+ }
+ // add to map
+ rowsetAliasMap.put(alias, rowset);
+ }
+
+ /**
+ * removes a rowset from the alias map
+ * @param rowset
+ */
+ protected void removeRowsetFromAliasMap(DBRowSet rowset)
+ {
+ String alias = rowset.getAlias();
+ rowsetAliasMap.remove(alias);
+ }
+
}
\ No newline at end of file
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBQuery.java b/empire-db/src/main/java/org/apache/empire/db/DBQuery.java
index 9ec792b7..28a08530 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBQuery.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBQuery.java
@@ -704,5 +704,11 @@ public class DBQuery extends DBRowSet
// use column
return column;
}
+
+ @Override
+ protected DBColumn cloneColumn(DBRowSet clone, DBColumn scourceColumn)
+ {
+ throw new NotSupportedException(this, "cloneColumn");
+ }
}
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBRowSet.java b/empire-db/src/main/java/org/apache/empire/db/DBRowSet.java
index af13a444..7844e086 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBRowSet.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBRowSet.java
@@ -18,6 +18,7 @@
*/
package org.apache.empire.db;
+import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -58,11 +59,11 @@ import org.apache.empire.dbms.DBMSFeature;
import org.apache.empire.dbms.DBMSHandler;
import org.apache.empire.dbms.DBSqlPhrase;
import org.apache.empire.exceptions.InvalidArgumentException;
+import org.apache.empire.exceptions.InvalidOperationException;
import org.apache.empire.exceptions.ItemNotFoundException;
import org.apache.empire.exceptions.NotSupportedException;
import org.apache.empire.exceptions.ObjectNotValidException;
import org.apache.empire.exceptions.UnexpectedReturnValueException;
-import org.apache.empire.exceptions.InvalidOperationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -1240,6 +1241,68 @@ public abstract class DBRowSet extends DBExpr implements EntityType
{
record.rowsetData = rowsetData;
}
+
+ /**
+ * Clone columns
+ * @param clone
+ * @throws CloneNotSupportedException
+ */
+ protected <T extends DBRowSet> void initClonedFields(T clone) throws CloneNotSupportedException
+ {
+ // clone all columns
+ Class<?> colClass = columns.get(0).getClass();
+ Class<?> colBase = colClass.getSuperclass();
+ clone.columns = new ArrayList<DBColumn>();
+ Field[] fields = getClass().getFields();
+ for (int i = 0; i < columns.size(); i++)
+ {
+ DBColumn srcCol = columns.get(i);
+ DBColumn newCol = cloneColumn(clone, srcCol);
+ // Replace all references for oldCol to newCol
+ for (int j = 0; j < fields.length; j++)
+ { // Find a class of Type DBColumn or DBTableColumn
+ Field f = fields[j];
+ Class<?> type = f.getType();
+ if (type == colClass || type == colBase)
+ { try
+ { // Check if the field points to the old Value
+ if (f.get(clone) == srcCol)
+ { // Check accessible
+ if (f.isAccessible()==false)
+ { // not accessible
+ f.setAccessible(true);
+ try {
+ f.set(clone, newCol);
+ } finally {
+ f.setAccessible(false);
+ }
+ }
+ else
+ { // already accessible
+ f.set(clone, newCol);
+ }
+ }
+ } catch (Exception e) {
+ // IllegalAccessException or IllegalArgumentException
+ String fieldName = fields[j].getName();
+ log.error("Failed to modify declared table field: " + fieldName + ". Reason is: " + e.toString());
+ // throw CloneNotSupportedException
+ CloneNotSupportedException cnse = new CloneNotSupportedException("Unable to replace field reference for field " + fieldName);
+ cnse.initCause(e);
+ throw cnse;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Clones a RowSet column
+ * @param clone the clonded rowset
+ * @param scourceColumn
+ * @return the cloned column
+ */
+ protected abstract DBColumn cloneColumn(DBRowSet clone, DBColumn scourceColumn);
}
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBTable.java b/empire-db/src/main/java/org/apache/empire/db/DBTable.java
index 9699a2fa..971771bd 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBTable.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBTable.java
@@ -18,8 +18,6 @@
*/
package org.apache.empire.db;
-// java
-import java.lang.reflect.Field;
import java.sql.Connection;
import java.text.MessageFormat;
import java.util.ArrayList;
@@ -37,11 +35,11 @@ import org.apache.empire.db.exceptions.NoPrimaryKeyException;
import org.apache.empire.db.exceptions.RecordDeleteFailedException;
import org.apache.empire.db.exceptions.RecordUpdateFailedException;
import org.apache.empire.exceptions.InvalidArgumentException;
+import org.apache.empire.exceptions.InvalidOperationException;
import org.apache.empire.exceptions.ItemExistsException;
import org.apache.empire.exceptions.NotSupportedException;
import org.apache.empire.exceptions.ObjectNotValidException;
import org.apache.empire.exceptions.UnexpectedReturnValueException;
-import org.apache.empire.exceptions.InvalidOperationException;
/**
@@ -175,10 +173,13 @@ public class DBTable extends DBRowSet implements Cloneable
{
DBTable clone = (DBTable) super.clone();
initClonedFields(clone);
+ // set primaryKey
+ clone.primaryKey = clonePrimaryKey(clone);
// set new alias
clone.alias = "t" + String.valueOf(tableCount.incrementAndGet());
// done
log.info("clone: Table " + name + " cloned! Alias old=" + alias + " new=" + clone.alias);
+ db.addTable(clone);
return clone;
}
@@ -188,6 +189,8 @@ public class DBTable extends DBRowSet implements Cloneable
try {
DBTable clone = (DBTable) super.clone();
initClonedFields(clone);
+ // set primaryKey
+ clone.primaryKey = clonePrimaryKey(clone);
// set new alias
if (StringUtils.isEmpty(newAlias))
clone.alias = "t" + String.valueOf(tableCount.incrementAndGet());
@@ -195,6 +198,7 @@ public class DBTable extends DBRowSet implements Cloneable
clone.alias = newAlias;
// done
log.info("clone: Table " + name + " cloned! Alias old=" + alias + " new=" + clone.alias);
+ db.addTable(clone);
return (T)clone;
} catch (CloneNotSupportedException e) {
// unable to clone table
@@ -203,53 +207,24 @@ public class DBTable extends DBRowSet implements Cloneable
}
}
- protected <T extends DBTable> void initClonedFields(T clone) throws CloneNotSupportedException
- {
- // clone all columns
- Class<?> colClass = columns.get(0).getClass();
- Class<?> colBase = colClass.getSuperclass();
- clone.columns = new ArrayList<DBColumn>();
- Field[] fields = getClass().getFields();
- for (int i = 0; i < columns.size(); i++)
- {
- DBTableColumn srcCol = (DBTableColumn) columns.get(i);
- DBTableColumn newCol = new DBTableColumn(clone, srcCol);
- // Replace all references for oldCol to newCol
- for (int j = 0; j < fields.length; j++)
- { // Find a class of Type DBColumn or DBTableColumn
- Field f = fields[j];
- Class<?> type = f.getType();
- if (type == colClass || type == colBase)
- { try
- { // Check if the field points to the old Value
- if (f.get(clone) == srcCol)
- { // Check accessible
- if (f.isAccessible()==false)
- { // not accessible
- f.setAccessible(true);
- try {
- f.set(clone, newCol);
- } finally {
- f.setAccessible(false);
- }
- }
- else
- { // already accessible
- f.set(clone, newCol);
- }
- }
- } catch (Exception e) {
- // IllegalAccessException or IllegalArgumentException
- String fieldName = fields[j].getName();
- log.error("Failed to modify declared table field: " + fieldName + ". Reason is: " + e.toString());
- // throw CloneNotSupportedException
- CloneNotSupportedException cnse = new CloneNotSupportedException("Unable to replace field reference for field " + fieldName);
- cnse.initCause(e);
- throw cnse;
- }
- }
- }
- }
+ @Override
+ protected DBColumn cloneColumn(DBRowSet clone, DBColumn sourceColumn)
+ {
+ DBTableColumn newCol = new DBTableColumn((DBTable)clone, (DBTableColumn)sourceColumn);
+ return newCol;
+ }
+
+ protected DBIndex clonePrimaryKey(DBRowSet clone)
+ {
+ if (this.primaryKey==null)
+ return null;
+ // clone columns
+ DBColumn[] source = this.primaryKey.getColumns();
+ DBColumn[] columns = new DBColumn[source.length];
+ for (int i=0; i<source.length; i++)
+ columns[i] = clone.getColumn(getColumnIndex(source[i]));
+ // Create clone
+ return new DBIndex(this.primaryKey.getName(), DBIndexType.PRIMARY_KEY, columns);
}
/**
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBView.java b/empire-db/src/main/java/org/apache/empire/db/DBView.java
index 98e40953..a7c227e7 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBView.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBView.java
@@ -36,7 +36,7 @@ import org.w3c.dom.Element;
* This class represents a database view.
* It contains methods to get and update records from the database
*/
-public abstract class DBView extends DBRowSet
+public abstract class DBView extends DBRowSet implements Cloneable
{
// *Deprecated* private static final long serialVersionUID = 1L;
@@ -81,6 +81,28 @@ public abstract class DBView extends DBRowSet
if (view != null)
view.addColumn(this);
}
+
+ /**
+ * Copy constructor
+ * @param view
+ * @param other
+ */
+ protected DBViewColumn(DBView view, DBViewColumn other)
+ { // call base
+ super(view, other.getName());
+ // set Expression
+ this.expr = other.expr;
+ this.dataType = other.dataType;
+ this.updateColumn = other.updateColumn;
+ this.size = other.size;
+ // Copy enumType
+ Class<Enum<?>> enumType = other.getEnumType();
+ if (enumType!=null)
+ setAttribute(Column.COLATTR_ENUMTYPE, enumType);
+ // Add to view
+ if (view != null)
+ view.addColumn(this);
+ }
public DBColumnExpr getSourceColumnExpr()
{
@@ -262,6 +284,73 @@ public abstract class DBView extends DBRowSet
this(name, db, false);
}
+ /**
+ * Allows a second instance of a view with a different alias
+ * @return another instance of the view
+ */
+ @Override
+ public Object clone() throws CloneNotSupportedException
+ {
+ DBView clone = (DBView) super.clone();
+ initClonedFields(clone);
+ // set key columns
+ clone.keyColumns = cloneKeyColumns(clone);
+ // set new alias
+ clone.alias = "v" + String.valueOf(viewCount.incrementAndGet());
+ // done
+ log.info("clone: Table " + name + " cloned! Alias old=" + alias + " new=" + clone.alias);
+ db.addView(clone);
+ return clone;
+ }
+
+ /**
+ * Allows a second instance of a view with a different alias
+ * @param newAlias the new alias
+ * @return another instance of the view
+ */
+ @SuppressWarnings("unchecked")
+ public <T extends DBView> T clone(String newAlias)
+ {
+ try {
+ DBView clone = (DBView) super.clone();
+ initClonedFields(clone);
+ // set key columns
+ clone.keyColumns = cloneKeyColumns(clone);
+ // set new alias
+ if (StringUtils.isEmpty(newAlias))
+ clone.alias = "t" + String.valueOf(viewCount.incrementAndGet());
+ else
+ clone.alias = newAlias;
+ // done
+ log.info("clone: Table " + name + " cloned! Alias old=" + alias + " new=" + clone.alias);
+ db.addView(clone);
+ return (T)clone;
+ } catch (CloneNotSupportedException e) {
+ // unable to clone table
+ log.error("Unable to clone table " + getName());
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ protected DBColumn cloneColumn(DBRowSet clone, DBColumn sourceColumn)
+ {
+ DBViewColumn newCol = new DBViewColumn((DBView)clone, (DBViewColumn)sourceColumn);
+ return newCol;
+ }
+
+ protected DBViewColumn[] cloneKeyColumns(DBView clone)
+ {
+ if (this.keyColumns==null)
+ return null;
+ // clone columns
+ DBViewColumn[] columns = new DBViewColumn[keyColumns.length];
+ for (int i=0; i<keyColumns.length; i++)
+ columns[i] = (DBViewColumn)clone.getColumn(getColumnIndex(keyColumns[i]));
+ // Create clone
+ return columns;
+ }
+
/**
* Returns an array of all key columns.
* @return an array of all key columns
diff --git a/empire-db/src/main/java/org/apache/empire/db/expr/compare/DBCompareColExpr.java b/empire-db/src/main/java/org/apache/empire/db/expr/compare/DBCompareColExpr.java
index d1ae5791..1d344406 100644
--- a/empire-db/src/main/java/org/apache/empire/db/expr/compare/DBCompareColExpr.java
+++ b/empire-db/src/main/java/org/apache/empire/db/expr/compare/DBCompareColExpr.java
@@ -56,7 +56,7 @@ public class DBCompareColExpr extends DBCompareExpr
protected final DBColumnExpr expr;
protected final DBCmpType cmpop;
protected Object value;
-
+ protected boolean parenthesis = false;
/**
* Constructs a DBCompareColExpr object set the specified parameters to this object.
*
@@ -132,6 +132,15 @@ public class DBCompareColExpr extends DBCompareExpr
this.value = value;
}
+ /**
+ * wraps the expression in parenthesises
+ */
+ public DBCompareColExpr parenthesis()
+ {
+ this.parenthesis = true;
+ return this;
+ }
+
/**
* Prepare function
* @param cmd
@@ -300,10 +309,16 @@ public class DBCompareColExpr extends DBCompareExpr
sql.appendValue(expr.getDataType(), value, context, null);
return;
}
+ // begin
+ if (this.parenthesis)
+ sql.append("(");
// Add Compare Expression
expr.addSQL(sql, context);
// Add Comparison Value
addCompareExpr(sql, context);
+ // end
+ if (this.parenthesis)
+ sql.append(")");
}
/**