// Copyright (C) Stichting Deltares 2016. All rights reserved.
//
// This file is part of Ringtoets.
//
// Ringtoets is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
//
// All names, logos, and references to "Deltares" are registered trademarks of
// Stichting Deltares and remain full property of Stichting Deltares at all times.
// All rights reserved.
using System;
using System.Data.SQLite;
using System.IO;
using Application.Ringtoets.Storage.Properties;
using Core.Common.Base.Storage;
using Core.Common.Utils;
using Core.Common.Utils.Builders;
namespace Application.Ringtoets.Storage
{
///
/// This class interacts with an empty or new SQLite database file.
///
public static class StorageSqliteCreator
{
///
/// Creates a new file with the basic database structure for a Ringtoets database at
/// .
///
/// Path of the new database file.
/// Thrown when either:
///
/// - is invalid
/// - points to an existing file
///
/// Thrown when executing DatabaseStructure script fails.
public static void CreateDatabaseStructure(string databaseFilePath)
{
IOUtils.ValidateFilePath(databaseFilePath);
if (File.Exists(databaseFilePath))
{
var message = string.Format("File '{0}' already exists.", databaseFilePath);
throw new ArgumentException(message);
}
SQLiteConnection.CreateFile(databaseFilePath);
var connectionString = SqLiteConnectionStringBuilder.BuildSqLiteConnectionString(databaseFilePath);
try
{
using (var dbContext = new SQLiteConnection(connectionString, true))
{
dbContext.Open();
using (var command = dbContext.CreateCommand())
{
command.CommandText = Resources.DatabaseStructure;
command.ExecuteNonQuery();
}
}
}
catch (SQLiteException exception)
{
var message = new FileWriterErrorMessageBuilder(databaseFilePath).Build(Resources.Error_writing_structure_to_database);
throw new StorageException(message, new UpdateStorageException("", exception));
}
finally
{
SQLiteConnection.ClearAllPools();
}
}
}
}