View Javadoc
1   package com.atlassian.activeobjects.admin.tables;
2   
3   import net.java.ao.DatabaseProvider;
4   import org.slf4j.Logger;
5   import org.slf4j.LoggerFactory;
6   
7   import java.sql.Connection;
8   import java.sql.PreparedStatement;
9   import java.sql.ResultSet;
10  import java.sql.SQLException;
11  
12  import static com.google.common.base.Preconditions.checkNotNull;
13  import static com.google.common.base.Preconditions.checkState;
14  import static net.java.ao.sql.SqlUtils.closeQuietly;
15  
16  public final class RowCounter {
17      private final Logger logger = LoggerFactory.getLogger(this.getClass());
18  
19      private final DatabaseProvider provider;
20  
21      private RowCounter(DatabaseProvider provider) {
22          this.provider = checkNotNull(provider);
23      }
24  
25      int count(String tableName) {
26          Connection connection = null;
27          PreparedStatement stmt = null;
28          ResultSet res = null;
29          try {
30              connection = provider.getConnection();
31              stmt = provider.preparedStatement(connection, "SELECT COUNT(*) FROM " + provider.withSchema(tableName));
32              res = stmt.executeQuery();
33  
34              checkState(res.next());
35              return res.getInt(1);
36          } catch (SQLException e) {
37              logger.warn("Could not count number of rows for table '{}'", tableName);
38              logger.warn("Here is the exception:", e);
39              return -1;
40          } finally {
41              closeQuietly(res);
42              closeQuietly(stmt);
43              closeQuietly(connection);
44          }
45      }
46  
47      static RowCounter from(DatabaseProvider provider) {
48          return new RowCounter(provider);
49      }
50  }