001 /*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2009 SonarSource SA
004 * mailto:contact AT sonarsource DOT com
005 *
006 * Sonar is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * Sonar is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public
017 * License along with Sonar; if not, write to the Free Software
018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
019 */
020 package org.sonar.api.database;
021
022 import java.sql.Connection;
023 import java.sql.ResultSet;
024 import java.sql.SQLException;
025 import java.sql.Statement;
026 import javax.persistence.*;
027
028 @Entity
029 @Table(name = SchemaMigration.TABLE_NAME, uniqueConstraints = {@UniqueConstraint(columnNames = {"version"})})
030 public class SchemaMigration {
031
032 public final static int VERSION_UNKNOWN = -1;
033 public static final int LAST_VERSION = 100;
034
035 public final static String TABLE_NAME = "schema_migrations";
036
037 @Id
038 @Column(name = "version", updatable = true)
039 private String version;
040
041 public String getVersion() {
042 return version;
043 }
044
045 public void setVersion(String s) {
046 this.version = s;
047 }
048
049 public void setVersion(int i) {
050 this.version = String.valueOf(i);
051 }
052
053 public static int getCurrentVersion(Connection connection) {
054 Statement stmt = null;
055 ResultSet rs = null;
056 int version = VERSION_UNKNOWN;
057 try {
058 stmt = connection.createStatement();
059 rs = stmt.executeQuery("SELECT version FROM " + SchemaMigration.TABLE_NAME);
060 while (rs.next()) {
061 int i = Integer.parseInt(rs.getString(1));
062 if (i > version) {
063 version = i;
064 }
065 }
066 } catch (SQLException e) {
067 // ignore
068 } finally {
069 close(rs);
070 close(stmt);
071 }
072
073 return version;
074 }
075
076 private static void close(ResultSet rs) {
077 if (rs != null) {
078 try {
079 rs.close();
080 } catch (SQLException e) {
081 // why does close() throw a checked-exception ???
082 }
083 }
084 }
085
086 private static void close(Statement st) {
087 if (st != null) {
088 try {
089 st.close();
090 } catch (SQLException e) {
091 // why does close() throw a checked-exception ???
092 }
093 }
094 }
095 }