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.commons.io.output.NullWriter;
023 import org.apache.ibatis.io.Resources;
024 import org.apache.ibatis.jdbc.ScriptRunner;
025
026 import java.io.PrintWriter;
027 import java.sql.Connection;
028
029 /**
030 * Util class to create Sonar database tables
031 *
032 * @since 2.12
033 */
034 public final class DdlUtils {
035
036 private DdlUtils() {
037 }
038
039 public static boolean supportsDialect(String dialect) {
040 return "derby".equals(dialect);
041 }
042
043 /**
044 * The connection is commited in this method but not closed.
045 */
046 public static void createSchema(Connection connection, String dialect) {
047 executeScript(connection, "org/sonar/core/persistence/schema-" + dialect + ".ddl");
048 executeScript(connection, "org/sonar/core/persistence/rows-" + dialect + ".sql");
049 }
050
051 private static void executeScript(Connection connection, String path) {
052 ScriptRunner scriptRunner = newScriptRunner(connection);
053 try {
054 scriptRunner.runScript(Resources.getResourceAsReader(path));
055 connection.commit();
056
057 } catch (Exception e) {
058 throw new IllegalStateException("Fail to restore: " + path, e);
059 }
060 }
061
062 private static ScriptRunner newScriptRunner(Connection connection) {
063 ScriptRunner scriptRunner = new ScriptRunner(connection);
064 scriptRunner.setDelimiter(";");
065 scriptRunner.setStopOnError(true);
066 scriptRunner.setLogWriter(new PrintWriter(new NullWriter()));
067 return scriptRunner;
068 }
069 }