// 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 Core.Common.IO;
using Core.Common.Utils;
namespace Application.Ringtoets.Migration
{
///
/// Class that provides methods for the migration database target file.
///
public class RingtoetsDatabaseFile : IDisposable
{
private readonly string filePath;
private SQLiteConnection connection;
private bool disposed;
///
/// Creates a new instance of the class.
///
/// The path to the target file.
/// Thrown when :
///
/// - is not empty or null,
/// - does not consist out of only whitespace characters,
/// - does not contain an invalid character,
/// - does not end with a directory or path separator (empty file name),
/// - is not writable.
///
/// Creates the file if it does not exist.
public RingtoetsDatabaseFile(string path)
{
IOUtils.CreateFileIfNotExists(path);
filePath = path;
}
///
/// Opens the connection to the file.
///
public void OpenDatabaseConnection()
{
connection = new SQLiteConnection(SqLiteConnectionStringBuilder.BuildSqLiteConnectionString(filePath, false));
connection.Open();
}
///
/// Executes the that will on the database.
///
/// Create structure query to execute.
/// Thrown when is null
/// or consist out of only whitespace characters.
/// Thrown when executing failed.
public void ExecuteQuery(string query)
{
if (string.IsNullOrWhiteSpace(query))
{
throw new ArgumentException(@"Parameter must be a valid database script.", nameof(query));
}
using (var command = new SQLiteCommand(connection)
{
CommandText = query
})
{
command.ExecuteNonQuery();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
connection?.Close();
connection?.Dispose();
connection = null;
}
disposed = true;
}
}
}