1 package com.atlassian.user.generic;
2
3 import org.springframework.dao.DataAccessException;
4 import org.springframework.jdbc.core.ConnectionCallback;
5 import org.springframework.jdbc.core.JdbcTemplate;
6 import org.springframework.jdbc.core.PreparedStatementCallback;
7
8 import java.sql.*;
9 import java.util.*;
10
11 public class JdbcHelper
12 {
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 @SuppressWarnings({"unchecked"})
30 public List<HashMap<Object, Object>> executeQuery(JdbcTemplate jdbcTemplate, String sql)
31 {
32 return (List<HashMap<Object, Object>>) jdbcTemplate.execute(sql, new PreparedStatementCallback()
33 {
34 public Object doInPreparedStatement(PreparedStatement preparedStatement) throws SQLException, DataAccessException
35 {
36 List<HashMap<Object, Object>> result = new ArrayList<HashMap<Object, Object>>();
37 ResultSet rs = preparedStatement.executeQuery();
38 ResultSetMetaData md = rs.getMetaData();
39 while (rs.next())
40 {
41 HashMap<Object, Object> row = new HashMap<Object, Object>();
42 for (int i = 1; i <= md.getColumnCount(); i++)
43 {
44 row.put(md.getColumnName(i), rs.getObject(i));
45 }
46 result.add(row);
47 }
48 return result;
49 }
50 });
51 }
52
53 public void deleteTable(JdbcTemplate jdbcTemplate, String table)
54 {
55 jdbcTemplate.execute("delete from " + table);
56 }
57
58 @SuppressWarnings({"unchecked"})
59 public List<String> getNonEmtpyTables(JdbcTemplate jdbcTemplate)
60 {
61 final List<String> tables = (List) jdbcTemplate.execute(new ConnectionCallback()
62 {
63 public Object doInConnection(Connection con) throws SQLException, DataAccessException
64 {
65 List<String> result = new ArrayList<String>();
66 DatabaseMetaData databaseMetaData = con.getMetaData();
67 ResultSet rs = databaseMetaData.getTables(null, null, null, new String[]{"TABLE"});
68 while (rs.next())
69 {
70 result.add(rs.getString("TABLE_NAME"));
71 }
72 return result;
73 }
74 });
75
76 List<String> result = new LinkedList<String>();
77 for (Object table : tables)
78 {
79 String tableName = (String) table;
80 int count = getTableCount(jdbcTemplate, tableName);
81 if (count > 0)
82 {
83 result.add(tableName);
84 }
85 }
86 return result;
87 }
88
89 public int getTableCount(JdbcTemplate jdbcTemplate, String tableName)
90 {
91 return (Integer) jdbcTemplate.execute("select count(*) from " + tableName, new PreparedStatementCallback()
92 {
93 public Object doInPreparedStatement(PreparedStatement preparedStatement) throws SQLException, DataAccessException
94 {
95 ResultSet rs = preparedStatement.executeQuery();
96 if (rs.next())
97 {
98 return rs.getInt(1);
99 }
100 else
101 {
102 throw new RuntimeException("unexpected empty result set");
103 }
104
105 }
106 });
107 }
108
109 }