Use AutoCloseable gwtorm/jdbc instances

Bump the gwtorm version, since gwtorm changed Schema and
StatementExecutor to be AutoCloseable. This allows us to simplify many
callers.

While we're in there, fix some usages of more javax.sql classes like
Statement that became AutoCloseable in Java 7.

Change-Id: Icf86fdb52a499563ccf2a7c761cc498ad758d99c
This commit is contained in:
Dave Borowitz
2015-01-09 09:55:06 -08:00
parent 79d1083450
commit 9625637eb4
30 changed files with 332 additions and 526 deletions

View File

@@ -363,21 +363,15 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
SqlHandle c = null;
try {
c = acquire();
Statement s = c.conn.createStatement();
try {
ResultSet r;
try (Statement s = c.conn.createStatement()) {
if (estimatedSize <= 0) {
r = s.executeQuery("SELECT COUNT(*) FROM data");
try {
try (ResultSet r = s.executeQuery("SELECT COUNT(*) FROM data")) {
estimatedSize = r.next() ? r.getInt(1) : 0;
} finally {
r.close();
}
}
BloomFilter<K> b = newBloomFilter();
r = s.executeQuery("SELECT k FROM data");
try {
try (ResultSet r = s.executeQuery("SELECT k FROM data")) {
while (r.next()) {
b.put(keyType.get(r, 1));
}
@@ -390,12 +384,8 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
} else {
throw e;
}
} finally {
r.close();
}
return b;
} finally {
s.close();
}
} catch (SQLException e) {
log.warn("Cannot build BloomFilter for " + url, e);
@@ -414,8 +404,7 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
c.get = c.conn.prepareStatement("SELECT v, created FROM data WHERE k=?");
}
keyType.set(c.get, 1, key);
ResultSet r = c.get.executeQuery();
try {
try (ResultSet r = c.get.executeQuery()) {
if (!r.next()) {
missCount.incrementAndGet();
return null;
@@ -436,7 +425,6 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
touch(c, key);
return h;
} finally {
r.close();
c.get.clearParameters();
}
} catch (SQLException e) {
@@ -533,11 +521,8 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
SqlHandle c = null;
try {
c = acquire();
Statement s = c.conn.createStatement();
try {
try (Statement s = c.conn.createStatement()) {
s.executeUpdate("DELETE FROM data");
} finally {
s.close();
}
bloomFilter = newBloomFilter();
} catch (SQLException e) {
@@ -552,28 +537,23 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
SqlHandle c = null;
try {
c = acquire();
Statement s = c.conn.createStatement();
try {
try (Statement s = c.conn.createStatement()) {
long used = 0;
ResultSet r = s.executeQuery("SELECT"
try (ResultSet r = s.executeQuery("SELECT"
+ " SUM(OCTET_LENGTH(k) + OCTET_LENGTH(v))"
+ " FROM data");
try {
+ " FROM data")) {
used = r.next() ? r.getLong(1) : 0;
} finally {
r.close();
}
if (used <= maxSize) {
return;
}
r = s.executeQuery("SELECT"
try (ResultSet r = s.executeQuery("SELECT"
+ " k"
+ ",OCTET_LENGTH(k) + OCTET_LENGTH(v)"
+ ",created"
+ " FROM data"
+ " ORDER BY accessed");
try {
+ " ORDER BY accessed")) {
while (maxSize < used && r.next()) {
K key = keyType.get(r, 1);
Timestamp created = r.getTimestamp(3);
@@ -584,11 +564,7 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
used -= r.getLong(2);
}
}
} finally {
r.close();
}
} finally {
s.close();
}
} catch (SQLException e) {
log.warn("Cannot prune cache " + url, e);
@@ -604,22 +580,15 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
SqlHandle c = null;
try {
c = acquire();
Statement s = c.conn.createStatement();
try {
ResultSet r = s.executeQuery("SELECT"
+ " COUNT(*)"
+ ",SUM(OCTET_LENGTH(k) + OCTET_LENGTH(v))"
+ " FROM data");
try {
if (r.next()) {
size = r.getLong(1);
space = r.getLong(2);
}
} finally {
r.close();
try (Statement s = c.conn.createStatement();
ResultSet r = s.executeQuery("SELECT"
+ " COUNT(*)"
+ ",SUM(OCTET_LENGTH(k) + OCTET_LENGTH(v))"
+ " FROM data")) {
if (r.next()) {
size = r.getLong(1);
space = r.getLong(2);
}
} finally {
s.close();
}
} catch (SQLException e) {
log.warn("Cannot get DiskStats for " + url, e);
@@ -665,16 +634,13 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
SqlHandle(String url, KeyType<?> type) throws SQLException {
this.url = url;
this.conn = org.h2.Driver.load().connect(url, null);
Statement stmt = conn.createStatement();
try {
try (Statement stmt = conn.createStatement()) {
stmt.execute("CREATE TABLE IF NOT EXISTS data"
+ "(k " + type.columnType() + " NOT NULL PRIMARY KEY HASH"
+ ",v OTHER NOT NULL"
+ ",created TIMESTAMP NOT NULL"
+ ",accessed TIMESTAMP NOT NULL"
+ ")");
} finally {
stmt.close();
}
}

View File

@@ -305,18 +305,11 @@ public class BaseInit extends SiteProgram {
System.err.flush();
} else if (ui.yesno(true, "%s\nExecute now", msg)) {
final JdbcSchema db = (JdbcSchema) schema.open();
try {
final JdbcExecutor e = new JdbcExecutor(db);
try {
for (String sql : pruneList) {
e.execute(sql);
}
} finally {
e.close();
try (JdbcSchema db = (JdbcSchema) schema.open();
JdbcExecutor e = new JdbcExecutor(db)) {
for (String sql : pruneList) {
e.execute(sql);
}
} finally {
db.close();
}
}
}

View File

@@ -182,13 +182,8 @@ public abstract class SiteProgram extends AbstractProgram {
private String getDbType(Provider<DataSource> dsProvider) {
String dbProductName;
try {
Connection conn = dsProvider.get().getConnection();
try {
dbProductName = conn.getMetaData().getDatabaseProductName().toLowerCase();
} finally {
conn.close();
}
try (Connection conn = dsProvider.get().getConnection()) {
dbProductName = conn.getMetaData().getDatabaseProductName().toLowerCase();
} catch (SQLException e) {
throw new RuntimeException(e);
}

View File

@@ -73,11 +73,8 @@ public class SchemaCreator {
public void create(final ReviewDb db) throws OrmException, IOException,
ConfigInvalidException {
final JdbcSchema jdbc = (JdbcSchema) db;
final JdbcExecutor e = new JdbcExecutor(jdbc);
try {
try (JdbcExecutor e = new JdbcExecutor(jdbc)) {
jdbc.updateSchema(e);
} finally {
e.close();
}
final CurrentSchemaVersion sVer = CurrentSchemaVersion.create();

View File

@@ -23,6 +23,7 @@ import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.StatementExecutor;
import com.google.inject.Provider;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
@@ -78,21 +79,23 @@ public abstract class SchemaVersion {
migrateData(pending, ui, curr, db);
JdbcSchema s = (JdbcSchema) db;
JdbcExecutor e = new JdbcExecutor(s);
try {
final List<String> pruneList = Lists.newArrayList();
s.pruneSchema(new StatementExecutor() {
@Override
public void execute(String sql) {
pruneList.add(sql);
}
});
final List<String> pruneList = Lists.newArrayList();
s.pruneSchema(new StatementExecutor() {
@Override
public void execute(String sql) {
pruneList.add(sql);
}
@Override
public void close() {
// Do nothing.
}
});
try (JdbcExecutor e = new JdbcExecutor(s)) {
if (!pruneList.isEmpty()) {
ui.pruneSchema(e, pruneList);
}
} finally {
e.close();
}
}
@@ -113,11 +116,8 @@ public abstract class SchemaVersion {
}
JdbcSchema s = (JdbcSchema) db;
JdbcExecutor e = new JdbcExecutor(s);
try {
try (JdbcExecutor e = new JdbcExecutor(s)) {
s.updateSchema(e);
} finally {
e.close();
}
}
@@ -162,36 +162,43 @@ public abstract class SchemaVersion {
}
/** Rename an existing table. */
protected void renameTable(ReviewDb db, String from, String to)
protected static void renameTable(ReviewDb db, String from, String to)
throws OrmException {
final JdbcSchema s = (JdbcSchema) db;
final JdbcExecutor e = new JdbcExecutor(s);
try {
JdbcSchema s = (JdbcSchema) db;
try (JdbcExecutor e = new JdbcExecutor(s)) {
s.renameTable(e, from, to);
} finally {
e.close();
}
}
/** Rename an existing column. */
protected void renameColumn(ReviewDb db, String table, String from, String to)
protected static void renameColumn(ReviewDb db, String table, String from, String to)
throws OrmException {
final JdbcSchema s = (JdbcSchema) db;
final JdbcExecutor e = new JdbcExecutor(s);
try {
JdbcSchema s = (JdbcSchema) db;
try (JdbcExecutor e = new JdbcExecutor(s)) {
s.renameField(e, table, from, to);
} finally {
e.close();
}
}
/** Execute an SQL statement. */
protected void execute(ReviewDb db, String sql) throws SQLException {
Statement s = ((JdbcSchema) db).getConnection().createStatement();
try {
protected static void execute(ReviewDb db, String sql) throws SQLException {
try (Statement s = newStatement(db)) {
s.execute(sql);
} finally {
s.close();
}
}
/** Open a new single statement. */
protected static Statement newStatement(ReviewDb db) throws SQLException {
return ((JdbcSchema) db).getConnection().createStatement();
}
/** Open a new prepared statement. */
protected static PreparedStatement prepareStatement(ReviewDb db, String sql)
throws SQLException {
return ((JdbcSchema) db).getConnection().prepareStatement(sql);
}
/** Open a new statement executor. */
protected static JdbcExecutor newExecutor(ReviewDb db) throws OrmException {
return new JdbcExecutor(((JdbcSchema) db).getConnection());
}
}

View File

@@ -68,16 +68,13 @@ public class Schema_101 extends SchemaVersion {
ui.message("The following tables are affected:");
ui.message(Joiner.on(", ").join(corrections.keySet()));
ui.message("fixing primary keys...");
JdbcExecutor executor = new JdbcExecutor(conn);
try {
try (JdbcExecutor executor = new JdbcExecutor(conn)) {
for (Map.Entry<String, PrimaryKey> c : corrections.entrySet()) {
ui.message(String.format(" table: %s ... ", c.getKey()));
recreatePK(executor, c.getKey(), c.getValue(), ui);
ui.message("done");
}
ui.message("done");
} finally {
executor.close();
}
}
@@ -115,8 +112,7 @@ public class Schema_101 extends SchemaVersion {
tableName = tableName.toLowerCase();
}
ResultSet cols = meta.getPrimaryKeys(null, null, tableName);
try {
try (ResultSet cols = meta.getPrimaryKeys(null, null, tableName)) {
PrimaryKey pk = new PrimaryKey();
Map<Short, String> seqToName = new TreeMap<>();
while (cols.next()) {
@@ -131,8 +127,6 @@ public class Schema_101 extends SchemaVersion {
pk.cols.add(name.toLowerCase(Locale.US));
}
return pk;
} finally {
cols.close();
}
}

View File

@@ -38,7 +38,7 @@ public class Schema_102 extends SchemaVersion {
throws OrmException, SQLException {
JdbcSchema schema = (JdbcSchema) db;
SqlDialect dialect = schema.getDialect();
try (Statement stmt = schema.getConnection().createStatement()) {
try (Statement stmt = newStatement(db)) {
// Drop left over indexes that were missed to be removed in schema 84.
// See "Delete SQL index support" commit for more details:
// d4ae3a16d5e1464574bd04f429a63eb9c02b3b43

View File

@@ -47,7 +47,6 @@ import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gerrit.server.group.SystemGroupBackend;
import com.google.gerrit.server.schema.Schema_77.LegacyLabelTypes;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
@@ -108,17 +107,9 @@ class Schema_53 extends SchemaVersion {
deleteActionCategories(db);
}
private void deleteActionCategories(ReviewDb db) throws OrmException {
try {
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
stmt.executeUpdate(
"DELETE FROM approval_categories WHERE position < 0");
} finally {
stmt.close();
}
} catch (SQLException e) {
throw new OrmException(e);
private void deleteActionCategories(ReviewDb db) throws SQLException {
try (Statement stmt = newStatement(db)) {
stmt.executeUpdate("DELETE FROM approval_categories WHERE position < 0");
}
}
@@ -154,57 +145,56 @@ class Schema_53 extends SchemaVersion {
private void exportProjectConfig(ReviewDb db) throws OrmException,
SQLException {
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM projects ORDER BY name");
while (rs.next()) {
final String name = rs.getString("name");
final Project.NameKey nameKey = new Project.NameKey(name);
try (Statement s = newStatement(db);
ResultSet rs = s.executeQuery("SELECT * FROM projects ORDER BY name")) {
while (rs.next()) {
final String name = rs.getString("name");
final Project.NameKey nameKey = new Project.NameKey(name);
Repository git;
try {
git = mgr.openRepository(nameKey);
} catch (RepositoryNotFoundException notFound) {
// A repository may be missing if this project existed only to store
// inheritable permissions. For example 'All-Projects'.
Repository git;
try {
git = mgr.createRepository(nameKey);
git = mgr.openRepository(nameKey);
} catch (RepositoryNotFoundException notFound) {
// A repository may be missing if this project existed only to store
// inheritable permissions. For example 'All-Projects'.
try {
git = mgr.createRepository(nameKey);
} catch (IOException err) {
throw new OrmException("Cannot create repository " + name, err);
}
} catch (IOException e) {
throw new OrmException(e);
}
try {
MetaDataUpdate md =
new MetaDataUpdate(GitReferenceUpdated.DISABLED, nameKey, git);
md.getCommitBuilder().setAuthor(serverUser);
md.getCommitBuilder().setCommitter(serverUser);
ProjectConfig config = ProjectConfig.read(md);
loadProject(rs, config.getProject());
config.getAccessSections().clear();
convertRights(config);
// Grant out read on the config branch by default.
//
if (config.getProject().getNameKey().equals(systemConfig.wildProjectName)) {
AccessSection meta = config.getAccessSection(RefNames.REFS_CONFIG, true);
Permission read = meta.getPermission(READ, true);
read.getRule(config.resolve(projectOwners), true);
}
md.setMessage("Import project configuration from SQL\n");
config.commit(md);
} catch (ConfigInvalidException err) {
throw new OrmException("Cannot read project " + name, err);
} catch (IOException err) {
throw new OrmException("Cannot create repository " + name, err);
throw new OrmException("Cannot export project " + name, err);
} finally {
git.close();
}
} catch (IOException e) {
throw new OrmException(e);
}
try {
MetaDataUpdate md =
new MetaDataUpdate(GitReferenceUpdated.DISABLED, nameKey, git);
md.getCommitBuilder().setAuthor(serverUser);
md.getCommitBuilder().setCommitter(serverUser);
ProjectConfig config = ProjectConfig.read(md);
loadProject(rs, config.getProject());
config.getAccessSections().clear();
convertRights(config);
// Grant out read on the config branch by default.
//
if (config.getProject().getNameKey().equals(systemConfig.wildProjectName)) {
AccessSection meta = config.getAccessSection(RefNames.REFS_CONFIG, true);
Permission read = meta.getPermission(READ, true);
read.getRule(config.resolve(projectOwners), true);
}
md.setMessage("Import project configuration from SQL\n");
config.commit(md);
} catch (ConfigInvalidException err) {
throw new OrmException("Cannot read project " + name, err);
} catch (IOException err) {
throw new OrmException("Cannot export project " + name, err);
} finally {
git.close();
}
}
rs.close();
stmt.close();
}
private void loadProject(ResultSet rs, Project project) throws SQLException,
@@ -246,42 +236,40 @@ class Schema_53 extends SchemaVersion {
private void readOldRefRights(ReviewDb db) throws SQLException {
rightsByProject = new HashMap<>();
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM ref_rights");
while (rs.next()) {
OldRefRight right = new OldRefRight(rs);
if (right.group == null || right.category == null) {
continue;
}
try (Statement s = newStatement(db);
ResultSet rs = s.executeQuery("SELECT * FROM ref_rights")) {
while (rs.next()) {
OldRefRight right = new OldRefRight(rs);
if (right.group == null || right.category == null) {
continue;
}
List<OldRefRight> list;
List<OldRefRight> list;
list = rightsByProject.get(right.project);
if (list == null) {
list = new ArrayList<>();
rightsByProject.put(right.project, list);
list = rightsByProject.get(right.project);
if (list == null) {
list = new ArrayList<>();
rightsByProject.put(right.project, list);
}
list.add(right);
}
list.add(right);
}
rs.close();
stmt.close();
}
private void readProjectParents(ReviewDb db) throws SQLException {
parentsByProject = new HashMap<>();
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM projects");
while (rs.next()) {
String name = rs.getString("name");
String parent_name = rs.getString("parent_name");
if (parent_name == null) {
parent_name = systemConfig.wildProjectName.get();
try (Statement s = newStatement(db);
ResultSet rs = s.executeQuery("SELECT * FROM projects")) {
while (rs.next()) {
String name = rs.getString("name");
String parent_name = rs.getString("parent_name");
if (parent_name == null) {
parent_name = systemConfig.wildProjectName.get();
}
parentsByProject.put(new Project.NameKey(name), //
new Project.NameKey(parent_name));
}
parentsByProject.put(new Project.NameKey(name), //
new Project.NameKey(parent_name));
}
rs.close();
stmt.close();
}
private void convertRights(ProjectConfig config) {

View File

@@ -30,7 +30,6 @@ import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
@@ -101,17 +100,15 @@ public class Schema_57 extends SchemaVersion {
String[] createGroupList = cfg.getStringList("repository", "*", "createGroup");
// Prepare the account_group_includes query
PreparedStatement stmt = ((JdbcSchema) db).getConnection().
prepareStatement("SELECT COUNT(1) FROM account_group_includes WHERE group_id = ?");
boolean isAccountGroupEmpty = false;
try {
try (PreparedStatement stmt = prepareStatement(db,
"SELECT COUNT(1) FROM account_group_includes WHERE group_id = ?")) {
stmt.setInt(1, sc.batchUsersGroupId.get());
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
isAccountGroupEmpty = rs.getInt(1) == 0;
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
isAccountGroupEmpty = rs.getInt(1) == 0;
}
}
} finally {
stmt.close();
}
for (String name : createGroupList) {

View File

@@ -31,8 +31,7 @@ public class Schema_63 extends SchemaVersion {
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws SQLException {
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
if (((JdbcSchema) db).getDialect() instanceof DialectPostgreSQL) {
stmt.execute("CREATE INDEX changes_byBranchClosed"
+ " ON changes (status, dest_project_name, dest_branch_name, sort_key)"
@@ -41,8 +40,6 @@ public class Schema_63 extends SchemaVersion {
stmt.execute("CREATE INDEX changes_byBranchClosed"
+ " ON changes (status, dest_project_name, dest_branch_name, sort_key)");
}
} finally {
stmt.close();
}
}
}

View File

@@ -27,7 +27,6 @@ import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
@@ -62,21 +61,14 @@ public class Schema_64 extends SchemaVersion {
protected void migrateData(ReviewDb db, UpdateUI ui)
throws OrmException, SQLException {
List<GroupReference> groups = Lists.newArrayList();
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
ResultSet rs = stmt.executeQuery(
"SELECT group_uuid, name FROM account_groups WHERE email_only_authors = 'Y'");
try {
while (rs.next()) {
AccountGroup.UUID uuid = new AccountGroup.UUID(rs.getString(1));
GroupReference group = new GroupReference(uuid, rs.getString(2));
groups.add(group);
}
} finally {
rs.close();
try (Statement stmt = newStatement(db);
ResultSet rs = stmt.executeQuery(
"SELECT group_uuid, name FROM account_groups WHERE email_only_authors = 'Y'")) {
while (rs.next()) {
AccountGroup.UUID uuid = new AccountGroup.UUID(rs.getString(1));
GroupReference group = new GroupReference(uuid, rs.getString(2));
groups.add(group);
}
} finally {
stmt.close();
}
if (groups.isEmpty()) {

View File

@@ -39,7 +39,6 @@ import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gerrit.server.git.VersionedMetaData.BatchMetaDataUpdate;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
@@ -222,8 +221,7 @@ public class Schema_65 extends SchemaVersion {
private Map<Integer, ContributorAgreement> getAgreementToAdd(
ReviewDb db, ProjectConfig config) throws SQLException {
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
ResultSet rs = stmt.executeQuery(
"SELECT short_name, id, require_contact_information," +
" short_description, agreement_url, auto_verify " +
@@ -249,8 +247,6 @@ public class Schema_65 extends SchemaVersion {
} finally {
rs.close();
}
} finally {
stmt.close();
}
}
@@ -341,8 +337,7 @@ public class Schema_65 extends SchemaVersion {
List<AccountGroup.UUID> adminGroupUUIDs,
Map<Integer, ContributorAgreement> agreements)
throws SQLException, OrmException {
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
ResultSet rs = stmt.executeQuery(
"SELECT account_id, cla_id, accepted_on, reviewed_by," +
" reviewed_on, review_comments " +
@@ -389,8 +384,6 @@ public class Schema_65 extends SchemaVersion {
} finally {
rs.close();
}
} finally {
stmt.close();
}
}
@@ -411,8 +404,7 @@ public class Schema_65 extends SchemaVersion {
ReviewDb db, Map<Integer, ContributorAgreement> agreements)
throws SQLException {
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
ResultSet rs = stmt.executeQuery(
"SELECT group_id, cla_id, accepted_on, reviewed_by, reviewed_on, " +
" review_comments " +
@@ -454,8 +446,6 @@ public class Schema_65 extends SchemaVersion {
} finally {
rs.close();
}
} finally {
stmt.close();
}
}
}

View File

@@ -20,7 +20,6 @@ import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
@@ -48,22 +47,15 @@ public class Schema_67 extends SchemaVersion {
// Scan all AccountGroup, and find the ones that need the owner_group_id
// migrated to owner_group_uuid.
Map<AccountGroup.Id, AccountGroup.Id> idMap = Maps.newHashMap();
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
ResultSet rs = stmt.executeQuery(
try (Statement stmt = newStatement(db);
ResultSet rs = stmt.executeQuery(
"SELECT group_id, owner_group_id FROM account_groups"
+ " WHERE owner_group_uuid is NULL or owner_group_uuid =''");
try {
while (rs.next()) {
AccountGroup.Id groupId = new AccountGroup.Id(rs.getInt(1));
AccountGroup.Id ownerId = new AccountGroup.Id(rs.getInt(2));
idMap.put(groupId, ownerId);
}
} finally {
rs.close();
+ " WHERE owner_group_uuid is NULL or owner_group_uuid =''")) {
while (rs.next()) {
AccountGroup.Id groupId = new AccountGroup.Id(rs.getInt(1));
AccountGroup.Id ownerId = new AccountGroup.Id(rs.getInt(2));
idMap.put(groupId, ownerId);
}
} finally {
stmt.close();
}
// Lookup up all groups by ID.

View File

@@ -15,7 +15,6 @@
package com.google.gerrit.server.schema;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.inject.Inject;
import com.google.inject.Provider;
@@ -31,8 +30,7 @@ public class Schema_68 extends SchemaVersion {
@Override
protected void migrateData(final ReviewDb db, final UpdateUI ui)
throws SQLException {
final Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
stmt.execute("CREATE INDEX submodule_subscription_access_bySubscription"
+ " ON submodule_subscriptions (submodule_project_name, submodule_branch_name)");
} catch (SQLException e) {
@@ -53,8 +51,6 @@ public class Schema_68 extends SchemaVersion {
throw e;
}
}
} finally {
stmt.close();
}
}
}

View File

@@ -29,7 +29,6 @@ import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
@@ -73,35 +72,28 @@ public class Schema_69 extends SchemaVersion {
Set<AccountGroup.UUID> toResolve = Sets.newHashSet();
List<AccountGroup.Id> toDelete = Lists.newArrayList();
List<AccountGroup.NameKey> namesToDelete = Lists.newArrayList();
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
ResultSet rs = stmt.executeQuery(
"SELECT group_id, group_uuid, external_name, name FROM account_groups"
+ " WHERE group_type ='LDAP'");
try {
while (rs.next()) {
AccountGroup.Id groupId = new AccountGroup.Id(rs.getInt(1));
AccountGroup.UUID groupUUID = new AccountGroup.UUID(rs.getString(2));
AccountGroup.NameKey name = new AccountGroup.NameKey(rs.getString(4));
String dn = rs.getString(3);
try (Statement stmt = newStatement(db);
ResultSet rs = stmt.executeQuery(
"SELECT group_id, group_uuid, external_name, name FROM account_groups"
+ " WHERE group_type ='LDAP'")) {
while (rs.next()) {
AccountGroup.Id groupId = new AccountGroup.Id(rs.getInt(1));
AccountGroup.UUID groupUUID = new AccountGroup.UUID(rs.getString(2));
AccountGroup.NameKey name = new AccountGroup.NameKey(rs.getString(4));
String dn = rs.getString(3);
if (isNullOrEmpty(dn)) {
// The LDAP group does not have a DN. Determine if the UUID is used.
toResolve.add(groupUUID);
} else {
toDelete.add(groupId);
namesToDelete.add(name);
GroupReference ref = groupReference(dn);
ldapUUIDMap.put(groupUUID, ref);
}
if (isNullOrEmpty(dn)) {
// The LDAP group does not have a DN. Determine if the UUID is used.
toResolve.add(groupUUID);
} else {
toDelete.add(groupId);
namesToDelete.add(name);
GroupReference ref = groupReference(dn);
ldapUUIDMap.put(groupUUID, ref);
}
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
rs.close();
}
} finally {
stmt.close();
} catch (NamingException e) {
throw new RuntimeException(e);
}
if (toDelete.isEmpty() && toResolve.isEmpty()) {
return; // No ldap groups. Nothing to do.

View File

@@ -15,7 +15,6 @@
package com.google.gerrit.server.schema;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.inject.Inject;
import com.google.inject.Provider;
@@ -32,12 +31,8 @@ public class Schema_71 extends SchemaVersion {
@Override
protected void migrateData(final ReviewDb db, final UpdateUI ui)
throws SQLException {
final Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
stmt.executeUpdate("UPDATE account_diff_preferences SET show_line_endings='Y'");
}
finally {
stmt.close();
}
}
}

View File

@@ -15,14 +15,12 @@
package com.google.gerrit.server.schema;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.sql.SQLException;
import java.sql.Statement;
public class Schema_73 extends SchemaVersion {
@Inject
Schema_73(Provider<Schema_72> prior) {
@@ -32,12 +30,8 @@ public class Schema_73 extends SchemaVersion {
@Override
protected void migrateData(final ReviewDb db, final UpdateUI ui)
throws SQLException {
final Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
stmt.executeUpdate("CREATE INDEX change_messages_byPatchset ON change_messages (patchset_change_id, patchset_patch_set_id )");
}
finally {
stmt.close();
}
}
}

View File

@@ -19,12 +19,10 @@ import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.AccountGroupById;
import com.google.gerrit.reviewdb.client.AccountGroupByIdAud;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@@ -49,15 +47,13 @@ public class Schema_74 extends SchemaVersion {
}
// Initialize some variables
Connection conn = ((JdbcSchema) db).getConnection();
ArrayList<AccountGroupById> newIncludes = new ArrayList<>();
ArrayList<AccountGroupByIdAud> newIncludeAudits = new ArrayList<>();
// Iterate over all entries in account_group_includes
Statement oldGroupIncludesStmt = conn.createStatement();
try {
ResultSet oldGroupIncludes = oldGroupIncludesStmt.
executeQuery("SELECT * FROM account_group_includes");
try (Statement oldGroupIncludesStmt = newStatement(db);
ResultSet oldGroupIncludes = oldGroupIncludesStmt.executeQuery(
"SELECT * FROM account_group_includes")) {
while (oldGroupIncludes.next()) {
AccountGroup.Id oldGroupId =
new AccountGroup.Id(oldGroupIncludes.getInt("group_id"));
@@ -77,35 +73,31 @@ public class Schema_74 extends SchemaVersion {
new AccountGroupById.Key(oldGroupId, uuidFromIncludeId));
// Iterate over all the audits (for this group)
PreparedStatement oldAuditsQueryStmt = conn.prepareStatement(
"SELECT * FROM account_group_includes_audit WHERE group_id=? AND include_id=?");
try {
try (PreparedStatement oldAuditsQueryStmt = prepareStatement(db,
"SELECT * FROM account_group_includes_audit WHERE group_id=? AND include_id=?")) {
oldAuditsQueryStmt.setInt(1, oldGroupId.get());
oldAuditsQueryStmt.setInt(2, oldIncludeId.get());
ResultSet oldGroupIncludeAudits = oldAuditsQueryStmt.executeQuery();
while (oldGroupIncludeAudits.next()) {
Account.Id addedBy = new Account.Id(oldGroupIncludeAudits.getInt("added_by"));
int removedBy = oldGroupIncludeAudits.getInt("removed_by");
try (ResultSet oldGroupIncludeAudits = oldAuditsQueryStmt.executeQuery()) {
while (oldGroupIncludeAudits.next()) {
Account.Id addedBy = new Account.Id(oldGroupIncludeAudits.getInt("added_by"));
int removedBy = oldGroupIncludeAudits.getInt("removed_by");
// Create the new audit entry
AccountGroupByIdAud destAuditEntry =
new AccountGroupByIdAud(destIncludeEntry, addedBy,
oldGroupIncludeAudits.getTimestamp("added_on"));
// Create the new audit entry
AccountGroupByIdAud destAuditEntry =
new AccountGroupByIdAud(destIncludeEntry, addedBy,
oldGroupIncludeAudits.getTimestamp("added_on"));
// If this was a "removed on" entry, note that
if (removedBy > 0) {
destAuditEntry.removed(new Account.Id(removedBy),
oldGroupIncludeAudits.getTimestamp("removed_on"));
// If this was a "removed on" entry, note that
if (removedBy > 0) {
destAuditEntry.removed(new Account.Id(removedBy),
oldGroupIncludeAudits.getTimestamp("removed_on"));
}
newIncludeAudits.add(destAuditEntry);
}
newIncludeAudits.add(destAuditEntry);
}
newIncludes.add(destIncludeEntry);
} finally {
oldAuditsQueryStmt.close();
}
}
} finally {
oldGroupIncludesStmt.close();
}
// Now insert all of the new entries to the database

View File

@@ -95,12 +95,9 @@ public class Schema_77 extends SchemaVersion {
}
private void alterTable(ReviewDb db, String sqlFormat) throws SQLException {
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
stmt.executeUpdate(
String.format(sqlFormat, "patch_set_approvals", "category_id"));
} finally {
stmt.close();
}
}
@@ -136,18 +133,15 @@ public class Schema_77 extends SchemaVersion {
private void migratePatchSetApprovals(ReviewDb db,
LegacyLabelTypes labelTypes) throws SQLException {
PreparedStatement stmt = ((JdbcSchema) db).getConnection().prepareStatement(
try (PreparedStatement stmt = prepareStatement(db,
"UPDATE patch_set_approvals SET category_id = ?, granted=granted"
+ " WHERE category_id = ?");
try {
+ " WHERE category_id = ?")) {
for (LegacyLabelType type : labelTypes.getLegacyLabelTypes()) {
stmt.setString(1, type.getName());
stmt.setString(2, type.getId());
stmt.addBatch();
}
stmt.executeBatch();
} finally {
stmt.close();
}
}
@@ -199,38 +193,32 @@ public class Schema_77 extends SchemaVersion {
static LegacyLabelTypes getLegacyTypes(ReviewDb db) throws SQLException {
List<LegacyLabelType> types = Lists.newArrayListWithCapacity(2);
Statement catStmt = ((JdbcSchema) db).getConnection().createStatement();
try {
ResultSet catRs = catStmt.executeQuery(
try (Statement catStmt = newStatement(db);
ResultSet catRs = catStmt.executeQuery(
"SELECT category_id, name, function_name, copy_min_score"
+ " FROM approval_categories"
+ " ORDER BY position, name");
PreparedStatement valStmt = ((JdbcSchema) db).getConnection().prepareStatement(
"SELECT value, name"
+ " FROM approval_category_values"
+ " WHERE category_id = ?");
try {
while (catRs.next()) {
String id = catRs.getString("category_id");
valStmt.setString(1, id);
List<LabelValue> values = Lists.newArrayListWithCapacity(5);
ResultSet valRs = valStmt.executeQuery();
PreparedStatement valStmt = prepareStatement(db,
"SELECT value, name"
+ " FROM approval_category_values"
+ " WHERE category_id = ?")) {
while (catRs.next()) {
String id = catRs.getString("category_id");
valStmt.setString(1, id);
List<LabelValue> values = Lists.newArrayListWithCapacity(5);
try (ResultSet valRs = valStmt.executeQuery()) {
while (valRs.next()) {
values.add(new LabelValue(
valRs.getShort("value"), valRs.getString("name")));
}
LegacyLabelType type =
new LegacyLabelType(getLabelName(catRs.getString("name")), values);
type.setId(id);
type.setFunctionName(catRs.getString("function_name"));
type.setCopyMinScore("Y".equals(catRs.getString("copy_min_score")));
types.add(type);
}
} finally {
valStmt.close();
LegacyLabelType type =
new LegacyLabelType(getLabelName(catRs.getString("name")), values);
type.setId(id);
type.setFunctionName(catRs.getString("function_name"));
type.setCopyMinScore("Y".equals(catRs.getString("copy_min_score")));
types.add(type);
}
} finally {
catStmt.close();
}
return new LegacyLabelTypes(types);
}

View File

@@ -51,10 +51,11 @@ public class Schema_82 extends SchemaVersion {
@Override
protected void preUpdateSchema(ReviewDb db) throws OrmException, SQLException {
final JdbcSchema s = (JdbcSchema) db;
final JdbcExecutor e = new JdbcExecutor(s);
renameTables(db, s, e);
renameColumn(db, s, e);
JdbcSchema s = (JdbcSchema) db;
try (JdbcExecutor e = new JdbcExecutor(s)) {
renameTables(db, s, e);
renameColumn(db, s, e);
}
renameIndexes(db);
}
@@ -92,19 +93,15 @@ public class Schema_82 extends SchemaVersion {
// Well it doesn't implemented anyway,
// check constraints are get parsed but do nothing
if (dialect instanceof DialectMySQL) {
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
addCheckConstraint(stmt);
} finally {
stmt.close();
}
}
}
private void renameIndexes(ReviewDb db) throws SQLException {
private void renameIndexes(ReviewDb db) {
SqlDialect dialect = ((JdbcSchema) db).getDialect();
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
// MySQL doesn't have alter index stmt, drop & create
if (dialect instanceof DialectMySQL) {
for (Map.Entry<String, Index> entry : indexes.entrySet()) {
@@ -128,8 +125,6 @@ public class Schema_82 extends SchemaVersion {
// we don't care
// better we would check if index was already renamed
// gwtorm doesn't expose this functionality
} finally {
stmt.close();
}
}

View File

@@ -17,7 +17,6 @@ package com.google.gerrit.server.schema;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.group.SystemGroupBackend;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
@@ -51,18 +50,14 @@ public class Schema_87 extends SchemaVersion {
private Set<AccountGroup.Id> scanSystemGroups(ReviewDb db)
throws SQLException {
JdbcSchema s = (JdbcSchema) db;
Statement stmt = s.getConnection().createStatement();
try {
ResultSet rs =
stmt.executeQuery("SELECT group_id FROM account_groups WHERE group_type = 'SYSTEM'");
try (Statement stmt = newStatement(db);
ResultSet rs = stmt.executeQuery(
"SELECT group_id FROM account_groups WHERE group_type = 'SYSTEM'")) {
Set<AccountGroup.Id> ids = new HashSet<>();
while (rs.next()) {
ids.add(new AccountGroup.Id(rs.getInt(1)));
}
return ids;
} finally {
stmt.close();
}
}
}

View File

@@ -36,8 +36,7 @@ public class Schema_89 extends SchemaVersion {
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException,
SQLException {
SqlDialect dialect = ((JdbcSchema) db).getDialect();
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
for (String name : ImmutableList.of(
"patch_set_approvals_openByUser",
"patch_set_approvals_closedByU")) {
@@ -47,8 +46,6 @@ public class Schema_89 extends SchemaVersion {
stmt.executeUpdate("DROP INDEX " + name);
}
}
} finally {
stmt.close();
}
}
}

View File

@@ -15,7 +15,6 @@
package com.google.gerrit.server.schema;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.inject.Inject;
import com.google.inject.Provider;
@@ -30,11 +29,8 @@ public class Schema_90 extends SchemaVersion {
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws SQLException {
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
stmt.executeUpdate("UPDATE accounts set size_bar_in_change_table = 'Y'");
} finally {
stmt.close();
}
}
}

View File

@@ -15,7 +15,6 @@
package com.google.gerrit.server.schema;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.inject.Inject;
import com.google.inject.Provider;
@@ -30,7 +29,7 @@ public class Schema_94 extends SchemaVersion {
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws SQLException {
try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement()) {
try (Statement stmt = newStatement(db)) {
stmt.execute("CREATE INDEX patch_sets_byRevision"
+ " ON patch_sets (revision)");
}

View File

@@ -15,7 +15,6 @@
package com.google.gerrit.server.schema;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.inject.Inject;
import com.google.inject.Provider;
@@ -32,13 +31,10 @@ public class Schema_98 extends SchemaVersion {
protected void migrateData(ReviewDb db, UpdateUI ui) throws SQLException {
ui.message("Migrate user preference showUserInReview to "
+ "reviewCategoryStrategy");
Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
try {
try (Statement stmt = newStatement(db)) {
stmt.executeUpdate("UPDATE accounts SET "
+ "REVIEW_CATEGORY_STRATEGY='NAME' "
+ "WHERE (SHOW_USER_IN_REVIEW='Y')");
} finally {
stmt.close();
}
}
}

View File

@@ -52,11 +52,10 @@ class ScriptRunner {
void run(final ReviewDb db) throws OrmException {
try {
final JdbcSchema schema = (JdbcSchema)db;
final JdbcSchema schema = (JdbcSchema) db;
final Connection c = schema.getConnection();
final SqlDialect dialect = schema.getDialect();
final Statement stmt = c.createStatement();
try {
try (Statement stmt = c.createStatement()) {
for (String sql : commands) {
try {
if (!dialect.isStatementDelimiterSupported()) {
@@ -67,8 +66,6 @@ class ScriptRunner {
throw new OrmException("Error in " + name + ":\n" + sql, e);
}
}
} finally {
stmt.close();
}
} catch (SQLException e) {
throw new OrmException("Cannot run statements for " + name, e);

View File

@@ -70,21 +70,11 @@ public class SchemaCreatorTest {
public void testGetCauses_CreateSchema() throws OrmException, SQLException,
IOException {
// Initially the schema should be empty.
//
{
final JdbcSchema d = (JdbcSchema) db.open();
try {
final String[] types = {"TABLE", "VIEW"};
final ResultSet rs =
d.getConnection().getMetaData().getTables(null, null, null, types);
try {
assertFalse(rs.next());
} finally {
rs.close();
}
} finally {
d.close();
}
String[] types = {"TABLE", "VIEW"};
try (JdbcSchema d = (JdbcSchema) db.open();
ResultSet rs = d.getConnection().getMetaData()
.getTables(null, null, null, types)) {
assertFalse(rs.next());
}
// Create the schema using the current schema version.

View File

@@ -224,20 +224,15 @@ public class QueryShell {
return;
}
try {
final String[] types = {"TABLE", "VIEW"};
ResultSet rs = meta.getTables(null, null, null, types);
try {
if (outputFormat == OutputFormat.PRETTY) {
println(" List of relations");
}
showResultSet(rs, false, 0,
Identity.create(rs, "TABLE_SCHEM"),
Identity.create(rs, "TABLE_NAME"),
Identity.create(rs, "TABLE_TYPE"));
} finally {
rs.close();
final String[] types = {"TABLE", "VIEW"};
try (ResultSet rs = meta.getTables(null, null, null, types)) {
if (outputFormat == OutputFormat.PRETTY) {
println(" List of relations");
}
showResultSet(rs, false, 0,
Identity.create(rs, "TABLE_SCHEM"),
Identity.create(rs, "TABLE_NAME"),
Identity.create(rs, "TABLE_TYPE"));
} catch (SQLException e) {
error(e);
}
@@ -260,91 +255,81 @@ public class QueryShell {
return;
}
try {
ResultSet rs = meta.getColumns(null, null, tableName, null);
try {
if (!rs.next()) {
throw new SQLException("Table " + tableName + " not found");
}
if (outputFormat == OutputFormat.PRETTY) {
println(" Table " + tableName);
}
showResultSet(rs, true, 0,
Identity.create(rs, "COLUMN_NAME"),
new Function("TYPE") {
@Override
String apply(final ResultSet rs) throws SQLException {
String type = rs.getString("TYPE_NAME");
switch (rs.getInt("DATA_TYPE")) {
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
type += "(" + rs.getInt("COLUMN_SIZE") + ")";
break;
}
String def = rs.getString("COLUMN_DEF");
if (def != null && !def.isEmpty()) {
type += " DEFAULT " + def;
}
int nullable = rs.getInt("NULLABLE");
if (nullable == DatabaseMetaData.columnNoNulls) {
type += " NOT NULL";
}
return type;
}
});
} finally {
rs.close();
try (ResultSet rs = meta.getColumns(null, null, tableName, null)) {
if (!rs.next()) {
throw new SQLException("Table " + tableName + " not found");
}
if (outputFormat == OutputFormat.PRETTY) {
println(" Table " + tableName);
}
showResultSet(rs, true, 0,
Identity.create(rs, "COLUMN_NAME"),
new Function("TYPE") {
@Override
String apply(final ResultSet rs) throws SQLException {
String type = rs.getString("TYPE_NAME");
switch (rs.getInt("DATA_TYPE")) {
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
type += "(" + rs.getInt("COLUMN_SIZE") + ")";
break;
}
String def = rs.getString("COLUMN_DEF");
if (def != null && !def.isEmpty()) {
type += " DEFAULT " + def;
}
int nullable = rs.getInt("NULLABLE");
if (nullable == DatabaseMetaData.columnNoNulls) {
type += " NOT NULL";
}
return type;
}
});
} catch (SQLException e) {
error(e);
return;
}
try {
ResultSet rs = meta.getIndexInfo(null, null, tableName, false, true);
try {
Map<String, IndexInfo> indexes = new TreeMap<>();
while (rs.next()) {
final String indexName = rs.getString("INDEX_NAME");
IndexInfo def = indexes.get(indexName);
if (def == null) {
def = new IndexInfo();
def.name = indexName;
indexes.put(indexName, def);
}
if (!rs.getBoolean("NON_UNIQUE")) {
def.unique = true;
}
final int pos = rs.getInt("ORDINAL_POSITION");
final String col = rs.getString("COLUMN_NAME");
String desc = rs.getString("ASC_OR_DESC");
if ("D".equals(desc)) {
desc = " DESC";
} else {
desc = "";
}
def.addColumn(pos, col + desc);
String filter = rs.getString("FILTER_CONDITION");
if (filter != null && !filter.isEmpty()) {
def.filter.append(filter);
}
try (ResultSet rs = meta.getIndexInfo(null, null, tableName, false, true)) {
Map<String, IndexInfo> indexes = new TreeMap<>();
while (rs.next()) {
final String indexName = rs.getString("INDEX_NAME");
IndexInfo def = indexes.get(indexName);
if (def == null) {
def = new IndexInfo();
def.name = indexName;
indexes.put(indexName, def);
}
if (outputFormat == OutputFormat.PRETTY) {
println("");
println("Indexes on " + tableName + ":");
for (IndexInfo def : indexes.values()) {
println(" " + def);
}
if (!rs.getBoolean("NON_UNIQUE")) {
def.unique = true;
}
final int pos = rs.getInt("ORDINAL_POSITION");
final String col = rs.getString("COLUMN_NAME");
String desc = rs.getString("ASC_OR_DESC");
if ("D".equals(desc)) {
desc = " DESC";
} else {
desc = "";
}
def.addColumn(pos, col + desc);
String filter = rs.getString("FILTER_CONDITION");
if (filter != null && !filter.isEmpty()) {
def.filter.append(filter);
}
}
if (outputFormat == OutputFormat.PRETTY) {
println("");
println("Indexes on " + tableName + ":");
for (IndexInfo def : indexes.values()) {
println(" " + def);
}
} finally {
rs.close();
}
} catch (SQLException e) {
error(e);
@@ -366,11 +351,8 @@ public class QueryShell {
try {
if (hasResultSet) {
final ResultSet rs = statement.getResultSet();
try {
try (ResultSet rs = statement.getResultSet()) {
showResultSet(rs, false, start);
} finally {
rs.close();
}
} else {

View File

@@ -54,8 +54,7 @@ public final class SiteInitializer {
return;
}
Connection conn = connectToDb();
try {
try (Connection conn = connectToDb()) {
File site = getSiteFromReviewDb(conn);
if (site == null && initPath != null) {
site = new File(initPath);
@@ -66,8 +65,6 @@ public final class SiteInitializer {
new BaseInit(site, new ReviewDbDataSourceProvider(), false, false,
pluginsDistribution, pluginsToInstall).run();
}
} finally {
conn.close();
}
} catch (Exception e) {
LOG.error("Site init failed", e);
@@ -80,19 +77,15 @@ public final class SiteInitializer {
}
private File getSiteFromReviewDb(Connection conn) {
try {
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery("SELECT site_path FROM system_config");
if (rs.next()) {
return new File(rs.getString(1));
}
} finally {
stmt.close();
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
"SELECT site_path FROM system_config")) {
if (rs.next()) {
return new File(rs.getString(1));
}
return null;
} catch (SQLException e) {
return null;
}
return null;
}
}

View File

@@ -26,11 +26,12 @@ define_license(name = 'DO_NOT_DISTRIBUTE')
maven_jar(
name = 'gwtorm',
id = 'com.google.gerrit:gwtorm:1.14',
bin_sha1 = '7e7562d2a8ae233ac9f23ec90dee1a01646483c0',
src_sha1 = 'ae991fdefe5e92ee7ed754786b924dc1ec119a8b',
id = 'com.google.gerrit:gwtorm:1.14-14-gf54f1f1',
bin_sha1 = 'c02267e0245dd06930ea64a2d7c5ddc5ba6d9cfb',
src_sha1 = '3d17ae8a173eb34d89098c748f28cddd5080adbc',
license = 'Apache2.0',
deps = [':protobuf'],
repository = GERRIT,
)
maven_jar(