View Javadoc

1   /**
2    * Copyright 2011 The Kuali Foundation Licensed under the
3    * Educational Community License, Version 2.0 (the "License"); you may
4    * not use this file except in compliance with the License. You may
5    * obtain a copy of the License at
6    *
7    * http://www.osedu.org/licenses/ECL-2.0
8    *
9    * Unless required by applicable law or agreed to in writing,
10   * software distributed under the License is distributed on an "AS IS"
11   * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing
13   * permissions and limitations under the License.
14   */
15   
16  package org.kuali.mobility.database.service;
17  
18  import java.util.Iterator;
19  import java.util.Map;
20  import java.util.Properties;
21  
22  import javax.annotation.Resource;
23  import javax.persistence.spi.PersistenceUnitInfo;
24  
25  import org.hibernate.cfg.Configuration;
26  import org.hibernate.cfg.Environment;
27  import org.hibernate.dialect.Dialect;
28  import org.hibernate.ejb.Ejb3Configuration;
29  import org.hibernate.jdbc.util.FormatStyle;
30  import org.hibernate.jdbc.util.Formatter;
31  import org.hibernate.mapping.ForeignKey;
32  import org.hibernate.mapping.Table;
33  import org.hibernate.tool.hbm2ddl.SchemaExport;
34  import org.hibernate.util.PropertiesHelper;
35  import org.kuali.mobility.database.dao.DatabaseDao;
36  import org.springframework.beans.factory.annotation.Autowired;
37  import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
38  import org.springframework.stereotype.Service;
39  
40  @Service
41  public class DatabaseServiceImpl implements DatabaseService {
42  
43  	private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(DatabaseServiceImpl.class);
44  	
45      @Autowired
46      private DatabaseDao dao;
47      public void setDatabaseDao(DatabaseDao dao) {
48          this.dao = dao;
49      }
50      public DatabaseDao getDatabaseDao() {
51          return dao;
52      }
53      
54  	@Resource(name="&entityManagerFactory")
55  	private LocalContainerEntityManagerFactoryBean entityManagerFactory;
56      
57  	@Override
58  	public String getSchema(String dialect, String delimiter, boolean overrideAlterTable) {
59  		return execute(dialect, delimiter, overrideAlterTable);
60  	}
61  
62  	private String execute(String dialectStr, String delimiter, boolean overrideAlterTable) {
63  	    PersistenceUnitInfo persistenceUnitInfo = entityManagerFactory.getPersistenceUnitInfo();
64  
65  	    Map<String, Object> jpaPropertyMap = entityManagerFactory.getJpaPropertyMap();	
66  	    jpaPropertyMap.put("hibernate.dialect", dialectStr); 
67  	    Configuration configuration = new Ejb3Configuration().configure( persistenceUnitInfo, jpaPropertyMap ).getHibernateConfiguration();
68  //	    KMEDatabaseConfiguration c = (KMEDatabaseConfiguration) configuration;
69  	    
70  	    if (overrideAlterTable) {
71  			Iterator iter = configuration.getTableMappings();
72  			while ( iter.hasNext() ) {
73  				Table table = (Table) iter.next();
74  				if ( table.isPhysicalTable() ) {
75  					Iterator subIter = table.getForeignKeyIterator();
76  					while ( subIter.hasNext() ) {
77  						ForeignKey fk = (ForeignKey) subIter.next();
78  						if ( fk.isPhysicalConstraint() ) {
79  							subIter.remove();
80  						}
81  					}
82  				}
83  			}	    	
84  	    }
85  	    
86  	    Properties configurationProperties = configuration.getProperties();
87  	    
88  	    Dialect dialect = Dialect.getDialect(configurationProperties);
89  //	    if (dialect instanceof KMEDialect) {
90  //	    	KMEDialect d = (KMEDialect) dialect;
91  //	    	d.setOverrideAlterTable(overrideAlterTable);
92  //	    }
93  	    
94  		Properties props = new Properties();
95  		props.putAll(dialect.getDefaultProperties());
96  		props.putAll(configurationProperties);
97  
98  		String[] dropSQL = configuration.generateDropSchemaScript(dialect);
99  		String[] createSQL = configuration.generateSchemaCreationScript(dialect);
100 
101 		Formatter formatter = (PropertiesHelper.getBoolean(Environment.FORMAT_SQL, props) ? FormatStyle.DDL
102 				: FormatStyle.NONE).getFormatter();
103 		boolean format = true;
104 		formatter = ( format ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
105 		
106 //		String delimiter = ";";
107 		StringBuffer output = new StringBuffer();
108 		for (String s : dropSQL) {
109 			output.append(formatMe(s, formatter, delimiter));
110 			output.append("\n");
111 		}
112 		for (String s : createSQL) {
113 			output.append(formatMe(s, formatter, delimiter));
114 			output.append("\n");
115 		}
116 
117 	    SchemaExport schema = new SchemaExport(configuration);
118 //	    schema.setFormat(true);
119 //	    schema.setDelimiter(";");
120 //	    schema.setOutputFile("/tmp/schema.sql");
121 //  	schema.create(false, false);
122 		
123 //org.hibernate.dialect.Oracle10gDialect
124 //org.hibernate.dialect.MySQL5Dialect
125 		return output.toString();
126 	}
127 	
128 	private String formatMe(String sql, Formatter formatter, String delimiter) {
129 		String formatted = formatter.format( sql );
130 		if ( delimiter != null ) {
131 			formatted += delimiter;
132 		}
133 		return formatted;
134 	}
135 	
136     
137 }