001 /* 002 * Sonar, open source software quality management tool. 003 * Copyright (C) 2008-2012 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. 030 * Other databases are created by Ruby on Rails migrations. 031 * 032 * @since 2.12 033 */ 034 public class DatabaseMigrator implements ServerComponent { 035 036 private MyBatis myBatis; 037 private Database database; 038 039 public DatabaseMigrator(MyBatis myBatis, Database database) { 040 this.myBatis = myBatis; 041 this.database = database; 042 } 043 044 /** 045 * @return true if the database has been created, false if this database is not supported 046 */ 047 public boolean createDatabase() { 048 if (DdlUtils.supportsDialect(database.getDialect().getId())) { 049 LoggerFactory.getLogger(getClass()).info("Create database"); 050 SqlSession session = myBatis.openSession(); 051 Connection connection = session.getConnection(); 052 try { 053 DdlUtils.createSchema(connection, database.getDialect().getId()); 054 } finally { 055 try { 056 MyBatis.closeQuietly(session); 057 058 // The connection is probably already closed by session.close() 059 // but it's not documented in mybatis javadoc. 060 connection.close(); 061 } catch (Exception e) { 062 // ignore 063 } 064 } 065 return true; 066 } 067 return false; 068 } 069 }