e.g. Calendar Search Help
You must enter a value before pressing Search
xplanner

Class: com.technoetic.xplanner.db.hibernate.TransformingSchemaExport   ©

 OK to copy?
001 package com.technoetic.xplanner.db.hibernate;
002 
003 import net.sf.hibernate.HibernateException;
004 import net.sf.hibernate.cfg.Configuration;
005 import net.sf.hibernate.connection.ConnectionProvider;
006 import net.sf.hibernate.connection.ConnectionProviderFactory;
007 import net.sf.hibernate.dialect.Dialect;
008 import net.sf.hibernate.util.JDBCExceptionReporter;
009 import net.sf.hibernate.util.StringHelper;
010 import org.apache.commons.logging.Log;
011 import org.apache.commons.logging.LogFactory;
012 
013 import java.io.File;
014 import java.io.FileInputStream;
015 import java.io.FileWriter;
016 import java.io.IOException;
017 import java.sql.Connection;
018 import java.sql.SQLException;
019 import java.sql.Statement;
020 import java.util.Properties;
021 import java.util.StringTokenizer;
022 
023 /**
024  * Modified version of Hibernate's SchemaExport to allow us to use XSL transformed mapping files. The
025  * original class couldn't be used because the execute() method is private.
026  */
027 public class TransformingSchemaExport {
028 
029     private static final Log log = LogFactory.getLog(TransformingSchemaExport.class);
030 
031     private String[] dropSQL;
032     private String[] createSQL;
033     private Properties connectionProperties;
034     private String outputFile = null;
035     private Dialect dialect;
036     private String delimiter;
037 
038     /**
039      * Create a schema exporter for the given Configuration
040      */
041     public TransformingSchemaExport(Configuration cfg) throws HibernateException {
042         this(cfg, cfg.getProperties());
043     }
044 
045     /**
046      * Create a schema exporter for the given Configuration, with the given
047      * database connection properties.
048      */
049     public TransformingSchemaExport(Configuration cfg, Properties connectionProperties) throws HibernateException {
050         this.connectionProperties = connectionProperties;
051         dialect = Dialect.getDialect(connectionProperties);
052         dropSQL = cfg.generateDropSchemaScript(dialect);
053         createSQL = cfg.generateSchemaCreationScript(dialect);
054     }
055 
056     /**
057      * Set an output filename. The generated script will be written to this file.
058      */
059     public TransformingSchemaExport setOutputFile(String filename) {
060         outputFile = filename;
061         return this;
062     }
063 
064     /**
065      * Set the end of statement delimiter
066      */
067     public TransformingSchemaExport setDelimiter(String delimiter) {
068         this.delimiter = delimiter;
069         return this;
070     }
071 
072     /**
073      * Run the schema creation script.
074      * @param script print the DDL to the console
075      * @param export export the script to the database
076      */
077     public void create(boolean script, boolean export) {
078         execute(script, export, false, true);
079     }
080 
081     /**
082      * Run the drop schema script.
083      * @param script print the DDL to the console
084      * @param export export the script to the database
085      */
086     public void drop(boolean script, boolean export) {
087         execute(script, export, true, true);
088     }
089 
090     private void execute(boolean script, boolean export, boolean justDrop, boolean format) {
091 
092         log.info("Running hbm2ddl schema export");
093 
094         Connection connection = null;
095         FileWriter fileOutput = null;
096         ConnectionProvider connectionProvider = null;
097         Statement statement = null;
098 
099         Properties props = new Properties();
100         props.putAll(dialect.getDefaultProperties());
101         props.putAll(connectionProperties);
102 
103         try {
104 
105             if (outputFile != null) {
106                 log.info("writing generated schema to file: " + outputFile);
107                 fileOutput = new FileWriter(outputFile);
108             }
109 
110             if (export) {
111                 log.info("exporting generated schema to database");
112                 connectionProvider = ConnectionProviderFactory.newConnectionProvider(props);
113                 connection = connectionProvider.getConnection();
114                 if (!connection.getAutoCommit()) {
115                     connection.commit();
116                     connection.setAutoCommit(true);
117                 }
118                 statement = connection.createStatement();
119             }
120 
121             for (int i = 0; i < dropSQL.length; i++) {
122                 try {
123                     String formatted = dropSQL[i];
124                     if (delimiter != null) formatted += delimiter;
125                     if (script) System.out.println(formatted);
126                     log.debug(formatted);
127                     if (outputFile != null) fileOutput.write(formatted + "\n");
128                     if (export) statement.executeUpdate(dropSQL[i]);
129                 } catch (SQLException e) {
130                     log.debug("Unsuccessful: " + dropSQL[i]);
131                     log.debug(e.getMessage());
132                 }
133 
134             }
135 
136             if (!justDrop) {
137                 for (int j = 0; j < createSQL.length; j++) {
138                     try {
139                         String formatted = format ? format(createSQL[j]) : createSQL[j];
140                         if (delimiter != null) formatted += delimiter;
141                         if (script) System.out.println(formatted);
142                         log.debug(formatted);
143                         if (outputFile != null) fileOutput.write(formatted + "\n");
144                         if (export) statement.executeUpdate(createSQL[j]);
145                     } catch (SQLException e) {
146                         log.error("Unsuccessful: " + createSQL[j]);
147                         log.error(e.getMessage());
148                     }
149                 }
150             }
151 
152             log.info("schema export complete");
153 
154         } catch (Exception e) {
155             log.error("schema export unsuccessful", e);
156         } finally {
157 
158             try {
159                 if (statement != null) statement.close();
160                 if (connection != null) {
161                     JDBCExceptionReporter.logWarnings(connection.getWarnings());
162                     connection.clearWarnings();
163                     connectionProvider.closeConnection(connection);
164                     connectionProvider.close();
165                 }
166             } catch (Exception e) {
167                 log.error("Could not close connection", e);
168             }
169 
170             try {
171                 if (fileOutput != null) fileOutput.close();
172             } catch (IOException ioe) {
173                 log.error("Error closing output file: " + outputFile, ioe);
174             }
175 
176         }
177     }
178 
179     /**
180      * Format an SQL statement using simple rules:
181      *  a) Insert newline after each comma;
182      *  b) Indent three spaces after each inserted newline;
183      * If the statement contains single/double quotes return unchanged,
184      * it is too complex and could be broken by simple formatting.
185      */
186     private static String format(String sql) {
187 
188         if (sql.indexOf("\"") > 0 || sql.indexOf("'") > 0) {
189             return sql;
190         }
191 
192         String formatted;
193 
194         if (sql.toLowerCase().startsWith("create table")) {
195 
196             StringBuffer result = new StringBuffer(60);
197             StringTokenizer tokens = new StringTokenizer(sql, "(,)", true);
198 
199             int depth = 0;
200 
201             while (tokens.hasMoreTokens()) {
202                 String tok = tokens.nextToken();
203                 if (StringHelper.CLOSE_PAREN.equals(tok)) {
204                     depth--;
205                     if (depth == 0) result.append("\n");
206                 }
207                 result.append(tok);
208                 if (StringHelper.COMMA.equals(tok) && depth == 1) result.append("\n  ");
209                 if (StringHelper.OPEN_PAREN.equals(tok)) {
210                     depth++;
211                     if (depth == 1) result.append("\n   ");
212                 }
213             }
214 
215             formatted = result.toString();
216 
217         } else {
218             formatted = sql;
219         }
220 
221         return formatted;
222     }
223 
224     public static void main(String[] args) {
225         try {
226             Configuration cfg = HibernateHelper.initializeConfiguration();
227 
228             boolean script = true;
229             boolean drop = false;
230             boolean export = true;
231             String outFile = null;
232             String propFile = null;
233             boolean formatSQL = false;
234             String delim = null;
235 
236             for (int i = 0; i < args.length; i++) {
237                 if (args[i].startsWith("--")) {
238                     if (args[i].equals("--quiet")) {
239                         script = false;
240                     } else if (args[i].equals("--drop")) {
241                         drop = true;
242                     } else if (args[i].equals("--text")) {
243                         export = false;
244                     } else if (args[i].startsWith("--output=")) {
245                         outFile = args[i].substring(9);
246                     } else if (args[i].startsWith("--properties=")) {
247                         propFile = args[i].substring(13);
248                     } else if (args[i].equals("--format")) {
249                         formatSQL = true;
250                     } else if (args[i].startsWith("--delimiter=")) {
251                         delim = args[i].substring(12);
252                     } else if (args[i].startsWith("--config=")) {
Rate253                         cfg.configure(args[i].substring(9));
254                     }
255                 } else {
256                     String filename = args[i];
257                     if (filename.endsWith(".jar")) {
258                         cfg.addJar(new File(filename));
259                     } else {
260                         cfg.addFile(filename);
261                     }
262                 }
263 
264             }
265             if (propFile != null) {
266                 Properties props = new Properties();
267                 props.load(new FileInputStream(propFile));
268                 new TransformingSchemaExport(cfg, props)
269                         .setOutputFile(outFile)
270                         .setDelimiter(delim)
271                         .execute(script, export, drop, formatSQL);
272             } else {
273                 new TransformingSchemaExport(cfg)
274                         .setOutputFile(outFile)
275                         .setDelimiter(delim)
276                         .execute(script, export, drop, formatSQL);
277             }
278         } catch (Exception e) {
279             log.error("Error creating schema ", e);
280             e.printStackTrace();
281         }
282     }
283 }
284 
285 
286 
287 
288 
289 


            
All Examples in File:
Example
Line
Rating (found
useful by...)
253 0% of 0