[Schmitzm-commits] r1727 - trunk/schmitzm-core/src/main/java/de/schmitzm/postgres

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Tue Sep 13 16:11:23 CEST 2011


Author: alfonx
Date: 2011-09-13 16:11:22 +0200 (Tue, 13 Sep 2011)
New Revision: 1727

Modified:
   trunk/schmitzm-core/src/main/java/de/schmitzm/postgres/PGUtil.java
Log:
Alle Verwendungen von ResultSet mit
		try {
			...
		} catch (Exception e) {
			rs.close();
		}
ausgestattet.

Modified: trunk/schmitzm-core/src/main/java/de/schmitzm/postgres/PGUtil.java
===================================================================
--- trunk/schmitzm-core/src/main/java/de/schmitzm/postgres/PGUtil.java	2011-09-12 18:20:55 UTC (rev 1726)
+++ trunk/schmitzm-core/src/main/java/de/schmitzm/postgres/PGUtil.java	2011-09-13 14:11:22 UTC (rev 1727)
@@ -26,8 +26,7 @@
 	 * @see http://www.postgresql.org/docs/9.1/static/sql-grant.html
 	 */
 	public enum Privileges {
-		SELECT, INSERT, UPDATE, DELETE, REFERENCES, TEMPORARY, ALL_PRIVILEGES(
-				"ALL PRIVILEGES");
+		SELECT, INSERT, UPDATE, DELETE, REFERENCES, TEMPORARY, ALL_PRIVILEGES("ALL PRIVILEGES");
 
 		String sql;
 
@@ -56,12 +55,11 @@
 	 *            List der zuzuordnenden Privilegien
 	 * @throws SQLException
 	 */
-	public static void grantPrivilegesOnTable(Connection c, String targetRole,
-			String tablename, Privileges... privileges) throws SQLException {
+	public static void grantPrivilegesOnTable(Connection c, String targetRole, String tablename,
+			Privileges... privileges) throws SQLException {
 		// GRANT SELECT, UPDATE, INSERT ON mytable TO admin;
-		String sql = "GRANT "
-				+ LangUtil.stringConcatWithSep(",", (Object[]) privileges)
-				+ " ON " + tablename + " TO " + targetRole;
+		String sql = "GRANT " + LangUtil.stringConcatWithSep(",", (Object[]) privileges) + " ON " + tablename + " TO "
+				+ targetRole;
 		c.createStatement().executeUpdate(sql);
 	}
 
@@ -74,20 +72,18 @@
 	 *            List der zuzuordnenden Privilegien
 	 * @throws SQLException
 	 */
-	public static void revokePrivilegesOnTable(Connection c, String tablename,
-			String targetRole, Privileges... privileges) throws SQLException {
+	public static void revokePrivilegesOnTable(Connection c, String tablename, String targetRole,
+			Privileges... privileges) throws SQLException {
 		// GRANT SELECT, UPDATE, INSERT ON mytable TO admin;
-		String sql = "REVOKE "
-				+ LangUtil.stringConcatWithSep(",", (Object[]) privileges)
-				+ " ON " + tablename + " FROM " + targetRole;
+		String sql = "REVOKE " + LangUtil.stringConcatWithSep(",", (Object[]) privileges) + " ON " + tablename
+				+ " FROM " + targetRole;
 		c.createStatement().executeUpdate(sql);
 	}
 
 	/**
 	 * Erstellt eine neue Rolle
 	 */
-	public static void createRole(Connection c, String rolename)
-			throws SQLException {
+	public static void createRole(Connection c, String rolename) throws SQLException {
 		String sql = "CREATE ROLE " + rolename;
 		c.createStatement().executeUpdate(sql);
 	}
@@ -99,10 +95,14 @@
 	static public String[] getColumnsDescribedInGeometryColumnsTable(Statement s) {
 		String[] columns = new String[0];
 		try {
-			ResultSet askGeoe = s
-					.executeQuery("SELECT f_table_name FROM geometry_columns;");
-			while (askGeoe.next()) {
-				columns = LangUtil.extendArray(columns, askGeoe.getString(1));
+			ResultSet rs = s.executeQuery("SELECT f_table_name FROM geometry_columns;");
+			try {
+
+				while (rs.next()) {
+					columns = LangUtil.extendArray(columns, rs.getString(1));
+				}
+			} catch (Exception e) {
+				rs.close();
 			}
 		} catch (SQLException e) {
 			log.error(e, e);
@@ -121,16 +121,10 @@
 	 */
 	@Deprecated
 	// tut noch nicht
-	public static void createOrUpdateGeometrysColumnsEntry(String tableName,
-			String geoColumnName, int srid) {
+	public static void createOrUpdateGeometrysColumnsEntry(String tableName, String geoColumnName, int srid) {
 
 		String createGeometryEntrySQL = "INSERT INTO geometry_columns (f_table_catalog, f_table_schema, f_table_name, f_geometry_column, coord_dimension, srid, \"type\") VALUES ( '', 'public', '"
-				+ tableName
-				+ "', '"
-				+ geoColumnName
-				+ "', 2, "
-				+ srid
-				+ ",'MULTIPOLYGON' ) LIMIT 1;";
+				+ tableName + "', '" + geoColumnName + "', 2, " + srid + ",'MULTIPOLYGON' ) LIMIT 1;";
 	}
 
 	// TODO isGeoColumn();
@@ -153,8 +147,7 @@
 			return "bigint";
 		}
 
-		throw new RuntimeException("DB Type mapping for " + binding
-				+ " not yet implemented.");
+		throw new RuntimeException("DB Type mapping for " + binding + " not yet implemented.");
 	}
 
 	/**
@@ -162,11 +155,9 @@
 	 * 
 	 * @return <code>true</code> wenn das Schema neu angelegt wurde.
 	 */
-	public static boolean createSchemaIfNotExists(Connection c,
-			String schemaname) throws SQLException {
+	public static boolean createSchemaIfNotExists(Connection c, String schemaname) throws SQLException {
 		if (!existsSchema(c, schemaname)) {
-			c.createStatement().execute(
-					"create schema " + schemaname.toLowerCase());
+			c.createStatement().execute("create schema " + schemaname.toLowerCase());
 			return true;
 		}
 		return false;
@@ -176,12 +167,16 @@
 	 * Liefert <code>true</code> wenn ein Schema mit dem Namen in der PG
 	 * Datenbank existiert.
 	 */
-	public static boolean existsSchema(Connection c, String schemaname)
-			throws SQLException {
-		ResultSet rs = c.createStatement().executeQuery(
-				"select 1 from pg_catalog.pg_namespace where nspname = '"
-						+ schemaname.toLowerCase() + "'");
-		return rs.next();
+	public static boolean existsSchema(Connection c, String schemaname) throws SQLException {
+		String sql = "select 1 from pg_catalog.pg_namespace where nspname = '" + schemaname.toLowerCase() + "'";
+		ResultSet rs = c.createStatement().executeQuery(sql);
+		try {
+			return rs.next();
+		} catch (Exception e) {
+			rs.close();
+			return false;
+		}
+
 	}
 
 	/**
@@ -189,16 +184,17 @@
 	 * ist. <br/>
 	 * Tested with PG 8.4
 	 */
-	public static List<String> listRolesForUser(Connection c, String username)
-			throws SQLException {
+	public static List<String> listRolesForUser(Connection c, String username) throws SQLException {
 		List<String> roles = new ArrayList<String>();
-		ResultSet rs = c
-				.createStatement()
-				.executeQuery(
-						"select rolname from pg_user join pg_auth_members on (pg_user.usesysid=pg_auth_members.member) join pg_roles on (pg_roles.oid=pg_auth_members.roleid) where pg_user.usename='"
-								+ username.toLowerCase() + "'");
-		while (rs.next()) {
-			roles.add(rs.getString(1));
+		String sql = "select rolname from pg_user join pg_auth_members on (pg_user.usesysid=pg_auth_members.member) join pg_roles on (pg_roles.oid=pg_auth_members.roleid) where pg_user.usename='"
+				+ username.toLowerCase() + "'";
+		ResultSet rs = c.createStatement().executeQuery(sql);
+		try {
+			while (rs.next()) {
+				roles.add(rs.getString(1));
+			}
+		} catch (Exception e) {
+			rs.close();
 		}
 		return roles;
 	}
@@ -210,10 +206,13 @@
 	 */
 	public static List<String> listUsers(Connection c) throws SQLException {
 		List<String> roles = new ArrayList<String>();
-		ResultSet rs = c.createStatement()
-				.executeQuery("select * from pg_user");
-		while (rs.next()) {
-			roles.add(rs.getString(1));
+		ResultSet rs = c.createStatement().executeQuery("select * from pg_user");
+		try {
+			while (rs.next()) {
+				roles.add(rs.getString(1));
+			}
+		} catch (Exception e) {
+			rs.close();
 		}
 		return roles;
 	}
@@ -226,15 +225,17 @@
 	 * @param schemaname
 	 *            if <code>null</code>, <code>public</code> is used.
 	 */
-	public static List<String> listTablesInSchema(Connection c,
-			String schemaname) throws SQLException {
+	public static List<String> listTablesInSchema(Connection c, String schemaname) throws SQLException {
 		List<String> tables = new ArrayList<String>();
 
-		String sql = "select tablename from pg_tables where schemaname = '"
-				+ schemaname.toLowerCase() + "'";
+		String sql = "select tablename from pg_tables where schemaname = '" + schemaname.toLowerCase() + "'";
 		ResultSet rs = c.createStatement().executeQuery(sql);
-		while (rs.next()) {
-			tables.add(rs.getString(1));
+		try {
+			while (rs.next()) {
+				tables.add(rs.getString(1));
+			}
+		} catch (Exception e) {
+			rs.close();
 		}
 		return tables;
 	}
@@ -242,41 +243,41 @@
 	/**
 	 * Liefert <code>true</code> wenn der Benutzername im DBMS Superuser ist.
 	 */
-	public static boolean isSuperuser(Connection c, String username)
-			throws SQLException {
+	public static boolean isSuperuser(Connection c, String username) throws SQLException {
 		ResultSet rs = c.createStatement().executeQuery(
-				"select usesuper from pg_user where usename = '" + username
-						+ "' and usesuper = true");
-		if (rs.next()) {
-			return true;
+				"select usesuper from pg_user where usename = '" + username + "' and usesuper = true");
+		try {
+			if (rs.next()) {
+				return true;
+			}
+		} catch (Exception e) {
+			rs.close();
 		}
 		return false;
 	}
 
-	public static boolean existsRole(Connection c, String rolename)
-			throws SQLException {
-		ResultSet rs = c.createStatement().executeQuery(
-				"select count(1) from pg_roles where rolname = '"
-						+ rolename.toLowerCase() + "'");
-		if (rs.next())
-			return rs.getInt(1) > 0;
+	public static boolean existsRole(Connection c, String rolename) throws SQLException {
+		String sql = "select count(1) from pg_roles where rolname = '" + rolename.toLowerCase() + "'";
+		ResultSet rs = c.createStatement().executeQuery(sql);
+		try {
+			if (rs.next())
+				return rs.getInt(1) > 0;
+		} catch (Exception e) {
+			rs.close();
+		}
 		return false;
 	}
 
-	public static void removeAllPrivilegesFrom(Connection c, String rolename,
-			String tablename) throws SQLException {
+	public static void removeAllPrivilegesFrom(Connection c, String rolename, String tablename) throws SQLException {
 		c.createStatement().executeUpdate(
-				"revoke all on TABLE " + tablename.toLowerCase() + " from "
-						+ rolename.toLowerCase() + " cascade");
+				"revoke all on TABLE " + tablename.toLowerCase() + " from " + rolename.toLowerCase() + " cascade");
 	}
 
 	/**
 	 * Löscht eine Rolle wenn sie vorher existiert
 	 */
-	public static void dropRoleIfExists(Connection c, String rolename)
-			throws SQLException {
-		c.createStatement().executeUpdate(
-				"drop role if exists " + rolename.toLowerCase());
+	public static void dropRoleIfExists(Connection c, String rolename) throws SQLException {
+		c.createStatement().executeUpdate("drop role if exists " + rolename.toLowerCase());
 	}
 
 	/**
@@ -286,11 +287,8 @@
 	 * @param triggerName
 	 * @param tableName
 	 */
-	public static void dropTriggerIfExists(Connection c, String triggerName,
-			String tableName) throws SQLException {
-		c.createStatement().executeUpdate(
-				"drop TRIGGER if exists " + triggerName.toLowerCase() + " ON "
-						+ tableName);
+	public static void dropTriggerIfExists(Connection c, String triggerName, String tableName) throws SQLException {
+		c.createStatement().executeUpdate("drop TRIGGER if exists " + triggerName.toLowerCase() + " ON " + tableName);
 	}
 
 	/**
@@ -304,12 +302,10 @@
 	 *            +NEW.risiko_spr+NEW.risiko_wohl;
 	 * @throws SQLException
 	 */
-	public static void createOrReplaceFunction(Connection c, String name,
-			String plCommands) throws SQLException {
+	public static void createOrReplaceFunction(Connection c, String name, String plCommands) throws SQLException {
 		// System.err.println(plCommands);
 		c.createStatement().executeUpdate(
-				"CREATE OR REPLACE FUNCTION " + name + "()"
-						+ "RETURNS trigger AS 'BEGIN " + plCommands
+				"CREATE OR REPLACE FUNCTION " + name + "()" + "RETURNS trigger AS 'BEGIN " + plCommands
 						+ "RETURN NEW; END;' LANGUAGE 'plpgsql'");
 	}
 
@@ -322,14 +318,12 @@
 	 * @param plCommands
 	 *            Simple PSQL commands
 	 */
-	public static void createOrRecreateTrigger(Connection c,
-			String triggerName, String type, String tableName, String plCommands)
-			throws SQLException {
+	public static void createOrRecreateTrigger(Connection c, String triggerName, String type, String tableName,
+			String plCommands) throws SQLException {
 		dropTriggerIfExists(c, triggerName, tableName);
 		createOrReplaceFunction(c, triggerName + "_fn", plCommands);
 		c.createStatement().executeUpdate(
-				"CREATE TRIGGER " + triggerName + " " + type + " ON "
-						+ tableName + " FOR EACH ROW EXECUTE PROCEDURE "
+				"CREATE TRIGGER " + triggerName + " " + type + " ON " + tableName + " FOR EACH ROW EXECUTE PROCEDURE "
 						+ triggerName + "_fn" + "()");
 	}
 
@@ -344,9 +338,8 @@
 	 *            <code>true</code> if the columns are unique. A UNIQUE INDEX
 	 *            will be created.
 	 */
-	public static void addIndex(Connection c, final String tableName,
-			final String columns, String idxPostfix, final boolean unique)
-			throws SQLException {
+	public static void addIndex(Connection c, final String tableName, final String columns, String idxPostfix,
+			final boolean unique) throws SQLException {
 		addIndex(c, tableName, columns, idxPostfix, unique, null);
 	}
 
@@ -357,23 +350,24 @@
 	 * Achtung: Diese abfrage ist nicht Schema-Spezifisch. Eine schema. Angabe
 	 * vor dem tabellennamen wird automatisch entfernt.
 	 */
-	public static List<String> listIndexesForTable(Connection c,
-			String tableName) throws SQLException {
+	public static List<String> listIndexesForTable(Connection c, String tableName) throws SQLException {
 		Statement s = c.createStatement();
 
 		if (tableName.contains("."))
-			tableName = tableName.substring(tableName.indexOf(".") + 1,
-					tableName.length());
+			tableName = tableName.substring(tableName.indexOf(".") + 1, tableName.length());
 
 		List<String> idxes = new ArrayList<String>();
 
 		String sql = "select t.relname as table_name, i.relname as index_name, array_to_string(array_agg(a.attname), ', ') as column_names from pg_class t, pg_class i, pg_index ix, pg_attribute a where t.oid = ix.indrelid and i.oid = ix.indexrelid and a.attrelid = t.oid and a.attnum = ANY(ix.indkey) and t.relkind = 'r' and t.relname like '"
-				+ tableName
-				+ "' group by t.relname, i.relname order by t.relname, i.relname";
+				+ tableName + "' group by t.relname, i.relname order by t.relname, i.relname";
 
 		ResultSet rs = s.executeQuery(sql);
-		while (rs.next()) {
-			idxes.add(rs.getString(2));
+		try {
+			while (rs.next()) {
+				idxes.add(rs.getString(2));
+			}
+		} catch (Exception e) {
+			rs.close();
 		}
 
 		return idxes;
@@ -394,9 +388,8 @@
 	 *            <code>null</code> oder der name des tablespace in dem der
 	 *            Index liegen soll.
 	 */
-	public static void addIndex(Connection c, final String tableName,
-			final String columns, String idxPostfix, final boolean unique,
-			String tablespace) throws SQLException {
+	public static void addIndex(Connection c, final String tableName, final String columns, String idxPostfix,
+			final boolean unique, String tablespace) throws SQLException {
 		final String idxName = (tableName + "_" + idxPostfix).replace(".", "_");
 
 		// Wenn der Tablename ein Schema mit "schema.name" enthält, dann liefert
@@ -409,10 +402,8 @@
 
 		Statement s = c.createStatement();
 
-		final String queryString = "CREATE " + (unique ? "UNIQUE " : "")
-				+ "INDEX " + idxName + " ON " + tableName + " (" + columns
-				+ ") "
-				+ (tablespace == null ? "" : " TABLESPACE " + tablespace);
+		final String queryString = "CREATE " + (unique ? "UNIQUE " : "") + "INDEX " + idxName + " ON " + tableName
+				+ " (" + columns + ") " + (tablespace == null ? "" : " TABLESPACE " + tablespace);
 		try {
 			s.execute(queryString);
 			c.commit();
@@ -429,11 +420,9 @@
 			// Ex abfangen, wenn IDX schon existiert
 
 			String msg = cause.getMessage();
-			if (msg.endsWith("already exists")
-					|| msg.endsWith("existiert bereits")) {
+			if (msg.endsWith("already exists") || msg.endsWith("existiert bereits")) {
 				// TO NOTHING, IDX already exists
-				log.info("Index existierte bereits, nicht neuerstellt: "
-						+ queryString);
+				log.info("Index existierte bereits, nicht neuerstellt: " + queryString);
 			} else
 				log.error(e.getLocalizedMessage(), e);
 
@@ -447,16 +436,14 @@
 	 * 
 	 * @throws SQLException
 	 */
-	public static void grantRoleToUser(Connection c, String rolename,
-			String username) throws SQLException {
-		c.createStatement().executeUpdate(
-				"GRANT " + rolename + " TO " + username);
+	public static void grantRoleToUser(Connection c, String rolename, String username) throws SQLException {
+		c.createStatement().executeUpdate("GRANT " + rolename + " TO " + username);
 	}
 
 	/**
 	 * Der : (Doppelpunkt) hat in PSQL eine besondere Bedeutung. Er wind mit
-	 * dieser methode escaped. Diese Methode sollte mit <code>like E'"+PGUtil.escape(...)+"'</code>
-	 * verwendet werden.
+	 * dieser methode escaped. Diese Methode sollte mit
+	 * <code>like E'"+PGUtil.escape(...)+"'</code> verwendet werden.
 	 */
 	public static String escape(String key) {
 		key = key.replaceAll(":", "\\:");



More information about the Schmitzm-commits mailing list