001 /*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2008-2011 SonarSource
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.jpa.entity;
021
022 import java.sql.Connection;
023 import java.sql.ResultSet;
024 import java.sql.SQLException;
025 import java.sql.Statement;
026
027 import javax.persistence.*;
028
029 @Entity
030 @Table(name = SchemaMigration.TABLE_NAME, uniqueConstraints = { @UniqueConstraint(columnNames = { "version" }) })
031 public class SchemaMigration {
032
033 public final static int VERSION_UNKNOWN = -1;
034 public static final int LAST_VERSION = 181;
035
036 public final static String TABLE_NAME = "schema_migrations";
037
038 @Id
039 @Column(name = "version", updatable = true)
040 private String version;
041
042 public String getVersion() {
043 return version;
044 }
045
046 public void setVersion(String s) {
047 this.version = s;
048 }
049
050 public void setVersion(int i) {
051 this.version = String.valueOf(i);
052 }
053
054 public static int getCurrentVersion(Connection connection) {
055 Statement stmt = null;
056 ResultSet rs = null;
057 int version = VERSION_UNKNOWN;
058 try {
059 stmt = connection.createStatement();
060 rs = stmt.executeQuery("SELECT version FROM " + SchemaMigration.TABLE_NAME);
061 while (rs.next()) {
062 int i = Integer.parseInt(rs.getString(1));
063 if (i > version) {
064 version = i;
065 }
066 }
067 } catch (SQLException e) {
068 // ignore
069 } finally {
070 close(rs);
071 close(stmt);
072 }
073
074 return version;
075 }
076
077 private static void close(ResultSet rs) {
078 if (rs != null) {
079 try {
080 rs.close();
081 } catch (SQLException e) {
082 // why does close() throw a checked-exception ???
083 }
084 }
085 }
086
087 private static void close(Statement st) {
088 if (st != null) {
089 try {
090 st.close();
091 } catch (SQLException e) {
092 // why does close() throw a checked-exception ???
093 }
094 }
095 }
096 }