From 2624e2d9e186c1b8ca9b446e3adc927440f7770f Mon Sep 17 00:00:00 2001 From: mdb Date: Mon, 20 Feb 2006 21:58:50 +0000 Subject: [PATCH] Added loadSchema(). git-svn-id: https://samskivert.googlecode.com/svn/trunk@1790 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- src/java/com/samskivert/jdbc/JDBCUtil.java | 56 +++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/src/java/com/samskivert/jdbc/JDBCUtil.java b/src/java/com/samskivert/jdbc/JDBCUtil.java index 346112c0..97812221 100644 --- a/src/java/com/samskivert/jdbc/JDBCUtil.java +++ b/src/java/com/samskivert/jdbc/JDBCUtil.java @@ -20,8 +20,15 @@ package com.samskivert.jdbc; +import java.io.InputStream; import java.io.UnsupportedEncodingException; -import java.sql.*; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import org.apache.commons.io.IOUtils; import com.samskivert.Log; import com.samskivert.io.PersistenceException; @@ -201,6 +208,53 @@ public class JDBCUtil return StringUtil.replace(jigger(text), "'", "\\'"); } + /** + * Loads in the specified schema configuration file. The file data is + * loaded as a resource from the classpath. This is used for the + * autocreation of repository tables. For example: + * + *
+     * if (!JDBCUtil.tableExists(conn, "MONKEYS")) {
+     *     Log.info("Creating monkeys repository schema...");
+     *     JDBCUtil.loadSchema(conn, "src/sql/monkeys.sql");
+     * }
+     * 
+ */ + public static void loadSchema (Connection conn, String path) + throws SQLException + { + InputStream schemaIn = + JDBCUtil.class.getClassLoader().getResourceAsStream(path); + if (schemaIn == null) { + throw new SQLException("Unable to load '" + path + + "' using class loader."); + } + loadSchema(conn, schemaIn); + } + + /** + * A version of {@link #loadSchema(Connection,String)} that allows the + * caller to obtain the schema data. + */ + public static void loadSchema (Connection conn, InputStream schemaIn) + throws SQLException + { + String schema; + try { + schema = IOUtils.toString(schemaIn); + } catch (Exception e) { + String errmsg = "Error reading schema [src=" + schemaIn + "]."; + throw (SQLException)new SQLException(errmsg).initCause(e); + } + + Statement stmt = conn.createStatement(); + try { + stmt.executeUpdate(schema); + } finally { + close(stmt); + } + } + /** * Returns true if the table with the specified name exists, false if * it does not. Note: the table name is case sensitive.