[Schmitzm-commits] r2145 - trunk/schmitzm-db/src/main/java/de/schmitzm/postgres
scm-commit at wald.intevation.org
scm-commit at wald.intevation.org
Sat Nov 24 00:44:14 CET 2012
Author: alfonx
Date: 2012-11-24 00:44:14 +0100 (Sat, 24 Nov 2012)
New Revision: 2145
Modified:
trunk/schmitzm-db/src/main/java/de/schmitzm/postgres/PGUtil.java
Log:
neue Hilfsfunktion setPk um PKs zu definieren.
Modified: trunk/schmitzm-db/src/main/java/de/schmitzm/postgres/PGUtil.java
===================================================================
--- trunk/schmitzm-db/src/main/java/de/schmitzm/postgres/PGUtil.java 2012-11-17 18:34:30 UTC (rev 2144)
+++ trunk/schmitzm-db/src/main/java/de/schmitzm/postgres/PGUtil.java 2012-11-23 23:44:14 UTC (rev 2145)
@@ -8,6 +8,7 @@
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
+import org.apache.lucene.analysis.hi.HindiStemFilter;
import org.postgresql.util.PGInterval;
import de.schmitzm.lang.LangUtil;
@@ -25,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;
@@ -55,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);
}
@@ -73,12 +72,11 @@
* 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);
}
@@ -90,13 +88,11 @@
* @param inhRoles
* Rollen in denen die neue Rolle Mitglied ist
*/
- public static void createRole(Connection c, String rolename,
- String... inhRoles) throws SQLException {
+ public static void createRole(Connection c, String rolename, String... inhRoles) throws SQLException {
String sql = "CREATE ROLE " + rolename;
c.createStatement().executeUpdate(sql);
for (String inhRole : inhRoles)
- c.createStatement().executeUpdate(
- "GRANT " + inhRole + " TO " + rolename);
+ c.createStatement().executeUpdate("GRANT " + inhRole + " TO " + rolename);
}
/**
@@ -107,8 +103,7 @@
* @param inhRoles
* Rollen in denen die neue Rolle Mitglied ist
*/
- public static void createRoleIfNotExists(Connection c, String rolename,
- String... inhRoles) throws SQLException {
+ public static void createRoleIfNotExists(Connection c, String rolename, String... inhRoles) throws SQLException {
if (existsRole(c, rolename))
return;
createRole(c, rolename, inhRoles);
@@ -153,8 +148,8 @@
*
* @see #getPostGisMetadata(Connection, String)
*/
- public static PGPostGisMetadata getPostGisMetadata(Connection c,
- String tablename, String geoCol) throws SQLException {
+ public static PGPostGisMetadata getPostGisMetadata(Connection c, String tablename, String geoCol)
+ throws SQLException {
String schema = "public";
if (tablename.contains(".")) {
@@ -173,9 +168,8 @@
try {
rs = s.executeQuery();
if (rs.next()) {
- PGPostGisMetadata metadata = new PGPostGisMetadata(schema,
- tablename, geoCol, rs.getInt(1), rs.getInt(2),
- rs.getString(3));
+ PGPostGisMetadata metadata = new PGPostGisMetadata(schema, tablename, geoCol, rs.getInt(1),
+ rs.getInt(2), rs.getString(3));
return metadata;
} else
return null;
@@ -193,8 +187,7 @@
*
* @see #getPostGisMetadata(Connection, String, String)
*/
- public static PGPostGisMetadata getPostGisMetadata(Connection c,
- String tablename) throws SQLException {
+ public static PGPostGisMetadata getPostGisMetadata(Connection c, String tablename) throws SQLException {
String schema = "public";
if (tablename.contains(".")) {
@@ -211,9 +204,8 @@
try {
rs = s.executeQuery();
if (rs.next()) {
- PGPostGisMetadata metadata = new PGPostGisMetadata(schema,
- tablename, rs.getString(4), rs.getInt(1), rs.getInt(2),
- rs.getString(3));
+ PGPostGisMetadata metadata = new PGPostGisMetadata(schema, tablename, rs.getString(4), rs.getInt(1),
+ rs.getInt(2), rs.getString(3));
return metadata;
} else
return null;
@@ -236,8 +228,8 @@
* @Deprecated tut es noch nicht
*
*/
- public static void createOrUpdateGeometrysColumnsEntry(Connection c,
- String tableName, String geoColumnName, int srid, String type) {
+ public static void createOrUpdateGeometrysColumnsEntry(Connection c, String tableName, String geoColumnName,
+ int srid, String type) {
String schema = "public";
if (tableName.contains(".")) {
@@ -252,7 +244,11 @@
+ tableName
+ "', '"
+ geoColumnName
- + "', 2, " + srid + ",'" + type.toUpperCase() + "' );";
+ + "', 2, "
+ + srid
+ + ",'"
+ + type.toUpperCase()
+ + "' );";
}
@@ -274,8 +270,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.");
}
/**
@@ -283,11 +278,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;
@@ -296,10 +289,8 @@
/**
* 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 {
- String sql = "select 1 from pg_catalog.pg_namespace where nspname = '"
- + schemaname.toLowerCase() + "'";
+ 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();
@@ -313,8 +304,7 @@
* Liefert eine Liste der Rollen in denen der Übergebenen USER (Login role) 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>();
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() + "'";
@@ -336,8 +326,7 @@
*/
public static List<String> listUsers(Connection c) throws SQLException {
List<String> roles = new ArrayList<String>();
- ResultSet rs = c.createStatement()
- .executeQuery("select * from pg_user");
+ ResultSet rs = c.createStatement().executeQuery("select * from pg_user");
try {
while (rs.next()) {
roles.add(rs.getString(1));
@@ -356,12 +345,10 @@
* @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);
try {
while (rs.next()) {
@@ -383,8 +370,7 @@
* darf auch schema-informationen enthalten.
* @throws SQLException
*/
- public List<String> listColumnNamesInTable(Connection c, String tableName)
- throws SQLException {
+ public List<String> listColumnNamesInTable(Connection c, String tableName) throws SQLException {
List<String> cols = new ArrayList<String>();
for (PGColumn pgcol : listColumnsInTable(c, tableName)) {
@@ -394,8 +380,7 @@
return cols;
}
- public static PGColumn getFirstGeometryColumn(Connection c, String tablename)
- throws SQLException {
+ public static PGColumn getFirstGeometryColumn(Connection c, String tablename) throws SQLException {
for (PGColumn col : PGUtil.listColumnsInTable(c, tablename)) {
if (col.isGeometry())
@@ -414,8 +399,7 @@
* darf auch schema-informationen enthalten.
* @throws SQLException
*/
- public static List<PGColumn> listColumnsInTable(Connection c,
- String tableName) throws SQLException {
+ public static List<PGColumn> listColumnsInTable(Connection c, String tableName) throws SQLException {
List<PGColumn> cols = new ArrayList<PGColumn>();
String schema = "public";
@@ -428,10 +412,9 @@
String sql = "SELECT a.attnum, a.attname AS field, t.typname AS type,"
+ " a.attlen AS length, a.atttypmod AS length_var,"
+ " a.attnotnull AS not_null, a.atthasdef as has_default"
- + " FROM pg_class c, pg_attribute a, pg_type t"
- + " WHERE c.relname = '" + tableName + "'"
- + " AND a.attnum > 0" + " AND a.attrelid = c.oid"
- + " AND a.atttypid = t.oid" + " ORDER BY a.attnum;";
+ + " FROM pg_class c, pg_attribute a, pg_type t" + " WHERE c.relname = '" + tableName + "'"
+ + " AND a.attnum > 0" + " AND a.attrelid = c.oid" + " AND a.atttypid = t.oid"
+ + " ORDER BY a.attnum;";
ResultSet rs = c.createStatement().executeQuery(sql);
try {
while (rs.next()) {
@@ -441,8 +424,7 @@
Boolean notNull = rs.getBoolean(6);
Boolean hasDefault = rs.getBoolean(7);
- PGColumn pgcol = new PGColumn(fieldname, typename, notNull,
- hasDefault);
+ PGColumn pgcol = new PGColumn(fieldname, typename, notNull, hasDefault);
cols.add(pgcol);
@@ -456,11 +438,9 @@
/**
* 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");
+ "select usesuper from pg_user where usename = '" + username + "' and usesuper = true");
try {
if (rs.next()) {
return true;
@@ -471,10 +451,8 @@
return false;
}
- public static boolean existsRole(Connection c, String rolename)
- throws SQLException {
- String sql = "select count(1) from pg_roles where rolname = '"
- + rolename.toLowerCase() + "'";
+ 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())
@@ -485,20 +463,16 @@
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());
}
/**
@@ -508,11 +482,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);
}
/**
@@ -526,8 +497,7 @@
* OHNE <code>RETURN NEW</code>, das wird automatisch angehangen.
* @throws SQLException
*/
- public static void createOrReplaceTriggerFunction(Connection c,
- String name, String plCommands) throws SQLException {
+ public static void createOrReplaceTriggerFunction(Connection c, String name, String plCommands) throws SQLException {
// System.err.println(plCommands);
// String sql = "CREATE OR REPLACE FUNCTION " + name + "()" +
@@ -544,8 +514,7 @@
// "$ LANGUAGE 'plpgsql'";
// c.createStatement().executeUpdate(sql);
- createOrReplaceFunction(c, name, null, "TRIGGER", null, plCommands
- + "\nRETURN NEW");
+ createOrReplaceFunction(c, name, null, "TRIGGER", null, plCommands + "\nRETURN NEW");
}
/**
@@ -562,9 +531,8 @@
* @param plCommands
* z.B. NEW.kpk_kreis = NEW.risiko_soz+NEW.risiko_emo+NEW.risiko_moti +NEW.risiko_spr+NEW.risiko_wohl;
*/
- public static void createOrReplaceFunction(Connection c, String name,
- String parameters, String returns, String declare, String plCommands)
- throws SQLException {
+ public static void createOrReplaceFunction(Connection c, String name, String parameters, String returns,
+ String declare, String plCommands) throws SQLException {
// System.err.println(plCommands);
// String sql = "CREATE OR REPLACE FUNCTION " + name + "()" +
@@ -578,10 +546,8 @@
parameters = LangUtil.removeWhitespacesToEmpty(parameters);
declare = LangUtil.removeWhitespacesToEmpty(declare);
- String sql = "CREATE OR REPLACE FUNCTION " + name + "(" + parameters
- + ")" + " RETURNS " + returns + " AS $$\n" + "DECLARE\n"
- + declare + "\n" + "BEGIN\n " + plCommands + ";"
- + "\nEND;\n$$ LANGUAGE 'plpgsql'";
+ String sql = "CREATE OR REPLACE FUNCTION " + name + "(" + parameters + ")" + " RETURNS " + returns + " AS $$\n"
+ + "DECLARE\n" + declare + "\n" + "BEGIN\n " + plCommands + ";" + "\nEND;\n$$ LANGUAGE 'plpgsql'";
c.createStatement().executeUpdate(sql);
}
@@ -602,14 +568,12 @@
END IF;
</code>
*/
- 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);
createOrReplaceTriggerFunction(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" + "()");
}
@@ -623,24 +587,46 @@
* @param unique
* <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 {
- addIndex(c, tableName, columns, idxPostfix, unique, null, null, false,
- null);
+ public static void addIndex(Connection c, final String tableName, final String columns, String idxPostfix,
+ final boolean unique, final boolean pk) throws SQLException {
+ addIndex(c, tableName, columns, idxPostfix, unique, null, null, false, null);
}
+ public static void setPk(Connection c, final String tableName, final String columns) throws SQLException {
+
+ Statement s = c.createStatement();
+
+ // Hier die Schreibweise mit . für schematrennung verwenden
+ String queryString = "ALTER TABLE " + tableName + " ADD PRIMARY KEY (" + columns + ")";
+ try {
+ s.execute(queryString);
+ c.commit();
+ log.debug("PK created: " + queryString);
+ } catch (SQLException e) {
+ log.debug("PK creation failed: " + queryString);
+ c.rollback();
+ // Throwable cause = e;
+ // if (e.getCause() != null)
+ // cause = e.getCause();
+
+ // keine Ausgabe bei: already EXISTs, EXISTiert
+ // bereits,
+ // Ex abfangen, wenn IDX schon existiert
+
+ // String msg = cause.getMessage();
+ log.error(e.getLocalizedMessage(), e);
+ return;
+ }
+
+ }
+
/**
* @see #addIndex(Connection, String, String, String, boolean, String, String, boolean, Double)
*
* Der Name des Index wird aus der/den Columns und einem Postfix "_idx" automatisch erstellt.
*/
- public static void addIndex(Connection c, final String tableName,
- final String columns,
- final boolean unique,
- String tablespace,
- String type,
- boolean forceRecreationIfExistsAlready, Double fillFactor)
+ public static void addIndex(Connection c, final String tableName, final String columns, final boolean unique,
+ String tablespace, String type, boolean forceRecreationIfExistsAlready, Double fillFactor)
throws SQLException {
addIndex(c, tableName, columns, columns.replaceAll("[\\s.]", "_") + "_idx", unique, tablespace, type,
forceRecreationIfExistsAlready, fillFactor);
@@ -652,20 +638,17 @@
* 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>();
// , array_to_string(array_agg(a.attname), ', ') as column_names
String sql = "select t.relname as table_name, i.relname as index_name 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);
try {
@@ -699,11 +682,9 @@
* Wert von >0. -> 1. Bei .5 wird für den Index doppelt so viel Platz reserviert wie aktuell benötig, um
* auf weiteres Wachstum der Tabelle ohne Indexfragmentierung reagieren zu können.
*/
- public static void addIndex(Connection c, final String tableName,
- final String columns, String idxPostfix, final boolean unique,
- String tablespace, String type,
- boolean forceRecreationIfExistsAlready, Double fillFactor)
- throws SQLException {
+ public static void addIndex(Connection c, final String tableName, final String columns, String idxPostfix,
+ final boolean unique, String tablespace, String type, boolean forceRecreationIfExistsAlready,
+ Double fillFactor) throws SQLException {
String idxNameWithDot = tableName + "_" + idxPostfix;
final String idxName = idxNameWithDot.replace(".", "_");
@@ -717,8 +698,8 @@
if (!forceRecreationIfExistsAlready)
return;
- log.info("Aufgrund von forceRecreationIfExistsAlready=true wird der Index "
- + idxNameWithDot + " jetzt gedroppt.");
+ log.info("Aufgrund von forceRecreationIfExistsAlready=true wird der Index " + idxNameWithDot
+ + " jetzt gedroppt.");
Statement s = c.createStatement();
@@ -752,23 +733,19 @@
Statement s = c.createStatement();
if (fillFactor != null && (fillFactor <= 0. || fillFactor > 1.))
- throw new IllegalArgumentException(
- "fillFactor muss großer 0 und kleinergleich 1 sein.");
+ throw new IllegalArgumentException("fillFactor muss großer 0 und kleinergleich 1 sein.");
String sqlFillFactor = "";
if (fillFactor != null)
- sqlFillFactor = " WITH (FILLFACTOR=" + (int) (fillFactor * 100)
- + ") ";
+ sqlFillFactor = " WITH (FILLFACTOR=" + (int) (fillFactor * 100) + ") ";
- String sqlTableSpace = (tablespace == null
- || tablespace.equalsIgnoreCase("null") || !existsTablespace(c,
+ String sqlTableSpace = (tablespace == null || tablespace.equalsIgnoreCase("null") || !existsTablespace(c,
tableName)) ? "" : " TABLESPACE " + tablespace;
String sqlUsing = type == null ? "" : " USING " + type;
- final String queryString = "CREATE " + (unique ? "UNIQUE " : "")
- + "INDEX " + idxName + " ON " + tableName + sqlUsing + " ("
- + columns + ") " + sqlFillFactor + sqlTableSpace;
+ final String queryString = "CREATE " + (unique ? "UNIQUE " : "") + "INDEX " + idxName + " ON " + tableName
+ + sqlUsing + " (" + columns + ") " + sqlFillFactor + sqlTableSpace;
try {
s.execute(queryString);
c.commit();
@@ -785,11 +762,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);
@@ -802,12 +777,10 @@
*
* @throws SQLException
*/
- private static boolean existsTablespace(Connection c, String spaceName)
- throws SQLException {
+ private static boolean existsTablespace(Connection c, String spaceName) throws SQLException {
// SELECT count(1) FROM pg_tablespace where spcname = 'spcname';
- String stmtSql = "SELECT COUNT(*) FROM pg_tablespace where spcname = '"
- + spaceName + "'";
+ String stmtSql = "SELECT COUNT(*) FROM pg_tablespace where spcname = '" + spaceName + "'";
PreparedStatement stmt = c.prepareStatement(stmtSql);
stmt.execute();
@@ -832,10 +805,8 @@
*
* @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);
}
/**
@@ -857,8 +828,7 @@
* @param userName
* Name des Users fuer den die Sessions gezaehlt werden (kann {@code null} sein)
*/
- public static int getOpenSessionCount(Connection c, String dbName,
- String userName) throws SQLException {
+ public static int getOpenSessionCount(Connection c, String dbName, String userName) throws SQLException {
return getOpenSessionCount(c, dbName, userName, null);
}
@@ -874,8 +844,8 @@
* @param queryLike
* like-Beindung auf die Query die in der Session ausgeführt wird, oder <code>null</code>
*/
- public static int getOpenSessionCount(Connection c, String dbName,
- String userName, String queryLike) throws SQLException {
+ public static int getOpenSessionCount(Connection c, String dbName, String userName, String queryLike)
+ throws SQLException {
String stmtSql = "SELECT COUNT(*) FROM pg_stat_activity WHERE TRUE";
if (dbName != null)
@@ -910,8 +880,7 @@
* Liefert <code>true</code> wenn eine Spalte mit dem Namen in der angegebenen Tabelle existiert. Die Tablle darf
* optional mit "schema." prefixiert werden.
*/
- public static boolean existsColumn(Connection c, String tableName,
- String columnName) throws SQLException {
+ public static boolean existsColumn(Connection c, String tableName, String columnName) throws SQLException {
String schema = "public";
@@ -921,12 +890,9 @@
tableName = split[1];
}
- ResultSet nativeCheckExistsColumnQuery = c.createStatement()
- .executeQuery(
- "SELECT * FROM information_schema.COLUMNS WHERE COLUMN_NAME = '"
- + columnName.toLowerCase()
- + "' AND TABLE_NAME='" + tableName
- + "' AND TABLE_SCHEMA='" + schema + "';");
+ ResultSet nativeCheckExistsColumnQuery = c.createStatement().executeQuery(
+ "SELECT * FROM information_schema.COLUMNS WHERE COLUMN_NAME = '" + columnName.toLowerCase()
+ + "' AND TABLE_NAME='" + tableName + "' AND TABLE_SCHEMA='" + schema + "';");
return nativeCheckExistsColumnQuery.next();
}
@@ -937,8 +903,7 @@
* Darf eine Schemaangabe mit . Trenner enthalten.
* @throws SQLException
*/
- public static boolean existsView(Connection c, String viewName)
- throws SQLException {
+ public static boolean existsView(Connection c, String viewName) throws SQLException {
String schema = "public";
@@ -948,8 +913,8 @@
viewName = split[1];
}
- final String checkView = "SELECT * FROM information_schema.VIEWS where table_schema = '"
- + schema + "' and table_name = '" + viewName + "' LIMIT 1";
+ final String checkView = "SELECT * FROM information_schema.VIEWS where table_schema = '" + schema
+ + "' and table_name = '" + viewName + "' LIMIT 1";
ResultSet rs = c.createStatement().executeQuery(checkView);
try {
@@ -966,8 +931,7 @@
* Darf eine Schemaangabe mit . Trenner enthalten.
* @throws SQLException
*/
- public static boolean existsTable(Connection c, String tableName)
- throws SQLException {
+ public static boolean existsTable(Connection c, String tableName) throws SQLException {
String schema = "public";
@@ -977,8 +941,8 @@
tableName = split[1];
}
- final String checkTableExists = "SELECT * FROM pg_tables where schemaname = '"
- + schema + "' and tablename = '" + tableName + "' LIMIT 1";
+ final String checkTableExists = "SELECT * FROM pg_tables where schemaname = '" + schema + "' and tablename = '"
+ + tableName + "' LIMIT 1";
ResultSet rs = c.createStatement().executeQuery(checkTableExists);
try {
@@ -988,8 +952,7 @@
}
}
- public static void dropViewIfExists(Connection c, String viewName)
- throws SQLException {
+ public static void dropViewIfExists(Connection c, String viewName) throws SQLException {
final String dropView = "DROP VIEW IF EXISTS " + viewName;
c.createStatement().executeUpdate(dropView);
}
@@ -1001,8 +964,7 @@
* @param blockedPid
* @return blockingPid oder <code>null</code>
*/
- static public Long getBlockingPid(Connection c, Long blockedPid)
- throws SQLException {
+ static public Long getBlockingPid(Connection c, Long blockedPid) throws SQLException {
final String sql = "SELECT kl.pid as blocking_pid FROM pg_catalog.pg_locks bl "
+ "JOIN pg_catalog.pg_stat_activity a on bl.pid = a.procpid "
+ "JOIN pg_catalog.pg_locks kl "
@@ -1032,8 +994,8 @@
* @param filter
* 0 = kein Filter, 1=Ohne IDLE, 2=Ohne IDLE und ohne 'IDLE in Transaction'
*/
- static public List<SqlQueryStat> listQueries(Connection c, String datName,
- Integer minSecondsRunning, int filter) throws SQLException {
+ static public List<SqlQueryStat> listQueries(Connection c, String datName, Integer minSecondsRunning, int filter)
+ throws SQLException {
ArrayList<SqlQueryStat> result = new ArrayList<SqlQueryStat>();
String where = "WHERE TRUE ";
@@ -1050,8 +1012,7 @@
if (minSecondsRunning < 0)
throw new IllegalStateException();
- where += " AND age (now(),query_start) >= interval '"
- + minSecondsRunning + "s' ";
+ where += " AND age (now(),query_start) >= interval '" + minSecondsRunning + "s' ";
}
final String sql = "SELECT current_query, age (now(),query_start) as qage, waiting, procpid, client_addr, usename, application_name from pg_stat_activity "
@@ -1068,8 +1029,8 @@
String username = rs.getString(6);
String application_name = rs.getString(7);
- result.add(new SqlQueryStat(q, new PGInterval(age), waiting,
- procId, client_addr, username, application_name));
+ result.add(new SqlQueryStat(q, new PGInterval(age), waiting, procId, client_addr, username,
+ application_name));
}
} finally {
@@ -1081,12 +1042,10 @@
/**
* Tablename der optinal als das Schema enthalten darf.
*/
- public static boolean removeColumn(Connection c, String tableName,
- String columnName) throws SQLException {
+ public static boolean removeColumn(Connection c, String tableName, String columnName) throws SQLException {
// Das eigentliche erstellen der neuen Spalte
- String queryString = "ALTER TABLE " + tableName + " DROP COLUMN "
- + columnName;
+ String queryString = "ALTER TABLE " + tableName + " DROP COLUMN " + columnName;
// System.out.println(queryString);
@@ -1110,8 +1069,7 @@
*
* @return Primary Key. <code>NULL</code> if empty
*/
- public static String getPrimaryKey(Connection dbc, String tableName)
- throws SQLException {
+ public static String getPrimaryKey(Connection dbc, String tableName) throws SQLException {
String schema = "public";
if (tableName.contains(".")) {
@@ -1146,10 +1104,8 @@
/**
* Returns cardinality of column in table
*/
- public long getCardinality(Connection dbc, String tableName, String column)
- throws SQLException {
- String sql = "select count( DISTINCT " + "(" + column + ")" + ") "
- + "from " + tableName;
+ public long getCardinality(Connection dbc, String tableName, String column) throws SQLException {
+ String sql = "select count( DISTINCT " + "(" + column + ")" + ") " + "from " + tableName;
ResultSet countRs = dbc.createStatement().executeQuery(sql);
try {
countRs.next();
@@ -1159,8 +1115,7 @@
}
}
- public static boolean isIntColumn(Connection c, String tableName,
- String columnName) throws SQLException {
+ public static boolean isIntColumn(Connection c, String tableName, String columnName) throws SQLException {
String schema = "public";
if (tableName.contains(".")) {
final String[] split = tableName.split("\\.");
@@ -1169,11 +1124,8 @@
}
Statement s = c.createStatement();
- ResultSet rs = s
- .executeQuery("SELECT data_type FROM information_schema.COLUMNS WHERE COLUMN_NAME = '"
- + columnName.toLowerCase()
- + "' AND TABLE_NAME='"
- + tableName + "' AND TABLE_SCHEMA='" + schema + "';");
+ ResultSet rs = s.executeQuery("SELECT data_type FROM information_schema.COLUMNS WHERE COLUMN_NAME = '"
+ + columnName.toLowerCase() + "' AND TABLE_NAME='" + tableName + "' AND TABLE_SCHEMA='" + schema + "';");
try {
rs.next();
@@ -1190,8 +1142,7 @@
/**
* Typischer Weise POSTGIS, wenn man sonst nichts anderen installiert hat.
*/
- public static boolean isUserDefinedColumn(Connection c, String tableName,
- String columnName) throws SQLException {
+ public static boolean isUserDefinedColumn(Connection c, String tableName, String columnName) throws SQLException {
String schema = "public";
if (tableName.contains(".")) {
@@ -1201,18 +1152,14 @@
}
Statement s = c.createStatement();
- ResultSet rs = s
- .executeQuery("SELECT data_type FROM information_schema.COLUMNS WHERE COLUMN_NAME = '"
- + columnName.toLowerCase()
- + "' AND TABLE_NAME='"
- + tableName + "' AND TABLE_SCHEMA='" + schema + "';");
+ ResultSet rs = s.executeQuery("SELECT data_type FROM information_schema.COLUMNS WHERE COLUMN_NAME = '"
+ + columnName.toLowerCase() + "' AND TABLE_NAME='" + tableName + "' AND TABLE_SCHEMA='" + schema + "';");
rs.next();
String typeDef = rs.getString(1);
return typeDef.toUpperCase().startsWith("USER-DEFINED");
}
- public static boolean isTextColumn(Connection c, String tableName,
- String columnName) throws SQLException {
+ public static boolean isTextColumn(Connection c, String tableName, String columnName) throws SQLException {
String schema = "public";
if (tableName.contains(".")) {
@@ -1222,11 +1169,8 @@
}
Statement s = c.createStatement();
- ResultSet rs = s
- .executeQuery("SELECT data_type FROM information_schema.COLUMNS WHERE COLUMN_NAME = '"
- + columnName.toLowerCase()
- + "' AND TABLE_NAME='"
- + tableName + "' AND TABLE_SCHEMA='" + schema + "';");
+ ResultSet rs = s.executeQuery("SELECT data_type FROM information_schema.COLUMNS WHERE COLUMN_NAME = '"
+ + columnName.toLowerCase() + "' AND TABLE_NAME='" + tableName + "' AND TABLE_SCHEMA='" + schema + "';");
try {
rs.next();
String typeDef = rs.getString(1);
@@ -1251,13 +1195,11 @@
* @return
* @throws SQLException
*/
- public static boolean addColumn(Connection dbc, String tableName,
- String columnName, String colTypeName, String comment)
- throws SQLException {
+ public static boolean addColumn(Connection dbc, String tableName, String columnName, String colTypeName,
+ String comment) throws SQLException {
if (dbc == null)
- throw new IllegalStateException(
- "Es besteht keine Datenbankverbindung!");
+ throw new IllegalStateException("Es besteht keine Datenbankverbindung!");
Statement s = dbc.createStatement();
@@ -1266,8 +1208,7 @@
}
// Das eigentliche erstellen der neuen Spalte
- String queryString = "ALTER TABLE " + tableName + " ADD " + columnName
- + " " + colTypeName;
+ String queryString = "ALTER TABLE " + tableName + " ADD " + columnName + " " + colTypeName;
// JRegDBUtils.log.debug(queryString);
@@ -1278,8 +1219,7 @@
}
if (comment != null && !comment.isEmpty()) {
- queryString = "COMMENT ON COLUMN " + tableName + "." + columnName
- + " IS '" + comment + "';";
+ queryString = "COMMENT ON COLUMN " + tableName + "." + columnName + " IS '" + comment + "';";
}
s.close();
@@ -1290,8 +1230,7 @@
/**
* Liefert alle Spalten einer Tabelle
*/
- public static ArrayList<String> getAllColumnsOf(Connection dbc,
- String tableName) throws SQLException {
+ public static ArrayList<String> getAllColumnsOf(Connection dbc, String tableName) throws SQLException {
String schema = "public";
if (tableName.contains(".")) {
final String[] split = tableName.split("\\.");
@@ -1303,8 +1242,8 @@
// String tableName = PropertyUtils.getDbTableName(i);
- String sql = "SELECT column_name FROM information_schema.COLUMNS WHERE TABLE_NAME = '"
- + tableName + "' and TABLE_SCHEMA = '" + schema + "';";
+ String sql = "SELECT column_name FROM information_schema.COLUMNS WHERE TABLE_NAME = '" + tableName
+ + "' and TABLE_SCHEMA = '" + schema + "';";
ResultSet colsRs = dbc.createStatement().executeQuery(sql);
try {
@@ -1321,8 +1260,7 @@
*
* @throws SQLException
*/
- public static boolean pg_terminate_backend(Connection dbc, Long procId)
- throws SQLException {
+ public static boolean pg_terminate_backend(Connection dbc, Long procId) throws SQLException {
String sql = "SELECT pg_terminate_backend(" + procId + ");";
ResultSet rs = dbc.createStatement().executeQuery(sql);
try {
More information about the Schmitzm-commits
mailing list