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.core.persistence;
021
022 import org.apache.ibatis.session.SqlSession;
023 import org.slf4j.LoggerFactory;
024 import org.sonar.api.ServerComponent;
025
026 import java.sql.Connection;
027
028 /**
029 * Restore schema by executing DDL scripts. Only Derby database is supported. Other databases are created by Ruby on Rails migrations.
030 *
031 * @since 2.12
032 */
033 public class DatabaseMigrator implements ServerComponent {
034
035 private MyBatis myBatis;
036 private Database database;
037
038 public DatabaseMigrator(MyBatis myBatis, Database database) {
039 this.myBatis = myBatis;
040 this.database = database;
041 }
042
043 /**
044 * @return true if the database has been created, false if this database is not supported
045 */
046 public boolean createDatabase() {
047 if (DdlUtils.supportsDialect(database.getDialect().getId())) {
048 LoggerFactory.getLogger(getClass()).info("Create database");
049 SqlSession session = myBatis.openSession();
050 Connection connection = session.getConnection();
051 try {
052 DdlUtils.createSchema(connection, database.getDialect().getId());
053 } finally {
054 try {
055 session.close();
056
057 // The connection is probably already closed by session.close()
058 // but it's not documented in mybatis javadoc.
059 connection.close();
060 } catch (Exception e) {
061 // ignore
062 }
063 }
064 return true;
065 }
066 return false;
067 }
068 }