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 2022/01/20 10:36:57 UTC
[empire-db] branch version3 updated: EMPIREDB-363 EMPIREDB-364 EMPIREDB-362
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 b4acc82 EMPIREDB-363 EMPIREDB-364 EMPIREDB-362
b4acc82 is described below
commit b4acc82a05e3dc73982c655500e02229ed074ced
Author: Rainer Döbele <do...@apache.org>
AuthorDate: Thu Jan 20 11:36:55 2022 +0100
EMPIREDB-363
EMPIREDB-364
EMPIREDB-362
---
.../apache/empire/db/codegen/WriterService.java | 1 -
.../empire/samples/db/advanced/SampleAdvApp.java | 22 +-
.../org/apache/empire/samples/db/SampleApp.java | 20 +-
.../jsf2/websample/db/records/EmployeeRecord.java | 2 +-
.../websample/web/AutheticationPhaseListener.java | 6 +-
.../jsf2/websample/web/SampleApplication.java | 10 +-
.../websample/web/pages/EmployeeDetailPage.java | 2 -
.../jsf2/websample/web/pages/EmployeeListPage.java | 4 +-
.../apache/empire/rest/app/SampleServiceApp.java | 63 +-
.../empire/rest/service/EmployeeService.java | 2 +-
.../rest/service/filter/ServiceResponseFilter.java | 35 +-
.../vue/sample/db/records/EmployeeRecord.java | 2 +-
.../org/apache/empire/jsf2/app/FacesUtils.java | 2 -
.../empire/jsf2/controls/CheckboxInputControl.java | 1 -
.../empire/jsf2/controls/RadioInputControl.java | 1 -
.../empire/jsf2/controls/TextAreaInputControl.java | 3 -
.../empire/jsf2/controls/TextInputControl.java | 2 +-
.../jsf2/pageelements/BeanListPageElement.java | 6 +-
.../jsf2/pageelements/RecordPageElement.java | 3 +-
.../empire/jsf2/utils/TagEncodingHelper.java | 1 -
.../main/java/org/apache/empire/data/DataMode.java | 39 -
.../main/java/org/apache/empire/data/DataType.java | 10 +-
.../org/apache/empire/data/bean/BeanProperty.java | 38 +-
.../org/apache/empire/data/bean/BeanResult.java | 1 -
.../java/org/apache/empire/db/DBCommandExpr.java | 4 +-
.../main/java/org/apache/empire/db/DBContext.java | 2 +
.../java/org/apache/empire/db/DBDDLGenerator.java | 1 -
.../main/java/org/apache/empire/db/DBDatabase.java | 838 +--------------------
.../org/apache/empire/db/DBDatabaseDriver.java | 114 ++-
.../src/main/java/org/apache/empire/db/DBExpr.java | 1 -
.../main/java/org/apache/empire/db/DBQuery.java | 5 +-
.../main/java/org/apache/empire/db/DBReader.java | 25 +-
.../main/java/org/apache/empire/db/DBRecord.java | 24 +-
.../main/java/org/apache/empire/db/DBRowSet.java | 25 +-
.../main/java/org/apache/empire/db/DBTable.java | 37 +-
.../java/org/apache/empire/db/DBTableColumn.java | 12 -
.../main/java/org/apache/empire/db/DBUtils.java | 732 ++++++++++++++++++
.../src/main/java/org/apache/empire/db/DBView.java | 3 +-
.../apache/empire/db/context/DBContextBase.java | 16 +
.../empire/db/derby/DBDatabaseDriverDerby.java | 1 -
.../exceptions/ConstraintViolationException.java | 6 +-
.../empire/db/exceptions/QueryFailedException.java | 8 +-
.../db/exceptions/StatementFailedException.java | 6 +-
.../apache/empire/db/h2/DBDatabaseDriverH2.java | 1 -
.../empire/db/hsql/DBDatabaseDriverHSql.java | 16 +-
.../empire/db/mysql/DBDatabaseDriverMySQL.java | 2 +-
.../apache/empire/db/mysql/MySQLDDLGenerator.java | 1 +
.../empire/db/oracle/DBDatabaseDriverOracle.java | 14 +-
.../empire/db/oracle/OracleDDLGenerator.java | 1 -
.../db/postgresql/DBDatabaseDriverPostgreSQL.java | 15 +-
.../empire/db/sqlite/DBDatabaseDriverSQLite.java | 3 +-
.../empire/db/sqlserver/DBDatabaseDriverMSSQL.java | 3 +-
.../empire/db/sqlserver/MSSqlDDLGenerator.java | 1 -
.../empire/db/validation/DBModelChecker.java | 1 -
.../java/org/apache/empire/db/DBCommandTest.java | 4 +-
.../java/org/apache/empire/db/IntegerTest.java | 3 +-
.../apache/empire/db/PreparedStatementTest.java | 2 +-
.../java/org/apache/empire/db/SerializeTest.java | 2 +-
.../apache/empire/db/expr/set/DBSetExprTest.java | 3 +-
.../empire/db/hsql/DBDatabaseDriverHSqlTest.java | 4 +-
.../db/mssql/DBDatabaseDriverMSSqlDateTest.java | 14 +-
.../empire/db/mssql/DBDatabaseDriverMSSqlTest.java | 14 +-
.../empire/db/mysql/DBDatabaseDriverMySQLTest.java | 5 +-
.../postgresql/DBDatabaseDriverPostgreSQLTest.java | 10 +-
.../db/sqlite/DBDatabaseDriverSQLiteTest.java | 4 +-
65 files changed, 1076 insertions(+), 1183 deletions(-)
diff --git a/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/WriterService.java b/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/WriterService.java
index bb158b1..d95cf19 100644
--- a/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/WriterService.java
+++ b/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/WriterService.java
@@ -228,7 +228,6 @@ public class WriterService {
switch(type){
case INTEGER:
return Long.class;
- case TEXT:
case VARCHAR:
return String.class;
case DATE:
diff --git a/empire-db-examples/empire-db-example-advanced/src/main/java/org/apache/empire/samples/db/advanced/SampleAdvApp.java b/empire-db-examples/empire-db-example-advanced/src/main/java/org/apache/empire/samples/db/advanced/SampleAdvApp.java
index 169583e..9de56ba 100644
--- a/empire-db-examples/empire-db-example-advanced/src/main/java/org/apache/empire/samples/db/advanced/SampleAdvApp.java
+++ b/empire-db-examples/empire-db-example-advanced/src/main/java/org/apache/empire/samples/db/advanced/SampleAdvApp.java
@@ -38,6 +38,7 @@ import org.apache.empire.db.DBReader;
import org.apache.empire.db.DBRecord;
import org.apache.empire.db.DBSQLScript;
import org.apache.empire.db.DBTableColumn;
+import org.apache.empire.db.DBUtils;
import org.apache.empire.db.context.DBContextStatic;
import org.apache.empire.db.exceptions.ConstraintViolationException;
import org.apache.empire.db.h2.DBDatabaseDriverH2;
@@ -97,9 +98,9 @@ public class SampleAdvApp
// Note: For custom SQL commands parameters must be explicitly declared using cmd.addCmdParam();
db.setPreparedStatementsEnabled(true);
// Open the database
- db.open(driver, conn);
+ db.open(context);
// Check whether database exists
- databaseExists(conn);
+ databaseExists();
System.out.println("*** Database already exists. Skipping Step4 ***");
} catch(Exception e) {
@@ -117,12 +118,12 @@ public class SampleAdvApp
}
// Open again
if (db.isOpen()==false)
- db.open(driver, conn);
+ db.open(context);
}
// STEP 5: Clear Database (Delete all records)
System.out.println("*** Step 5: clearDatabase() ***");
- clearDatabase(conn);
+ clearDatabase();
// STEP 6: Insert Records
// Insert Departments
@@ -288,14 +289,14 @@ public class SampleAdvApp
* Please note that in this case an error will appear in the log wich can be ingored.
* </PRE>
*/
- private static boolean databaseExists(Connection conn)
+ private static boolean databaseExists()
{
// Check whether DB exists
DBCommand cmd = db.createCommand();
cmd.select(T_DEP.count());
// Check using "select count(*) from DEPARTMENTS"
System.out.println("Checking whether table DEPARTMENTS exists (SQLException will be logged if not - please ignore) ...");
- return (db.querySingleInt(cmd, -1, conn) >= 0);
+ return (context.getUtils().querySingleInt(cmd, -1) >= 0);
}
/**
@@ -322,15 +323,16 @@ public class SampleAdvApp
* Empties all Tables.
* </PRE>
*/
- private static void clearDatabase(Connection conn)
+ private static void clearDatabase()
{
+ DBUtils utils = context.getUtils();
DBCommand cmd = db.createCommand();
// Delete all Employee Department History records
- db.executeDelete(T_EDH, cmd, conn);
+ utils.executeDelete(T_EDH, cmd);
// Delete all Employees (no constraints)
- db.executeDelete(T_EMP, cmd, conn);
+ utils.executeDelete(T_EMP, cmd);
// Delete all Departments (no constraints)
- db.executeDelete(T_DEP, cmd, conn);
+ utils.executeDelete(T_DEP, cmd);
}
/**
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 84a4beb..ef89180 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
@@ -31,6 +31,7 @@ import org.apache.empire.db.DBDatabaseDriver;
import org.apache.empire.db.DBReader;
import org.apache.empire.db.DBRecord;
import org.apache.empire.db.DBSQLScript;
+import org.apache.empire.db.DBUtils;
import org.apache.empire.db.context.DBContextStatic;
import org.apache.empire.db.derby.DBDatabaseDriverDerby;
import org.apache.empire.db.h2.DBDatabaseDriverH2;
@@ -93,9 +94,9 @@ public class SampleApp
System.out.println("*** Step 3: openDatabase() ***");
try {
// Open the database
- db.open(driver, conn);
+ db.open(context);
// Check whether database exists
- databaseExists(conn);
+ databaseExists();
System.out.println("*** Database already exists. Skipping Step4 ***");
} catch(Exception e) {
@@ -113,12 +114,12 @@ public class SampleApp
}
// Open again
if (db.isOpen()==false)
- db.open(driver, conn);
+ db.open(context);
}
// STEP 5: Clear Database (Delete all records)
System.out.println("*** Step 5: clearDatabase() ***");
- clearDatabase(conn);
+ clearDatabase();
// STEP 6: Insert Departments
System.out.println("*** Step 6: insertDepartment() & insertEmployee() ***");
@@ -247,14 +248,14 @@ public class SampleApp
* Please note that in this case an error will appear in the log which can be ignored.
* </PRE>
*/
- private static boolean databaseExists(Connection conn)
+ private static boolean databaseExists()
{
// Check whether DB exists
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) ...");
- return (db.querySingleInt(cmd, -1, conn) >= 0);
+ return (context.getUtils().querySingleInt(cmd, -1) >= 0);
}
/**
@@ -281,13 +282,14 @@ public class SampleApp
* Empties all Tables.
* </PRE>
*/
- private static void clearDatabase(Connection conn)
+ private static void clearDatabase()
{
+ DBUtils utils = context.getUtils();
DBCommand cmd = db.createCommand();
// Delete all Employees (no constraints)
- db.executeDelete(db.EMPLOYEES, cmd, conn);
+ utils.executeDelete(db.EMPLOYEES, cmd);
// Delete all Departments (no constraints)
- db.executeDelete(db.DEPARTMENTS, cmd, conn);
+ utils.executeDelete(db.DEPARTMENTS, cmd);
}
/**
diff --git a/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/db/records/EmployeeRecord.java b/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/db/records/EmployeeRecord.java
index 7f95b69..b1e76c2 100644
--- a/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/db/records/EmployeeRecord.java
+++ b/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/db/records/EmployeeRecord.java
@@ -60,7 +60,7 @@ public class EmployeeRecord extends SampleRecord<TEmployees>
cmd.select(db.T_DEPARTMENTS.DEPARTMENT_ID);
cmd.select(db.T_DEPARTMENTS.NAME);
cmd.orderBy(db.T_DEPARTMENTS.NAME);
- return db.queryOptionList(cmd, getContext().getConnection());
+ return context.getUtils().queryOptionList(cmd);
}
// base class implementation
return super.getFieldOptions(column);
diff --git a/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/AutheticationPhaseListener.java b/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/AutheticationPhaseListener.java
index 0198255..ee9700d 100644
--- a/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/AutheticationPhaseListener.java
+++ b/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/AutheticationPhaseListener.java
@@ -44,13 +44,13 @@ public class AutheticationPhaseListener implements PhaseListener
{
}
- // @Override
+ @Override
public PhaseId getPhaseId()
{
return PhaseId.RESTORE_VIEW;
}
- // @Override
+ @Override
public void beforePhase(PhaseEvent pe)
{
// Check App
@@ -79,7 +79,7 @@ public class AutheticationPhaseListener implements PhaseListener
}
}
- // @Override
+ @Override
public void afterPhase(PhaseEvent event)
{
diff --git a/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/SampleApplication.java b/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/SampleApplication.java
index 02c62e9..b54ce50 100644
--- a/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/SampleApplication.java
+++ b/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/SampleApplication.java
@@ -140,8 +140,8 @@ public class SampleApplication extends WebApplication {
try {
conn = getConnection(sampleDB);
context = new DBContextStatic(driver, conn);
- sampleDB.open(driver, conn);
- if (!databaseExists(conn)) {
+ sampleDB.open(context);
+ if (!databaseExists(context)) {
// STEP 4: Create Database
log.info("Creating database {}", sampleDB.getClass().getSimpleName());
createSampleDatabase(context);
@@ -188,12 +188,12 @@ public class SampleApplication extends WebApplication {
return sampleDB;
}
- private boolean databaseExists(Connection conn) {
+ private boolean databaseExists(DBContext context) {
// Check wether DB exists
DBCommand cmd = sampleDB.createCommand();
cmd.select(sampleDB.T_DEPARTMENTS.count());
try {
- return (sampleDB.querySingleInt(cmd, -1, conn) >= 0);
+ return (context.getUtils().querySingleInt(cmd, -1) >= 0);
} catch (QueryFailedException e) {
return false;
}
@@ -216,7 +216,7 @@ public class SampleApplication extends WebApplication {
context.commit();
// Open again
if (!sampleDB.isOpen()) {
- sampleDB.open(context.getDriver(), conn);
+ sampleDB.open(context);
}
// Insert Sample Departments
insertDepartmentSampleRecord(context, "Procurement", "ITTK");
diff --git a/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/pages/EmployeeDetailPage.java b/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/pages/EmployeeDetailPage.java
index 6aa6aa4..7bcf4f1 100644
--- a/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/pages/EmployeeDetailPage.java
+++ b/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/pages/EmployeeDetailPage.java
@@ -18,10 +18,8 @@
*/
package org.apache.empire.jsf2.websample.web.pages;
-import org.apache.empire.exceptions.MiscellaneousErrorException;
import org.apache.empire.jsf2.pageelements.RecordPageElement;
import org.apache.empire.jsf2.pages.PageOutcome;
-import org.apache.empire.jsf2.websample.db.SampleDB;
import org.apache.empire.jsf2.websample.db.records.EmployeeRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/pages/EmployeeListPage.java b/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/pages/EmployeeListPage.java
index dcdf356..c967428 100644
--- a/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/pages/EmployeeListPage.java
+++ b/empire-db-examples/empire-db-example-jsf2/src/main/java/org/apache/empire/jsf2/websample/web/pages/EmployeeListPage.java
@@ -33,7 +33,6 @@ import org.apache.empire.exceptions.BeanPropertyGetException;
import org.apache.empire.jsf2.pageelements.BeanListPageElement;
import org.apache.empire.jsf2.pageelements.ListPageElement;
import org.apache.empire.jsf2.pageelements.ListPageElement.ParameterizedItem;
-import org.apache.empire.jsf2.websample.db.SampleDB;
import org.apache.empire.jsf2.websample.db.SampleDB.TDepartments;
import org.apache.empire.jsf2.websample.db.SampleDB.TEmployees;
import org.apache.empire.jsf2.websample.web.SampleUtils;
@@ -206,8 +205,7 @@ public class EmployeeListPage extends SamplePage
DBCommand queryCmd = createQueryCommand();
queryCmd.select(DEP.DEPARTMENT_ID,DEP.NAME);
- SampleDB db = getDatabase();
- return db.queryOptionList(queryCmd, getSampleContext().getConnection());
+ return getSampleContext().getUtils().queryOptionList(queryCmd);
}
diff --git a/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/rest/app/SampleServiceApp.java b/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/rest/app/SampleServiceApp.java
index 392949d..4b90abb 100644
--- a/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/rest/app/SampleServiceApp.java
+++ b/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/rest/app/SampleServiceApp.java
@@ -32,7 +32,6 @@ import javax.servlet.ServletContextListener;
import org.apache.empire.commons.StringUtils;
import org.apache.empire.db.DBCommand;
import org.apache.empire.db.DBContext;
-import org.apache.empire.db.DBDatabase;
import org.apache.empire.db.DBDatabaseDriver;
import org.apache.empire.db.DBRecord;
import org.apache.empire.db.DBSQLScript;
@@ -97,17 +96,18 @@ public class SampleServiceApp
// get connection
Connection conn = getJDBCConnection(ctx);
-
- // DB
- SampleDB db = initDatabase(ctx);
- DBDatabaseDriver driver = new DBDatabaseDriverHSql();
- db.open(driver, conn);
-
- // Add to context
- ctx.setAttribute(Service.Consts.ATTRIBUTE_DB, db);
- // sce.getServletContext().setAttribute(MobileImportServiceConsts.ATTRIBUTE_DATASOURCE, ds);
- // sce.getServletContext().setAttribute(MobileImportServiceConsts.ATTRIBUTE_CONFIG, config);
-
+ try {
+ // DB
+ DBDatabaseDriver driver = new DBDatabaseDriverHSql();
+ DBContext context = new DBContextStatic(driver, conn);
+ SampleDB db = initDatabase(ctx, context);
+ // Add to context
+ ctx.setAttribute(Service.Consts.ATTRIBUTE_DB, db);
+ // sce.getServletContext().setAttribute(MobileImportServiceConsts.ATTRIBUTE_DATASOURCE, ds);
+ // sce.getServletContext().setAttribute(MobileImportServiceConsts.ATTRIBUTE_CONFIG, config);
+ } finally {
+ releaseConnection(conn, true);
+ }
}
public TextResolver getTextResolver(Locale locale) {
@@ -145,7 +145,7 @@ public class SampleServiceApp
return conn;
}
- protected void releaseConnection(DBDatabase db, Connection conn, boolean commit) {
+ public void releaseConnection(Connection conn, boolean commit) {
// release connection
try
{ // release connection
@@ -164,50 +164,39 @@ public class SampleServiceApp
conn.rollback();
log.debug("REQUEST rolled back.");
}
- // Don't Release Connection
- // conn.close();
+ // close connection / return to pool
+ conn.close();
}
catch (SQLException e)
{
log.error("Error releasing connection", e);
- e.printStackTrace();
+ throw new RuntimeException(e);
}
}
// ********************* private *********************
- private SampleDB initDatabase(ServletContext ctx) {
+ private SampleDB initDatabase(ServletContext ctx, DBContext context) {
SampleDB db = new SampleDB();
-
// Open Database (and create if not existing)
- DBDatabaseDriver driver = new DBDatabaseDriverHSql();
+ DBDatabaseDriver driver = context.getDriver();
log.info("Opening database '{}' using driver '{}'", db.getClass().getSimpleName(), driver.getClass().getSimpleName());
- Connection conn = null;
- DBContext context = null;
- try {
- conn = getJDBCConnection(ctx);
- context = new DBContextStatic(driver, conn);
- db.open(driver, conn);
- if (!databaseExists(db, conn)) {
- // STEP 4: Create Database
- log.info("Creating database {}", db.getClass().getSimpleName());
- createSampleDatabase(db, context);
- }
- } finally {
- context.discard();
- releaseConnection(db, conn, true);
+ db.open(context);
+ if (!databaseExists(db, context)) {
+ // STEP 4: Create Database
+ log.info("Creating database {}", db.getClass().getSimpleName());
+ createSampleDatabase(db, context);
}
-
return db;
}
- private static boolean databaseExists(SampleDB db, Connection conn) {
+ private static boolean databaseExists(SampleDB db, DBContext context) {
// Check wether DB exists
DBCommand cmd = db.createCommand();
cmd.select(db.T_DEPARTMENTS.count());
try {
- return (db.querySingleInt(cmd, -1, conn) >= 0);
+ return (context.getUtils().querySingleInt(cmd, -1) >= 0);
} catch (QueryFailedException e) {
return false;
}
@@ -224,7 +213,7 @@ public class SampleServiceApp
context.commit();
// Open again
if (!db.isOpen()) {
- db.open(context.getDriver(), context.getConnection());
+ db.open(context);
}
// Insert Sample Departments
insertDepartmentSampleRecord(db, context, "Procurement", "ITTK");
diff --git a/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/rest/service/EmployeeService.java b/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/rest/service/EmployeeService.java
index eb1a24c..481034e 100644
--- a/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/rest/service/EmployeeService.java
+++ b/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/rest/service/EmployeeService.java
@@ -71,7 +71,7 @@ public class EmployeeService extends Service {
cmd.join (db.T_DEPARTMENTS.DEPARTMENT_ID, db.T_EMPLOYEES.DEPARTMENT_ID);
cmd.groupBy(cmd.getSelectExprList());
cmd.orderBy(db.T_DEPARTMENTS.NAME);
- Options departmentOptions = db.queryOptionList(cmd, ctx.getConnection());
+ Options departmentOptions = ctx.getUtils().queryOptionList(cmd);
// Create Metadata
TEmployees TE = db.T_EMPLOYEES;
diff --git a/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/rest/service/filter/ServiceResponseFilter.java b/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/rest/service/filter/ServiceResponseFilter.java
index 0c84d62..27544da 100644
--- a/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/rest/service/filter/ServiceResponseFilter.java
+++ b/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/rest/service/filter/ServiceResponseFilter.java
@@ -20,7 +20,6 @@ package org.apache.empire.rest.service.filter;
import java.io.IOException;
import java.sql.Connection;
-import java.sql.SQLException;
import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
@@ -29,6 +28,7 @@ import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Response.Status.Family;
import javax.ws.rs.ext.Provider;
+import org.apache.empire.rest.app.SampleServiceApp;
import org.apache.empire.rest.service.Service;
import org.glassfish.jersey.server.ContainerRequest;
import org.slf4j.Logger;
@@ -48,31 +48,16 @@ public class ServiceResponseFilter implements ContainerResponseFilter {
ContainerRequest containerRequest = (ContainerRequest) requestContext;
Connection conn = (Connection) containerRequest.getProperty(Service.Consts.ATTRIBUTE_CONNECTION);
- boolean success = responseContext.getStatusInfo().getFamily() == Family.SUCCESSFUL;
-
- try {
-
- if (conn == null || conn.isClosed()) {
- // Connection not found or already closed
- return;
- }
-
- if (success) {
- // commit
- conn.commit();
- } else {
- // rollback
- conn.rollback();
- }
-
- // close connection / return to pool
- conn.close();
-
- } catch (SQLException e) {
- log.error("Error releasing connection", e);
- responseContext.setStatus(500);
- }
+ try {
+
+ boolean success = responseContext.getStatusInfo().getFamily() == Family.SUCCESSFUL;
+ SampleServiceApp.instance().releaseConnection(conn, success);
+
+ } catch(Exception e) {
+ log.error("Error releasing connection", e);
+ responseContext.setStatus(500);
+ }
}
}
diff --git a/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/vue/sample/db/records/EmployeeRecord.java b/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/vue/sample/db/records/EmployeeRecord.java
index 38656a5..bcc3dce 100644
--- a/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/vue/sample/db/records/EmployeeRecord.java
+++ b/empire-db-examples/empire-db-example-vue/src/main/java/org/apache/empire/vue/sample/db/records/EmployeeRecord.java
@@ -59,7 +59,7 @@ public class EmployeeRecord extends SampleRecord<TEmployees>
cmd.select(db.T_DEPARTMENTS.DEPARTMENT_ID);
cmd.select(db.T_DEPARTMENTS.NAME);
cmd.orderBy(db.T_DEPARTMENTS.NAME);
- return db.queryOptionList(cmd, recordContext.getConnection());
+ return recordContext.getUtils().queryOptionList(cmd);
}
// base class implementation
return super.getFieldOptions(column);
diff --git a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/app/FacesUtils.java b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/app/FacesUtils.java
index d20add2..7af50c9 100644
--- a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/app/FacesUtils.java
+++ b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/app/FacesUtils.java
@@ -37,8 +37,6 @@ import javax.servlet.http.HttpServletRequest;
import org.apache.empire.commons.ObjectUtils;
import org.apache.empire.commons.StringUtils;
import org.apache.empire.data.Column;
-import org.apache.empire.db.DBContext;
-import org.apache.empire.db.DBDatabase;
import org.apache.empire.exceptions.EmpireException;
import org.apache.empire.exceptions.InternalException;
import org.apache.empire.exceptions.ItemNotFoundException;
diff --git a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/CheckboxInputControl.java b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/CheckboxInputControl.java
index 1d6b129..edc2d8d 100644
--- a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/CheckboxInputControl.java
+++ b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/CheckboxInputControl.java
@@ -30,7 +30,6 @@ import javax.faces.event.PhaseId;
import org.apache.empire.commons.ObjectUtils;
import org.apache.empire.exceptions.InvalidArgumentException;
import org.apache.empire.exceptions.UnexpectedReturnValueException;
-import org.apache.empire.jsf2.controls.InputControl.DisabledType;
public class CheckboxInputControl extends InputControl
{
diff --git a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/RadioInputControl.java b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/RadioInputControl.java
index feb929d..a717918 100644
--- a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/RadioInputControl.java
+++ b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/RadioInputControl.java
@@ -39,7 +39,6 @@ import org.apache.empire.data.Column;
import org.apache.empire.exceptions.InvalidArgumentException;
import org.apache.empire.exceptions.UnexpectedReturnValueException;
import org.apache.empire.jsf2.app.TextResolver;
-import org.apache.empire.jsf2.controls.InputControl.DisabledType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/TextAreaInputControl.java b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/TextAreaInputControl.java
index 02a713e..1a63295 100644
--- a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/TextAreaInputControl.java
+++ b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/TextAreaInputControl.java
@@ -26,12 +26,9 @@ import javax.faces.component.html.HtmlInputTextarea;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
-import org.apache.empire.commons.ObjectUtils;
import org.apache.empire.commons.StringUtils;
import org.apache.empire.exceptions.InvalidArgumentException;
import org.apache.empire.exceptions.UnexpectedReturnValueException;
-import org.apache.empire.jsf2.controls.InputControl.DisabledType;
-import org.apache.empire.jsf2.controls.InputControl.ValueInfo;
public class TextAreaInputControl extends InputControl
{
diff --git a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/TextInputControl.java b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/TextInputControl.java
index 3a051fd..a585d5b 100644
--- a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/TextInputControl.java
+++ b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/controls/TextInputControl.java
@@ -439,7 +439,7 @@ public class TextInputControl extends InputControl
Column col = ii.getColumn();
// cast to DBTableColumn
DataType type = col.getDataType();
- if (type == DataType.CHAR || type == DataType.VARCHAR || type == DataType.TEXT)
+ if (type == DataType.CHAR || type == DataType.VARCHAR)
return (int) Math.round(col.getSize());
if (type == DataType.AUTOINC || type == DataType.INTEGER)
return 10;
diff --git a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/pageelements/BeanListPageElement.java b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/pageelements/BeanListPageElement.java
index cecd9a8..abe0789 100644
--- a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/pageelements/BeanListPageElement.java
+++ b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/pageelements/BeanListPageElement.java
@@ -18,7 +18,6 @@
*/
package org.apache.empire.jsf2.pageelements;
-import java.sql.Connection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -32,6 +31,7 @@ import org.apache.empire.data.Column;
import org.apache.empire.db.DBColumn;
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.DBDriverFeature;
import org.apache.empire.db.DBReader;
@@ -248,7 +248,7 @@ public class BeanListPageElement<T> extends ListPageElement<T> implements ListIt
public void initItems(DBCommand queryCmd, DBCommand countCmd, int pageSize)
{
clearItems();
- Connection conn = getDBContext(rowset).getConnection();
+ DBContext context = getDBContext(rowset);
// Init List Table Info
BeanListTableInfo lti = (BeanListTableInfo) getTableInfo();
lti.setQueryCmd(queryCmd);
@@ -256,7 +256,7 @@ public class BeanListPageElement<T> extends ListPageElement<T> implements ListIt
{ // Negative count means: loadItems should load all items.
countCmd.clearSelect();
countCmd.select(rowset.count());
- int count = rowset.getDatabase().querySingleInt(countCmd.getSelect(), countCmd.getParamValues(), 0, conn);
+ int count = context.getUtils().querySingleInt(countCmd.getSelect(), countCmd.getParamValues(), 0);
lti.init(count, pageSize);
}
else
diff --git a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/pageelements/RecordPageElement.java b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/pageelements/RecordPageElement.java
index b3c8e67..d874c44 100644
--- a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/pageelements/RecordPageElement.java
+++ b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/pageelements/RecordPageElement.java
@@ -18,8 +18,6 @@
*/
package org.apache.empire.jsf2.pageelements;
-import java.sql.Connection;
-
import javax.faces.context.FacesContext;
import org.apache.empire.db.DBRecord;
@@ -122,6 +120,7 @@ public class RecordPageElement<T extends DBRecord> extends PageElement
// Check Key
if (recKey==null || recKey.length==0)
{ // Invalid Record key
+ @SuppressWarnings("unchecked")
T rec = (T)getSessionObject(DBRecord.class);
if (rec!=null)
{ // A new record
diff --git a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/utils/TagEncodingHelper.java b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/utils/TagEncodingHelper.java
index cd5db80..335ae7c 100644
--- a/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/utils/TagEncodingHelper.java
+++ b/empire-db-jsf2/src/main/java/org/apache/empire/jsf2/utils/TagEncodingHelper.java
@@ -1644,7 +1644,6 @@ public class TagEncodingHelper implements NamingContainer
case DECIMAL:
case FLOAT:
return CSS_DATA_TYPE_NUMBER;
- case TEXT:
case VARCHAR:
case CHAR:
return CSS_DATA_TYPE_TEXT;
diff --git a/empire-db/src/main/java/org/apache/empire/data/DataMode.java b/empire-db/src/main/java/org/apache/empire/data/DataMode.java
deleted file mode 100644
index 70cb0ba..0000000
--- a/empire-db/src/main/java/org/apache/empire/data/DataMode.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.empire.data;
-
-/**
- * DataMode is an enumeration that specifies whether the value of a column is readonly, optional (nullable), required (NotNull), or auto-generated
- * @deprecated will be removed in a future release
- */
-@Deprecated
-public enum DataMode {
- /**
- * Optional = value may be null
- */
- Nullable, // i.e. Optional
- /**
- * Required = value may not be null
- */
- NotNull, // i.e. Required
- /**
- * AutoGenerated = value is automatically generated by the database on inserts
- */
- AutoGenerated,
-}
diff --git a/empire-db/src/main/java/org/apache/empire/data/DataType.java b/empire-db/src/main/java/org/apache/empire/data/DataType.java
index ab3b2e9..3f3a212 100644
--- a/empire-db/src/main/java/org/apache/empire/data/DataType.java
+++ b/empire-db/src/main/java/org/apache/empire/data/DataType.java
@@ -46,14 +46,6 @@ public enum DataType
VARCHAR, // = 3;
/**
- * Variable text (represents varchar)
- *
- * @deprecated Use VARCHAR instead
- */
- @Deprecated
- TEXT, // = 3;
-
- /**
* Date only value (without time)
*/
DATE, // = 4;
@@ -109,7 +101,7 @@ public enum DataType
*/
public boolean isText()
{
- return (this==DataType.TEXT || this==DataType.VARCHAR || this==DataType.CHAR || this==DataType.CLOB);
+ return (this==DataType.VARCHAR || this==DataType.CHAR || this==DataType.CLOB);
}
/**
diff --git a/empire-db/src/main/java/org/apache/empire/data/bean/BeanProperty.java b/empire-db/src/main/java/org/apache/empire/data/bean/BeanProperty.java
index 63690b0..9efba03 100644
--- a/empire-db/src/main/java/org/apache/empire/data/bean/BeanProperty.java
+++ b/empire-db/src/main/java/org/apache/empire/data/bean/BeanProperty.java
@@ -22,7 +22,6 @@ import org.apache.empire.commons.Attributes;
import org.apache.empire.commons.ObjectUtils;
import org.apache.empire.commons.Options;
import org.apache.empire.data.Column;
-import org.apache.empire.data.DataMode;
import org.apache.empire.data.DataType;
import org.apache.empire.db.exceptions.FieldNotNullException;
@@ -35,8 +34,8 @@ public class BeanProperty implements Column
{
private final String name;
private final DataType dataType;
- private final DataMode dataMode;
private final double size;
+ private final boolean required;
private String controlType; // optional (default is 'text')
private String title; // optional
@@ -47,24 +46,6 @@ public class BeanProperty implements Column
protected BeanClass beanClass; // internal;
// --- ColumnExpr interface implementation ---
-
- /**
- * Constructs a bean property definition
- * @param name the name of the property (case insensitive)
- * @param dataType the data type
- * @param size size depending on data type. For data type TEXT the maximum number of characters.
- * @param dataMode determines whether this property is read only, optional, required or auto-generated
- * @param controlType the control type to be used for editing this value. Depends on the client. Default is "text"
- */
- protected BeanProperty(String name, DataType dataType, double size, DataMode dataMode, String controlType, boolean readOnly)
- {
- this.name = name;
- this.dataType = dataType;
- this.size = size;
- this.dataMode = dataMode;
- this.controlType = controlType;
- this.readOnly = readOnly;
- }
/**
* Constructs a bean property definition
@@ -77,7 +58,12 @@ public class BeanProperty implements Column
*/
public BeanProperty(String name, DataType dataType, double size, boolean required, String controlType, boolean readOnly)
{
- this(name, dataType, size, (dataType==DataType.AUTOINC ? DataMode.AutoGenerated : (required ? DataMode.NotNull : DataMode.Nullable)), controlType, readOnly);
+ this.name = name;
+ this.dataType = dataType;
+ this.size = size;
+ this.required = required;
+ this.controlType = controlType;
+ this.readOnly = readOnly;
}
/**
@@ -91,7 +77,7 @@ public class BeanProperty implements Column
*/
public BeanProperty(String name, DataType dataType, double size, boolean required, String controlType)
{
- this(name, dataType, size, (dataType==DataType.AUTOINC ? DataMode.AutoGenerated : (required ? DataMode.NotNull : DataMode.Nullable)), controlType, false);
+ this(name, dataType, size, required, controlType, false);
}
/**
@@ -103,7 +89,7 @@ public class BeanProperty implements Column
*/
public BeanProperty(String name, DataType dataType, double size, boolean required)
{
- this(name, dataType, size, (dataType==DataType.AUTOINC ? DataMode.AutoGenerated : (required ? DataMode.NotNull : DataMode.Nullable)), "text", false);
+ this(name, dataType, size, required, "text", false);
}
/**
@@ -223,19 +209,19 @@ public class BeanProperty implements Column
@Override
public boolean isReadOnly()
{
- return (this.readOnly || dataMode==DataMode.AutoGenerated);
+ return (this.readOnly || dataType==DataType.AUTOINC);
}
@Override
public boolean isAutoGenerated()
{
- return (dataMode==DataMode.AutoGenerated);
+ return (dataType==DataType.AUTOINC);
}
@Override
public boolean isRequired()
{
- return (dataMode==DataMode.NotNull);
+ return this.required;
}
@Override
diff --git a/empire-db/src/main/java/org/apache/empire/data/bean/BeanResult.java b/empire-db/src/main/java/org/apache/empire/data/bean/BeanResult.java
index 9a179fb..54e681d 100644
--- a/empire-db/src/main/java/org/apache/empire/data/bean/BeanResult.java
+++ b/empire-db/src/main/java/org/apache/empire/data/bean/BeanResult.java
@@ -19,7 +19,6 @@
package org.apache.empire.data.bean;
import java.lang.reflect.Method;
-import java.sql.Connection;
import java.util.ArrayList;
import org.apache.empire.db.DBColumn;
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 33b86b2..6a51360 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
@@ -18,8 +18,6 @@
*/
package org.apache.empire.db;
-// java
-import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -164,7 +162,7 @@ public abstract class DBCommandExpr extends DBExpr
/** Returns the error message: ERR_NOTSUPPORTED */
@Override
- public void deleteRecord(Object[] keys, Connection conn)
+ public void deleteRecord(Object[] keys, DBContext context)
{
throw new NotSupportedException(this, "deleteRecord");
}
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBContext.java b/empire-db/src/main/java/org/apache/empire/db/DBContext.java
index 9e9adb7..d8f660d 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBContext.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBContext.java
@@ -11,6 +11,8 @@ public interface DBContext
Connection getConnection();
+ DBUtils getUtils();
+
void commit();
void rollback();
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBDDLGenerator.java b/empire-db/src/main/java/org/apache/empire/db/DBDDLGenerator.java
index 51d9b69..d13a7f7 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBDDLGenerator.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBDDLGenerator.java
@@ -109,7 +109,6 @@ public abstract class DBDDLGenerator<T extends DBDatabaseDriver>
sql.append(DATATYPE_INTEGER); // Default integer length
}
break;
- case TEXT:
case VARCHAR:
case CHAR:
{ // Char or Varchar
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 264c55f..3d55d1e 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
@@ -21,12 +21,7 @@ package org.apache.empire.db;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.SQLIntegrityConstraintViolationException;
-import java.sql.Statement;
import java.util.ArrayList;
-import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
@@ -35,26 +30,16 @@ import java.util.List;
import java.util.Map;
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.DataType;
import org.apache.empire.db.DBRelation.DBCascadeAction;
-import org.apache.empire.db.exceptions.ConstraintViolationException;
import org.apache.empire.db.exceptions.DatabaseNotOpenException;
-import org.apache.empire.db.exceptions.EmpireSQLException;
-import org.apache.empire.db.exceptions.QueryFailedException;
-import org.apache.empire.db.exceptions.QueryNoResultException;
-import org.apache.empire.db.exceptions.StatementFailedException;
import org.apache.empire.db.expr.column.DBCaseWhenExpr;
import org.apache.empire.db.expr.column.DBValueExpr;
import org.apache.empire.db.expr.compare.DBCompareExpr;
-import org.apache.empire.exceptions.InternalException;
import org.apache.empire.exceptions.InvalidArgumentException;
import org.apache.empire.exceptions.ItemExistsException;
import org.apache.empire.exceptions.MiscellaneousErrorException;
import org.apache.empire.exceptions.PropertyReadOnlyException;
-import org.apache.empire.exceptions.UnexpectedReturnValueException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -92,9 +77,6 @@ public abstract class DBDatabase extends DBObject
}
}
- // Threshold for long running queries in milliseconds
- protected long longRunndingStmtThreshold = 30000;
-
// Database specific date
public static final DBSystemDate SYSDATE = new DBSystemDate();
@@ -328,13 +310,14 @@ public abstract class DBDatabase extends DBObject
* @param driver the database driver
* @param conn the connection
*/
- public void open(DBDatabaseDriver driver, Connection conn)
+ public void open(DBContext context)
{
// Close Database if already open
if (isOpen())
- close(conn);
+ close(context);
// Attach to driver
- driver.attachDatabase(this, conn);
+ DBDatabaseDriver driver = context.getDriver();
+ driver.attachDatabase(this, context.getConnection());
// set new driver
this.driver = driver;
}
@@ -346,10 +329,10 @@ public abstract class DBDatabase extends DBObject
*
* @param conn the connection to close
*/
- public void close(Connection conn)
+ public void close(DBContext context)
{
if (driver != null)
- driver.detachDatabase(this, conn);
+ driver.detachDatabase(this, context.getConnection());
// No diver
this.driver = null;
}
@@ -367,15 +350,16 @@ public abstract class DBDatabase extends DBObject
public synchronized void getCreateDDLScript(DBSQLScript script)
{
DBDatabaseDriver prevDriver = this.driver;
+ DBDatabaseDriver ddlDriver = script.getContext().getDriver();
try {
// Set driver
- if (this.driver!=null && this.driver!=driver && driver!=null)
+ if (this.driver!=null && this.driver!=ddlDriver && ddlDriver!=null)
{ // The database belongs to a different driver
throw new MiscellaneousErrorException("The database is attached to a different driver.");
}
// Temporarily change driver
if (this.driver== null)
- this.driver = driver;
+ this.driver = ddlDriver;
// Get DDL Command
generateDDLScript(script);
@@ -855,810 +839,6 @@ public abstract class DBDatabase extends DBObject
checkOpen();
return driver.getUpdateTimestamp(conn);
}
-
- // Sequences
- public Object getNextSequenceValue(String seqName, Connection conn)
- {
- // Ask driver
- checkOpen();
- return driver.getNextSequenceValue(this, seqName, 1, conn);
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as an object.
- * If the query does not return a result the value ObjectUtils.NO_VALUE is returned.
- *
- * @param sqlCmd the SQL-Command
- * @param sqlParams list of query parameter values
- * @param dataType the expected data type
- * @param conn a valid connection to the database.
- *
- * @return the value of the first column in the first row of the query
- */
- public Object querySingleValue(String sqlCmd, Object[] sqlParams, DataType dataType, Connection conn)
- {
- checkOpen();
- ResultSet rs = null;
- try
- { // Debug
- long start = System.currentTimeMillis();
- if (log.isDebugEnabled())
- log.debug("Executing: " + sqlCmd);
- // Get the next Value
- rs = driver.executeQuery(sqlCmd, sqlParams, false, conn);
- if (rs == null)
- throw new UnexpectedReturnValueException(rs, "driver.executeQuery()");
- // Check Result
- if (rs.next() == false)
- { // no result
- log.debug("querySingleValue returned no result");
- return ObjectUtils.NO_VALUE;
- }
- // Read value
- Object result = driver.getResultValue(rs, 1, dataType);
- // Debug
- long queryTime = (System.currentTimeMillis() - start);
- if (log.isDebugEnabled())
- log.debug("querySingleValue successful in {} ms. Result value={}.", queryTime, result);
- else if (queryTime>=longRunndingStmtThreshold)
- log.warn("Long running query took {} seconds for statement {}.", queryTime / 1000, sqlCmd);
- // done
- return result;
- } catch (SQLException sqle)
- { // Error
- throw new QueryFailedException(this, sqlCmd, sqle);
- } finally
- { // Cleanup
- closeResultSet(rs);
- }
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as an object.
- * If the query does not return a result a QueryNoResultException is thrown
- *
- * @param sqlCmd the SQL-Command
- * @param sqlParams list of query parameter values
- * @param conn a valid connection to the database.
- *
- * @return the value of the first column in the first row of the query
- */
- public final Object querySingleValue(String sqlCmd, Object[] sqlParams, Connection conn)
- {
- Object value = querySingleValue(sqlCmd, sqlParams, DataType.UNKNOWN, conn);
- if (value==ObjectUtils.NO_VALUE)
- throw new QueryNoResultException(sqlCmd);
- return value;
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as an object.
- * If the query does not return a result a QueryNoResultException is thrown
- *
- * @param cmd the Command object that contains the select statement
- * @param dataType the expected data type
- * @param conn a valid connection to the database.
- *
- * @return the value of the first column in the first row of the query
- */
- public final Object querySingleValue(DBCommand cmd, DataType dataType, Connection conn)
- {
- Object value = querySingleValue(cmd.getSelect(), cmd.getParamValues(), dataType, conn);
- if (value==ObjectUtils.NO_VALUE)
- throw new QueryNoResultException(cmd.getSelect());
- return value;
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as an object.
- * If the query does not return a result a QueryNoResultException is thrown
- *
- * @param cmd the Command object that contains the select statement
- * @param conn a valid connection to the database.
- *
- * @return the value of the first column in the first row of the query
- */
- public final Object querySingleValue(DBCommand cmd, Connection conn)
- {
- return querySingleValue(cmd, DataType.UNKNOWN, conn);
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as an int.
- * If the query does not return a result or if the query result is NULL, then the defaultValue is returned
- *
- * @param sqlCmd the SQL statement
- * @param sqlParams list of query parameter values
- * @param defaultValue the default value if no value was returned by the database
- * @param conn a valid connection to the database.
- *
- * @return the value of the first column in the first row of the query
- */
- public final int querySingleInt(String sqlCmd, Object[] sqlParams, int defaultValue, Connection conn)
- {
- Object value = querySingleValue(sqlCmd, sqlParams, DataType.INTEGER, conn);
- return ObjectUtils.getInteger(value, defaultValue);
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as an int.
- * If the query does not return a result or if the query result is NULL, then the defaultValue is returned
- *
- * @param cmd the Command object that contains the select statement
- * @param defaultValue the default value if no value was returned by the database
- * @param conn a valid connection to the database.
- *
- * @return the result as a int value
- */
- public final int querySingleInt(DBCommand cmd, int defaultValue, Connection conn)
- {
- return querySingleInt(cmd.getSelect(), cmd.getParamValues(), defaultValue, conn);
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as an int.
- * If the query does not return a result a QueryNoResultException is thrown
- *
- * @param cmd the Command object that contains the select statement
- * @param conn a valid connection to the database.
- *
- * @return the result as a int value
- */
- public final int querySingleInt(DBCommand cmd, Connection conn)
- {
- Object value = querySingleValue(cmd.getSelect(), cmd.getParamValues(), DataType.INTEGER, conn);
- if (ObjectUtils.isEmpty(value))
- throw new QueryNoResultException(cmd.getSelect());
- return ObjectUtils.getInteger(value);
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as a long.
- * If the query does not return a result or if the query result is NULL, then the defaultValue is returned
- *
- * @param sqlCmd the SQL statement
- * @param sqlParams list of query parameter values
- * @param defaultValue the default value
- * @param conn a valid connection to the database.
- *
- * @return the result as a long value
- */
- public final long querySingleLong(String sqlCmd, Object[] sqlParams, long defaultValue, Connection conn)
- {
- Object value = querySingleValue(sqlCmd, sqlParams, DataType.INTEGER, conn);
- return ObjectUtils.getLong(value, defaultValue);
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as a long.
- * If the query does not return a result or if the query result is NULL, then the defaultValue is returned
- *
- * @param cmd the Command object that contains the select statement
- * @param defaultValue the default value
- * @param conn a valid connection to the database.
- *
- * @return the result as a long value
- */
- public final long querySingleLong(DBCommand cmd, long defaultValue, Connection conn)
- {
- return querySingleLong(cmd.getSelect(), cmd.getParamValues(), defaultValue, conn);
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as a long.
- * If the query does not return a result a QueryNoResultException is thrown
- *
- * @param cmd the Command object that contains the select statement
- * @param conn a valid connection to the database.
- *
- * @return the result as a long value
- */
- public final long querySingleLong(DBCommand cmd, Connection conn)
- {
- Object value = querySingleValue(cmd.getSelect(), cmd.getParamValues(), DataType.INTEGER, conn);
- if (ObjectUtils.isEmpty(value))
- throw new QueryNoResultException(cmd.getSelect());
- return ObjectUtils.getLong(value);
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as a string.
- * If the query does not return a result or if the query result is NULL, then the defaultValue is returned
- *
- * @param sqlCmd the SQL statement
- * @param sqlParams list of query parameter values
- * @param defaultValue the default value if no value was returned by the database
- * @param conn a valid connection to the database.
- *
- * @return the result as a String object
- */
- public final String querySingleString(String sqlCmd, Object[] sqlParams, String defaultValue, Connection conn)
- {
- Object value = querySingleValue(sqlCmd, sqlParams, DataType.VARCHAR, conn);
- return (ObjectUtils.isEmpty(value) ? defaultValue : value.toString());
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as a string.
- * If the query does not return a result or if the query result is NULL, then the defaultValue is returned
- *
- * @param cmd the Command object that contains the select statement
- * @param defaultValue the default value if no value was returned by the database
- * @param conn a valid connection to the database.
- *
- * @return the result as a String object, if no result a empty String
- */
- public final String querySingleString(DBCommand cmd, String defaultValue, Connection conn)
- {
- return querySingleString(cmd.getSelect(), cmd.getParamValues(), defaultValue, conn);
- }
-
- /**
- * Returns the value of the first row/column of a sql-query as a string.
- * If the query does not return a result a QueryNoResultException is thrown.
- * If the query result is NULL an empty string is returned.
- *
- * @param cmd the Command object that contains the select statement
- * @param conn a valid connection to the database.
- *
- * @return the result as a String object, if no result a empty String
- */
- public final String querySingleString(DBCommand cmd, Connection conn)
- {
- Object value = querySingleValue(cmd.getSelect(), cmd.getParamValues(), DataType.VARCHAR, conn);
- if (value==ObjectUtils.NO_VALUE)
- throw new QueryNoResultException(cmd.getSelect());
- return StringUtils.toString(value, "");
- }
-
- /**
- * Adds the first column of a query result to a collection.
- * If the query has no result, an empty list is returned.
- *
- * @param c the class type for the list
- * @param <T> the type for the list
- * @param sqlCmd the SQL statement
- * @param dataType the expected data type
- * @param conn a valid connection to the database.
- * @param maxRows maximum number of rows or -1 for all rows
- *
- * @return the number of elements that have been added to the collection
- */
- public <T> int querySimpleList(Class<T> c, String sqlCmd, Object[] sqlParams, DataType dataType, Connection conn, Collection<T> result, int maxRows)
- { // Start query
- checkOpen();
- ResultSet rs = null;
- try
- { // Log performance
- long start = System.currentTimeMillis();
- if (log.isDebugEnabled())
- log.debug("Executing: " + sqlCmd);
- // Get the next Value
- rs = driver.executeQuery(sqlCmd, sqlParams, false, conn);
- if (rs == null)
- throw new UnexpectedReturnValueException(rs, "driver.executeQuery()");
- // Check Result
- int count=0;
- while (rs.next() && (maxRows<0 || count<maxRows))
- {
- T item = ObjectUtils.convert(c, driver.getResultValue(rs, 1, dataType));
- result.add(item);
- count++;
- }
- // Debug
- long queryTime = (System.currentTimeMillis() - start);
- if (log.isDebugEnabled())
- log.debug("querySimpleList retured {} items in {} ms.", count, queryTime);
- else if (queryTime>=longRunndingStmtThreshold)
- log.warn("Long running query took {} seconds for statement {}.", queryTime / 1000, sqlCmd);
- // done
- return count;
- } catch (ClassCastException e)
- { log.error("querySingleValue cast exception: ", e);
- throw new InternalException(e);
- } catch (SQLException sqle)
- { // Error
- throw new QueryFailedException(this, sqlCmd, sqle);
- } finally
- { // Cleanup
- closeResultSet(rs);
- }
- }
-
- /**
- * Adds the first column of a query result to a collection.
- * If the query has no result, an empty list is returned.
- *
- * @param c the class type for the list
- * @param <T> the type for the list
- * @param cmd the Command object that contains the select statement
- * @param conn a valid connection to the database.
- *
- * @return the number of elements that have been added to the collection
- */
- public final <T> int querySimpleList(Class<T> c, DBCommand cmd, Connection conn, Collection<T> result)
- {
- return querySimpleList(c, cmd.getSelect(), cmd.getParamValues(), DataType.UNKNOWN, conn, result, -1);
- }
-
- /**
- * Returns a one dimensional array from an sql query.
- * The array is filled with the values of the first column.
- *
- * @param c the class type for the list
- * @param <T> the type for the list
- * @param cmd the Command object that contains the select statement
- * @param conn a valid connection to the database.
- *
- * @return a list of the values of the first column of an sql query
- */
- public final <T> List<T> querySimpleList(Class<T> c, DBCommand cmd, Connection conn)
- { // Execute the Statement
- List<T> result = new ArrayList<T>();
- if (querySimpleList(c, cmd, conn, result)<0)
- return null;
- return result;
- }
-
- /**
- * Returns a one dimensional array from an sql query.
- * The array is filled with the values of the first column.
- *
- * @param cmd the Command object that contains the select statement
- * @param conn a valid connection to the database.
- * @return a list of values of type Object
- */
- public final List<Object> querySimpleList(DBCommand cmd, Connection conn)
- { // Execute the Statement
- return querySimpleList(Object.class, cmd, conn);
- }
-
- /**
- * Fills an option list provided with the result from a query.
- * The option list is filled with the values of the first and second column.
- *
- * @param sqlCmd the SQL statement
- * @param conn a valid connection to the database.
- * @return an Options object containing a set a of values and their corresponding names
- */
- public int queryOptionList(String sqlCmd, Object[] sqlParams, Connection conn, Options result)
- { // Execute the Statement
- checkOpen();
- ResultSet rs = null;
- try
- { // Debug
- long start = System.currentTimeMillis();
- if (log.isDebugEnabled())
- log.debug("Executing: " + sqlCmd);
- // Get the next Value
- rs = driver.executeQuery(sqlCmd, sqlParams, false, conn);
- if (rs == null)
- throw new UnexpectedReturnValueException(rs, "driver.executeQuery()");
- if (rs.getMetaData().getColumnCount()<2)
- throw new InvalidArgumentException("sqlCmd", sqlCmd);
- // Check Result
- int count = 0;
- while (rs.next())
- {
- Object value = rs.getObject(1);
- String text = rs.getString(2);
- result.add(value, text, true);
- count++;
- }
- // Debug
- long queryTime = (System.currentTimeMillis() - start);
- if (log.isDebugEnabled())
- log.debug("queryOptionList retured {} items in {} ms.", count, queryTime);
- else if (queryTime>=longRunndingStmtThreshold)
- log.warn("Long running query took {} seconds for statement {}.", queryTime / 1000, sqlCmd);
- // done
- return count;
- } catch (SQLException sqle)
- { // Error
- throw new QueryFailedException(this, sqlCmd, sqle);
- } finally
- { // Cleanup
- closeResultSet(rs);
- }
- }
-
- /**
- * Fills an option list provided with the result from a query.
- * The option list is filled with the values of the first and second column.
- *
- * @param cmd the Command object that contains the select statement
- * @param conn a valid connection to the database.
- * @return an Options object containing a set a of values and their corresponding names
- */
- public final int queryOptionList(DBCommand cmd, Connection conn, Options result)
- { // Execute the Statement
- return queryOptionList(cmd.getSelect(), cmd.getParamValues(), conn, result);
- }
-
- /**
- * Returns a list of key value pairs from an sql query.
- * The option list is filled with the values of the first and second column.
- *
- * @param cmd the Command object that contains the select statement
- * @param conn a valid connection to the database.
- * @return an Options object containing a set a of values and their corresponding names
- */
- public final Options queryOptionList(DBCommand cmd, Connection conn)
- { // Execute the Statement
- Options options = new Options();
- queryOptionList(cmd.getSelect(), cmd.getParamValues(), conn, options);
- return options;
- }
-
- /**
- * Adds the result of a query to a given collection.<br>
- * The individual rows will be added as an array of objects (object[])
- * <p>This function should only be used for small lists.
- * Otherwise a DBReader should be used!</p>
- *
- * @param sqlCmd the SQL statement
- * @param conn a valid connection to the database.
- * @return a list of object arrays
- */
- public int queryObjectList(String sqlCmd, Object[] sqlParams, Connection conn, Collection<Object[]> result, int maxRows)
- { // Perform query
- checkOpen();
- ResultSet rs = null;
- try
- { // Log performance
- long start = System.currentTimeMillis();
- if (log.isDebugEnabled())
- log.debug("Executing: " + sqlCmd);
- // Get the next Value
- rs = driver.executeQuery(sqlCmd, sqlParams, false, conn);
- if (rs == null)
- throw new UnexpectedReturnValueException(rs, "driver.executeQuery()");
- // Read List
- int colCount = rs.getMetaData().getColumnCount();
- int count = 0;
- while (rs.next() && (maxRows<0 || count<maxRows))
- { // Read row
- Object[] item = new Object[colCount];
- for (int i=0; i<colCount; i++)
- { // Read from Resultset
- item[i] = driver.getResultValue(rs, i+1, DataType.UNKNOWN);
- }
- result.add(item);
- count++;
- }
- // Debug
- long queryTime = (System.currentTimeMillis() - start);
- if (log.isDebugEnabled())
- log.debug("queryObjectList retured {} items in {} ms.", count, queryTime);
- else if (queryTime>=longRunndingStmtThreshold)
- log.warn("Long running query took {} seconds for statement {}.", queryTime / 1000, sqlCmd);
- // done
- return count;
- } catch (SQLException sqle)
- { // Error
- throw new QueryFailedException(this, sqlCmd, sqle);
- } finally
- { // Cleanup
- closeResultSet(rs);
- }
- }
-
- /**
- * Adds the result of a query to a given collection.<br>
- * The individual rows will be added as an array of objects (object[])
- * <p>This function should only be used for small lists.
- * Otherwise a DBReader should be used!</p>
- *
- * @param cmd the Command object that contains the select statement
- * @param conn a valid connection to the database.
- * @return a list of object arrays
- */
- public final int queryObjectList(DBCommand cmd, Connection conn, Collection<Object[]> result)
- { // Perform query
- return queryObjectList(cmd.getSelect(), cmd.getParamValues(), conn, result, -1);
- }
-
- /**
- * Returns the result of a query as a list Object-Arrays
- * This function should only be used for small lists.
- *
- * @param cmd the Command object that contains the select statement
- * @param conn a valid connection to the database.
- * @return a list of object arrays
- */
- public final List<Object[]> queryObjectList(DBCommand cmd, Connection conn)
- { // Execute the Statement
- List<Object[]> result = new ArrayList<Object[]>();
- queryObjectList(cmd.getSelect(), cmd.getParamValues(), conn, result, -1);
- return result;
- }
-
- /**
- * Returns all values of the first row of a sql-query as an array.
- * If the query does not return a result a QueryNoResultException is thrown
- *
- * @param sqlCmd the SQL-Command
- * @param sqlParams list of query parameter values
- * @param conn a valid connection to the database.
- *
- * @return the values of the first row
- */
- public Object[] querySingleRow(String sqlCmd, Object[] sqlParams, Connection conn)
- {
- List<Object[]> result = new ArrayList<Object[]>();
- queryObjectList(sqlCmd, sqlParams, conn, result, 1);
- if (result.size()<1)
- throw new QueryNoResultException(sqlCmd);
- return result.get(0);
- }
-
- /**
- * Returns all values of the first row of a sql-query as an array.
- * If the query does not return a result a QueryNoResultException is thrown
- *
- * @param cmd the Command object that contains the select statement
- * @param conn a valid connection to the database.
- *
- * @return the values of the first row
- */
- public final Object[] querySingleRow(DBCommand cmd, Connection conn)
- {
- return querySingleRow(cmd.getSelect(), cmd.getParamValues(), conn);
- }
-
- /**
- * Executes an update, insert or delete SQL-Statement.<BR>
- * We recommend to use a DBCommand object in order to build the sqlCmd.<BR>
- * <P>
- * @param sqlCmd the SQL-Command
- * @param sqlParams a list of objects to replace sql parameters
- * @param conn a valid connection to the database.
- * @param setGenKeys object to set the generated keys for
- * @return the row count for insert, update or delete or 0 for SQL statements that return nothing
- */
- public int executeSQL(String sqlCmd, Object[] sqlParams, Connection conn, DBDatabaseDriver.DBSetGenKeys setGenKeys)
- {
- checkOpen();
- try
- { // Check argument
- if (conn==null)
- throw new InvalidArgumentException("conn", conn);
- // Debug
- if (log.isInfoEnabled())
- log.info("Executing: " + sqlCmd);
- // execute SQL
- long start = System.currentTimeMillis();
- int affected = driver.executeSQL(sqlCmd, sqlParams, conn, setGenKeys);
- // number of affected records
- if (affected < 0)
- throw new UnexpectedReturnValueException(affected, "driver.executeSQL()");
- // Log
- long execTime = (System.currentTimeMillis() - start);
- if (log.isInfoEnabled())
- log.info("executeSQL affected {} Records in {} ms ", affected, execTime);
- else if (execTime>=longRunndingStmtThreshold)
- log.warn("Long running statement took {} seconds for statement {}.", execTime / 1000, sqlCmd);
- // Return number of affected records
- return affected;
-
- } catch (SQLIntegrityConstraintViolationException sqle) {
- // ConstraintViolation
- throw new ConstraintViolationException(this, sqlCmd, sqle);
- } catch (SQLException sqle) {
- // Other error
- throw new StatementFailedException(this, sqlCmd, sqle);
- }
- }
-
- public final int executeSQL(String sqlCmd, Object[] sqlParams, Connection conn)
- {
- return executeSQL(sqlCmd, sqlParams, conn, null);
- }
-
- /**
- * @deprecated This method has be deprecated in order to avoid missing command parameters for prepared statements
- * <pre>
- * Instead of using this method signature please use any of the following:
- * executeInsert(...)
- * executeUpdate(...)
- * executeDelete(...)
- * or use
- * executeSQL(String sqlCmd, Object[] sqlParams, Connection conn)
- * </pre>
- */
- @Deprecated
- public final int executeSQL(String sqlCmd, Connection conn)
- {
- // Params missing?
- if (isPreparedStatementsEnabled() && sqlCmd.indexOf("?")>0)
- { // Params may not be provided
- log.warn("Command params may be missing for prepared statement. Please supply params by calling executeSQL with cmd.getParamValues()!");
- }
- return executeSQL(sqlCmd, null, conn);
- }
-
- /**
- * Executes an Insert statement from a command object
- * @param cmd the command object containing the insert command
- * @param conn a valid connection to the database.
- * @return the number of records that have been inserted with the supplied statement
- */
- public final int executeInsert(DBCommand cmd, Connection conn)
- {
- return executeSQL(cmd.getInsert(), cmd.getParamValues(), conn);
- }
-
- /**
- * Executes an InsertInfo statement from a command object
- * @param table the table into which to insert the selected data
- * @param cmd the command object containing the selection command
- * @param conn a valid connection to the database.
- * @return the number of records that have been inserted with the supplied statement
- */
- public final int executeInsertInto(DBTable table, DBCommand cmd, Connection conn)
- {
- return executeSQL(cmd.getInsertInto(table), cmd.getParamValues(), conn);
- }
-
- /**
- * Executes an Update statement from a command object
- * @param cmd the command object containing the update command
- * @param conn a valid connection to the database.
- * @return the number of records that have been updated with the supplied statement
- */
- public final int executeUpdate(DBCommand cmd, Connection conn)
- {
- return executeSQL(cmd.getUpdate(), cmd.getParamValues(), conn);
- }
-
- /**
- * Executes a Delete statement from a command object
- * @param from the database table from which to delete records
- * @param cmd the command object containing the delete constraints
- * @param conn a valid connection to the database.
- * @return the number of records that have been deleted with the supplied statement
- */
- public final int executeDelete(DBTable from, DBCommand cmd, Connection conn)
- {
- return executeSQL(cmd.getDelete(from), cmd.getParamValues(), conn);
- }
-
- /**
- * Executes a select SQL-Statement and returns a ResultSet containing the query results.<BR>
- * This function returns a JDBC ResultSet.<BR>
- * Instead of using this function directly you should use a DBReader object instead.<BR>
- * <P>
- * @param sqlCmd the SQL-Command
- * @param sqlParams a list of parameters for parameter queries (may depend on driver)
- * @param scrollable true if the reader should be scrollable or false if not
- * @param conn a valid connection to the database.
- * @return the JDBC ResutSet
- */
- public ResultSet executeQuery(String sqlCmd, Object[] sqlParams, boolean scrollable, Connection conn)
- {
- checkOpen();
- try
- { // Check argument
- if (conn==null)
- throw new InvalidArgumentException("conn", conn);
- // Debug
- if (log.isDebugEnabled())
- log.debug("Executing: " + sqlCmd);
- // Execute the Statement
- long start = System.currentTimeMillis();
- ResultSet rs = driver.executeQuery(sqlCmd, sqlParams, scrollable, conn);
- if (rs == null)
- throw new UnexpectedReturnValueException(rs, "driver.executeQuery()");
- // Debug
- long queryTime = (System.currentTimeMillis() - start);
- if (log.isDebugEnabled())
- log.debug("executeQuery successful in {} ms", queryTime);
- else if (queryTime>=longRunndingStmtThreshold)
- log.warn("Long running query took {} seconds for statement {}.", queryTime / 1000, sqlCmd);
- // Return number of affected records
- return rs;
-
- } catch (SQLException sqle)
- { // Error
- throw new QueryFailedException(this, sqlCmd, sqle);
- }
- }
-
- /**
- * Makes all changes made since the previous commit/rollback
- * permanent and releases any database locks currently held by the
- * Connection.
- *
- * @param conn a valid database connection
- */
- private void commit(Connection conn)
- {
- try
- { // Check argument
- if (conn==null)
- throw new InvalidArgumentException("conn", conn);
- // Commit
- if (conn.getAutoCommit()==false)
- conn.commit();
- // Done
- return;
- } catch (SQLException sqle) {
- // Commit failed!
- throw new EmpireSQLException(this, sqle);
- }
- }
-
- /**
- * Discards all changes made since the previous commit/rollback
- * and releases any database locks currently held by this
- * Connection.
- * <P>
- * @param conn a valid database connection
- */
- private void rollback(Connection conn)
- {
- try
- { // Check argument
- if (conn==null)
- throw new InvalidArgumentException("conn", conn);
- // rollback
- log.info("Database rollback issued!");
- conn.rollback();
- // Done
- return;
- } catch (SQLException sqle) {
- // Commit failed!
- throw new EmpireSQLException(this, sqle);
- }
- }
-
- /**
- * Convenience function for closing a JDBC Resultset<BR>
- * Use it instead of stmt.close()<BR>
- * <P>
- * @param stmt a Statement object
- */
- public void closeStatement(Statement stmt)
- {
- try
- { // Statement close
- if (stmt != null)
- stmt.close();
- // done
- return;
- } catch (SQLException sqle) {
- // Commit failed!
- throw new EmpireSQLException(this, sqle);
- }
- }
-
- /**
- * Convenience function for closing a JDBC Resultset<BR>
- * Use it instead of rset.close() and stmt.close()<BR>
- * <P>
- * @param rset a ResultSet object
- */
- public void closeResultSet(ResultSet rset)
- {
- try
- { // check ResultSet
- if (rset == null)
- return; // nothing to do
- // close Resultset
- Statement stmt = rset.getStatement();
- rset.close();
- // check Statement
- if (stmt == null)
- return;
- // close Statement
- stmt.close();
- // done
- return;
- } catch (SQLException sqle) {
- // Commit failed!
- throw new EmpireSQLException(this, sqle);
- }
- }
/**
* Detects the DataType of a given value.
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBDatabaseDriver.java b/empire-db/src/main/java/org/apache/empire/db/DBDatabaseDriver.java
index 934e72a..0b0887a 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBDatabaseDriver.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBDatabaseDriver.java
@@ -36,9 +36,11 @@ import org.apache.empire.commons.ObjectUtils;
import org.apache.empire.commons.StringUtils;
import org.apache.empire.data.DataType;
import org.apache.empire.db.exceptions.EmpireSQLException;
+import org.apache.empire.db.exceptions.QueryFailedException;
import org.apache.empire.exceptions.InvalidArgumentException;
import org.apache.empire.exceptions.NotImplementedException;
import org.apache.empire.exceptions.NotSupportedException;
+import org.apache.empire.exceptions.UnexpectedReturnValueException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -188,7 +190,7 @@ public abstract class DBDatabaseDriver implements Serializable
{ // Read the Sequence Value
seqValue = Math.max(rs.getLong(1) + 1, minValue);
java.sql.Timestamp current = rs.getTimestamp(2);
- db.closeResultSet(rs);
+ driver.closeResultSet(rs);
// Update existing Record
cmd.clear();
DBCmdParam name = cmd.addParam(SeqName);
@@ -202,7 +204,7 @@ public abstract class DBDatabaseDriver implements Serializable
}
else
{ // Close Reader
- db.closeResultSet(rs);
+ driver.closeResultSet(rs);
// sequence does not exist
seqValue = minValue;
log.warn("Sequence {} does not exist! Creating sequence with start-value of {}", SeqName, seqValue);
@@ -218,7 +220,7 @@ public abstract class DBDatabaseDriver implements Serializable
if (seqValue == 0)
log.warn("Failed to increment sequence {}. Trying again!", SeqName);
// close
- db.closeStatement(stmt);
+ driver.closeStatement(stmt);
cmd.clear();
rs = null;
}
@@ -230,7 +232,7 @@ public abstract class DBDatabaseDriver implements Serializable
throw new EmpireSQLException(this, e);
} finally
{ // Cleanup
- db.closeStatement(stmt);
+ driver.closeStatement(stmt);
}
}
}
@@ -386,8 +388,8 @@ public abstract class DBDatabaseDriver implements Serializable
{ // Use a numeric sequence
if (isSupported(DBDriverFeature.SEQUENCES)==false)
return null; // Create Later
- String SeqName = column.getSequenceName();
- return db.getNextSequenceValue(SeqName, conn);
+ String sequenceName = column.getSequenceName();
+ return getNextSequenceValue(db, sequenceName, 1, conn);
}
else if (type== DataType.UNIQUEID)
{ // emulate using java.util.UUID
@@ -579,9 +581,8 @@ public abstract class DBDatabaseDriver implements Serializable
}
// done
return count;
- } finally
- {
- close(stmt);
+ } finally {
+ closeStatement(stmt);
}
}
@@ -616,7 +617,7 @@ public abstract class DBDatabaseDriver implements Serializable
for (int j=0; j<res.length; j++)
result[pos+j]=res[j];
pos+=res.length;
- close(pstmt);
+ closeStatement(pstmt);
pstmt = null;
}
// has next?
@@ -637,7 +638,7 @@ public abstract class DBDatabaseDriver implements Serializable
}
return result;
} finally {
- close(pstmt);
+ closeStatement(pstmt);
}
}
else
@@ -654,12 +655,20 @@ public abstract class DBDatabaseDriver implements Serializable
int result[] = stmt.executeBatch();
return result;
} finally {
- close(stmt);
+ closeStatement(stmt);
}
}
}
- // executeQuery
+ /**
+ * Query a sql ResultSet
+ * @param sqlCmd
+ * @param sqlParams
+ * @param scrollable
+ * @param conn
+ * @return
+ * @throws SQLException
+ */
public ResultSet executeQuery(String sqlCmd, Object[] sqlParams, boolean scrollable, Connection conn)
throws SQLException
{
@@ -683,24 +692,88 @@ public abstract class DBDatabaseDriver implements Serializable
} catch(SQLException e) {
// close statement (if not null)
log.error("Error executing query '"+sqlCmd+"' --> "+e.getMessage(), e);
- close(stmt);
+ closeStatement(stmt);
throw e;
}
}
+
+ /**
+ * Query a single value
+ * @return the value of the first column in the first row of the query
+ */
+ public Object querySingleValue(String sqlCmd, Object[] sqlParams, DataType dataType, Connection conn)
+ {
+ ResultSet rs = null;
+ try
+ { // Get the next Value
+ rs = executeQuery(sqlCmd, sqlParams, false, conn);
+ if (rs == null)
+ throw new UnexpectedReturnValueException(rs, "driver.executeQuery()");
+ // Check Result
+ if (rs.next() == false)
+ { // no result
+ log.debug("querySingleValue returned no result");
+ return ObjectUtils.NO_VALUE;
+ }
+ // Read value
+ return getResultValue(rs, 1, dataType);
+ } catch (SQLException sqle)
+ { // Error
+ throw new QueryFailedException(this, sqlCmd, sqle);
+ } finally {
+ // Cleanup
+ closeResultSet(rs);
+ }
+ }
- // close
- protected void close(Statement stmt)
+ /**
+ * Convenience function for closing a JDBC Resultset<BR>
+ * Use it instead of stmt.close()<BR>
+ * <P>
+ * @param stmt a Statement object
+ */
+ public void closeStatement(Statement stmt)
{
try
{ // Statement close
if (stmt != null)
stmt.close();
- } catch (SQLException sqle)
- {
- log.error("close statement:" + sqle.toString());
+ // done
+ return;
+ } catch (SQLException sqle) {
+ // Commit failed!
+ throw new EmpireSQLException(this, sqle);
}
}
-
+
+ /**
+ * Convenience function for closing a JDBC Resultset<BR>
+ * Use it instead of rset.close() and stmt.close()<BR>
+ * <P>
+ * @param rset a ResultSet object
+ */
+ public void closeResultSet(ResultSet rset)
+ {
+ try
+ { // check ResultSet
+ if (rset == null)
+ return; // nothing to do
+ // close Resultset
+ Statement stmt = rset.getStatement();
+ rset.close();
+ // check Statement
+ if (stmt == null)
+ return;
+ // close Statement
+ stmt.close();
+ // done
+ return;
+ } catch (SQLException sqle) {
+ // Commit failed!
+ throw new EmpireSQLException(this, sqle);
+ }
+ }
+
/**
* Creates a sql string for a given value.
* Text will be enclosed in single quotes and existing single quotes will be doubled.
@@ -735,7 +808,6 @@ public abstract class DBDatabaseDriver implements Serializable
return getSQLDateTimeString(value, SQL_DATETIME_TEMPLATE, SQL_DATETIME_PATTERN, SQL_CURRENT_TIMESTAMP);
case TIMESTAMP:
return getSQLDateTimeString(value, SQL_TIMESTAMP_TEMPLATE, SQL_TIMESTAMP_PATTERN, SQL_CURRENT_TIMESTAMP);
- case TEXT:
case VARCHAR:
case CHAR:
case CLOB:
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBExpr.java b/empire-db/src/main/java/org/apache/empire/db/DBExpr.java
index 38b5199..7d21ac0 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBExpr.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBExpr.java
@@ -138,7 +138,6 @@ public abstract class DBExpr extends DBObject
case AUTOINC:
case INTEGER:
return Long.class;
- case TEXT:
case VARCHAR:
case CLOB:
case CHAR:
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 f6dafb5..04bf5a1 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
@@ -561,7 +561,8 @@ public class DBQuery extends DBRowSet
}
// Execute SQL
- int affected = db.executeSQL(upd.getUpdate(), upd.getParamValues(), conn);
+ DBUtils utils = rec.getContext().getUtils();
+ int affected = utils.executeSQL(upd.getUpdate(), upd.getParamValues());
if (affected<= 0)
{ // Error
if (affected == 0)
@@ -597,7 +598,7 @@ public class DBQuery extends DBRowSet
* @param conn a valid database connection
*/
@Override
- public void deleteRecord(Object[] keys, Connection conn)
+ public void deleteRecord(Object[] keys, DBContext context)
{
throw new NotImplementedException(this, "deleteRecord()");
}
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 7f9978a..be52aaa 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
@@ -75,6 +75,11 @@ public class DBReader extends DBRecordData implements DBContextAware
{
private final static long serialVersionUID = 1L;
+ /**
+ * DBReaderIterator
+ * Base class for DBReader interators
+ * @author rainer
+ */
public abstract class DBReaderIterator implements Iterator<DBRecordData>
{
protected int curCount = 0;
@@ -136,7 +141,7 @@ public class DBReader extends DBRecordData implements DBContextAware
return true;
} catch (SQLException e) {
// Error
- throw new EmpireSQLException(getDatabase(), e);
+ throw new EmpireSQLException(context.getDriver(), e);
}
}
@@ -286,7 +291,7 @@ public class DBReader extends DBRecordData implements DBContextAware
@Override
public DBDatabase getDatabase()
{
- return db;
+ return this.db;
}
public boolean getScrollable()
@@ -393,11 +398,11 @@ public class DBReader extends DBRecordData implements DBContextAware
try
{ // Get Value from Resultset
DataType dataType = colList[index].getDataType();
- return db.driver.getResultValue(rset, index + 1, dataType);
+ return context.getDriver().getResultValue(rset, index + 1, dataType);
} catch (SQLException e)
{ // Operation failed
- throw new EmpireSQLException(this, e);
+ throw new EmpireSQLException(context.getDriver(), e);
}
}
@@ -446,12 +451,12 @@ public class DBReader extends DBRecordData implements DBContextAware
}
}
// Execute the query
- DBDatabase queryDb = cmd.getDatabase();
- ResultSet queryRset = queryDb.executeQuery(sqlCmd, paramValues, scrollable, context.getConnection());
+ DBUtils utils = context.getUtils();
+ ResultSet queryRset = utils.executeQuery(sqlCmd, paramValues, scrollable);
if (queryRset==null)
throw new QueryNoResultException(sqlCmd);
// init
- init(queryDb, cmd.getSelectExprList(), queryRset);
+ init(cmd.getDatabase(), cmd.getSelectExprList(), queryRset);
}
/**
@@ -507,7 +512,7 @@ public class DBReader extends DBRecordData implements DBContextAware
// Close Recordset
if (rset != null)
{
- getDatabase().closeResultSet(rset);
+ context.getDriver().closeResultSet(rset);
// remove from tracking-list
endTrackingThisResultSet();
}
@@ -572,7 +577,7 @@ public class DBReader extends DBRecordData implements DBContextAware
} catch (SQLException e) {
// an error occurred
- throw new EmpireSQLException(this, e);
+ throw new EmpireSQLException(context.getDriver(), e);
}
}
@@ -597,7 +602,7 @@ public class DBReader extends DBRecordData implements DBContextAware
} catch (SQLException e) {
// an error occurred
- throw new EmpireSQLException(this, e);
+ throw new EmpireSQLException(context.getDriver(), e);
}
}
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 0c627b7..33dc99f 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
@@ -200,8 +200,8 @@ public class DBRecord extends DBRecordData implements DBContextAware, Record, Cl
protected static final Logger log = LoggerFactory.getLogger(DBRecord.class);
- private final DBContext context;
- private final DBRowSet rowset;
+ protected final DBContext context;
+ protected final DBRowSet rowset;
// This is the record data
private State state;
@@ -333,25 +333,25 @@ public class DBRecord extends DBRecordData implements DBContextAware, Record, Cl
}
/**
- * Returns the current DBDatabase object.
- *
- * @return the current DBDatabase object
+ * Returns the current Context
+ * @return
*/
@Override
- public DBDatabase getDatabase()
+ @SuppressWarnings("unchecked")
+ public <T extends DBContext> T getContext()
{
- return (rowset != null) ? rowset.db : null;
+ return ((T)context);
}
/**
- * Returns the current Context
- * @return
+ * Returns the current DBDatabase object.
+ *
+ * @return the current DBDatabase object
*/
@Override
- @SuppressWarnings("unchecked")
- public <T extends DBContext> T getContext()
+ public DBDatabase getDatabase()
{
- return ((T)context);
+ return rowset.db;
}
/**
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 379eac4..c7a7d66 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
@@ -226,7 +226,7 @@ public abstract class DBRowSet extends DBExpr
public abstract void createRecord(DBRecord rec, boolean deferredInit);
- public abstract void deleteRecord(Object[] keys, Connection conn);
+ public abstract void deleteRecord(Object[] keys, DBContext context);
/**
* Returns the full qualified name of the rowset.
@@ -729,18 +729,18 @@ public abstract class DBRowSet extends DBExpr
* @param conn a valid JDBC connection.
* @return true if the record exists or false otherwise
*/
- public boolean recordExists(Object[] key, Connection conn)
+ public boolean recordExists(Object[] key, DBContext context)
{
// Check Arguments
- if (conn == null)
- throw new InvalidArgumentException("conn", conn);
+ if (context == null)
+ throw new InvalidArgumentException("context", context);
// Select
DBCommand cmd = db.createCommand();
cmd.select(count());
// Set key constraints
setKeyConstraints(cmd, key);
// check exits
- return (db.querySingleInt(cmd, 0, conn)==1);
+ return (context.getUtils().querySingleInt(cmd, 0)==1);
}
/**
@@ -901,7 +901,8 @@ public abstract class DBRowSet extends DBExpr
return;
}
// Perform action
- int affected = db.executeSQL(sql, cmd.getParamValues(), conn, setGenKey);
+ DBUtils utils = rec.getContext().getUtils();
+ int affected = utils.executeSQL(sql, cmd.getParamValues(), setGenKey);
if (affected < 0)
{ // Update Failed
throw new UnexpectedReturnValueException(affected, "db.executeSQL()");
@@ -942,7 +943,7 @@ public abstract class DBRowSet extends DBExpr
* @param key the key the record to be deleted
* @param conn a valid connection
*/
- protected final void deleteAllReferences(Object[] key, Connection conn)
+ protected final void deleteAllReferences(Object[] key, DBContext context)
{
// Merge Sub-Records
List<DBRelation> relations = db.getRelations();
@@ -961,7 +962,7 @@ public abstract class DBRowSet extends DBExpr
if (refs[i].getTargetColumn().equals(keyColumns[0]))
{ // Found a reference on RowSet
DBRowSet rs = refs[0].getSourceColumn().getRowSet();
- rs.deleteReferenceRecords(refs, key, conn);
+ rs.deleteReferenceRecords(refs, key, context);
}
}
}
@@ -974,7 +975,7 @@ public abstract class DBRowSet extends DBExpr
* @param parentKey the key of the parent element
* @param conn a valid connection
*/
- protected void deleteReferenceRecords(DBReference[] refs, Object[] parentKey, Connection conn)
+ protected void deleteReferenceRecords(DBReference[] refs, Object[] parentKey, DBContext context)
{
// Key length and reference length must match
if (refs.length!=parentKey.length)
@@ -986,7 +987,7 @@ public abstract class DBRowSet extends DBExpr
DBCommand cmd = db.createCommand();
for (int i=0; i<parentKey.length; i++)
cmd.where(refs[i].getSourceColumn().is(parentKey[i]));
- if (db.executeSQL(cmd.getDelete((DBTable)this), cmd.getParamValues(), conn)<0)
+ if (context.getUtils().executeSQL(cmd.getDelete((DBTable)this), cmd.getParamValues())<0)
throw new UnexpectedReturnValueException(-1, "db.executeSQL()");
}
else
@@ -1004,11 +1005,11 @@ public abstract class DBRowSet extends DBExpr
cmd.orderBy(keyColumns[i], true);
}
// Query all keys
- List<Object[]> recKeys = db.queryObjectList(cmd, conn);
+ List<Object[]> recKeys = context.getUtils().queryObjectList(cmd);
for (Object[] recKey : recKeys)
{
log.info("Deleting Record " + StringUtils.valueOf(recKey) + " from table " + getName());
- deleteRecord(recKey, conn);
+ deleteRecord(recKey, context);
}
}
// Done
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 507ffae..6c99ffe 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
@@ -29,7 +29,6 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.apache.empire.commons.ObjectUtils;
import org.apache.empire.commons.Options;
import org.apache.empire.commons.StringUtils;
-import org.apache.empire.data.DataMode;
import org.apache.empire.data.DataType;
import org.apache.empire.db.DBIndex.DBIndexType;
import org.apache.empire.db.DBRelation.DBCascadeAction;
@@ -166,6 +165,7 @@ public class DBTable extends DBRowSet implements Cloneable
return clone;
}
+ @SuppressWarnings("unchecked")
public <T extends DBTable> T clone(String newAlias)
{
try {
@@ -284,30 +284,6 @@ public class DBTable extends DBRowSet implements Cloneable
}
/**
- * Deprecacted function to add a table column.
- * This function will be removed in a further release.
- * @deprecated use {@link #addColumn(String columnName, DataType type, double size, boolean required, Object defValue)} instead.
- * @return the new column object
- */
- @Deprecated
- public final DBTableColumn addColumn(String columnName, DataType type, double size, DataMode dataMode, Object defValue)
- {
- return this.addColumn(columnName, type, size, (dataMode!=DataMode.Nullable), defValue);
- }
-
- /**
- * Deprecacted function to add a table column
- * This function will be removed in a further release.
- * @deprecated use {@link #addColumn(String columnName, DataType type, double size, boolean required)} instead.
- * @return the new column object
- */
- @Deprecated
- public final DBTableColumn addColumn(String columnName, DataType type, double size, DataMode dataMode)
- {
- return this.addColumn(columnName, type, size, (dataMode!=DataMode.Nullable));
- }
-
- /**
* Creates a new DBTableColumn object and adds it to the column collection.
* Instead of the data mode enum, a boolean flag is used to indicate whether the column is required or optional.
*
@@ -617,7 +593,7 @@ public class DBTable extends DBRowSet implements Cloneable
* @param id the record's primary key
* @param conn a valid JDBC connection
*/
- public DBIndex checkUniqueConstraints(DBRecord rec, Connection conn)
+ public DBIndex checkUniqueConstraints(DBRecord rec)
{
for (DBIndex idx : getIndexes())
{
@@ -643,7 +619,8 @@ public class DBTable extends DBRowSet implements Cloneable
Object value = rec.getValue(c);
cmd.where(c.is(value));
}
- int count = db.querySingleInt(cmd, conn);
+ DBUtils utils = rec.getContext().getUtils();
+ int count = utils.querySingleInt(cmd);
if (count>0)
{ // Index is violated
return idx;
@@ -697,7 +674,7 @@ public class DBTable extends DBRowSet implements Cloneable
* @param conn a valid connection to the database.
*/
@Override
- public void deleteRecord(Object[] key, Connection conn)
+ public void deleteRecord(Object[] key, DBContext context)
{
// Check Primary key
if (primaryKey == null )
@@ -709,7 +686,7 @@ public class DBTable extends DBRowSet implements Cloneable
throw new InvalidArgumentException("key", key);
// Delete References
- deleteAllReferences(key, conn);
+ deleteAllReferences(key, context);
// Build SQL-Statement
DBCommand cmd = db.createCommand();
@@ -717,7 +694,7 @@ public class DBTable extends DBRowSet implements Cloneable
setKeyConstraints(cmd, key);
// Perform delete
String sqlCmd = cmd.getDelete(this);
- int affected = db.executeSQL(sqlCmd, cmd.getParamValues(), conn);
+ int affected = context.getUtils().executeSQL(sqlCmd, cmd.getParamValues());
if (affected < 0)
{ // Delete Failed
throw new UnexpectedReturnValueException(affected, "db.executeSQL()");
diff --git a/empire-db/src/main/java/org/apache/empire/db/DBTableColumn.java b/empire-db/src/main/java/org/apache/empire/db/DBTableColumn.java
index 47e11bf..3ab157a 100644
--- a/empire-db/src/main/java/org/apache/empire/db/DBTableColumn.java
+++ b/empire-db/src/main/java/org/apache/empire/db/DBTableColumn.java
@@ -31,7 +31,6 @@ import org.apache.empire.commons.OptionEntry;
import org.apache.empire.commons.Options;
import org.apache.empire.commons.StringUtils;
import org.apache.empire.data.Column;
-import org.apache.empire.data.DataMode;
import org.apache.empire.data.DataType;
import org.apache.empire.db.exceptions.FieldIllegalValueException;
import org.apache.empire.db.exceptions.FieldNotNullException;
@@ -93,16 +92,6 @@ public class DBTableColumn extends DBColumn
// size (after attributes!)
setSize(size);
}
-
- /**
- * Old constructor which will be removed in a further release.
- * @deprecated use {@link #DBTableColumn(DBTable table, DataType type, String name, double size, boolean required, boolean autoGenerated, Object defValue)} instead.
- */
- @Deprecated
- public DBTableColumn(DBTable table, DataType type, String name, double size, DataMode dataMode, Object defValue)
- {
- this(table, type, name, size, (dataMode!=DataMode.Nullable), (dataMode==DataMode.AutoGenerated), defValue);
- }
/**
* Clone Constructor - use clone()
@@ -491,7 +480,6 @@ public class DBTableColumn extends DBColumn
value = validateNumber(type, (Number)value);
break;
- case TEXT:
case VARCHAR:
case CHAR:
// check enum
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
new file mode 100644
index 0000000..83847ee
--- /dev/null
+++ b/empire-db/src/main/java/org/apache/empire/db/DBUtils.java
@@ -0,0 +1,732 @@
+package org.apache.empire.db;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.SQLIntegrityConstraintViolationException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.apache.empire.commons.ObjectUtils;
+import org.apache.empire.commons.Options;
+import org.apache.empire.commons.StringUtils;
+import org.apache.empire.data.DataType;
+import org.apache.empire.db.exceptions.ConstraintViolationException;
+import org.apache.empire.db.exceptions.QueryFailedException;
+import org.apache.empire.db.exceptions.QueryNoResultException;
+import org.apache.empire.db.exceptions.StatementFailedException;
+import org.apache.empire.exceptions.InternalException;
+import org.apache.empire.exceptions.InvalidArgumentException;
+import org.apache.empire.exceptions.UnexpectedReturnValueException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class DBUtils implements DBContextAware
+{
+ // Logger
+ protected static final Logger log = LoggerFactory.getLogger(DBUtils.class);
+
+ // Threshold for long running queries in milliseconds
+ protected long longRunndingStmtThreshold = 30000;
+
+ private final DBContext context;
+
+ private final DBDatabaseDriver driver;
+
+ /**
+ * Constructs an empty DBRecordSet object.
+ * @param useFieldIndexMap
+ */
+ public DBUtils(DBContext context)
+ {
+ this.context = context;
+ this.driver = context.getDriver();
+ }
+
+ /**
+ * Returns the current Context
+ * @return
+ */
+ @Override
+ @SuppressWarnings("unchecked")
+ public <T extends DBContext> T getContext()
+ {
+ return ((T)context);
+ }
+
+ /*
+ // Sequences
+ public Object getNextSequenceValue(String seqName)
+ {
+ // Ask driver
+ return driver.getNextSequenceValue(this, seqName, 1, context.getConnection());
+ }
+ */
+
+ /**
+ * Returns the value of the first row/column of a sql-query as an object.
+ * If the query does not return a result the value ObjectUtils.NO_VALUE is returned.
+ *
+ * @param sqlCmd the SQL-Command
+ * @param sqlParams list of query parameter values
+ * @param dataType the expected data type
+ * @param conn a valid connection to the database.
+ *
+ * @return the value of the first column in the first row of the query
+ */
+ public Object querySingleValue(String sqlCmd, Object[] sqlParams, DataType dataType)
+ {
+ // Debug
+ long start = System.currentTimeMillis();
+ if (log.isDebugEnabled())
+ log.debug("Executing: " + sqlCmd);
+ /*
+ // Get the next Value
+ rs = driver.executeQuery(sqlCmd, sqlParams, false, context.getConnection());
+ if (rs == null)
+ throw new UnexpectedReturnValueException(rs, "driver.executeQuery()");
+ // Check Result
+ if (rs.next() == false)
+ { // no result
+ log.debug("querySingleValue returned no result");
+ return ObjectUtils.NO_VALUE;
+ }
+ // Read value
+ Object result = driver.getResultValue(rs, 1, dataType);
+ */
+ Object result = driver.querySingleValue(sqlCmd, sqlParams, dataType, context.getConnection());
+ // Debug
+ long queryTime = (System.currentTimeMillis() - start);
+ if (log.isDebugEnabled())
+ log.debug("querySingleValue successful in {} ms. Result value={}.", queryTime, result);
+ else if (queryTime>=longRunndingStmtThreshold)
+ log.warn("Long running query took {} seconds for statement {}.", queryTime / 1000, sqlCmd);
+ // done
+ return result;
+ }
+
+ /**
+ * Returns the value of the first row/column of a sql-query as an object.
+ * If the query does not return a result a QueryNoResultException is thrown
+ *
+ * @param sqlCmd the SQL-Command
+ * @param sqlParams list of query parameter values
+ * @param conn a valid connection to the database.
+ *
+ * @return the value of the first column in the first row of the query
+ */
+ public final Object querySingleValue(String sqlCmd, Object[] sqlParams)
+ {
+ Object value = querySingleValue(sqlCmd, sqlParams, DataType.UNKNOWN);
+ if (value==ObjectUtils.NO_VALUE)
+ throw new QueryNoResultException(sqlCmd);
+ return value;
+ }
+
+ /**
+ * Returns the value of the first row/column of a sql-query as an object.
+ * If the query does not return a result a QueryNoResultException is thrown
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param dataType the expected data type
+ * @param conn a valid connection to the database.
+ *
+ * @return the value of the first column in the first row of the query
+ */
+ public final Object querySingleValue(DBCommand cmd, DataType dataType)
+ {
+ Object value = querySingleValue(cmd.getSelect(), cmd.getParamValues(), dataType);
+ if (value==ObjectUtils.NO_VALUE)
+ throw new QueryNoResultException(cmd.getSelect());
+ return value;
+ }
+
+ /**
+ * Returns the value of the first row/column of a sql-query as an object.
+ * If the query does not return a result a QueryNoResultException is thrown
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param conn a valid connection to the database.
+ *
+ * @return the value of the first column in the first row of the query
+ */
+ public final Object querySingleValue(DBCommand cmd)
+ {
+ return querySingleValue(cmd, DataType.UNKNOWN);
+ }
+
+ /**
+ * Returns the value of the first row/column of a sql-query as an int.
+ * If the query does not return a result or if the query result is NULL, then the defaultValue is returned
+ *
+ * @param sqlCmd the SQL statement
+ * @param sqlParams list of query parameter values
+ * @param defaultValue the default value if no value was returned by the database
+ * @param conn a valid connection to the database.
+ *
+ * @return the value of the first column in the first row of the query
+ */
+ public final int querySingleInt(String sqlCmd, Object[] sqlParams, int defaultValue)
+ {
+ Object value = querySingleValue(sqlCmd, sqlParams, DataType.INTEGER);
+ return ObjectUtils.getInteger(value, defaultValue);
+ }
+
+ /**
+ * Returns the value of the first row/column of a sql-query as an int.
+ * If the query does not return a result or if the query result is NULL, then the defaultValue is returned
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param defaultValue the default value if no value was returned by the database
+ * @param conn a valid connection to the database.
+ *
+ * @return the result as a int value
+ */
+ public final int querySingleInt(DBCommand cmd, int defaultValue)
+ {
+ return querySingleInt(cmd.getSelect(), cmd.getParamValues(), defaultValue);
+ }
+
+ /**
+ * Returns the value of the first row/column of a sql-query as an int.
+ * If the query does not return a result a QueryNoResultException is thrown
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param conn a valid connection to the database.
+ *
+ * @return the result as a int value
+ */
+ public final int querySingleInt(DBCommand cmd)
+ {
+ Object value = querySingleValue(cmd.getSelect(), cmd.getParamValues(), DataType.INTEGER);
+ if (ObjectUtils.isEmpty(value))
+ throw new QueryNoResultException(cmd.getSelect());
+ return ObjectUtils.getInteger(value);
+ }
+
+ /**
+ * Returns the value of the first row/column of a sql-query as a long.
+ * If the query does not return a result or if the query result is NULL, then the defaultValue is returned
+ *
+ * @param sqlCmd the SQL statement
+ * @param sqlParams list of query parameter values
+ * @param defaultValue the default value
+ * @param conn a valid connection to the database.
+ *
+ * @return the result as a long value
+ */
+ public final long querySingleLong(String sqlCmd, Object[] sqlParams, long defaultValue)
+ {
+ Object value = querySingleValue(sqlCmd, sqlParams, DataType.INTEGER);
+ return ObjectUtils.getLong(value, defaultValue);
+ }
+
+ /**
+ * Returns the value of the first row/column of a sql-query as a long.
+ * If the query does not return a result or if the query result is NULL, then the defaultValue is returned
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param defaultValue the default value
+ * @param conn a valid connection to the database.
+ *
+ * @return the result as a long value
+ */
+ public final long querySingleLong(DBCommand cmd, long defaultValue)
+ {
+ return querySingleLong(cmd.getSelect(), cmd.getParamValues(), defaultValue);
+ }
+
+ /**
+ * Returns the value of the first row/column of a sql-query as a long.
+ * If the query does not return a result a QueryNoResultException is thrown
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param conn a valid connection to the database.
+ *
+ * @return the result as a long value
+ */
+ public final long querySingleLong(DBCommand cmd)
+ {
+ Object value = querySingleValue(cmd.getSelect(), cmd.getParamValues(), DataType.INTEGER);
+ if (ObjectUtils.isEmpty(value))
+ throw new QueryNoResultException(cmd.getSelect());
+ return ObjectUtils.getLong(value);
+ }
+
+ /**
+ * Returns the value of the first row/column of a sql-query as a string.
+ * If the query does not return a result or if the query result is NULL, then the defaultValue is returned
+ *
+ * @param sqlCmd the SQL statement
+ * @param sqlParams list of query parameter values
+ * @param defaultValue the default value if no value was returned by the database
+ * @param conn a valid connection to the database.
+ *
+ * @return the result as a String object
+ */
+ public final String querySingleString(String sqlCmd, Object[] sqlParams, String defaultValue)
+ {
+ Object value = querySingleValue(sqlCmd, sqlParams, DataType.VARCHAR);
+ return (ObjectUtils.isEmpty(value) ? defaultValue : value.toString());
+ }
+
+ /**
+ * Returns the value of the first row/column of a sql-query as a string.
+ * If the query does not return a result or if the query result is NULL, then the defaultValue is returned
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param defaultValue the default value if no value was returned by the database
+ * @param conn a valid connection to the database.
+ *
+ * @return the result as a String object, if no result a empty String
+ */
+ public final String querySingleString(DBCommand cmd, String defaultValue)
+ {
+ return querySingleString(cmd.getSelect(), cmd.getParamValues(), defaultValue);
+ }
+
+ /**
+ * Returns the value of the first row/column of a sql-query as a string.
+ * If the query does not return a result a QueryNoResultException is thrown.
+ * If the query result is NULL an empty string is returned.
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param conn a valid connection to the database.
+ *
+ * @return the result as a String object, if no result a empty String
+ */
+ public final String querySingleString(DBCommand cmd)
+ {
+ Object value = querySingleValue(cmd.getSelect(), cmd.getParamValues(), DataType.VARCHAR);
+ if (value==ObjectUtils.NO_VALUE)
+ throw new QueryNoResultException(cmd.getSelect());
+ return StringUtils.toString(value, "");
+ }
+
+ /**
+ * Adds the first column of a query result to a collection.
+ * If the query has no result, an empty list is returned.
+ *
+ * @param c the class type for the list
+ * @param <T> the type for the list
+ * @param sqlCmd the SQL statement
+ * @param dataType the expected data type
+ * @param conn a valid connection to the database.
+ * @param maxRows maximum number of rows or -1 for all rows
+ *
+ * @return the number of elements that have been added to the collection
+ */
+ public <T> int querySimpleList(Class<T> c, String sqlCmd, Object[] sqlParams, DataType dataType, Collection<T> result, int maxRows)
+ { // Start query
+ ResultSet rs = null;
+ try
+ { // Log performance
+ long start = System.currentTimeMillis();
+ if (log.isDebugEnabled())
+ log.debug("Executing: " + sqlCmd);
+ // Get the next Value
+ rs = driver.executeQuery(sqlCmd, sqlParams, false, context.getConnection());
+ if (rs == null)
+ throw new UnexpectedReturnValueException(rs, "driver.executeQuery()");
+ // Check Result
+ int count=0;
+ while (rs.next() && (maxRows<0 || count<maxRows))
+ {
+ T item = ObjectUtils.convert(c, driver.getResultValue(rs, 1, dataType));
+ result.add(item);
+ count++;
+ }
+ // Debug
+ long queryTime = (System.currentTimeMillis() - start);
+ if (log.isDebugEnabled())
+ log.debug("querySimpleList retured {} items in {} ms.", count, queryTime);
+ else if (queryTime>=longRunndingStmtThreshold)
+ log.warn("Long running query took {} seconds for statement {}.", queryTime / 1000, sqlCmd);
+ // done
+ return count;
+ } catch (ClassCastException e)
+ { log.error("querySingleValue cast exception: ", e);
+ throw new InternalException(e);
+ } catch (SQLException sqle)
+ { // Error
+ throw new QueryFailedException(driver, sqlCmd, sqle);
+ } finally
+ { // Cleanup
+ driver.closeResultSet(rs);
+ }
+ }
+
+ /**
+ * Adds the first column of a query result to a collection.
+ * If the query has no result, an empty list is returned.
+ *
+ * @param c the class type for the list
+ * @param <T> the type for the list
+ * @param cmd the Command object that contains the select statement
+ * @param conn a valid connection to the database.
+ *
+ * @return the number of elements that have been added to the collection
+ */
+ public final <T> int querySimpleList(Class<T> c, DBCommand cmd, Collection<T> result)
+ {
+ return querySimpleList(c, cmd.getSelect(), cmd.getParamValues(), DataType.UNKNOWN, result, -1);
+ }
+
+ /**
+ * Returns a one dimensional array from an sql query.
+ * The array is filled with the values of the first column.
+ *
+ * @param c the class type for the list
+ * @param <T> the type for the list
+ * @param cmd the Command object that contains the select statement
+ * @param conn a valid connection to the database.
+ *
+ * @return a list of the values of the first column of an sql query
+ */
+ public final <T> List<T> querySimpleList(Class<T> c, DBCommand cmd)
+ { // Execute the Statement
+ List<T> result = new ArrayList<T>();
+ if (querySimpleList(c, cmd, result)<0)
+ return null;
+ return result;
+ }
+
+ /**
+ * Returns a one dimensional array from an sql query.
+ * The array is filled with the values of the first column.
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param conn a valid connection to the database.
+ * @return a list of values of type Object
+ */
+ public final List<Object> querySimpleList(DBCommand cmd)
+ { // Execute the Statement
+ return querySimpleList(Object.class, cmd);
+ }
+
+ /**
+ * Fills an option list provided with the result from a query.
+ * The option list is filled with the values of the first and second column.
+ *
+ * @param sqlCmd the SQL statement
+ * @param conn a valid connection to the database.
+ * @return an Options object containing a set a of values and their corresponding names
+ */
+ public int queryOptionList(String sqlCmd, Object[] sqlParams, Options result)
+ { // Execute the Statement
+ ResultSet rs = null;
+ try
+ { // Debug
+ long start = System.currentTimeMillis();
+ if (log.isDebugEnabled())
+ log.debug("Executing: " + sqlCmd);
+ // Get the next Value
+ rs = driver.executeQuery(sqlCmd, sqlParams, false, context.getConnection());
+ if (rs == null)
+ throw new UnexpectedReturnValueException(rs, "driver.executeQuery()");
+ if (rs.getMetaData().getColumnCount()<2)
+ throw new InvalidArgumentException("sqlCmd", sqlCmd);
+ // Check Result
+ int count = 0;
+ while (rs.next())
+ {
+ Object value = rs.getObject(1);
+ String text = rs.getString(2);
+ result.add(value, text, true);
+ count++;
+ }
+ // Debug
+ long queryTime = (System.currentTimeMillis() - start);
+ if (log.isDebugEnabled())
+ log.debug("queryOptionList retured {} items in {} ms.", count, queryTime);
+ else if (queryTime>=longRunndingStmtThreshold)
+ log.warn("Long running query took {} seconds for statement {}.", queryTime / 1000, sqlCmd);
+ // done
+ return count;
+ } catch (SQLException sqle)
+ { // Error
+ throw new QueryFailedException(driver, sqlCmd, sqle);
+ } finally
+ { // Cleanup
+ driver.closeResultSet(rs);
+ }
+ }
+
+ /**
+ * Fills an option list provided with the result from a query.
+ * The option list is filled with the values of the first and second column.
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param conn a valid connection to the database.
+ * @return an Options object containing a set a of values and their corresponding names
+ */
+ public final int queryOptionList(DBCommand cmd, Options result)
+ { // Execute the Statement
+ return queryOptionList(cmd.getSelect(), cmd.getParamValues(), result);
+ }
+
+ /**
+ * Returns a list of key value pairs from an sql query.
+ * The option list is filled with the values of the first and second column.
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param conn a valid connection to the database.
+ * @return an Options object containing a set a of values and their corresponding names
+ */
+ public final Options queryOptionList(DBCommand cmd)
+ { // Execute the Statement
+ Options options = new Options();
+ queryOptionList(cmd.getSelect(), cmd.getParamValues(), options);
+ return options;
+ }
+
+ /**
+ * Adds the result of a query to a given collection.<br>
+ * The individual rows will be added as an array of objects (object[])
+ * <p>This function should only be used for small lists.
+ * Otherwise a DBReader should be used!</p>
+ *
+ * @param sqlCmd the SQL statement
+ * @param conn a valid connection to the database.
+ * @return a list of object arrays
+ */
+ public int queryObjectList(String sqlCmd, Object[] sqlParams, Collection<Object[]> result, int maxRows)
+ { // Perform query
+ ResultSet rs = null;
+ try
+ { // Log performance
+ long start = System.currentTimeMillis();
+ if (log.isDebugEnabled())
+ log.debug("Executing: " + sqlCmd);
+ // Get the next Value
+ rs = driver.executeQuery(sqlCmd, sqlParams, false, context.getConnection());
+ if (rs == null)
+ throw new UnexpectedReturnValueException(rs, "driver.executeQuery()");
+ // Read List
+ int colCount = rs.getMetaData().getColumnCount();
+ int count = 0;
+ while (rs.next() && (maxRows<0 || count<maxRows))
+ { // Read row
+ Object[] item = new Object[colCount];
+ for (int i=0; i<colCount; i++)
+ { // Read from Resultset
+ item[i] = driver.getResultValue(rs, i+1, DataType.UNKNOWN);
+ }
+ result.add(item);
+ count++;
+ }
+ // Debug
+ long queryTime = (System.currentTimeMillis() - start);
+ if (log.isDebugEnabled())
+ log.debug("queryObjectList retured {} items in {} ms.", count, queryTime);
+ else if (queryTime>=longRunndingStmtThreshold)
+ log.warn("Long running query took {} seconds for statement {}.", queryTime / 1000, sqlCmd);
+ // done
+ return count;
+ } catch (SQLException sqle)
+ { // Error
+ throw new QueryFailedException(driver, sqlCmd, sqle);
+ } finally
+ { // Cleanup
+ driver.closeResultSet(rs);
+ }
+ }
+
+ /**
+ * Adds the result of a query to a given collection.<br>
+ * The individual rows will be added as an array of objects (object[])
+ * <p>This function should only be used for small lists.
+ * Otherwise a DBReader should be used!</p>
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param conn a valid connection to the database.
+ * @return a list of object arrays
+ */
+ public final int queryObjectList(DBCommand cmd, Collection<Object[]> result)
+ { // Perform query
+ return queryObjectList(cmd.getSelect(), cmd.getParamValues(), result, -1);
+ }
+
+ /**
+ * Returns the result of a query as a list Object-Arrays
+ * This function should only be used for small lists.
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param conn a valid connection to the database.
+ * @return a list of object arrays
+ */
+ public final List<Object[]> queryObjectList(DBCommand cmd)
+ { // Execute the Statement
+ List<Object[]> result = new ArrayList<Object[]>();
+ queryObjectList(cmd.getSelect(), cmd.getParamValues(), result, -1);
+ return result;
+ }
+
+ /**
+ * Returns all values of the first row of a sql-query as an array.
+ * If the query does not return a result a QueryNoResultException is thrown
+ *
+ * @param sqlCmd the SQL-Command
+ * @param sqlParams list of query parameter values
+ * @param conn a valid connection to the database.
+ *
+ * @return the values of the first row
+ */
+ public Object[] querySingleRow(String sqlCmd, Object[] sqlParams)
+ {
+ List<Object[]> result = new ArrayList<Object[]>();
+ queryObjectList(sqlCmd, sqlParams, result, 1);
+ if (result.size()<1)
+ throw new QueryNoResultException(sqlCmd);
+ return result.get(0);
+ }
+
+ /**
+ * Returns all values of the first row of a sql-query as an array.
+ * If the query does not return a result a QueryNoResultException is thrown
+ *
+ * @param cmd the Command object that contains the select statement
+ * @param conn a valid connection to the database.
+ *
+ * @return the values of the first row
+ */
+ public final Object[] querySingleRow(DBCommand cmd)
+ {
+ return querySingleRow(cmd.getSelect(), cmd.getParamValues());
+ }
+
+ /**
+ * Executes an update, insert or delete SQL-Statement.<BR>
+ * We recommend to use a DBCommand object in order to build the sqlCmd.<BR>
+ * <P>
+ * @param sqlCmd the SQL-Command
+ * @param sqlParams a list of objects to replace sql parameters
+ * @param conn a valid connection to the database.
+ * @param setGenKeys object to set the generated keys for
+ * @return the row count for insert, update or delete or 0 for SQL statements that return nothing
+ */
+ public int executeSQL(String sqlCmd, Object[] sqlParams, DBDatabaseDriver.DBSetGenKeys setGenKeys)
+ {
+ try
+ { // Debug
+ if (log.isInfoEnabled())
+ log.info("Executing: " + sqlCmd);
+ // execute SQL
+ long start = System.currentTimeMillis();
+ int affected = driver.executeSQL(sqlCmd, sqlParams, context.getConnection(), setGenKeys);
+ // number of affected records
+ if (affected < 0)
+ throw new UnexpectedReturnValueException(affected, "driver.executeSQL()");
+ // Log
+ long execTime = (System.currentTimeMillis() - start);
+ if (log.isInfoEnabled())
+ log.info("executeSQL affected {} Records in {} ms ", affected, execTime);
+ else if (execTime>=longRunndingStmtThreshold)
+ log.warn("Long running statement took {} seconds for statement {}.", execTime / 1000, sqlCmd);
+ // Return number of affected records
+ return affected;
+
+ } catch (SQLIntegrityConstraintViolationException sqle) {
+ // ConstraintViolation
+ throw new ConstraintViolationException(driver, sqlCmd, sqle);
+ } catch (SQLException sqle) {
+ // Other error
+ throw new StatementFailedException(driver, sqlCmd, sqle);
+ }
+ }
+
+ /**
+ * Executes an SQLStatment
+ * @param sqlCmd the SQL-Command
+ * @param sqlParams a list of objects to replace sql parameters
+ */
+ public final int executeSQL(String sqlCmd, Object[] sqlParams)
+ {
+ return executeSQL(sqlCmd, sqlParams, null);
+ }
+
+ /**
+ * Executes an Insert statement from a command object
+ * @param cmd the command object containing the insert command
+ * @param conn a valid connection to the database.
+ * @return the number of records that have been inserted with the supplied statement
+ */
+ public final int executeInsert(DBCommand cmd)
+ {
+ return executeSQL(cmd.getInsert(), cmd.getParamValues());
+ }
+
+ /**
+ * Executes an InsertInfo statement from a command object
+ * @param table the table into which to insert the selected data
+ * @param cmd the command object containing the selection command
+ * @param conn a valid connection to the database.
+ * @return the number of records that have been inserted with the supplied statement
+ */
+ public final int executeInsertInto(DBTable table, DBCommand cmd)
+ {
+ return executeSQL(cmd.getInsertInto(table), cmd.getParamValues());
+ }
+
+ /**
+ * Executes an Update statement from a command object
+ * @param cmd the command object containing the update command
+ * @param conn a valid connection to the database.
+ * @return the number of records that have been updated with the supplied statement
+ */
+ public final int executeUpdate(DBCommand cmd)
+ {
+ return executeSQL(cmd.getUpdate(), cmd.getParamValues());
+ }
+
+ /**
+ * Executes a Delete statement from a command object
+ * @param from the database table from which to delete records
+ * @param cmd the command object containing the delete constraints
+ * @param conn a valid connection to the database.
+ * @return the number of records that have been deleted with the supplied statement
+ */
+ public final int executeDelete(DBTable from, DBCommand cmd)
+ {
+ return executeSQL(cmd.getDelete(from), cmd.getParamValues());
+ }
+
+ /**
+ * Executes a select SQL-Statement and returns a ResultSet containing the query results.<BR>
+ * This function returns a JDBC ResultSet.<BR>
+ * Instead of using this function directly you should use a DBReader object instead.<BR>
+ * <P>
+ * @param sqlCmd the SQL-Command
+ * @param sqlParams a list of parameters for parameter queries (may depend on driver)
+ * @param scrollable true if the reader should be scrollable or false if not
+ * @param conn a valid connection to the database.
+ * @return the JDBC ResutSet
+ */
+ public ResultSet executeQuery(String sqlCmd, Object[] sqlParams, boolean scrollable)
+ {
+ try
+ { // Debug
+ if (log.isDebugEnabled())
+ log.debug("Executing: " + sqlCmd);
+ // Execute the Statement
+ long start = System.currentTimeMillis();
+ ResultSet rs = driver.executeQuery(sqlCmd, sqlParams, scrollable, context.getConnection());
+ if (rs == null)
+ throw new UnexpectedReturnValueException(rs, "driver.executeQuery()");
+ // Debug
+ long queryTime = (System.currentTimeMillis() - start);
+ if (log.isDebugEnabled())
+ log.debug("executeQuery successful in {} ms", queryTime);
+ else if (queryTime>=longRunndingStmtThreshold)
+ log.warn("Long running query took {} seconds for statement {}.", queryTime / 1000, sqlCmd);
+ // Return number of affected records
+ return rs;
+
+ } catch (SQLException sqle)
+ { // Error
+ throw new QueryFailedException(driver, sqlCmd, sqle);
+ }
+ }
+
+
+}
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 97d1b9f..f18570c 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
@@ -18,7 +18,6 @@
*/
package org.apache.empire.db;
-import java.sql.Connection;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.empire.commons.Options;
@@ -420,7 +419,7 @@ public abstract class DBView extends DBRowSet
* @see org.apache.empire.db.DBRowSet#deleteRecord(java.lang.Object[], java.sql.Connection, boolean)
*/
@Override
- public void deleteRecord(Object[] keys, Connection conn)
+ public void deleteRecord(Object[] keys, DBContext context)
{
throw new NotSupportedException(this, "deleteRecord");
}
diff --git a/empire-db/src/main/java/org/apache/empire/db/context/DBContextBase.java b/empire-db/src/main/java/org/apache/empire/db/context/DBContextBase.java
index 2965f5e..cdc9a64 100644
--- a/empire-db/src/main/java/org/apache/empire/db/context/DBContextBase.java
+++ b/empire-db/src/main/java/org/apache/empire/db/context/DBContextBase.java
@@ -11,6 +11,7 @@ import java.util.Map;
import org.apache.empire.db.DBContext;
import org.apache.empire.db.DBObject;
import org.apache.empire.db.DBRollbackHandler;
+import org.apache.empire.db.DBUtils;
import org.apache.empire.db.exceptions.EmpireSQLException;
import org.apache.empire.exceptions.InvalidArgumentException;
import org.slf4j.Logger;
@@ -23,6 +24,21 @@ public abstract class DBContextBase implements DBContext
private Map<DBObject, DBRollbackHandler> rollbackHandler;
+ private DBUtils utils = null;
+
+ @Override
+ public DBUtils getUtils()
+ {
+ if (utils==null)
+ utils = createUtils();
+ return utils;
+ }
+
+ protected DBUtils createUtils()
+ {
+ return new DBUtils(this);
+ }
+
@Override
public synchronized void commit()
{
diff --git a/empire-db/src/main/java/org/apache/empire/db/derby/DBDatabaseDriverDerby.java b/empire-db/src/main/java/org/apache/empire/db/derby/DBDatabaseDriverDerby.java
index 8eed386..0f88dfa 100644
--- a/empire-db/src/main/java/org/apache/empire/db/derby/DBDatabaseDriverDerby.java
+++ b/empire-db/src/main/java/org/apache/empire/db/derby/DBDatabaseDriverDerby.java
@@ -259,7 +259,6 @@ public class DBDatabaseDriverDerby extends DBDatabaseDriver
case DATETIME:
case TIMESTAMP: return "CAST(? AS TIMESTAMP)";
// Convert to text
- case TEXT:
case VARCHAR:
case CHAR:
return "CAST(? AS CHAR)";
diff --git a/empire-db/src/main/java/org/apache/empire/db/exceptions/ConstraintViolationException.java b/empire-db/src/main/java/org/apache/empire/db/exceptions/ConstraintViolationException.java
index 22693cc..569a7fb 100644
--- a/empire-db/src/main/java/org/apache/empire/db/exceptions/ConstraintViolationException.java
+++ b/empire-db/src/main/java/org/apache/empire/db/exceptions/ConstraintViolationException.java
@@ -21,7 +21,7 @@ package org.apache.empire.db.exceptions;
import java.sql.SQLException;
import org.apache.empire.commons.ErrorType;
-import org.apache.empire.db.DBObject;
+import org.apache.empire.db.DBDatabaseDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,9 +37,9 @@ public class ConstraintViolationException extends EmpireSQLException
public static final ErrorType errorType = new ErrorType("error.db.statementFailed", "Error executing statement {0}.\r\nNative error is: {1}");
- public ConstraintViolationException(DBObject obj, String sqlCmd, SQLException cause)
+ public ConstraintViolationException(DBDatabaseDriver driver, String sqlCmd, SQLException cause)
{
- super(ConstraintViolationException.errorType, new String[] { sqlCmd, messageFromSQLException(driverFromObject(obj), cause) }, 1, cause);
+ super(ConstraintViolationException.errorType, new String[] { sqlCmd, messageFromSQLException(driver, cause) }, 1, cause);
}
/**
diff --git a/empire-db/src/main/java/org/apache/empire/db/exceptions/QueryFailedException.java b/empire-db/src/main/java/org/apache/empire/db/exceptions/QueryFailedException.java
index 85ca3c4..0c4cc33 100644
--- a/empire-db/src/main/java/org/apache/empire/db/exceptions/QueryFailedException.java
+++ b/empire-db/src/main/java/org/apache/empire/db/exceptions/QueryFailedException.java
@@ -21,6 +21,7 @@ package org.apache.empire.db.exceptions;
import java.sql.SQLException;
import org.apache.empire.commons.ErrorType;
+import org.apache.empire.db.DBDatabaseDriver;
import org.apache.empire.db.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,9 +38,14 @@ public class QueryFailedException extends EmpireSQLException
public static final ErrorType errorType = new ErrorType("error.db.queryFailed", "Error executing query {0}.\r\nNative error is: {1}");
+ public QueryFailedException(DBDatabaseDriver driver, String sqlCmd, SQLException cause)
+ {
+ super(QueryFailedException.errorType, new String[] { sqlCmd, messageFromSQLException(driver, cause) }, 1, cause);
+ }
+
public QueryFailedException(DBObject obj, String sqlCmd, SQLException cause)
{
- super(QueryFailedException.errorType, new String[] { sqlCmd, messageFromSQLException(driverFromObject(obj), cause) }, 1, cause);
+ this(driverFromObject(obj), sqlCmd, cause);
}
/**
diff --git a/empire-db/src/main/java/org/apache/empire/db/exceptions/StatementFailedException.java b/empire-db/src/main/java/org/apache/empire/db/exceptions/StatementFailedException.java
index 69c27fa..6c9c83c 100644
--- a/empire-db/src/main/java/org/apache/empire/db/exceptions/StatementFailedException.java
+++ b/empire-db/src/main/java/org/apache/empire/db/exceptions/StatementFailedException.java
@@ -21,7 +21,7 @@ package org.apache.empire.db.exceptions;
import java.sql.SQLException;
import org.apache.empire.commons.ErrorType;
-import org.apache.empire.db.DBObject;
+import org.apache.empire.db.DBDatabaseDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,9 +37,9 @@ public class StatementFailedException extends EmpireSQLException
public static final ErrorType errorType = new ErrorType("error.db.statementFailed", "Error executing statement {0}.\r\nNative error is: {1}");
- public StatementFailedException(DBObject obj, String sqlCmd, SQLException cause)
+ public StatementFailedException(DBDatabaseDriver driver, String sqlCmd, SQLException cause)
{
- super(StatementFailedException.errorType, new String[] { sqlCmd, messageFromSQLException(driverFromObject(obj), cause) }, 1, cause);
+ super(StatementFailedException.errorType, new String[] { sqlCmd, messageFromSQLException(driver, cause) }, 1, cause);
}
/**
diff --git a/empire-db/src/main/java/org/apache/empire/db/h2/DBDatabaseDriverH2.java b/empire-db/src/main/java/org/apache/empire/db/h2/DBDatabaseDriverH2.java
index 67289ec..36aea77 100644
--- a/empire-db/src/main/java/org/apache/empire/db/h2/DBDatabaseDriverH2.java
+++ b/empire-db/src/main/java/org/apache/empire/db/h2/DBDatabaseDriverH2.java
@@ -306,7 +306,6 @@ public class DBDatabaseDriverH2 extends DBDatabaseDriver
case DATETIME:
case TIMESTAMP: return "CAST(? AS DATETIME)";
// Convert to text
- case TEXT:
case VARCHAR:
case CHAR:
return "CAST(? AS CHAR)";
diff --git a/empire-db/src/main/java/org/apache/empire/db/hsql/DBDatabaseDriverHSql.java b/empire-db/src/main/java/org/apache/empire/db/hsql/DBDatabaseDriverHSql.java
index 72a2f03..f1e008c 100644
--- a/empire-db/src/main/java/org/apache/empire/db/hsql/DBDatabaseDriverHSql.java
+++ b/empire-db/src/main/java/org/apache/empire/db/hsql/DBDatabaseDriverHSql.java
@@ -21,6 +21,7 @@ package org.apache.empire.db.hsql;
import java.sql.Connection;
import java.util.GregorianCalendar;
+import org.apache.empire.commons.ObjectUtils;
import org.apache.empire.data.DataType;
import org.apache.empire.db.DBCmdType;
import org.apache.empire.db.DBColumnExpr;
@@ -32,6 +33,7 @@ import org.apache.empire.db.DBDriverFeature;
import org.apache.empire.db.DBObject;
import org.apache.empire.db.DBSQLScript;
import org.apache.empire.db.DBTableColumn;
+import org.apache.empire.db.exceptions.QueryNoResultException;
import org.apache.empire.exceptions.NotSupportedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -196,7 +198,6 @@ public class DBDatabaseDriverHSql extends DBDatabaseDriver
* DBExpr.DT_DATE: return "convert(datetime, ?, 111)"; case DBExpr.DT_DATETIME: return "convert(datetime, ?, 120)";
*/
// Convert to text
- case TEXT:
case VARCHAR:
case CHAR:
if (format != null)
@@ -242,14 +243,17 @@ public class DBDatabaseDriverHSql extends DBDatabaseDriver
sql.append("NEXT VALUE FOR ");
db.appendQualifiedName(sql, seqName, detectQuoteName(seqName));
sql.append(" FROM INFORMATION_SCHEMA.SYSTEM_SEQUENCES WHERE SEQUENCE_NAME='").append(seqName).append("'");
-
- Object val = db.querySingleValue(sql.toString(), null, conn);
- if (val == null)
- { // Error!
+ // Query next sequence value
+ String sqlCmd = sql.toString();
+ if (log.isDebugEnabled())
+ log.debug("Executing: " + sqlCmd);
+ Object val = querySingleValue(sqlCmd, null, DataType.UNKNOWN, conn);
+ if (ObjectUtils.isEmpty(val))
+ { // Error!
log.error("getNextSequenceValue: Invalid sequence value for sequence " + seqName);
+ throw new QueryNoResultException(sqlCmd);
}
// Done
-
return val;
}
diff --git a/empire-db/src/main/java/org/apache/empire/db/mysql/DBDatabaseDriverMySQL.java b/empire-db/src/main/java/org/apache/empire/db/mysql/DBDatabaseDriverMySQL.java
index 11c9859..1b50359 100644
--- a/empire-db/src/main/java/org/apache/empire/db/mysql/DBDatabaseDriverMySQL.java
+++ b/empire-db/src/main/java/org/apache/empire/db/mysql/DBDatabaseDriverMySQL.java
@@ -873,6 +873,7 @@ public class DBDatabaseDriverMySQL extends DBDatabaseDriver
*
* @see org.apache.empire.db.DBDatabaseDriver#openDatabase(org.apache.empire.db.DBDatabase, java.sql.Connection)
*/
+ @SuppressWarnings("unused")
@Override
public void attachDatabase(DBDatabase db, Connection conn)
{
@@ -1066,7 +1067,6 @@ public class DBDatabaseDriverMySQL extends DBDatabaseDriver
case DATETIME:
case TIMESTAMP: return "CAST(? AS DATETIME)";
// Convert to text
- case TEXT:
case VARCHAR:
case CHAR:
if (format != null)
diff --git a/empire-db/src/main/java/org/apache/empire/db/mysql/MySQLDDLGenerator.java b/empire-db/src/main/java/org/apache/empire/db/mysql/MySQLDDLGenerator.java
index cc9b4ff..0575673 100644
--- a/empire-db/src/main/java/org/apache/empire/db/mysql/MySQLDDLGenerator.java
+++ b/empire-db/src/main/java/org/apache/empire/db/mysql/MySQLDDLGenerator.java
@@ -113,6 +113,7 @@ public class MySQLDDLGenerator extends DBDDLGenerator<DBDatabaseDriverMySQL>
return true;
}
+ @SuppressWarnings("unused")
@Override
protected void createDatabase(DBDatabase db, DBSQLScript script)
{
diff --git a/empire-db/src/main/java/org/apache/empire/db/oracle/DBDatabaseDriverOracle.java b/empire-db/src/main/java/org/apache/empire/db/oracle/DBDatabaseDriverOracle.java
index ba1ac06..0065780 100644
--- a/empire-db/src/main/java/org/apache/empire/db/oracle/DBDatabaseDriverOracle.java
+++ b/empire-db/src/main/java/org/apache/empire/db/oracle/DBDatabaseDriverOracle.java
@@ -23,6 +23,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
+import org.apache.empire.commons.ObjectUtils;
import org.apache.empire.commons.StringUtils;
import org.apache.empire.data.DataType;
import org.apache.empire.db.DBCmdType;
@@ -44,6 +45,7 @@ import org.apache.empire.db.DBTableColumn;
import org.apache.empire.db.DBView;
import org.apache.empire.db.context.DBContextStatic;
import org.apache.empire.db.exceptions.EmpireSQLException;
+import org.apache.empire.db.exceptions.QueryNoResultException;
import org.apache.empire.db.expr.column.DBValueExpr;
import org.apache.empire.exceptions.InvalidArgumentException;
import org.slf4j.Logger;
@@ -230,7 +232,6 @@ public class DBDatabaseDriverOracle extends DBDatabaseDriver
* DBExpr.DT_DATE: return "convert(datetime, ?, 111)"; case DBExpr.DT_DATETIME: return "convert(datetime, ?, 120)";
*/
// Convert to text
- case TEXT:
case VARCHAR:
case CHAR:
case CLOB:
@@ -326,10 +327,15 @@ public class DBDatabaseDriverOracle extends DBDatabaseDriver
sql.append("SELECT ");
db.appendQualifiedName(sql, seqName, detectQuoteName(seqName));
sql.append(".NEXTVAL FROM DUAL");
- Object val = db.querySingleValue(sql.toString(), null, conn);
- if (val == null)
- { // Error!
+ // Query next sequence value
+ String sqlCmd = sql.toString();
+ if (log.isDebugEnabled())
+ log.debug("Executing: " + sqlCmd);
+ Object val = querySingleValue(sqlCmd, null, DataType.UNKNOWN, conn);
+ if (ObjectUtils.isEmpty(val))
+ { // Error!
log.error("getNextSequenceValue: Invalid sequence value for sequence " + seqName);
+ throw new QueryNoResultException(sqlCmd);
}
// Done
return val;
diff --git a/empire-db/src/main/java/org/apache/empire/db/oracle/OracleDDLGenerator.java b/empire-db/src/main/java/org/apache/empire/db/oracle/OracleDDLGenerator.java
index 94176ef..821f796 100644
--- a/empire-db/src/main/java/org/apache/empire/db/oracle/OracleDDLGenerator.java
+++ b/empire-db/src/main/java/org/apache/empire/db/oracle/OracleDDLGenerator.java
@@ -65,7 +65,6 @@ public class OracleDDLGenerator extends DBDDLGenerator<DBDatabaseDriverOracle>
{
switch (type)
{
- case TEXT:
case VARCHAR:
case CHAR:
{ // Char or Varchar
diff --git a/empire-db/src/main/java/org/apache/empire/db/postgresql/DBDatabaseDriverPostgreSQL.java b/empire-db/src/main/java/org/apache/empire/db/postgresql/DBDatabaseDriverPostgreSQL.java
index 39965e5..f884dcc 100644
--- a/empire-db/src/main/java/org/apache/empire/db/postgresql/DBDatabaseDriverPostgreSQL.java
+++ b/empire-db/src/main/java/org/apache/empire/db/postgresql/DBDatabaseDriverPostgreSQL.java
@@ -23,6 +23,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.GregorianCalendar;
+import org.apache.empire.commons.ObjectUtils;
import org.apache.empire.commons.StringUtils;
import org.apache.empire.data.DataType;
import org.apache.empire.db.DBCmdType;
@@ -36,6 +37,7 @@ import org.apache.empire.db.DBObject;
import org.apache.empire.db.DBSQLScript;
import org.apache.empire.db.DBTableColumn;
import org.apache.empire.db.exceptions.EmpireSQLException;
+import org.apache.empire.db.exceptions.QueryNoResultException;
import org.apache.empire.db.expr.column.DBValueExpr;
import org.apache.empire.exceptions.InvalidArgumentException;
import org.slf4j.Logger;
@@ -406,7 +408,6 @@ public class DBDatabaseDriverPostgreSQL extends DBDatabaseDriver
case DATETIME:
case TIMESTAMP:return "CAST(? AS TIMESTAMP)";
// Convert to text
- case TEXT:
case VARCHAR:
case CHAR: return "CAST(? AS CHAR)";
case BLOB: return "CAST(? AS bytea)";
@@ -430,11 +431,17 @@ public class DBDatabaseDriverPostgreSQL extends DBDatabaseDriver
sql.append("SELECT nextval('");
db.appendQualifiedName(sql, seqName, detectQuoteName(seqName));
sql.append("')");
- Object val = db.querySingleValue(sql.toString(), null, conn);
- if (val == null)
- { // Error!
+ // Query next sequence value
+ String sqlCmd = sql.toString();
+ if (log.isDebugEnabled())
+ log.debug("Executing: " + sqlCmd);
+ Object val = querySingleValue(sqlCmd, null, DataType.UNKNOWN, conn);
+ if (ObjectUtils.isEmpty(val))
+ { // Error!
log.error("getNextSequenceValue: Invalid sequence value for sequence " + seqName);
+ throw new QueryNoResultException(sqlCmd);
}
+ // Done
return val;
}
diff --git a/empire-db/src/main/java/org/apache/empire/db/sqlite/DBDatabaseDriverSQLite.java b/empire-db/src/main/java/org/apache/empire/db/sqlite/DBDatabaseDriverSQLite.java
index d038427..c8a1c64 100644
--- a/empire-db/src/main/java/org/apache/empire/db/sqlite/DBDatabaseDriverSQLite.java
+++ b/empire-db/src/main/java/org/apache/empire/db/sqlite/DBDatabaseDriverSQLite.java
@@ -409,7 +409,7 @@ public class DBDatabaseDriverSQLite extends DBDatabaseDriver
}
finally
{
- close(stmt);
+ closeStatement(stmt);
}
return count;
}
@@ -457,7 +457,6 @@ public class DBDatabaseDriverSQLite extends DBDatabaseDriver
switch (destType)
{
// Convert to text
- case TEXT:
case VARCHAR:
case CHAR:
if (format != null)
diff --git a/empire-db/src/main/java/org/apache/empire/db/sqlserver/DBDatabaseDriverMSSQL.java b/empire-db/src/main/java/org/apache/empire/db/sqlserver/DBDatabaseDriverMSSQL.java
index d013245..2314b3a 100644
--- a/empire-db/src/main/java/org/apache/empire/db/sqlserver/DBDatabaseDriverMSSQL.java
+++ b/empire-db/src/main/java/org/apache/empire/db/sqlserver/DBDatabaseDriverMSSQL.java
@@ -376,7 +376,6 @@ public class DBDatabaseDriverMSSQL extends DBDatabaseDriver
case TIMESTAMP: return isUseDateTime2() ? "convert(datetime2, ?, 121)"
: "convert(datetime, ?, 121)";
// Convert to text
- case TEXT:
case VARCHAR:
case CHAR:
case CLOB:
@@ -468,7 +467,7 @@ public class DBDatabaseDriverMSSQL extends DBDatabaseDriver
// Supports sequences?
if (column.getDataType()==DataType.UNIQUEID)
{
- return db.querySingleValue("select newid()", null, conn);
+ return querySingleValue("select newid()", null, DataType.UNIQUEID, conn);
}
return super.getColumnAutoValue(db, column, conn);
}
diff --git a/empire-db/src/main/java/org/apache/empire/db/sqlserver/MSSqlDDLGenerator.java b/empire-db/src/main/java/org/apache/empire/db/sqlserver/MSSqlDDLGenerator.java
index 7109d59..d5af98b 100644
--- a/empire-db/src/main/java/org/apache/empire/db/sqlserver/MSSqlDDLGenerator.java
+++ b/empire-db/src/main/java/org/apache/empire/db/sqlserver/MSSqlDDLGenerator.java
@@ -75,7 +75,6 @@ public class MSSqlDDLGenerator extends DBDDLGenerator<DBDatabaseDriverMSSQL>
return false;
}
break;
- case TEXT:
case VARCHAR:
case CHAR:
{ // Char or Varchar
diff --git a/empire-db/src/main/java/org/apache/empire/db/validation/DBModelChecker.java b/empire-db/src/main/java/org/apache/empire/db/validation/DBModelChecker.java
index db36dec..508ea4e 100644
--- a/empire-db/src/main/java/org/apache/empire/db/validation/DBModelChecker.java
+++ b/empire-db/src/main/java/org/apache/empire/db/validation/DBModelChecker.java
@@ -394,7 +394,6 @@ public class DBModelChecker
case AUTOINC:
checkAutoIncColumn(column, remoteColumn, handler);
break;
- case TEXT:
case VARCHAR:
checkTextColumn(column, remoteColumn, handler);
break;
diff --git a/empire-db/src/test/java/org/apache/empire/db/DBCommandTest.java b/empire-db/src/test/java/org/apache/empire/db/DBCommandTest.java
index d125fb0..578aaf9 100644
--- a/empire-db/src/test/java/org/apache/empire/db/DBCommandTest.java
+++ b/empire-db/src/test/java/org/apache/empire/db/DBCommandTest.java
@@ -25,6 +25,7 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.empire.data.DataType;
+import org.apache.empire.db.context.DBContextStatic;
import org.junit.Test;
/**
@@ -38,7 +39,8 @@ public class DBCommandTest
public void testDBCommand()
{
MockDB mock = new MockDB();
- mock.open(new MockDriver(), null);
+ DBContext context = new DBContextStatic(new MockDriver(), null);
+ mock.open(context);
List<DBColumn> list = new ArrayList<DBColumn>();
DBCommand command = mock.createCommand();
diff --git a/empire-db/src/test/java/org/apache/empire/db/IntegerTest.java b/empire-db/src/test/java/org/apache/empire/db/IntegerTest.java
index 77895dd..2871b98 100644
--- a/empire-db/src/test/java/org/apache/empire/db/IntegerTest.java
+++ b/empire-db/src/test/java/org/apache/empire/db/IntegerTest.java
@@ -108,8 +108,7 @@ public class IntegerTest {
DBDatabaseDriver driver = getDatabaseDriver(config, connection);
DBContext context = new DBContextStatic(driver, connection);
- database.open(driver, connection);
-
+ database.open(context);
createDatabase(database, driver, context);
DBRecord maxRec = new DBRecord(context, database.SAMPLE);
diff --git a/empire-db/src/test/java/org/apache/empire/db/PreparedStatementTest.java b/empire-db/src/test/java/org/apache/empire/db/PreparedStatementTest.java
index 1b80164..910d47d 100644
--- a/empire-db/src/test/java/org/apache/empire/db/PreparedStatementTest.java
+++ b/empire-db/src/test/java/org/apache/empire/db/PreparedStatementTest.java
@@ -46,7 +46,7 @@ public class PreparedStatementTest{
DBContext context = new DBContextStatic(driver, conn);
CompanyDB db = new CompanyDB();
- db.open(driver, conn);
+ db.open(context);
DBSQLScript script = new DBSQLScript(context);
db.getCreateDDLScript(script);
script.executeAll(false);
diff --git a/empire-db/src/test/java/org/apache/empire/db/SerializeTest.java b/empire-db/src/test/java/org/apache/empire/db/SerializeTest.java
index b8edcb6..aae916e 100644
--- a/empire-db/src/test/java/org/apache/empire/db/SerializeTest.java
+++ b/empire-db/src/test/java/org/apache/empire/db/SerializeTest.java
@@ -59,7 +59,7 @@ public class SerializeTest {
DBContext context = new DBContextStatic(new MockDriver(), null);
DBRecord rec = new DBRecord(context, db.T_TEST);
rec.init(true);
- db.open(context.getDriver(), null);
+ db.open(context);
return new DBObject[] {
db,
db.T_TEST,
diff --git a/empire-db/src/test/java/org/apache/empire/db/expr/set/DBSetExprTest.java b/empire-db/src/test/java/org/apache/empire/db/expr/set/DBSetExprTest.java
index 9375931..760449d 100644
--- a/empire-db/src/test/java/org/apache/empire/db/expr/set/DBSetExprTest.java
+++ b/empire-db/src/test/java/org/apache/empire/db/expr/set/DBSetExprTest.java
@@ -29,6 +29,7 @@ import org.apache.empire.db.DBColumn;
import org.apache.empire.db.DBDatabase;
import org.apache.empire.db.DBExpr;
import org.apache.empire.db.MockDriver;
+import org.apache.empire.db.context.DBContextStatic;
import org.junit.Before;
import org.junit.Test;
@@ -41,7 +42,7 @@ public class DBSetExprTest
@Before
public void setup(){
testDB = new CompanyDB();
- testDB.open(new MockDriver(), null);
+ testDB.open(new DBContextStatic(new MockDriver(), null));
expr = new DBSetExpr(testDB.EMPLOYEE.FIRSTNAME, "JUnit");
}
diff --git a/empire-db/src/test/java/org/apache/empire/db/hsql/DBDatabaseDriverHSqlTest.java b/empire-db/src/test/java/org/apache/empire/db/hsql/DBDatabaseDriverHSqlTest.java
index d5128a2..183bf69 100644
--- a/empire-db/src/test/java/org/apache/empire/db/hsql/DBDatabaseDriverHSqlTest.java
+++ b/empire-db/src/test/java/org/apache/empire/db/hsql/DBDatabaseDriverHSqlTest.java
@@ -56,7 +56,7 @@ public class DBDatabaseDriverHSqlTest{
DBContext context = new DBContextStatic(driver, conn);
CompanyDB db = new CompanyDB();
- db.open(driver, dbResource.getConnection());
+ db.open(context);
DBSQLScript script = new DBSQLScript(context);
db.getCreateDDLScript(script);
script.executeAll(false);
@@ -113,7 +113,7 @@ public class DBDatabaseDriverHSqlTest{
DBContext context = new DBContextStatic(driver, conn);
SeqDB db = new SeqDB();
- db.open(driver, dbResource.getConnection());
+ db.open(context);
DBSQLScript script = new DBSQLScript(context);
db.getCreateDDLScript(script);
script.executeAll(false);
diff --git a/empire-db/src/test/java/org/apache/empire/db/mssql/DBDatabaseDriverMSSqlDateTest.java b/empire-db/src/test/java/org/apache/empire/db/mssql/DBDatabaseDriverMSSqlDateTest.java
index 11e2a56..f15839f 100644
--- a/empire-db/src/test/java/org/apache/empire/db/mssql/DBDatabaseDriverMSSqlDateTest.java
+++ b/empire-db/src/test/java/org/apache/empire/db/mssql/DBDatabaseDriverMSSqlDateTest.java
@@ -68,9 +68,9 @@ public class DBDatabaseDriverMSSqlDateTest {
// Encoding issue occur when prepared statement is disabled
// db.setPreparedStatementsEnabled(true);
- db.open(driver, dbResource.getConnection());
+ db.open(context);
- if (!databaseExists(conn, db)) {
+ if (!databaseExists(context, db)) {
DBSQLScript script = new DBSQLScript(context);
db.getCreateDDLScript(script);
System.out.println(script.toString());
@@ -78,7 +78,7 @@ public class DBDatabaseDriverMSSqlDateTest {
}
// STEP 5: Clear Database (Delete all records)
- clearDatabase(conn, db);
+ clearDatabase(context, db);
// MSSQL datetime Accuracy => Rounded to increments of .000, .003, or
// .007 seconds => ignore ms for comparison
@@ -120,10 +120,10 @@ public class DBDatabaseDriverMSSqlDateTest {
* Empties all Tables.
* </PRE>
*/
- private static void clearDatabase(Connection conn, DateTimeTestDB db) {
+ private static void clearDatabase(DBContext context, DateTimeTestDB db) {
DBCommand cmd = db.createCommand();
// Delete all Employees (no constraints)
- db.executeDelete(db.USER_INFO, cmd, conn);
+ context.getUtils().executeDelete(db.USER_INFO, cmd);
}
/**
@@ -134,7 +134,7 @@ public class DBDatabaseDriverMSSqlDateTest {
* Please note that in this case an error will appear in the log which can be ignored.
* </PRE>
*/
- private static boolean databaseExists(Connection conn, DateTimeTestDB db) {
+ private static boolean databaseExists(DBContext context, DateTimeTestDB db) {
// Check whether DB exists
DBCommand cmd = db.createCommand();
cmd.select(db.USER_INFO.count());
@@ -143,7 +143,7 @@ public class DBDatabaseDriverMSSqlDateTest {
//System.out
//.println("Checking whether table USER_INFO exists (SQLException will be logged if not - please ignore) ...");
try {
- return (db.querySingleInt(cmd, -1, conn) >= 0);
+ return (context.getUtils().querySingleInt(cmd, -1) >= 0);
} catch (Exception e) {
return false;
}
diff --git a/empire-db/src/test/java/org/apache/empire/db/mssql/DBDatabaseDriverMSSqlTest.java b/empire-db/src/test/java/org/apache/empire/db/mssql/DBDatabaseDriverMSSqlTest.java
index fe2e036..0972ffb 100644
--- a/empire-db/src/test/java/org/apache/empire/db/mssql/DBDatabaseDriverMSSqlTest.java
+++ b/empire-db/src/test/java/org/apache/empire/db/mssql/DBDatabaseDriverMSSqlTest.java
@@ -54,9 +54,9 @@ public class DBDatabaseDriverMSSqlTest
// Encoding issue occur when prepared statement is disabled
//db.setPreparedStatementsEnabled(true);
- db.open(driver, dbResource.getConnection());
+ db.open(context);
- if(!databaseExists(conn, db)){
+ if(!databaseExists(context, db)){
DBSQLScript script = new DBSQLScript(context);
db.getCreateDDLScript(script);
System.out.println(script.toString());
@@ -65,7 +65,7 @@ public class DBDatabaseDriverMSSqlTest
// STEP 5: Clear Database (Delete all records)
System.out.println("*** Step 5: clearDatabase() ***");
- clearDatabase(conn, db);
+ clearDatabase(context, db);
DBRecord dep = new DBRecord(context, db.DEPARTMENT);
dep.setValue(db.DEPARTMENT.NAME, "junit");
@@ -87,11 +87,11 @@ public class DBDatabaseDriverMSSqlTest
* Empties all Tables.
* </PRE>
*/
- private static void clearDatabase(Connection conn, CompanyDB db)
+ private static void clearDatabase(DBContext context, CompanyDB db)
{
DBCommand cmd = db.createCommand();
// Delete all Employees (no constraints)
- db.executeDelete(db.DEPARTMENT, cmd, conn);
+ context.getUtils().executeDelete(db.DEPARTMENT, cmd);
}
/**
@@ -102,13 +102,13 @@ public class DBDatabaseDriverMSSqlTest
* Please note that in this case an error will appear in the log which can be ignored.
* </PRE>
*/
- private static boolean databaseExists(Connection conn, CompanyDB db)
+ private static boolean databaseExists(DBContext context, CompanyDB db)
{
// Check whether DB exists
DBCommand cmd = db.createCommand();
cmd.select(db.DEPARTMENT.count());
// Check using "select count(*) from DEPARTMENTS"
System.out.println("Checking whether table DEPARTMENTS exists (SQLException will be logged if not - please ignore) ...");
- return (db.querySingleInt(cmd, -1, conn) >= 0);
+ return (context.getUtils().querySingleInt(cmd, -1) >= 0);
}
}
diff --git a/empire-db/src/test/java/org/apache/empire/db/mysql/DBDatabaseDriverMySQLTest.java b/empire-db/src/test/java/org/apache/empire/db/mysql/DBDatabaseDriverMySQLTest.java
index 029bac2..d759b1a 100644
--- a/empire-db/src/test/java/org/apache/empire/db/mysql/DBDatabaseDriverMySQLTest.java
+++ b/empire-db/src/test/java/org/apache/empire/db/mysql/DBDatabaseDriverMySQLTest.java
@@ -25,7 +25,9 @@ import org.apache.empire.data.DataType;
import org.apache.empire.db.CompanyDB;
import org.apache.empire.db.CompanyDB.Departments;
import org.apache.empire.db.DBCommand;
+import org.apache.empire.db.DBContext;
import org.apache.empire.db.DBDatabaseDriver;
+import org.apache.empire.db.context.DBContextStatic;
import org.junit.Test;
public class DBDatabaseDriverMySQLTest {
@@ -36,7 +38,8 @@ public class DBDatabaseDriverMySQLTest {
CompanyDB db = new CompanyDB();
DBDatabaseDriver driver = new DBDatabaseDriverMySQL();
- db.open(driver, null);
+ DBContext context = new DBContextStatic(driver, null);
+ db.open(context);
Departments TD = db.DEPARTMENT;
diff --git a/empire-db/src/test/java/org/apache/empire/db/postgresql/DBDatabaseDriverPostgreSQLTest.java b/empire-db/src/test/java/org/apache/empire/db/postgresql/DBDatabaseDriverPostgreSQLTest.java
index c35c131..b01cf8c 100644
--- a/empire-db/src/test/java/org/apache/empire/db/postgresql/DBDatabaseDriverPostgreSQLTest.java
+++ b/empire-db/src/test/java/org/apache/empire/db/postgresql/DBDatabaseDriverPostgreSQLTest.java
@@ -79,9 +79,9 @@ public class DBDatabaseDriverPostgreSQLTest
// Encoding issue occurs when prepared statement is disabled
//db.setPreparedStatementsEnabled(true);
- db.open(driver, dbResource.getConnection());
+ db.open(context);
- if(!databaseExists(conn, db)){
+ if(!databaseExists(context, db)){
DBSQLScript script = new DBSQLScript(context);
db.getCreateDDLScript(script);
System.out.println(script.toString());
@@ -104,7 +104,7 @@ public class DBDatabaseDriverPostgreSQLTest
// Encoding issue occurs when prepared statement is disabled
//db.setPreparedStatementsEnabled(true);
- db.open(driver, dbResource.getConnection());
+ db.open(context);
DBRecord emp = new DBRecord(context, db.DATA);
emp.create();
@@ -129,7 +129,7 @@ public class DBDatabaseDriverPostgreSQLTest
* If the Departments table does not exist the querySingleInt() function return -1 for failure.
* Please note that in this case an error will appear in the log which can be ignored.
*/
- private static boolean databaseExists(Connection conn, CompanyDB db)
+ private static boolean databaseExists(DBContext context, CompanyDB db)
{
// Check whether DB exists
DBCommand cmd = db.createCommand();
@@ -137,7 +137,7 @@ public class DBDatabaseDriverPostgreSQLTest
// Check using "select count(*) from DEPARTMENTS"
try{
- return (db.querySingleInt(cmd, -1, conn) >= 0);
+ return (context.getUtils().querySingleInt(cmd, -1) >= 0);
}catch(QueryFailedException ex){
System.out.println("Checking whether table DEPARTMENTS exists (SQLException will be logged if not - please ignore) ...");
System.out.println(ex.getMessage());
diff --git a/empire-db/src/test/java/org/apache/empire/db/sqlite/DBDatabaseDriverSQLiteTest.java b/empire-db/src/test/java/org/apache/empire/db/sqlite/DBDatabaseDriverSQLiteTest.java
index 92603d5..8f53248 100644
--- a/empire-db/src/test/java/org/apache/empire/db/sqlite/DBDatabaseDriverSQLiteTest.java
+++ b/empire-db/src/test/java/org/apache/empire/db/sqlite/DBDatabaseDriverSQLiteTest.java
@@ -55,7 +55,7 @@ public class DBDatabaseDriverSQLiteTest{
DBContext context = new DBContextStatic(driver, conn);
CompanyDB db = new CompanyDB();
- db.open(driver, dbResource.getConnection());
+ db.open(context);
DBSQLScript script = new DBSQLScript(context);
db.getCreateDDLScript(script);
script.executeAll(false);
@@ -114,7 +114,7 @@ public class DBDatabaseDriverSQLiteTest{
DBContext context = new DBContextStatic(driver, conn);
SeqDB db = new SeqDB();
- db.open(driver, dbResource.getConnection());
+ db.open(context);
DBSQLScript script = new DBSQLScript(context);
db.getCreateDDLScript(script);
script.executeAll(false);