This is an automated email from the ASF dual-hosted git repository.

doebele pushed a commit to branch version3
in repository https://gitbox.apache.org/repos/asf/empire-db.git


The following commit(s) were added to refs/heads/version3 by this push:
     new 65c7456  EMPIREDB-362 cleanup
65c7456 is described below

commit 65c7456d23acc3b3c697b7b0a3efe5999f97e61d
Author: Rainer Döbele <[email protected]>
AuthorDate: Fri Jan 21 17:57:52 2022 +0100

    EMPIREDB-362
    cleanup
---
 .../org/apache/empire/samples/db/SampleApp.java    | 60 ++++++++++++++---
 .../main/java/org/apache/empire/db/DBQuery.java    | 32 ++++-----
 .../main/java/org/apache/empire/db/DBReader.java   |  2 +-
 .../main/java/org/apache/empire/db/DBRecord.java   | 77 ++++++++--------------
 .../main/java/org/apache/empire/db/DBRowSet.java   | 47 +++++++++++--
 .../main/java/org/apache/empire/db/DBUtils.java    |  4 +-
 6 files changed, 139 insertions(+), 83 deletions(-)

diff --git 
a/empire-db-examples/empire-db-example-basic/src/main/java/org/apache/empire/samples/db/SampleApp.java
 
b/empire-db-examples/empire-db-example-basic/src/main/java/org/apache/empire/samples/db/SampleApp.java
index 7613da8..726344a 100644
--- 
a/empire-db-examples/empire-db-example-basic/src/main/java/org/apache/empire/samples/db/SampleApp.java
+++ 
b/empire-db-examples/empire-db-example-basic/src/main/java/org/apache/empire/samples/db/SampleApp.java
@@ -28,8 +28,10 @@ import org.apache.empire.db.DBColumnExpr;
 import org.apache.empire.db.DBCommand;
 import org.apache.empire.db.DBContext;
 import org.apache.empire.db.DBDatabaseDriver;
+import org.apache.empire.db.DBQuery;
 import org.apache.empire.db.DBReader;
 import org.apache.empire.db.DBRecord;
+import org.apache.empire.db.DBRowSet.PartialMode;
 import org.apache.empire.db.DBSQLScript;
 import org.apache.empire.db.DBUtils;
 import org.apache.empire.db.context.DBContextStatic;
@@ -126,9 +128,9 @@ public class SampleApp
                        int idDevDep = insertDepartment("Development", "ITTK");
                        int idSalDep = insertDepartment("Sales", "ITTK");
                        // Insert Employees
-                       int idPers1 = insertEmployee("Peter", "Sharp", 
Gender.M, idDevDep);
-                       int idPers2 = insertEmployee("Fred", "Bloggs", 
Gender.M, idDevDep);
-                       int idPers3 = insertEmployee("Emma", "White",  
Gender.F, idSalDep);
+                       int idEmp1 = insertEmployee("Peter", "Sharp", Gender.M, 
idDevDep);
+                       int idEmp2 = insertEmployee("Fred", "Bloggs", Gender.M, 
idDevDep);
+                       int idEmp3 = insertEmployee("Emma", "White",  Gender.F, 
idSalDep);
 
             // commit
                        context.commit();
@@ -139,9 +141,12 @@ public class SampleApp
 
                        // STEP 7: Update Records (by setting the phone Number)
                        System.out.println("*** Step 7: updateEmployee() ***");
-                       updateEmployee(idPers1, "+49-7531-457160");
-                       updateEmployee(idPers2, "+49-5555-505050");
-                       updateEmployee(idPers3, "+49-040-125486");
+                       updateEmployee(idEmp1, "+49-7531-457160");
+                       updateEmployee(idEmp2, "+49-5555-505050");
+                       // Partial Record
+            updatePartialRecord(idEmp3, "+49-040-125486");
+                       // Update Joined Records (Make Fred Bloggs head of 
department and set salary)
+                       updateJoinedRecords(idEmp2, 100000);
 
                        // commit
                        context.commit();
@@ -333,16 +338,55 @@ public class SampleApp
         * Updates an employee record by setting the phone number.
      * </PRE>
         */
-       private static void updateEmployee(int idPers, String phoneNumber)
+       private static void updateEmployee(int idEmp, String phoneNumber)
     {
                // Update an Employee
                DBRecord rec = new DBRecord(context, db.EMPLOYEES);
-               rec.read(idPers);
+               rec.read(idEmp);
                // Set
                rec.setValue(db.EMPLOYEES.PHONE_NUMBER, phoneNumber);
                rec.update();
        }
 
+    /**
+     * <PRE>
+     * Updates an employee record by setting the phone number.
+     * </PRE>
+     */
+    private static void updatePartialRecord(int idEmp, String phoneNumber)
+    {
+        // Update an Employee
+        DBRecord rec = new DBRecord(context, db.EMPLOYEES);
+        db.EMPLOYEES.readRecord(rec, DBRecord.key(idEmp), PartialMode.INCLUDE, 
db.EMPLOYEES.PHONE_NUMBER);
+        // Set
+        rec.setValue(db.EMPLOYEES.PHONE_NUMBER, phoneNumber);
+        rec.update();
+    }
+
+    /**
+     * <PRE>
+     * Updates an employee record by setting the phone number.
+     * </PRE>
+     */
+    private static void updateJoinedRecords(int idEmp, int salary)
+    {
+        SampleDB.Employees E = db.EMPLOYEES;
+        SampleDB.Departments D = db.DEPARTMENTS;
+        
+        DBCommand cmd = db.createCommand();
+        cmd.select(E.getColumns());
+        cmd.select(D.getColumns());
+        cmd.join(E.DEPARTMENT_ID, D.DEPARTMENT_ID);
+
+        // Make employee Head of Department and update salary
+        DBQuery query = new DBQuery(cmd, E.EMPLOYEE_ID);
+        DBRecord rec = new DBRecord(context, query);
+        rec.read(idEmp);
+        rec.setValue(E.SALARY, salary);
+        rec.setValue(D.HEAD, rec.getString(E.LASTNAME));
+        rec.update();
+    }
+
        /**
         * @param context
         * @param idDep
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 1015358..5b91c56 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
@@ -312,7 +312,10 @@ public class DBQuery extends DBRowSet
         if (record == null || record.getRowSet() != this)
             throw new InvalidArgumentException("record", record);
         // get Key
-        return (Object[]) record.getRowSetData();
+        Object rowSetData = record.getRowSetData();
+        if (rowSetData==null)
+            log.warn("No Record-key provided for query record!");
+        return (Object[])rowSetData;
     }
 
     /**
@@ -403,9 +406,7 @@ public class DBQuery extends DBRowSet
         // Read Record
         try {
             // Read Record
-            readRecord(rec, cmd);
-            // Set RowSetData
-            rec.onUpdateComplete(key.clone());
+            readRecord(rec, cmd, key.clone()); 
         } catch (QueryNoResultException e) {
             // Record not found
             throw new RecordNotFoundException(this, key);
@@ -469,7 +470,7 @@ public class DBQuery extends DBRowSet
         Connection conn = rec.getContext().getConnection();
         // the commands
         DBCommand cmd = getCommandFromExpression();
-        Object[] keys = (Object[]) rec.getRowSetData();
+        Object[] key  = getRecordKey(rec);
         DBRowSet table= null;
         DBCommand upd = null;
         for(Entry<DBRowSet,DBCommand> entry:updCmds.entrySet())
@@ -491,10 +492,10 @@ public class DBQuery extends DBRowSet
                 DBColumn left  = join.getLeft() .getUpdateColumn();
                 DBColumn right = join.getRight().getUpdateColumn();
                 if (left.getRowSet()==table && table.isKeyColumn(left))
-                    if (!addJoinRestriction(upd, left, right, keyColumns, rec))
+                    if (!addJoinRestriction(upd, left, right, keyColumns, key, 
rec))
                         throw new ItemNotFoundException(left.getFullName());
                 if (right.getRowSet()==table && table.isKeyColumn(right))
-                    if (!addJoinRestriction(upd, right, left, keyColumns, rec))
+                    if (!addJoinRestriction(upd, right, left, keyColumns, key, 
rec))
                         throw new ItemNotFoundException(right.getFullName());
             }
             // Evaluate Existing restrictions
@@ -527,7 +528,7 @@ public class DBQuery extends DBRowSet
             {
                 if (keyColumns[i].getRowSet() == table)
                 {   // Set key column constraint
-                    Object value = keys[i];
+                    Object value = key[i];
                     if (db.isPreparedStatementsEnabled())
                         value = upd.addParam(keyColumns[i], value);
                     upd.where(keyColumns[i].is(value));
@@ -567,7 +568,7 @@ public class DBQuery extends DBRowSet
             {   // Error
                 if (affected == 0)
                 { // Record not found
-                    throw new RecordUpdateFailedException(this, keys);
+                    throw new RecordUpdateFailedException(this, key);
                 }
                 // Rollback
                 // context.rollback();
@@ -575,7 +576,7 @@ public class DBQuery extends DBRowSet
             } 
             else if (affected > 1)
             { // More than one record
-                throw new RecordUpdateInvalidException(this, keys);
+                throw new RecordUpdateInvalidException(this, key);
             } 
             else
             { // success
@@ -588,7 +589,7 @@ public class DBQuery extends DBRowSet
             }
         }
         // success
-        rec.onUpdateComplete(keys);
+        rec.updateComplete(key);
     }
 
     /**
@@ -606,13 +607,12 @@ public class DBQuery extends DBRowSet
     /**
      * Adds join restrictions to the supplied command object.
      */
-    protected boolean addJoinRestriction(DBCommand upd, DBColumn updCol, 
DBColumn keyCol, DBColumn[] keyColumns, DBRecord rec)
+    protected boolean addJoinRestriction(DBCommand upd, DBColumn updCol, 
DBColumn keyCol, DBColumn[] keyColumns, Object[] keyValues, DBRecord rec)
     {   // Find key for foreign field
-        Object rowsetData = rec.getRowSetData();
-        for (int i = 0; i < keyColumns.length; i++)
-            if (keyColumns[i]==keyCol && rowsetData!=null)
+        for (int i = 0; keyValues!=null && i < keyColumns.length; i++)
+            if (keyColumns[i]==keyCol)
             {   // Set Field from Key
-                upd.where(updCol.is(((Object[]) rowsetData)[i]));
+                upd.where(updCol.is(keyValues[i]));
                 return true;
             }
         // Not found, what about the record
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBReader.java 
b/empire-db/src/main/java/org/apache/empire/db/DBReader.java
index 43997eb..96a44ce 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBReader.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBReader.java
@@ -655,7 +655,7 @@ public class DBReader extends DBRecordData implements 
DBContextAware
     {
         // init Record
         DBRowSet rowset = rec.getRowSet();
-       rowset.initRecord(rec, this);
+       rowset.initRecord(rec, this, null);
     }
 
     /**
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBRecord.java 
b/empire-db/src/main/java/org/apache/empire/db/DBRecord.java
index bf04d55..3e4f183 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBRecord.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBRecord.java
@@ -21,9 +21,7 @@ package org.apache.empire.db;
 import java.lang.reflect.InvocationTargetException;
 import java.sql.Connection;
 import java.util.Collection;
-import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
 
 import org.apache.commons.beanutils.BeanUtilsBean;
 import org.apache.commons.beanutils.PropertyUtilsBean;
@@ -72,7 +70,7 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
         private final State     state;  /* the original state */
         private Object[]        fields;
         private boolean[]       modified;
-        private Object          rowsetData;
+        private Object          rowSetData;
         
         public DBRecordRollbackHandler(DBRecord record)
         {
@@ -84,7 +82,7 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
             this.state = record.state;            
             this.modified = copy(record.modified);
             this.fields   = copy(record.fields);
-            this.rowsetData = record.rowsetData;
+            this.rowSetData = record.rowSetData;
         }
 
         @Override
@@ -128,7 +126,7 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
             record.state = this.state;
             record.fields = this.fields;
             record.modified = this.modified;
-            record.rowsetData = rowsetData;
+            record.rowSetData = rowSetData;
             // done
             log.info("Rollback for record {}[{}] performed", 
record.getRowSet().getName(), StringUtils.arrayToString(record.getKeyValues(), 
"|"));
         }
@@ -189,7 +187,7 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
      * @param parts
      * @return
      */
-    public static Object[] toKey(Object... parts)
+    public static Object[] key(Object... parts)
     {
         return parts;
     }
@@ -205,7 +203,7 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
     private Object[]        fields;
     private boolean[]       modified;
     // Special Rowset Data (usually null)
-    private Object          rowsetData;
+    private Object          rowSetData;
 
     // options
     private boolean         validateFieldValues;
@@ -221,7 +219,7 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
         rowset = null;
         fields = null;
         modified = null;
-        rowsetData = null;
+        rowSetData = null;
         validateFieldValues = true;
     }
 
@@ -244,7 +242,7 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
         this.state = State.Invalid;
         this.fields = null;
         this.modified = null;
-        this.rowsetData = null;
+        this.rowSetData = null;
         this.validateFieldValues = true;
     }
     
@@ -254,7 +252,7 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
      * @param rowSetData any further RowSet specific data
      * @param newRecord
      */
-    void initData(Object rowSetData, boolean newRecord)
+    protected void initData(Object rowSetData, boolean newRecord)
     {
         // Init rowset
         int colCount = rowset.getColumns().size();
@@ -267,12 +265,27 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
                     fields[i]=null;
         }
         // Set State
-        this.rowsetData = rowSetData;
+        this.rowSetData = rowSetData;
         this.modified = null;
         changeState((rowset==null ? State.Invalid : (newRecord ? State.New : 
State.Valid)));
     }
     
     /**
+     * This method is used internally to indicate that the record update has 
completed<BR>
+     * This will set change the record's state to Valid
+     * @param rowSetData additional data held by the rowset for this record 
(optional)
+     */
+    protected void updateComplete(Object rowSetData)
+    {
+        // change rowSetData
+        if (rowSetData!=ObjectUtils.NO_VALUE)
+            this.rowSetData = rowSetData;
+        // Change state
+        this.modified = null;
+        changeState(State.Valid);
+    }
+    
+    /**
      * changes the state of the record
      * @param newState
      */
@@ -300,7 +313,7 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
         // clear fields
         fields = null;
         modified = null;
-        rowsetData = null;
+        rowSetData = null;
         // change state
         if (state!=State.Invalid)
             changeState(State.Invalid);
@@ -322,7 +335,7 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
                 rec.fields = fields.clone();
             if (rec.modified == modified && modified!=null)
                 rec.modified = modified.clone();
-            rec.rowsetData = this.rowsetData;
+            rec.rowSetData = this.rowSetData;
             rec.validateFieldValues = this.validateFieldValues;
             return rec;
             
@@ -373,7 +386,7 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
      */
     public Object getRowSetData()
     {
-        return rowsetData;
+        return rowSetData;
     }
 
     /**
@@ -996,19 +1009,7 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
      */
     public void read(DBCompareExpr whereConstraints)
     {
-        if (whereConstraints==null)
-            throw new InvalidArgumentException("whereConstraints", null);
-        // check constraints
-        Set<DBColumn> columns = new HashSet<DBColumn>();
-        whereConstraints.addReferencedColumns(columns);
-        for (DBColumn c : columns)
-            if (!rowset.equals(c.getRowSet()))
-                throw new InvalidArgumentException("whereConstraints", 
c.getFullName());
-        // read now
-        DBCommand cmd = getDatabase().createCommand();
-        cmd.select(rowset.getColumns());
-        cmd.where(whereConstraints);
-        rowset.readRecord(this, cmd);
+        rowset.readRecord(this, whereConstraints);
     }
 
     /**
@@ -1287,16 +1288,6 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
     }
     
     /**
-     * Override this to do extra handling when the rowset for this record 
changes
-     
-    protected void onRowSetChanged()
-    {
-        if (log.isTraceEnabled() && rowset!=null)
-            log.trace("Record has been attached to rowset " + 
rowset.getName());
-    }
-    */
-    
-    /**
      * Override this to do extra handling when the record changes
      */
     protected void onRecordChanged()
@@ -1317,16 +1308,4 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
             log.debug("Record field " + rowset.getColumn(i).getName() + " 
changed to " + String.valueOf(fields[i]));
     }
     
-    /**
-     * This method is used internally to indicate that the record update has 
completed<BR>
-     * This will set change the record's state to Valid
-     * @param rowSetData additional data held by the rowset for this record 
(optional)
-     */
-    protected void onUpdateComplete(Object rowSetData)
-    {
-        this.rowsetData = rowSetData;
-        this.modified = null;
-        changeState(State.Valid);
-    }
-    
 }
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 889146c..d337f4a 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
@@ -27,6 +27,7 @@ import java.sql.Timestamp;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -45,6 +46,7 @@ import 
org.apache.empire.db.exceptions.RecordNotFoundException;
 import org.apache.empire.db.exceptions.RecordUpdateFailedException;
 import org.apache.empire.db.exceptions.RecordUpdateInvalidException;
 import org.apache.empire.db.expr.column.DBCountExpr;
+import org.apache.empire.db.expr.compare.DBCompareExpr;
 import org.apache.empire.exceptions.InvalidArgumentException;
 import org.apache.empire.exceptions.ItemNotFoundException;
 import org.apache.empire.exceptions.NotSupportedException;
@@ -104,6 +106,16 @@ public abstract class DBRowSet extends DBExpr
     protected List<DBColumn> columns          = new ArrayList<DBColumn>();
 
     /**
+     * varArgs to Array
+     * @param parts
+     * @return
+     */
+    public static DBColumn[] key(DBColumn... parts)
+    {
+        return parts;
+    }
+
+    /**
      * Constructs a DBRecord object set the current database object.
      * @param db the database object
      */
@@ -571,10 +583,10 @@ public abstract class DBRowSet extends DBExpr
      * @param rec the record object
      * @param recData the record data from which to initialized the record
      */
-    public void initRecord(DBRecord rec, DBRecordData recData)
+    protected void initRecord(DBRecord rec, DBRecordData recData, Object 
rowSetData)
     {
         // Initialize the record
-        prepareInitRecord(rec, null, false);
+        prepareInitRecord(rec, rowSetData, false);
         // Get Record Field Values
         Object[] fields = rec.getFields();
         for (int i = 0; i < fields.length; i++)
@@ -648,14 +660,14 @@ public abstract class DBRowSet extends DBExpr
      * @param cmd the SQL-Command used to query the record
      * @param conn a valid JDBC connection.
      */
-    protected void readRecord(DBRecord rec, DBCommand cmd)
+    protected void readRecord(DBRecord rec, DBCommand cmd, Object rowSetData)
     {
         DBReader reader = null;
         try
         {   // read record using a DBReader
             reader = new DBReader(rec.getContext(), false);
             reader.getRecordData(cmd);
-            initRecord(rec, reader);
+            initRecord(rec, reader, rowSetData);
             
         } finally {
             reader.close();
@@ -682,12 +694,33 @@ public abstract class DBRowSet extends DBExpr
         setKeyConstraints(cmd, key);
         try {
             // Read Record
-            readRecord(rec, cmd);
+            readRecord(rec, cmd, null);
         } catch (QueryNoResultException e) {
             // Translate exception
             throw new RecordNotFoundException(this, key);
         }
     }
+   
+    /**
+     * Reads a record from the database
+     * @param key an array of the primary key values
+     */
+    public void readRecord(DBRecord rec, DBCompareExpr whereConstraints)
+    {
+        if (whereConstraints==null)
+            throw new InvalidArgumentException("whereConstraints", null);
+        // check constraints
+        Set<DBColumn> columns = new HashSet<DBColumn>();
+        whereConstraints.addReferencedColumns(columns);
+        for (DBColumn c : columns)
+            if (c.getRowSet().equals(this)==false)
+                throw new InvalidArgumentException("whereConstraints", 
c.getFullName());
+        // read now
+        DBCommand cmd = getDatabase().createCommand();
+        cmd.select(getColumns());
+        cmd.where(whereConstraints);
+        readRecord(rec, cmd, null);
+    }
     
     /**
      * Reads the partial record for a given primary key from the database
@@ -729,7 +762,7 @@ public abstract class DBRowSet extends DBExpr
         setKeyConstraints(cmd, key);
         try {
             // Read Record
-            readRecord(rec, cmd);
+            readRecord(rec, cmd, null);
         } catch (QueryNoResultException e) {
             // Translate exception
             throw new RecordNotFoundException(this, key);
@@ -937,7 +970,7 @@ public abstract class DBRowSet extends DBExpr
                 fields[i] = timestamp;
         }
         // Change State
-        rec.onUpdateComplete(rec.getRowSetData());        
+        rec.updateComplete(ObjectUtils.NO_VALUE);        
     }
     
     /**
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBUtils.java 
b/empire-db/src/main/java/org/apache/empire/db/DBUtils.java
index 7d2adb8..4f95d57 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBUtils.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBUtils.java
@@ -24,8 +24,8 @@ import org.slf4j.LoggerFactory;
 
 public class DBUtils implements DBContextAware
 {
-    // Logger
-    protected static final Logger log = LoggerFactory.getLogger(DBUtils.class);
+    // Logger (Use logger from DBDatabase.class)
+    protected static final Logger log = 
LoggerFactory.getLogger(DBDatabase.class);
     
     // Threshold for long running queries in milliseconds
     protected long longRunndingStmtThreshold = 30000;

Reply via email to