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 08f92b1  EMPIREDB-362 SampleDB enhancements
08f92b1 is described below

commit 08f92b1b47b15a8251b07946348e1d7d0e5526c7
Author: Rainer Döbele <[email protected]>
AuthorDate: Tue Jan 25 12:11:01 2022 +0100

    EMPIREDB-362 SampleDB enhancements
---
 .../empire-db-example-basic/config.xml             | 11 ++-
 .../org/apache/empire/samples/db/SampleApp.java    | 80 ++++++++++++----------
 .../main/java/org/apache/empire/db/DBRecord.java   |  5 ++
 .../main/java/org/apache/empire/db/DBRowSet.java   | 11 ++-
 .../apache/empire/db/context/DBContextStatic.java  |  8 +--
 .../org/apache/empire/xml/XMLConfiguration.java    |  2 +-
 6 files changed, 69 insertions(+), 48 deletions(-)

diff --git a/empire-db-examples/empire-db-example-basic/config.xml 
b/empire-db-examples/empire-db-example-basic/config.xml
index 49fb734..2db9cf7 100644
--- a/empire-db-examples/empire-db-example-basic/config.xml
+++ b/empire-db-examples/empire-db-example-basic/config.xml
@@ -131,7 +131,14 @@
                        <!-- layout class="org.apache.log4j.TTCCLayout"/ -->
                        <layout class="org.apache.log4j.PatternLayout">
                                <!-- param name="ConversionPattern" 
value="NSB(%c) %-5p %m      at %l%n"/ -->
-                               <param name="ConversionPattern" value="%-5p 
[%d{yyyy/MM/dd HH:mm}]: %m          at %l %n"/>
+                               <param name="ConversionPattern" value="%-5p : 
%m                at %l %n"/>
+                       </layout>
+               </appender>
+
+               <appender name="sample" 
class="org.apache.log4j.ConsoleAppender">
+                       <layout class="org.apache.log4j.PatternLayout">
+                               <!-- param name="ConversionPattern" 
value="NSB(%c) %-5p %m      at %l%n"/ -->
+                               <param name="ConversionPattern" value="%-5p : 
*** %m *** %n"/>
                        </layout>
                </appender>
        
@@ -164,7 +171,7 @@
 
                <logger name="org.apache.empire.samples.db" additivity="false">
                        <level value="debug"/>
-                       <appender-ref ref="default"/>
+                       <appender-ref ref="sample"/>
                </logger>
 
                <root>
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 0c4ce41..57afacd 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
@@ -80,32 +80,32 @@ public class SampleApp
                        // Init Configuration
                        config.init((args.length > 0 ? args[0] : "config.xml" 
));
 
-                       System.out.println("Running DB Sample...");
+                       log.info("Running DB Sample...");
 
                        // STEP 1: Get a JDBC Connection
-                       System.out.println("*** Step 1: getJDBCConnection() 
***");
+                       log.info("Step 1: getJDBCConnection()");
                        
                        Connection conn = getJDBCConnection();
 
                        // STEP 2: Choose a DBMSHandler
-                       System.out.println("*** Step 2: getDatabaseProvider() 
***");
+                       log.info("Step 2: getDatabaseProvider()");
                        DBMSHandler dbms = 
getDBMSHandler(config.getDatabaseProvider(), conn);
                        
             // STEP 2.2: Create a Context
                        context = new DBContextStatic(dbms, conn, false, true); 
 
             // STEP 3: Open Database (and create if not existing)
-            System.out.println("*** Step 3: openDatabase() ***");
+            log.info("Step 3: openDatabase()");
                        try {
                            // Open the database
                 db.open(context);
                 // Check whether database exists
                            databaseExists();
-                System.out.println("*** Database already exists. Skipping 
Step4 ***");
+                log.info("Database already exists. Skipping Step4");
                 
                        } catch(Exception e) {
                 // STEP 4: Create Database
-                System.out.println("*** Step 4: createDDL() ***");
+                log.info("Step 4: createDDL()");
                 // postgre does not support DDL in transaction
                 if(db.getDbms() instanceof DBMSHandlerPostgreSQL)
                 {
@@ -122,11 +122,11 @@ public class SampleApp
                        }
 
                        // STEP 5: Clear Database (Delete all records)
-                       System.out.println("*** Step 5: clearDatabase() ***");
+                       log.info("Step 5: clearDatabase()");
                        clearDatabase();
 
                        // STEP 6: Insert Departments
-                       System.out.println("*** Step 6: insertDepartment() & 
insertEmployee() ***");
+                       log.info("Step 6: insertDepartment() & 
insertEmployee()");
                        int idDevDep = insertDepartment("Development", "ITTK");
                        int idSalDep = insertDepartment("Sales", "ITTK");
                        // Insert Employees
@@ -147,7 +147,7 @@ public class SampleApp
             */
 
                        // STEP 7: Update Records (by setting the phone Number)
-                       System.out.println("*** Step 7: updateEmployee() ***");
+                       log.info("Step 7: updateEmployee()");
                        updateEmployee(idEmp1, "+49-7531-457160");
                        updateEmployee(idEmp2, "+49-5555-505050");
                        // Partial Record
@@ -159,28 +159,26 @@ public class SampleApp
                        context.commit();
 
                        // STEP 8: Option 1: Query Records and print 
tab-separated
-                       System.out.println("*** Step 8 Option 1: queryRecords() 
/ Tab-Output ***");
+                       log.info("Step 8 Option 1: queryRecords() / 
Tab-Output");
                        queryRecords(QueryType.Reader); // Tab-Output
 
             // STEP 8: Option 2: Query Records as a list of java beans
-            System.out.println("*** Step 8 Option 2: queryRecords() / 
Bean-List-Output ***");
+            log.info("Step 8 Option 2: queryRecords() / Bean-List-Output");
             queryRecords(QueryType.BeanList); // Bean-List-Output
 
                        // STEP 8: Option 3: Query Records as XML
-                       System.out.println("*** Step 8 Option 3: queryRecords() 
/ XML-Output ***");
+                       log.info("Step 8 Option 3: queryRecords() / 
XML-Output");
                        queryRecords(QueryType.XmlDocument); // XML-Output
 
                        // STEP 9: Use Bean Result to query beans
                        queryBeans(conn);
                        
                        // Done
-                       System.out.println("DB Sample finished successfully.");
+                       log.info("DB Sample finished successfully.");
 
                } catch (Exception e)
-        {
-                       // Error
-                       System.out.println(e.toString());
-                       e.printStackTrace();
+        {      // Error
+                       log.error("Running SampleApp failed with Exception" + 
e.toString(), e);
                        
                } finally {
                    context.discard();
@@ -208,7 +206,7 @@ public class SampleApp
                        // set the AutoCommit to false for this connection. 
                        // commit must be called explicitly! 
                        conn.setAutoCommit(false);
-                       log.info("AutoCommit is " + conn.getAutoCommit());
+                       log.info("AutoCommit has been set to " + 
conn.getAutoCommit());
 
                } catch (Exception e)
         {
@@ -266,7 +264,7 @@ public class SampleApp
                DBCommand cmd = db.createCommand();
                cmd.select(db.DEPARTMENTS.count());
                // Check using "select count(*) from DEPARTMENTS"
-               System.out.println("Checking whether table DEPARTMENTS exists 
(SQLException will be logged if not - please ignore) ...");
+               log.info("Checking whether table DEPARTMENTS exists 
(SQLException will be logged if not - please ignore) ...");
                return (context.getUtils().querySingleInt(cmd, -1) >= 0);
        }
 
@@ -282,7 +280,7 @@ public class SampleApp
            DBSQLScript script = new DBSQLScript(context);
                db.getCreateDDLScript(script);
                // Show DDL Statement
-               System.out.println(script.toString());
+               log.info(script.toString());
                // Execute Script
                script.executeAll(false);
                // Commit
@@ -333,7 +331,7 @@ public class SampleApp
         SampleDB.Employees EMP = db.EMPLOYEES;
                // Insert an Employee
                DBRecord rec = new DBRecord(context, EMP);
-               rec.create();
+               rec.create(null);
                rec.setValue(EMP.FIRSTNAME, firstName);
                rec.setValue(EMP.LASTNAME, lastName);
                rec.setValue(EMP.GENDER, gender);
@@ -567,8 +565,9 @@ public class SampleApp
     {
         int lastYear = LocalDate.now().getYear()-1;
            
-           // Define the query
+           // Create a command
            DBCommand cmd = db.createCommand();
+           
            // Define shortcuts for tables used - not necessary but convenient
            SampleDB.Employees   EMP = db.EMPLOYEES;
            SampleDB.Departments DEP = db.DEPARTMENTS;
@@ -590,23 +589,28 @@ public class SampleApp
         DBColumnExpr PHONE_EXT_NUMBER = 
EMP.PHONE_NUMBER.substring(PHONE_LAST_DASH).as("PHONE_EXTENSION");
 
         // DBColumnExpr genderExpr = 
cmd.select(EMP.GENDER.decode(EMP.GENDER.getOptions()).as(EMP.GENDER.getName()));
-        // Select required columns
+
+        // Select Employee and Department columns
         cmd.select(EMP.ID, EMPLOYEE_FULLNAME);
         cmd.select(EMP.GENDER, EMP.PHONE_NUMBER, PHONE_EXT_NUMBER);
         cmd.select(DEP.NAME.as("DEPARTMENT"));
         cmd.select(DEP.BUSINESS_UNIT);
-        // add payment of current year
-        cmd.groupBy(cmd.getSelectExprList());
+        // Add payment of last year using a SUM aggregation
+        cmd.groupBy(cmd.getSelectExpressions());
         cmd.select(PAYMENTS_LAST_YEAR);
-        // join
+        // Joins
         cmd.join(EMP.DEPARTMENT_ID, DEP.ID);
         cmd.joinLeft(EMP.ID, PAY.EMPLOYEE_ID).where(PAY.YEAR.is(lastYear));
-        // Set constraints and order
+        // Where constraints
+        cmd.where(EMP.RETIRED.is(false));
         cmd.where(EMP.LASTNAME.length().isGreaterThan(0));
+        // Order by
         cmd.orderBy(EMPLOYEE_FULLNAME);
 
         /*
-        // Example for limitRows() and skipRows()
+         * Example for limitRows() and skipRows()
+         * Uncomment if you wish
+         *
         if (db.getDbms().isSupported(DBMSFeature.QUERY_LIMIT_ROWS))
         {      // set maximum number of rows
                cmd.limitRows(20);
@@ -619,9 +623,10 @@ public class SampleApp
                DBReader reader = new DBReader(context);
                try
         {
-                       // Open Reader
-                       System.out.println("Running Query:");
-                       System.out.println(cmd.getSelect());
+                   // log select statement (but only once)
+                   if (queryType==QueryType.Reader)
+                       log.info("Running Query: {}", cmd.getSelect());
+                   // Open Reader 
                        reader.open(cmd);
                        // Print output
                        System.out.println("---------------------------------");
@@ -642,7 +647,7 @@ public class SampleApp
                 case BeanList:
                     // Text-Output using a list of Java Beans supplied by the 
DBReader
                     List<SampleBean> beanList = 
reader.getBeanList(SampleBean.class);
-                    System.out.println(String.valueOf(beanList.size()) + " 
SampleBeans returned from Query.");
+                    // log.info(String.valueOf(beanList.size()) + " 
SampleBeans returned from Query.");
                     for (SampleBean b : beanList)
                     {
                         System.out.println(b.toString());
@@ -655,10 +660,9 @@ public class SampleApp
                     XMLWriter.debug(doc);
                     break;
                        }
-
-               } finally
-        {
-                       // always close Reader
+            System.out.println("---------------------------------");
+               } finally  {
+                       // Always close Reader!
                        reader.close();
                }
        }
@@ -671,13 +675,13 @@ public class SampleApp
         result.getCommand().where(EMP.GENDER.is(Gender.M));
            result.fetch(context);
            
-           System.out.println("Number of male employees is: "+result.size());
+           log.info("Number of male employees is: "+result.size());
 
            // And now, the females
            result.getCommand().where(EMP.GENDER.is(Gender.F));
            result.fetch(context);
            
-        System.out.println("Number of female employees is: "+result.size());
+        log.info("Number of female employees is: "+result.size());
        }
        
 }
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 c6e86a8..f6b4717 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
@@ -46,6 +46,7 @@ import org.apache.empire.exceptions.InvalidArgumentException;
 import org.apache.empire.exceptions.ItemNotFoundException;
 import org.apache.empire.exceptions.NotSupportedException;
 import org.apache.empire.exceptions.ObjectNotValidException;
+import org.apache.empire.exceptions.UnspecifiedErrorException;
 import org.apache.empire.xml.XMLUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -799,6 +800,10 @@ public class DBRecord extends DBRecordData implements 
DBContextAware, Record, Cl
      */
        public void setRollbackHandlingEnabled(boolean enabled) 
        {
+           // check
+           if (enabled && !context.isRollbackHandlingEnabled())
+               throw new UnspecifiedErrorException("Rollback handling cannot 
be enabled for this record since it is not supported for this context!");
+           // enable now
                this.enableRollbackHandling = enabled;
        }
 
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 2d1a5c5..897cd7d 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
@@ -34,6 +34,7 @@ import org.apache.empire.data.Column;
 import org.apache.empire.data.DataType;
 import org.apache.empire.db.DBRelation.DBCascadeAction;
 import org.apache.empire.db.DBRelation.DBReference;
+import org.apache.empire.db.exceptions.FieldIsReadOnlyException;
 import org.apache.empire.db.exceptions.FieldNotNullException;
 import org.apache.empire.db.exceptions.InvalidKeyException;
 import org.apache.empire.db.exceptions.NoPrimaryKeyException;
@@ -43,8 +44,8 @@ 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.dbms.DBMSHandler;
 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.ItemNotFoundException;
@@ -530,8 +531,12 @@ public abstract class DBRowSet extends DBExpr
         {   // Check Columns
             DBColumn[] keyColumns = primaryKey.getColumns();
             for (int i = 0; i < keyColumns.length; i++)
-            { // Ignore Validity Checks
-                int field = getColumnIndex(keyColumns[i]);
+            {   // check
+                DBColumn keyColumn = keyColumns[i]; 
+                if (newRecord && keyColumn.isAutoGenerated())
+                    throw new FieldIsReadOnlyException(keyColumn);
+                // Ignore Validity Checks
+                int field = getColumnIndex(keyColumn);
                 fields[field] = keyValues[i];
             }
         }
diff --git 
a/empire-db/src/main/java/org/apache/empire/db/context/DBContextStatic.java 
b/empire-db/src/main/java/org/apache/empire/db/context/DBContextStatic.java
index 5ffda53..2085a6f 100644
--- a/empire-db/src/main/java/org/apache/empire/db/context/DBContextStatic.java
+++ b/empire-db/src/main/java/org/apache/empire/db/context/DBContextStatic.java
@@ -45,7 +45,7 @@ public class DBContextStatic extends DBContextBase
      */
     public DBContextStatic(DBMSHandler dbmsHandler, Connection conn)
     {
-        this(dbmsHandler, conn, (conn!=null), false);
+        this(dbmsHandler, conn, false, false);
     }
     
     /**
@@ -81,11 +81,11 @@ public class DBContextStatic extends DBContextBase
         super.discard();
         // close
         if (closeOnDiscard) 
-        {   // Close the connection
-            closeConnection();
-            // rollbackManager release
+        {   // rollbackManager release
             if (enableRollbackHandling)
                 staticRollbackManager.releaseConnection(conn, 
ReleaseAction.Discard);
+            // Close the connection
+            closeConnection();
         }
     }
 
diff --git 
a/empire-db/src/main/java/org/apache/empire/xml/XMLConfiguration.java 
b/empire-db/src/main/java/org/apache/empire/xml/XMLConfiguration.java
index 30b1ab0..3c54700 100644
--- a/empire-db/src/main/java/org/apache/empire/xml/XMLConfiguration.java
+++ b/empire-db/src/main/java/org/apache/empire/xml/XMLConfiguration.java
@@ -215,7 +215,7 @@ public class XMLConfiguration
             log.error("Unable to set Property {}", name);
         } catch (NoSuchMethodException e)
         {
-            log.error("Property '{}' not found in {}", name, 
bean.getClass().getName());
+            log.warn("Property '{}' not found in {}. Will be ingored.", name, 
bean.getClass().getName());
         }
     }
     

Reply via email to