empire-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From doeb...@apache.org
Subject svn commit: r831663 - in /incubator/empire-db/trunk/empire-db-codegen: ./ src/main/java/org/apache/empire/db/codegen/ src/main/java/org/apache/empire/db/codegen/types/ src/main/java/org/apache/empire/db/codegen/util/ src/main/resources/templates/
Date Sun, 01 Nov 2009 10:21:13 GMT
Author: doebele
Date: Sun Nov  1 10:21:13 2009
New Revision: 831663

URL: http://svn.apache.org/viewvc?rev=831663&view=rev
Log:
EMPIREDB-52 - code submitted by Benjamin (codegen.0.3.patch of Oct.26)

Added:
    incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/util/DBUtil.java   (with props)
Modified:
    incubator/empire-db/trunk/empire-db-codegen/config.xml
    incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGen.java
    incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenConfig.java
    incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Column.java
    incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Database.java
    incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Table.java
    incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/BaseRecord.vm
    incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/BaseTable.vm
    incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Database.vm
    incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Record.vm
    incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Table.vm

Modified: incubator/empire-db/trunk/empire-db-codegen/config.xml
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/config.xml?rev=831663&r1=831662&r2=831663&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/config.xml (original)
+++ incubator/empire-db/trunk/empire-db-codegen/config.xml Sun Nov  1 10:21:13 2009
@@ -29,8 +29,10 @@
 		<jdbcPwd>DBSAMPLE</jdbcPwd>
 
 		<!-- Schema options -->
+		<dbCatalog></dbCatalog>
 		<dbSchema>DBSAMPLE</dbSchema>
-		<timestampColumn></timestampColumn>
+		<dbTablePattern></dbTablePattern>
+		<timestampColumn>CREATIONDATE</timestampColumn>
 		
 		<!-- generation options -->
 		<targetFolder>target/generated/dbsample</targetFolder>
@@ -43,7 +45,7 @@
 		<viewClassPrefix>V</viewClassPrefix>
 		<nestTables>True</nestTables>
 		<nestViews>False</nestViews>
-		<createRecordProperties>True</createRecordProperties>
+		<createRecordProperties>true</createRecordProperties>
 	</properties>
 	
 	<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGen.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGen.java?rev=831663&r1=831662&r2=831663&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGen.java (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGen.java Sun Nov  1 10:21:13 2009
@@ -39,285 +39,286 @@
 
 /**
  * This is the entry class for generating the java persistence model based on a
- * database schema.  It uses the Empire DB open-source framework to build a 
- * java persistence layer for an application.  The Apache Velocity template 
- * engine is used to create the output interfaces and classes.  
+ * database schema. It uses the Empire DB open-source framework to build a java
+ * persistence layer for an application. The Apache Velocity template engine is
+ * used to create the output interfaces and classes.
  * 
- * The Empire DB framework doesn't try to hide the underlying database and data 
- * model but instead embraces its power by modeling it within java.  The result 
+ * The Empire DB framework doesn't try to hide the underlying database and data
+ * model but instead embraces its power by modeling it within java. The result
  * is a persistence layer that uses a more "object-oriented, type safe" SQL to
- * access persistent data. 
+ * access persistent data.
  * 
- * NOTE:  THIS VERSION HAS SEVERE RESTRICTIONS:
- * 1. Only tables are currently modeled (we'll add views to a later version).
- * 2. Table indexes are not yet modeled (exception is primary key).  Again, this
- *      will be added to later editions.
- * 3. It is assumed that each table has a single INTEGER auto-generated primary
- *      key column that has the same name for all tables.
- * 4. It is assumed that each table has a single TIMESTAMP optimistic locking
- *      column that has the same name for all tables.
+ * NOTE: THIS VERSION HAS SEVERE RESTRICTIONS: 1. Only tables are currently
+ * modeled (we'll add views to a later version). 2. Table indexes are not yet
+ * modeled (exception is primary key). Again, this will be added to later
+ * editions. 3. It is assumed that each table has a single INTEGER
+ * auto-generated primary key column that has the same name for all tables. 4.
+ * It is assumed that each table has a single TIMESTAMP optimistic locking
+ * column that has the same name for all tables.
  */
 
-public class CodeGen
-{
-    private static final Log log = LogFactory.getLog(CodeGen.class);
-
-    // Templates
-    public static final String TEMPLATE_PATH     =    "src/main/resources/templates/";
-    public static final String DATABASE_TEMPLATE =    "Database.vm";
-    public static final String BASE_TABLE_TEMPLATE =  "BaseTable.vm";
-    public static final String TABLE_TEMPLATE =       "Table.vm";
-    public static final String BASE_RECORD_TEMPLATE = "BaseRecord.vm";
-    public static final String RECORD_TEMPLATE =      "Record.vm";
-    
-    // Properties
-    private CodeGenConfig config;
-    private File baseDir;
-    private File tableDir;
-    private File recordDir;
-    
-    /**
-     * Constructor
-     */
-    public CodeGen() {
-        try {
-            Velocity.init();
-        } catch(Exception e) {
-            log.fatal(e);
-            throw new RuntimeException(e);
-        }
-    }
-    
-    /**
-     * <PRE>
-     * This is the entry point of the Empire-DB Sample Application
-     * Please check the config.xml configuration file for Database and Connection settings.
-     * </PRE>
-     * @param args arguments
-     */
-    public static void main(String[] args)
-    {
-        Connection conn = null;
-        try
-        {
-            // Init Configuration
-            CodeGenConfig config = new CodeGenConfig();
-            config.init((args.length > 0 ? args[0] : "config.xml" ));
-
-            // Enable Exceptions
-            ErrorObject.setExceptionsEnabled(true);
-
-            // Get a JDBC Connection
-            conn = getJDBCConnection(config);
-            
-            // List options
-            log.info("Database connection successful. Config options are:");
-            log.info("SchemaName="+String.valueOf(config.getDbSchema()));
-            log.info("TimestampColumn="+String.valueOf(config.getTimestampColumn()));
-            log.info("TargetFolder="+config.getTargetFolder());
-            log.info("PackageName="+config.getPackageName());
-            log.info("DbClassName="+config.getDbClassName());
-            log.info("TableBaseName="+config.getTableBaseName());
-            log.info("ViewBaseName="+config.getViewBaseName());
-            log.info("RecordBaseName="+config.getRecordBaseName());
-            log.info("TableClassPrefix="+config.getTableClassPrefix());
-            log.info("ViewClassPrefi="+config.getViewClassPrefix());
-            log.info("NestTable="+config.isNestTables());
-            log.info("NestViews="+config.isNestViews());
-            log.info("CreateRecordProperties="+config.isCreateRecordProperties());
-            
-            CodeGen codeGen = new CodeGen();
-            codeGen.generateCode(conn, config);
-            
-            log.info("Code generation completed sucessfully!");
-            
-        } catch(Exception e) {
-            // Error
-            log.error(e.getMessage(), e);
-        } finally {
-            // done
-            if (conn!=null)
-                close(conn);
-        }
-    }
-    
-    /**
-     * <PRE>
-     * Opens and returns a JDBC-Connection.
-     * JDBC url, user and password for the connection are obained from the SampleConfig bean
-     * Please use the config.xml file to change connection params.
-     * </PRE>
-     */
-    private static Connection getJDBCConnection(CodeGenConfig config)
-    {
-        // Establish a new database connection
-        Connection conn = null;
-        log.info("Connecting to Database'" + config.getJdbcURL() + "' / User=" + config.getJdbcUser());
-        try
-        {
-            // Connect to the databse
-            Class.forName(config.getJdbcClass()).newInstance();
-            conn = DriverManager.getConnection(config.getJdbcURL(), config.getJdbcUser(), config.getJdbcPwd());
-            log.info("Connected successfully");
-            // set the AutoCommit to false this session. You must commit
-            // explicitly now
-            conn.setAutoCommit(true);
-            log.info("AutoCommit is " + conn.getAutoCommit());
-
-        } catch (Exception e)
-        {
-            log.fatal("Failed to connect directly to '" + config.getJdbcURL() + "' / User=" + config.getJdbcUser(), e);
-            throw new RuntimeException(e);
-        }
-        return conn;
-    }
-    
-    /**
-     * Closes a JDBC-Connection.
-     */
-    private static void close(Connection conn)
-    {
-        log.info("Closing database connection");
-        try {
-            conn.close();
-        } catch (Exception e) {
-            log.fatal("Error closing connection", e);
-        }
-    }
-    
-    /**
-     * Generates the source code for the persistence layer.
-     */
-    public void generateCode(Connection conn, CodeGenConfig config) {
-        
-        this.config = config;
-        String packageName = config.getPackageName();
-        String targetFolder = config.getTargetFolder();
-        String dbSchema = config.getDbSchema();
-        String dbLockingCol = config.getTimestampColumn();
-        String dbPkCol = "ID"; // must be made obsolete
-        
-        Database db = new Database(conn, dbSchema);
-        db.populateTableMetaData(dbPkCol, dbLockingCol);
-        
-        // Prepare directories for generated source files
-        this.initDirectories(targetFolder, packageName);
-        
-        // Create the DB class
-        this.createDatabaseClass(db);
-    
-        // Create base table class
-        this.createBaseTableClass(db);
-
-        // Create base record class
-        this.createBaseRecordClass(db);
-        
-        // Create table classes, record interfaces and record classes
-        for (Table table: db.getTables()) {
-            this.createTableClass(db, table);
-            this.createRecordClass(db, table);
-        }
-    }
-    
-    private void initDirectories(String srcLocation, String packageName) {
-        // Create the directory structure for the generated source code.
-        File baseDir = new File(srcLocation);
-        if (!baseDir.exists()) {
-            baseDir.mkdirs();
-        }       
-        StringBuilder sb = new StringBuilder();
-        sb.append(srcLocation).append("/");
-        sb.append(packageName.replaceAll("\\.", "/"));
-        this.baseDir = new File(sb.toString());
-        if (!this.baseDir.exists()) {
-            this.baseDir.mkdirs();
-        }
-        
-        // Clean out the directory so old code is wiped out.
-        FileUtils.cleanDirectory(this.baseDir);
-        
-        // Create the table package directory
-        this.tableDir = new File(this.baseDir, "tables");
-        this.tableDir.mkdir();
-
-        // Create the record package directory
-        this.recordDir = new File(this.baseDir, "records");
-        this.recordDir.mkdir();
-    }
-    
-    private void createDatabaseClass(Database db) {
-        File file = new File(this.baseDir, db.getClassName() + ".java");
-        String packageName = config.getPackageName();
-        VelocityContext context = new VelocityContext();
-        context.put("basePackageName", packageName);       
-        context.put("tableSubPackage", "tables");
-        context.put("database", db);
-        this.writeFile(file, DATABASE_TEMPLATE, context);
-    }
-    
-    private void createBaseTableClass(Database db) {
-        File file = new File(this.tableDir,  db.getBaseTableClassName() + ".java");
-        String packageName = config.getPackageName();
-        VelocityContext context = new VelocityContext();
-        context.put("tablePackageName", packageName + ".tables");      
-        context.put("db", db);
-        this.writeFile(file, BASE_TABLE_TEMPLATE, context);
-    }
-    
-    private void createTableClass(Database db, Table table) {
-        File file = new File(this.tableDir, table.getClassName() + ".java");
-        String packageName = config.getPackageName();
-        VelocityContext context = new VelocityContext();
-        context.put("tablePackageName", packageName + ".tables");      
-        context.put("db", db);
-        context.put("table", table);
-        this.writeFile(file, TABLE_TEMPLATE, context);
-    }
-    
-    private void createBaseRecordClass(Database db) {
-        File file = new File(this.recordDir, "BaseRecord.java");
-        String packageName = config.getPackageName();
-        VelocityContext context = new VelocityContext();
-        context.put("basePackageName", packageName);       
-        context.put("tablePackageName", packageName + ".tables");      
-        context.put("recordPackage", packageName + ".records");        
-        context.put("database", db);
-        this.writeFile(file, BASE_RECORD_TEMPLATE, context);
-    }
-    
-    private void createRecordClass(Database db, Table table) {
-        File file = new File(this.recordDir, table.getRecordClassName() + ".java");
-        String packageName = config.getPackageName();
-        VelocityContext context = new VelocityContext();
-        context.put("basePackageName", packageName);       
-        context.put("tablePackageName", packageName + ".tables");      
-        context.put("recordPackage", packageName + ".records");        
-        context.put("database", db);
-        context.put("table", table);        
-        this.writeFile(file, RECORD_TEMPLATE, context);
-    }
-
-    private void writeFile(File file, String templateName, VelocityContext context) {
-        try {
-            log.info("Writing file for template: " + templateName);
-            Template template = Velocity.getTemplate(TEMPLATE_PATH + templateName);
-            Writer writer = new FileWriter(file);
-            template.merge(context, writer);
-            writer.close();
-        } catch (IOException e) {
-            log.error(e.getClass().getName()+": "+e.getMessage());
-            throw new RuntimeException(e);
-        } catch (ResourceNotFoundException e) {
-            log.error(e.getClass().getName()+": "+e.getMessage());
-            throw new RuntimeException(e);
-        } catch (ParseErrorException e) {
-            log.error(e.getClass().getName()+": "+e.getMessage());
-            throw new RuntimeException(e);
-        } catch (Exception e) {
-            log.error(e.getClass().getName()+": "+e.getMessage());
-            throw new RuntimeException(e);
-        }
-        
-    }
-    
+public class CodeGen {
+	private static final Log log = LogFactory.getLog(CodeGen.class);
+
+	// Templates
+	public static final String TEMPLATE_PATH = "src/main/resources/templates/";
+	public static final String DATABASE_TEMPLATE = "Database.vm";
+	public static final String BASE_TABLE_TEMPLATE = "BaseTable.vm";
+	public static final String TABLE_TEMPLATE = "Table.vm";
+	public static final String BASE_RECORD_TEMPLATE = "BaseRecord.vm";
+	public static final String RECORD_TEMPLATE = "Record.vm";
+
+	// Properties
+	private CodeGenConfig config;
+	private File baseDir;
+	private File tableDir;
+	private File recordDir;
+
+	/**
+	 * Constructor
+	 */
+	public CodeGen() {
+		try {
+			Velocity.init();
+		} catch (Exception e) {
+			log.fatal(e);
+			throw new RuntimeException(e);
+		}
+	}
+
+	/**
+	 * <PRE>
+	 * This is the entry point of the Empire-DB Sample Application
+	 * Please check the config.xml configuration file for Database and Connection settings.
+	 * </PRE>
+	 * 
+	 * @param args
+	 *            arguments
+	 */
+	public static void main(String[] args) {
+		Connection conn = null;
+		try {
+			// Init Configuration
+			CodeGenConfig config = new CodeGenConfig();
+			config.init((args.length > 0 ? args[0] : "config.xml"));
+
+			// Enable Exceptions
+			ErrorObject.setExceptionsEnabled(true);
+
+			// Get a JDBC Connection
+			conn = getJDBCConnection(config);
+
+			// List options
+			log.info("Database connection successful. Config options are:");
+			log.info("SchemaName=" + String.valueOf(config.getDbSchema()));
+			log.info("TimestampColumn="
+					+ String.valueOf(config.getTimestampColumn()));
+			log.info("TargetFolder=" + config.getTargetFolder());
+			log.info("PackageName=" + config.getPackageName());
+			log.info("DbClassName=" + config.getDbClassName());
+			log.info("TableBaseName=" + config.getTableBaseName());
+			log.info("ViewBaseName=" + config.getViewBaseName());
+			log.info("RecordBaseName=" + config.getRecordBaseName());
+			log.info("TableClassPrefix=" + config.getTableClassPrefix());
+			log.info("ViewClassPrefi=" + config.getViewClassPrefix());
+			log.info("NestTable=" + config.isNestTables());
+			log.info("NestViews=" + config.isNestViews());
+			log.info("CreateRecordProperties="
+					+ config.isCreateRecordProperties());
+
+			CodeGen codeGen = new CodeGen();
+			codeGen.generateCode(conn, config);
+
+			log.info("Code generation completed sucessfully!");
+
+		} catch (Exception e) {
+			// Error
+			log.error(e.getMessage(), e);
+		} finally {
+			// done
+			if (conn != null)
+				close(conn);
+		}
+	}
+
+	/**
+	 * <PRE>
+	 * Opens and returns a JDBC-Connection.
+	 * JDBC url, user and password for the connection are obained from the SampleConfig bean
+	 * Please use the config.xml file to change connection params.
+	 * </PRE>
+	 */
+	private static Connection getJDBCConnection(CodeGenConfig config) {
+		// Establish a new database connection
+		Connection conn = null;
+		log.info("Connecting to Database'" + config.getJdbcURL() + "' / User="
+				+ config.getJdbcUser());
+		try {
+			// Connect to the databse
+			Class.forName(config.getJdbcClass()).newInstance();
+			conn = DriverManager.getConnection(config.getJdbcURL(), config
+					.getJdbcUser(), config.getJdbcPwd());
+			log.info("Connected successfully");
+			// set the AutoCommit to false this session. You must commit
+			// explicitly now
+			conn.setAutoCommit(true);
+			log.info("AutoCommit is " + conn.getAutoCommit());
+
+		} catch (Exception e) {
+			log.fatal("Failed to connect directly to '" + config.getJdbcURL()
+					+ "' / User=" + config.getJdbcUser(), e);
+			throw new RuntimeException(e);
+		}
+		return conn;
+	}
+
+	/**
+	 * Closes a JDBC-Connection.
+	 */
+	private static void close(Connection conn) {
+		log.info("Closing database connection");
+		try {
+			conn.close();
+		} catch (Exception e) {
+			log.fatal("Error closing connection", e);
+		}
+	}
+
+	/**
+	 * Generates the source code for the persistence layer.
+	 */
+	public void generateCode(Connection conn, CodeGenConfig config) {
+
+		this.config = config;
+		String packageName = config.getPackageName();
+		String targetFolder = config.getTargetFolder();
+		String dbLockingCol = config.getTimestampColumn();
+		
+		// passing an empty string my
+		String dbCatalog = config.getDbCatalog();
+		String dbSchema = config.getDbSchema();
+		String dbTablePattern = config.getDbTablePattern();
+		dbTablePattern=dbTablePattern==""?dbTablePattern:null;
+
+		Database db = new Database(conn, log, dbSchema, dbCatalog, dbTablePattern);
+		db.populateTableMetaData(dbLockingCol);
+		
+		// Prepare directories for generated source files
+		this.initDirectories(targetFolder, packageName);
+
+		// Create the DB class
+		this.createDatabaseClass(db);
+
+		// Create base table class
+		this.createBaseTableClass(db);
+
+		// Create base record class
+		this.createBaseRecordClass(db);
+
+		// Create table classes, record interfaces and record classes
+		for (Table table : db.getTables()) {
+			this.createTableClass(db, table);
+			this.createRecordClass(db, table);
+		}
+	}
+
+	private void initDirectories(String srcLocation, String packageName) {
+		// Create the directory structure for the generated source code.
+		File baseDir = new File(srcLocation);
+		if (!baseDir.exists()) {
+			baseDir.mkdirs();
+		}
+		StringBuilder sb = new StringBuilder();
+		sb.append(srcLocation).append("/");
+		sb.append(packageName.replaceAll("\\.", "/"));
+		this.baseDir = new File(sb.toString());
+		if (!this.baseDir.exists()) {
+			this.baseDir.mkdirs();
+		}
+
+		// Clean out the directory so old code is wiped out.
+		FileUtils.cleanDirectory(this.baseDir);
+
+		// Create the table package directory
+		this.tableDir = new File(this.baseDir, "tables");
+		this.tableDir.mkdir();
+
+		// Create the record package directory
+		this.recordDir = new File(this.baseDir, "records");
+		this.recordDir.mkdir();
+	}
+
+	private void createDatabaseClass(Database db) {
+		File file = new File(baseDir, config.getDbClassName() + ".java");
+		VelocityContext context = new VelocityContext();
+		context.put("basePackageName", config.getPackageName());
+		context.put("dbClassName", config.getDbClassName());
+		context.put("tableSubPackage", "tables");
+		context.put("database", db);
+		writeFile(file, TEMPLATE_PATH + "/" + DATABASE_TEMPLATE, context);
+	}
+
+	private void createBaseTableClass(Database db) {
+		File file = new File(tableDir, config.getTableBaseName() + ".java");
+		VelocityContext context = new VelocityContext();
+		context.put("tablePackageName", config.getPackageName() + ".tables");
+		context.put("baseTableClassName", config.getTableBaseName());
+		writeFile(file, TEMPLATE_PATH + "/" + BASE_TABLE_TEMPLATE, context);
+	}
+
+	private void createTableClass(Database db, Table table) {
+		File file = new File(tableDir, table.getClassName() + ".java");
+		VelocityContext context = new VelocityContext();
+		context.put("basePackageName", config.getPackageName());
+		context.put("tablePackageName", config.getPackageName() + ".tables");
+		context.put("baseTableClassName", config.getTableBaseName());
+		context.put("dbClassName", config.getDbClassName());
+		context.put("table", table);
+		writeFile(file, TEMPLATE_PATH + "/" + TABLE_TEMPLATE, context);
+	}
+
+	private void createBaseRecordClass(Database db) {
+		File file = new File(recordDir, config.getRecordBaseName() + ".java");
+		VelocityContext context = new VelocityContext();
+		context.put("baseRecordClassName", config.getRecordBaseName());
+		context.put("basePackageName", config.getPackageName());
+		context.put("tablePackageName", config.getPackageName() + ".tables");
+		context.put("recordPackageName", config.getPackageName() + ".records");
+		context.put("baseTableClassName", config.getTableBaseName());
+		writeFile(file, TEMPLATE_PATH + "/" + BASE_RECORD_TEMPLATE, context);
+	}
+
+	private void createRecordClass(Database db, Table table) {
+		File file = new File(recordDir, table.getRecordClassName() + ".java");
+		VelocityContext context = new VelocityContext();
+		context.put("basePackageName", config.getPackageName());
+		context.put("tablePackageName", config.getPackageName() + ".tables");
+		context.put("recordPackageName", config.getPackageName() + ".records");
+		context.put("baseRecordClassName", config.getRecordBaseName());
+		context.put("dbClassName", config.getDbClassName());
+		context.put("createRecordProperties", config.isCreateRecordProperties());
+		
+		context.put("table", table);
+		writeFile(file, TEMPLATE_PATH + "/" + RECORD_TEMPLATE, context);
+	}
+
+	private static void writeFile(File file, String templatePath,
+			VelocityContext context) {
+		try {
+			Template template = Velocity.getTemplate(templatePath);
+			Writer writer = new FileWriter(file);
+			template.merge(context, writer);
+			writer.close();
+		} catch (IOException e) {
+			e.printStackTrace();
+		} catch (ResourceNotFoundException e) {
+			e.printStackTrace();
+		} catch (ParseErrorException e) {
+			e.printStackTrace();
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+
+	}
+
 }

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenConfig.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenConfig.java?rev=831663&r1=831662&r2=831663&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenConfig.java (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenConfig.java Sun Nov  1 10:21:13 2009
@@ -32,9 +32,19 @@
     
     // generation options
     /**
+     * name of the database catalog (may be null)
+     */
+    private String dbCatalog = null;
+    
+    /**
      * name of the database schema (may be null)
      */
     private String dbSchema = null;
+    
+    /**
+     * name of the table pattern (may be null)
+     */
+    private String dbTablePattern = null;
     /**
      * Name of the timestamp column used for optimistic locking (may be null)
      */
@@ -168,15 +178,36 @@
     
     // ------- generation options -------
 
+    public String getDbCatalog()
+    {
+        return dbCatalog;
+    }
+    
+    public void setDbCatalog(String dbCatalog)
+    {
+        this.dbCatalog=dbCatalog;
+    }
+    
     public String getDbSchema()
     {
         return dbSchema;
     }
-
+    
     public void setDbSchema(String dbSchema)
     {
         this.dbSchema = dbSchema;
     }
+    
+    public String getDbTablePattern()
+    {
+        return dbTablePattern;
+    }
+
+    public void setDbTablePattern(String dbTablePattern)
+    {
+        this.dbTablePattern = dbTablePattern;
+    }
+    
 
     public String getTimestampColumn()
     {

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Column.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Column.java?rev=831663&r1=831662&r2=831663&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Column.java (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Column.java Sun Nov  1 10:21:13 2009
@@ -22,175 +22,129 @@
 import java.sql.SQLException;
 import java.sql.Types;
 
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
 import org.apache.empire.data.DataType;
 import org.apache.empire.db.codegen.util.StringUtils;
 
 public class Column {
-    private static final Log log = LogFactory.getLog(Column.class);
-
-    private String name;
+	private String name;
 	private int sqlType;
-	private int colSize;		// max length if string, precision is numeric
-	private int decimalDigits;	// max decimal digits allowed (real numbers)
+	private int colSize; // max length if string, precision is numeric
+	private int decimalDigits; // max decimal digits allowed (real numbers)
 	private boolean required;
-	private String defaultValue;	
-	private String fkTableName;	// Reference parent table if column if FK
+	private String defaultValue;
 	private boolean pkCol;
-	private boolean lockingCol;	// 
-	
+
 	// Java transformation
 	private String javaName;
 	private DataType empireType;
 	private String empireTypeString;
 	private String originalJavaTypeString;
 	private String javaTypeString;
-	
+
 	private boolean convertToBoolean;
 	private String trueValue;
 	private String falseValue;
 
 	private boolean convertToEnum;
-	
+
 	public String getJavaName() {
 		return javaName;
 	}
+
 	public void setJavaName(String javaName) {
 		this.javaName = javaName;
 	}
+
 	public String getJavaTypeString() {
 		return javaTypeString;
 	}
+
 	public String getEmpireTypeString() {
 		return empireTypeString;
 	}
+
 	public DataType getEmpireType() {
 		return empireType;
 	}
+
 	public Column(ResultSet rs) {
-		this(rs, false, false);
+		this(rs, false);
 	}
+
 	public Column(ResultSet rs, boolean primaryKey) {
-		this(rs, primaryKey, false);
-	}
-	public Column(ResultSet rs, boolean primaryKey, boolean foreignKey) {
-		if (primaryKey && foreignKey) {
-			throw new RuntimeException("Can't have a column that is both " +
-					"a primary and a foreign key.");
-		}
-		
+
+		this.pkCol = primaryKey;
 		try {
-			if (!primaryKey && !foreignKey) {
-				// Simple column
-				this.name = rs.getString("COLUMN_NAME").toUpperCase();
-				this.sqlType = rs.getInt("DATA_TYPE");
-				this.empireType = this.deriveJavaInfo();
-				this.colSize = rs.getInt("COLUMN_SIZE");
-				this.decimalDigits = rs.getInt("DECIMAL_DIGITS");
-				String nullable = rs.getString("IS_NULLABLE");
-				if (nullable.equalsIgnoreCase("NO"))
-					this.required = true;
-				else
-					this.required = false;
-				this.defaultValue = rs.getString("COLUMN_DEF");
-			}
-			else if (primaryKey) {
-				// Primary key column
-				this.name = rs.getString("COLUMN_NAME").toUpperCase();
-				this.sqlType = Types.INTEGER;
-				this.empireType = DataType.AUTOINC;
+			this.name = rs.getString("COLUMN_NAME").toUpperCase();
+			this.sqlType = rs.getInt("DATA_TYPE");
+			this.empireType = this.deriveJavaInfo();
+			this.colSize = rs.getInt("COLUMN_SIZE");
+			this.decimalDigits = rs.getInt("DECIMAL_DIGITS");
+			String nullable = rs.getString("IS_NULLABLE");
+			if (nullable.equalsIgnoreCase("NO"))
 				this.required = true;
-				this.javaName = StringUtils.deriveAttributeName(this.name);
-				this.javaTypeString = "Integer";
-				this.pkCol = true;
-			}
-			else {
-				// Foreign key column
-				this.name = rs.getString("FKCOLUMN_NAME").toUpperCase();
-				this.sqlType = Types.INTEGER;
-				this.empireType = DataType.INTEGER;
-				this.fkTableName = rs.getString("PKTABLE_NAME").toUpperCase();
-				this.javaName = StringUtils.deriveAttributeName(this.name);
-				this.javaTypeString = "Integer";
-			}
-			
+			else
+				this.required = false;
+			this.defaultValue = rs.getString("COLUMN_DEF");
+
 			this.originalJavaTypeString = this.javaTypeString;
-		}
-		catch (SQLException e) {
+		} catch (SQLException e) {
 			throw new RuntimeException(e);
 		}
 	}
+
 	@Override
 	public boolean equals(Object obj) {
 		if (obj instanceof Column) {
-			Column that = (Column)obj;
+			Column that = (Column) obj;
 			if (this.name.equals(that.name)) {
 				return true;
 			}
 		}
 		return false;
 	}
-	
-	public void convertToBoolean(String trueValue, String falseValue) {
-		if (this.empireType != DataType.TEXT) {
-			throw new RuntimeException(this.name + " must be a string type " +
-					"to convert to boolean");
-		}
-		this.convertToBoolean = true;
-		this.javaTypeString = "Boolean";
-		this.trueValue = trueValue;
-		this.falseValue = falseValue;
-	}
-	
-	public boolean isForeignKey() {
-		return (this.fkTableName != null);
-	}
-	public String getFkTableName() {
-		return fkTableName;
-	}
+
 	public String getName() {
 		return name.toUpperCase();
 	}
+
 	public int getSqlType() {
 		return sqlType;
 	}
+
 	public int getColSize() {
 		return colSize;
 	}
+
 	public int getDecimalDigits() {
 		return decimalDigits;
 	}
+
 	public boolean isRequired() {
 		return required;
 	}
+
 	public String getDefaultValue() {
-		if (defaultValue == null) return "null";
-		
+		if (defaultValue == null)
+			return "null";
+
 		return "\"" + defaultValue + "\"";
 	}
-	public boolean isLockingCol() {
-		return lockingCol;
-	}
-	public void setLockingCol(boolean lockingCol) {
-		this.lockingCol = lockingCol;
-	}
-	public boolean isPkCol() {
+
+	public boolean isPrimaryColumn() {
 		return this.pkCol;
 	}
+
 	public boolean isBoolean() {
 		if (this.javaTypeString.equalsIgnoreCase("Boolean"))
 			return true;
 		return false;
 	}
-	public boolean isModifiable() {
-		return (!this.isPkCol() && !this.isLockingCol());
-	}
-	
+
 	private DataType deriveJavaInfo() {
 		this.javaName = StringUtils.deriveAttributeName(this.name);
 		DataType empireType = DataType.UNKNOWN;
-		switch(this.sqlType) {
+		switch (this.sqlType) {
 		case Types.INTEGER:
 		case Types.SMALLINT:
 		case Types.TINYINT:
@@ -257,70 +211,65 @@
 			empireType = DataType.UNKNOWN;
 			empireTypeString = "DataType.UNKNOWN";
 			javaTypeString = "Byte[]";
-			System.out.println("SQL column type " + this.sqlType + " not supported.");
+			System.out.println("SQL column type " + this.sqlType
+					+ " not supported.");
 		}
-		
+
 		return empireType;
 	}
+
 	public boolean isConvertToBoolean() {
 		return convertToBoolean;
 	}
+
 	public String getTrueValue() {
 		return trueValue;
 	}
+
 	public String getFalseValue() {
 		return falseValue;
 	}
+
 	public String getOriginalJavaTypeString() {
 		return originalJavaTypeString;
 	}
+
 	public boolean isConvertToEnum() {
 		return convertToEnum;
 	}
+
 	public String getJavaAccessorName() {
-		return StringUtils.deriveAccessorName(javaName, 
-				this.javaTypeString.equalsIgnoreCase("boolean"));
+		return StringUtils.deriveAccessorName(javaName, this.javaTypeString
+				.equalsIgnoreCase("boolean"));
 	}
+
 	public String getJavaMutatorName() {
 		return StringUtils.deriveMutatorName(javaName);
 	}
-	
+
 	public String getReturnExpression() {
 		if (this.convertToBoolean) {
 			StringBuilder sb = new StringBuilder(this.javaName);
 			sb.append(".equalsIgnoreCase(\"");
 			sb.append(this.trueValue).append("\")");
 			return sb.toString();
-		}
-		else if (this.convertToEnum) {
-			return this.javaTypeString + ".fromDbString(" +
-			this.javaName + ")";
-		}
-		else {
+		} else if (this.convertToEnum) {
+			return this.javaTypeString + ".fromDbString(" + this.javaName + ")";
+		} else {
 			return this.javaName;
 		}
 	}
+
 	public String getSetExpression() {
 		if (this.convertToBoolean) {
 			StringBuilder sb = new StringBuilder(this.javaName);
 			sb.append(" ? \"").append(this.trueValue).append("\" ");
 			sb.append(" : \"").append(this.falseValue).append("\")");
 			return sb.toString();
-		}
-		else if (this.convertToEnum) {
+		} else if (this.convertToEnum) {
 			return this.javaName + ".toDbString()";
-		}
-		else {
+		} else {
 			return this.javaName;
 		}
 	}
-	public String getPopulateFkRecordMethodName() {
-		StringBuilder sb = new StringBuilder(this.getName());
-		StringUtils.replaceAll(sb, "_" + Table.getPkColName(),
-				"");
-		StringBuilder methodName = new StringBuilder("populate");
-		methodName.append(StringUtils.javaClassName(sb.toString()));
-		methodName.append("Record");
-		return methodName.toString();
-	}
 }

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Database.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Database.java?rev=831663&r1=831662&r2=831663&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Database.java (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Database.java Sun Nov  1 10:21:13 2009
@@ -27,110 +27,65 @@
 import java.util.Map;
 
 import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.empire.db.codegen.util.StringUtils;
+import org.apache.empire.db.codegen.util.DBUtil;
 
 public class Database {
-    private static final Log log = LogFactory.getLog(Database.class);
-    
-    private Connection connection;
-	private String schemaName;
-	
+	private DatabaseMetaData metaData;
+	private String catalogName;
+	private String schemaPattern;
+	private String tablePattern;
+	private Connection con;
+	private Log log;
+
 	private Map<String, Table> tableMap = new HashMap<String, Table>();
 
-	public Database(Connection connection, String schemaName) {
-		// Set properties
-		this.connection = connection;
-        this.schemaName = schemaName;
-	}
-	
-	public Connection getConnection() {
-	    return connection;
-	}
-	
-	private void close(ResultSet rs) {
-	    try {
-	        rs.close();
-	    } catch(SQLException e) {
-            throw new RuntimeException(e);
-	    }
+	public Database(Connection con, Log log, String schemaPattern,
+			String catalogName, String tablePattern) {
+
+		this.log = log;
+		this.con = con;
+		this.schemaPattern = schemaPattern;
+		this.catalogName = catalogName;
+		this.tablePattern = tablePattern;
+		
+		try {
+			this.metaData = this.con.getMetaData();
+		} catch (SQLException e) {
+			throw new RuntimeException("Unable to retrieve database metadata!",
+					e);
+		}
+
 	}
 
 	/**
 	 * Populates meta data for tables in the database.
-	 * @param pkColName Primary key column name.  Note: We assume a single
-	 * 		auto-generated PK column with the same name is used for every
-	 * 		table in the DB.
-	 * @param lockColName Lock column name used for optimistic locking.
-	 * 		Note: We assume a single timestamp column with the same name 
-	 * 		is used for every table in the DB.
+	 * 
 	 */
-	public void populateTableMetaData(String pkColName, String lockColName) {
-		Table.setPkColName(pkColName);
-		Table.setLockColName(lockColName);
-		DatabaseMetaData dbMeta = this.getDbMetaData();
+	public void populateTableMetaData(String lockColName) {
+		DatabaseMetaData dbMeta = this.metaData;
 		ResultSet tables = null;
 		try {
-            log.info("Reading Tables for schema " + schemaName);
-			tables = dbMeta.getTables(null, this.schemaName, null, new String[] {"TABLE"});
+			tables = dbMeta.getTables(catalogName, schemaPattern, tablePattern,
+					new String[] { "TABLE" });
 			while (tables.next()) {
 				String tableName = tables.getString("TABLE_NAME");
-				// rd: required for oracle
-				if (tableName.indexOf('$')>=0)
-				    continue; // ignore table names with a "$"
-				// end oracle
-				log.info("Reading Table metadata for " + tableName);
-				Table table = new Table(tableName, this.schemaName, dbMeta);
-				this.tableMap.put(tableName.toUpperCase(), table);				
-			}
-			
-			for (String tableName: this.tableMap.keySet()) {
-				Table table = this.tableMap.get(tableName);
-				for (Column fkCol: table.getFkCols()) {
-					Table parentTable = this.tableMap.get(
-							fkCol.getFkTableName());
-					parentTable.addChildTable(fkCol.getName(), table);
-				}
+				System.out.println("TABLE:\t" + tableName);
+				Table table = new Table(tableName, lockColName, schemaPattern, catalogName,
+						dbMeta, log);
+				this.tableMap.put(tableName.toUpperCase(), table);
 			}
 		} catch (SQLException e) {
 			throw new RuntimeException(e);
 		} finally {
-		    close(tables);
-		}
-	}
-	/**
-	 * Gets the database meta data.
-	 * @return The database meta data.
-	 */
-	public DatabaseMetaData getDbMetaData() {
-		try {
-			return this.getConnection().getMetaData();
-		} catch (SQLException e) {
-			e.printStackTrace();
-			throw new RuntimeException(e);
+			DBUtil.closeResultSet(tables, log);
 		}
 	}
 	
-	public String getClassName() {
-		return StringUtils.javaClassName(this.schemaName) + "Database";
-	}
-
-	public String getBaseTableClassName() {
-		return StringUtils.javaClassName(this.schemaName) + "Table";
-	}
-
-	public String getInstanceName() {
-		return StringUtils.deriveAttributeNameFromClass(this.getClassName());
-	}
-
 	public Collection<Table> getTables() {
 		return tableMap.values();
 	}
+
 	public Table getTable(String name) {
 		return this.tableMap.get(name.toUpperCase());
 	}
-	
-	public String getSchemaName() {
-		return schemaName;
-	}
 }

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Table.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Table.java?rev=831663&r1=831662&r2=831663&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Table.java (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/types/Table.java Sun Nov  1 10:21:13 2009
@@ -27,80 +27,55 @@
 import java.util.Map;
 
 import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
 import org.apache.empire.data.DataType;
+import org.apache.empire.db.codegen.util.DBUtil;
 import org.apache.empire.db.codegen.util.StringUtils;
 
 public class Table {
-    private static final Log log = LogFactory.getLog(Table.class);
-    
-    private String tableName;
-	private Column pkCol;
-	private List<Column> fkCols;
-	private List<Column> simpleCols;
-	private Column lockingCol;
-	
+	private String tableName;
+	private List<String> pkCols;
+	private List<Column> columns;
+	private Column lockCol;
+	private Log log;
+	private String lockColName;
+
 	private Map<String, Column> columnMap = new HashMap<String, Column>();
-	
-	private List<Child> childTables = new ArrayList<Child>();
-	
-	private static String pkColName;
-	private static String lockColName;
 
-	public Table(String tableName, String schema, 
-			DatabaseMetaData dbMeta) {
+	public Table(String tableName,String lockColName, String schemaPattern, String catalogName,
+			DatabaseMetaData dbMeta, Log log) {
 		this.tableName = tableName.toUpperCase();
-		this.createColumns(dbMeta, schema);
-	}
-	
-	public static String getPkColName() {
-		return pkColName;
-	}
-	public static void setPkColName(String name) {
-		pkColName = name;
-	}
-	public static String getLockColName() {
-		return lockColName;
-	}
-	public static void setLockColName(String name) {
-		lockColName = name;
-	}
-	
-	public void addChildTable(String fkColName, Table table) {
-		this.childTables.add(new Child(fkColName, table));
-	}
-	public List<Child> getChildTables() {
-		return this.childTables;
+		this.log = log;
+		this.lockColName=lockColName;
+		this.createColumns(dbMeta, schemaPattern, catalogName);
 	}
+
 	public String getTableName() {
 		return tableName.toUpperCase();
 	}
 
-	public Column getPkCol() {
-		return pkCol;
+	public List<Column> getColumns() {
+		return columns;
 	}
-
-	public List<Column> getFkCols() {
-		return fkCols;
+	
+	public boolean getHasLockColumn() {
+		return lockCol!=null;
 	}
-
-	public List<Column> getSimpleCols() {
-		return simpleCols;
+	
+	public Column getLockColumn() {
+		return lockCol;
 	}
 
-	public Column getLockingCol() {
-		return this.lockingCol;
-	}
-	
 	public String getClassName() {
 		return StringUtils.javaClassName(this.tableName) + "Table";
 	}
+
 	public String getRecordClassName() {
 		return StringUtils.javaClassName(this.tableName) + "Record";
 	}
+
 	public boolean hasBigDecimalField() {
 		boolean bdField = false;
-		for (Column col: this.simpleCols) {
+		for (Column col : this.columns) {
 			if (col.getEmpireType() == DataType.DECIMAL) {
 				bdField = true;
 				break;
@@ -108,97 +83,56 @@
 		}
 		return bdField;
 	}
-	public boolean hasChildRecords() {
-		return !this.childTables.isEmpty();
-	}
+
 	public Column getColumn(String name) {
 		return this.columnMap.get(name.toUpperCase());
 	}
-	public static class Child {
-		Child(String fkColName, Table childTable) {
-			this.fkColName = fkColName;
-			this.childTable = childTable;
-		}
-		private String fkColName;
-		private Table childTable;
-		public String getFkColName() {
-			return fkColName.toUpperCase();
-		}
-		public Table getChildTable() {
-			return childTable;
-		}
-		public String getChildType() {
-			return StringUtils.javaClassName(childTable.getTableName());
-		}
-		public String getFkType() {
-			StringBuilder sb = new StringBuilder(this.fkColName.toUpperCase());
-			StringUtils.replaceAll(sb, "_" + Table.getPkColName(),
-					"");
-			return StringUtils.javaClassName(sb.toString());
-		}
-		public String getFkMutatorName() {
-			Column col = childTable.getColumn(this.fkColName);
-			return col.getJavaMutatorName();
-		}
-	}
+
 	// ------------------------------------------------------------------------
 	// Private members
 	// ------------------------------------------------------------------------
-	private void createColumns(DatabaseMetaData dbMeta, String schema) {
-		this.pkCol = this.findPkColumn(dbMeta, schema);
-		this.columnMap.put(pkCol.getName().toUpperCase(), pkCol);
-		this.simpleCols = new ArrayList<Column>();
-		this.fkCols = this.findFkColumns(dbMeta, schema);
-		for (Column col: this.fkCols) {
-			this.columnMap.put(col.getName().toUpperCase(), col);
-		}
+	private void createColumns(DatabaseMetaData dbMeta, String schemaPattern,
+			String catalogName) {
+		this.pkCols = this.findPkColumns(dbMeta, schemaPattern, catalogName);
+		this.columns = new ArrayList<Column>();
+		ResultSet rs = null;
 		try {
-			ResultSet rs = dbMeta.getColumns(null, schema, tableName, "");			
+			rs = dbMeta.getColumns(catalogName, schemaPattern, tableName, null);
+			boolean isKeyCol;
+			String colName;
 			while (rs.next()) {
-				Column col = new Column(rs);
-				if (!col.equals(pkCol) && !fkCols.contains(col)) {
-					if (col.getName().equalsIgnoreCase(lockColName)) {
-						this.lockingCol = col;
-						col.setLockingCol(true);
-					}
-					else {
-						this.simpleCols.add(col);
-					}
-					this.columnMap.put(col.getName().toUpperCase(), col);
-				}
+				colName = rs.getString("COLUMN_NAME").toUpperCase();
+				log.info("\tCOLUMN:\t" + colName);
+				isKeyCol = pkCols.contains(colName);
+
+				Column col = new Column(rs, isKeyCol);
+				this.columns.add(col);
+				this.columnMap.put(col.getName().toUpperCase(), col);
+				if(lockColName!=null && col.getName().toUpperCase().equals(lockColName.toUpperCase()))
+					lockCol=col;
 			}
 		} catch (SQLException e) {
 			throw new RuntimeException(e);
-		}		
+		} finally {
+			DBUtil.closeResultSet(rs, log);
+		}
 	}
-	
-	private Column findPkColumn(DatabaseMetaData dbMeta, String schema) {
-		try {
-			ResultSet pkRs = dbMeta.getPrimaryKeys(null, schema, tableName);
-			if(pkRs.next()) {
-				Column col = new Column(pkRs, true);
-				return col;
-			}
-			else {
-				throw new RuntimeException("Primary key not found for table " +
-						this.tableName);
-			}
 
-		} catch (SQLException e) {
-			throw new RuntimeException(e);
-		}		
-	}
-	private List<Column> findFkColumns(DatabaseMetaData dbMeta, String schema) {
-		List<Column> fkCols = new ArrayList<Column>();
+	private List<String> findPkColumns(DatabaseMetaData dbMeta,
+			String schemaPattern, String catalogName) {
+		List<String> cols = new ArrayList<String>();
+		ResultSet rs = null;
 		try {
-			ResultSet fkRs = dbMeta.getImportedKeys(null, schema, tableName);
-			while(fkRs.next()) {
-				Column col = new Column(fkRs, false, true);
-				fkCols.add(col);
+			rs = dbMeta.getPrimaryKeys(catalogName, schemaPattern, tableName);
+			while (rs.next()) {
+				cols.add(rs.getString("COLUMN_NAME").toUpperCase());
 			}
+
 		} catch (SQLException e) {
 			throw new RuntimeException(e);
-		}		
-		return fkCols;
+		} finally {
+			DBUtil.closeResultSet(rs, log);
+		}
+		return cols;
 	}
 }

Added: incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/util/DBUtil.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/util/DBUtil.java?rev=831663&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/util/DBUtil.java (added)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/util/DBUtil.java Sun Nov  1 10:21:13 2009
@@ -0,0 +1,20 @@
+package org.apache.empire.db.codegen.util;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import org.apache.commons.logging.Log;
+
+public class DBUtil {
+	public static boolean closeResultSet(ResultSet rs, Log log) {
+		boolean b = false;
+		try {
+			if(rs!=null)
+				rs.close();
+			b = true;
+		} catch (SQLException e) {
+			log.error("The resultset could not bel closed!", e);
+		}
+		return b;
+	}
+}

Propchange: incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/util/DBUtil.java
------------------------------------------------------------------------------
    eol-style = native

Propchange: incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/util/DBUtil.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/BaseRecord.vm
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/BaseRecord.vm?rev=831663&r1=831662&r2=831663&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/BaseRecord.vm (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/BaseRecord.vm Sun Nov  1 10:21:13 2009
@@ -16,15 +16,14 @@
  * specific language governing permissions and limitations
  * under the License.
  *#
-package ${recordPackage};
+package ${recordPackageName};
 
 import org.apache.empire.db.DBRecord;
-import ${tablePackageName}.${database.baseTableClassName};
+import ${tablePackageName}.${baseTableClassName};
 
-//import ${basePackageName}.${database.className};
 
-public abstract class BaseRecord<T extends ${database.baseTableClassName}> extends DBRecord {
-	public BaseRecord(T table) {
+public abstract class ${baseRecordClassName}<T extends ${baseTableClassName}> extends DBRecord {
+	public ${baseRecordClassName}(T table) {
 		super.init(table, DBRecord.REC_EMTPY, null);
 	}
 

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/BaseTable.vm
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/BaseTable.vm?rev=831663&r1=831662&r2=831663&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/BaseTable.vm (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/BaseTable.vm Sun Nov  1 10:21:13 2009
@@ -21,8 +21,8 @@
 import org.apache.empire.db.DBDatabase;
 import org.apache.empire.db.DBTable;
 
-public class ${db.baseTableClassName} extends DBTable {
-	public ${db.baseTableClassName}(String name, DBDatabase db) {
+public class ${baseTableClassName} extends DBTable {
+	public ${baseTableClassName}(String name, DBDatabase db) {
 		super(name, db);
 	}
 }

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Database.vm
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Database.vm?rev=831663&r1=831662&r2=831663&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Database.vm (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Database.vm Sun Nov  1 10:21:13 2009
@@ -30,7 +30,11 @@
 
 import $basePackageName.$tableSubPackage.*;
 
-public class $database.className extends DBDatabase {
+public class $dbClassName extends DBDatabase {
+
+	private static $dbClassName instance;
+	private static final long serialVersionUID = 1L;
+
 #foreach($table in $database.tables)
 	public final $table.className T_$table.tableName = new ${table.className}(this);
 #end
@@ -39,24 +43,17 @@
 	 * Returns the instance of the database.
 	 * @return
 	 */
-	public static $database.className get() {
+	public static $dbClassName get() {
 		if (instance == null) {
-			instance = new GamesDatabase();
+			instance = new ${dbClassName}();
 		}
 		return instance;
 	}
 	
 	/**
-	 * Default constructor for the $database.className.  Relationship between the
-	 * tables that make up the database are specified here. 
+	 * Default constructor for the $dbClassName.
 	 */
-	private ${database.className}() {
-		// FK relationships
-#foreach($table in $database.tables)
-#foreach($fkCol in $table.fkCols)
-		super.addRelation(T_${table.tableName}.${fkCol.name}.referenceOn(T_${fkCol.fkTableName}.${table.pkColName}));
-#end
-#end
+	private ${dbClassName}() {
 	}
 	
 	/**
@@ -117,7 +114,4 @@
 		}
 		return records;
 	}
-		
-	private static $database.className instance;
-	private static final long serialVersionUID = 1L;
 }

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Record.vm
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Record.vm?rev=831663&r1=831662&r2=831663&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Record.vm (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Record.vm Sun Nov  1 10:21:13 2009
@@ -16,14 +16,14 @@
  * specific language governing permissions and limitations
  * under the License.
  *#
-package ${recordPackage};
+package ${recordPackageName};
 
 #if ($table.hasBigDecimalField())
 import java.math.BigDecimal;
 #end
-import java.util.Date;
 
-import ${basePackageName}.${database.className};
+import ${basePackageName}.${dbClassName};
+import ${recordPackageName}.${baseRecordClassName};
 import ${tablePackageName}.${table.className};
 
 /**
@@ -37,54 +37,23 @@
  * This class provides protected method that subclasses should use to provide
  * access to related records.
  */
-public class ${table.recordClassName} extends BaseRecord<${table.className}> {
+public class ${table.recordClassName} extends ${baseRecordClassName}<${table.className}> {
 	public ${table.recordClassName}() {
-		super(${database.className}.get().T_${table.tableName});
+		super(${dbClassName}.get().T_${table.tableName});
 	}
 	
-	// Primary key getter
-	public Integer ${table.pkCol.javaAccessorName}() {
-		return (Integer)super.getValue(getDbTable().${table.pkCol.name});
-	}
-	
-	// Access methods for simple attributes
-#foreach($col in $table.simpleCols)
+#if($createRecordProperties == true)
+	// Access methods for all attributes
+#foreach($col in $table.columns)
 	public ${col.javaTypeString} ${col.javaAccessorName}() {
-		${col.originalJavaTypeString} ${col.javaName} = (${col.originalJavaTypeString})super.getValue(getDbTable().${col.name});
+		${col.originalJavaTypeString} ${col.javaName} = (${col.originalJavaTypeString})super.getValue(getDbTable().C_${col.name});
 		return ${col.returnExpression};
 	}
 	public void ${col.javaMutatorName}(${col.javaTypeString} ${col.javaName}) {
-		super.setValue(getDbTable().${col.name}, ${col.setExpression});
+		super.setValue(getDbTable().C_${col.name}, ${col.setExpression});
 	}
 #end
+#end
+
 
-	// Optimistic locking getter
-	public ${table.lockingCol.javaTypeString} ${table.lockingCol.javaAccessorName}() {
-		return (${table.lockingCol.javaTypeString})super.getValue(getDbTable().${table.lockingCol.name});		
-	}
-	
-	@Override
-    public boolean equals(Object object) {  
-        if (object == this)  
-            return true;  
-        if ((object == null) || !(object instanceof ${table.recordClassName}))  
-            return false;  
-   
-        final ${table.recordClassName} a = (${table.recordClassName})object;  
-   
-        if (${table.pkCol.javaAccessorName}() != null && a.${table.pkCol.javaAccessorName}() != null) {  
-            return ${table.pkCol.javaAccessorName}().equals(a.${table.pkCol.javaAccessorName}());  
-        }  
-        return false;  
-    }
-    
-    // FK references
-    #foreach($col in $table.fkCols)
-	public Integer ${col.javaAccessorName}() {
-		return (Integer)super.getValue(getDbTable().${col.name});
-	}
-	public void ${col.javaMutatorName}(Integer ${col.javaName}) {
-		super.setValue(getDbTable().${col.name}, ${col.javaName});
-	}
-    #end
 }
\ No newline at end of file

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Table.vm
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Table.vm?rev=831663&r1=831662&r2=831663&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Table.vm (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/resources/templates/Table.vm Sun Nov  1 10:21:13 2009
@@ -18,51 +18,47 @@
  *#
 package $tablePackageName;
 
+import java.util.ArrayList;
+import java.util.List;
+
 import org.apache.empire.data.DataType;
-import org.apache.empire.db.DBDatabase;
 import org.apache.empire.db.DBTableColumn;
 
-public class ${table.className} extends ${db.baseTableClassName} {
+import $basePackageName.${dbClassName};
+
+public class ${table.className} extends ${baseTableClassName} {
 	// Primary key column
-	public final DBTableColumn ${table.pkCol.name};
+	private List<DBTableColumn> keyColumns= new ArrayList<DBTableColumn>();
 	
 	// Regular attributes
-#foreach ($col in $table.simpleCols)
-	public final DBTableColumn ${col.name};
+#foreach ($col in $table.columns)
+	public final DBTableColumn C_${col.name};
 #end
 	
-	// Optimistic locking attribute
-	public final DBTableColumn ${table.lockingCol.name};
-	
-	// Foreign key columns
-#foreach ($col in $table.fkCols)
-	public final DBTableColumn ${col.name};
-#end
-	
-	public ${table.className}(DBDatabase db) {
+	public ${table.className}(${dbClassName} db) {
 		super("${table.tableName}", db);
 		
-		// Primary key column
-		${table.pkCol.name} = super.addColumn("${table.pkCol.name}", DataType.AUTOINC, 0, true);
-		
-		// Regular attributes
-#foreach ($col in $table.simpleCols)
-		${col.name} = super.addColumn("${col.name}", DataType.${col.empireType}, ${col.colSize}, ${col.required}, ${col.defaultValue});
+		// all columns
+#foreach ($col in $table.columns)
+		C_${col.name} = super.addColumn("${col.name}", DataType.${col.empireType}, ${col.colSize}, ${col.required}, ${col.defaultValue});
 #end
 
-		// Optimistic locking attribute
-		${table.lockingCol.name} = super.addColumn("${table.lockingCol.name}", DataType.DATETIME, 0, false);
-		
-		// Foreign key columns
-#foreach ($col in $table.fkCols)
-		${col.name} = super.addColumn("${col.name}", DataType.INTEGER, 0, ${col.required});
-#end		
-		// Primary key
-		super.setPrimaryKey(${table.pkCol.name});
+
+		// configure primary columns
+#foreach ($col in $table.columns)
+#if($col.primaryColumn == true)
+    	keyColumns.add(C_${col.name});
+#end
+#end
+		super.setPrimaryKey((DBTableColumn[]) keyColumns.toArray());
 		
 		// Optimistic locking column
-		super.setTimestampColumn(${table.lockingCol.name});
-		
+#if($table.hasLockColumn == true)
+		super.setTimestampColumn(C_${table.lockColumn.name});
+#else
+		/*no locking column specified*/
+#end
+
 		// Set cascade delete
 		super.setCascadeDelete(true);		
 	}



Mime
View raw message